问:
ManagedObject and ObservedObject
I'm trying to learn SwiftUI and Core Data (no experience with swift or objective C at all), and working my way through it by writing an app to track gym workouts.

I have a Workout entity that has a one-many relationship to an Exercise entity.

In my app, I start with a list of Workouts in a nav view pulled from core data.  Then I use a nav link to pass the selected Workout object to a details view that displays the properties of the Workout object.  The details view includes the workout name, date created, and a list of exercises tied to that workout.  The exercise list is loaded from the relationship property of the Workout object.

Next, I use a button to pass the Workout object to a sheet view that has a list of exercises.  The exercise list is a fetchrequest of the Exercise entity, and there is a checkmark next to each exercise in the list that has a relationship to the workout.  Each row in the list is an instance of another "row" view, and the entire row is a button.  The user can tap on row to add/remove it from the workout.

So far, this all works great. My problem is that the workout details view doesn't update when I use the exercise list sheet view to make changes to the workout's relationship to the exercise entity.  Core data does get updated, but the details view doesn't refresh the updated object from core data when the exercise sheet view is closed.

If I go back one step more to the parent view with the list of Workouts, and select that same Workout object again, now the details view refreshes with the correct exercise list from core data.

I think this is because the parent workout list is using a fetch request to get workout objects, and all the child views are just passing a single instance of the workout object down but not monitoring it for changes.  When I get back to the workout list, I guess fetch request is replacing the object instance with the latest data.

I want the details view to realize when the relationship property is changed in the exercise sheet view, and then update the Exercise list that appears on that details view with those changes.

How can I make this work? I've tried @ObservedObject on the Workout object that is getting passed through the view hierarchy, and I've tried managedObjectContext.refresh(Workout, mergeChanges: true) when the dismiss button on the sheet view is tapped, but nothing.

Any ideas?

```<code>//
//  WorkoutDetail.swift

import SwiftUI

struct WorkoutDetail: View {

    @Environment (\.managedObjectContext) var moc

    @ObservedObject var workout: Workout
    @State private var workoutDate: Date
    @State private var exerciseArray: [Exercise]
    @State private var workoutName: String
    @State private var showingAddScreen = false
    var fetchRequest: FetchRequest<Workout>

    static let setDateFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM d, y, h:mm a"
        return formatter
    }()

    init(workout: Workout) {
        self.workout = workout
        // Define the initial form field values
        _workoutName = .init(initialValue: workout.wrappedWorkoutName)
        _workoutDate = .init(initialValue: workout.wrappedWorkoutDate)
        _exerciseArray = .init(initialValue: workout.workoutExerciseArray)
        let workoutPredicate = NSPredicate(format: "workoutName == %@", workout.workoutName!)
        fetchRequest = FetchRequest<Workout>(entity: Workout.entity(), sortDescriptors: [], predicate: workoutPredicate)

    }

    var body: some View {
            Form {
                Section(header: Text("Workout Name")) {
                    TextField("Workout Name", text: $workoutName)
                    Text("Created \(workoutDate, formatter: Self.setDateFormat)")

                    Button("Save Changes") {
                        self.workout.setValue(self.workoutName, forKey: "workoutName")
                        try? self.moc.save()
                    }
                }
                Section(header: Text("Exercises")) {
                    Button(action: {self.showingAddScreen.toggle()}) {
                    HStack {
                        Image(systemName: "pencil")
                        Text("Add/Remove Exercises")}
                    }
                    List{
                        ForEach(exerciseArray, id:\ .self) { exercise in
                            VStack(alignment: .leading) {
                                NavigationLink(destination: ExerciseSet(exerciseSetExercise: exercise, exerciseSetWorkout: self.workout)) {
                                    WorkoutExercise(exercise: exercise)
                                }
                            }
                        }
                    }
                }
            }.navigationBarTitle("\(workoutName)")
            .sheet(isPresented: $showingAddScreen) {
                AddExerciseToWorkout(workout: self.workout).environment(\.managedObjectContext, self.moc)}
        }
}
</code>```

```<code>//
//  AddExerciseToWorkout.swift

import SwiftUI

struct AddExerciseToWorkout: View {
    @ObservedObject var workout: Workout
    @State private var exerciseArray: [Exercise]
    @State private var workoutName: String
    var exerciseNameArray: [String] = []
    @State var selectedExercises: [String] = []
    @FetchRequest(entity: Type.entity(), sortDescriptors: [NSSortDescriptor(key:"typeName", ascending: true)]) var strengthExercises: FetchedResults<Type>
    @Environment(\.presentationMode) var presentationMode

    init(workout: Workout) {
        self.workout = workout
        _exerciseArray = .init(initialValue: workout.workoutExerciseArray)
        _workoutName = .init(initialValue: workout.wrappedWorkoutName)
    }

    var body: some View {
        VStack {

            Text("\(workoutName) exercises:")
                .font(.headline)
                .padding()
            List{
                ForEach(strengthExercises, id:\.self) { strengthExercise in
                    Section(header: Text(strengthExercise.wrappedTypeName)) {
                        ForEach(strengthExercise.typeExerciseArray, id: \.self) { exercise in
                            AddExerciseToWorkoutRow(workout: self.workout, exercise: exercise)

                        }
                    }
                }
            }
            Button("Done") {self.presentationMode.wrappedValue.dismiss()
            }
        }
    }
}
</code>```

```<code>//
//  AddExerciseToWorkoutRow.swift

import SwiftUI
import CoreData

struct AddExerciseToWorkoutRow: View {
    @Environment(\.managedObjectContext) var moc
    let exercise: Exercise
    @ObservedObject var workout: Workout
    @State private var exerciseArray: [Exercise]
    @State private var isSelected: Bool = false

    init(workout: Workout, exercise: Exercise) {
        self.workout = workout
        self.exercise = exercise
        _exerciseArray = .init(initialValue: workout.workoutExerciseArray)
        if exerciseArray.contains(exercise) {
            _isSelected = .init(initialValue: true)
        } else {
            _isSelected = .init(initialValue: false)
        }
    }

    var body: some View {
        Button(action: {
            if self.exerciseArray.contains(self.exercise) {
                self.workout.removeFromWorkoutToExercise(self.exercise)
                self.isSelected = false
            } else {
                self.workout.addToWorkoutToExercise(self.exercise)
                self.isSelected = true
            }
            try? self.moc.save()
                self.moc.refresh(self.workout, mergeChanges: true)
                self.workout.didChangeValue(forKey: "workoutToExercise")
        }) {
            HStack {
                Text(exercise.wrappedExerciseName)
                Spacer()
                if self.isSelected {
                    Image(systemName: "checkmark")
                        .foregroundColor(.green)
                }
            }
        }
    }
}
</code>```

答:
I was able to resolve this by taking the exercise list that appears on the Workout detail view and putting it into another subview.  I would pass the workout date (which is the unique ID for each workout) to the subview, then use that date as a NSPredicate within a FetchRequest on the subview to pull the updated list of exercises assigned to the workout.
It works, but it sure feels like there must be an easier way.

Title: ManagedObject and ObservedObject

Body:
I'm trying to learn SwiftUI and Core Data (no experience with swift or objective C at all), and working my way through it by writing an app to track gym workouts.

I have a Workout entity that has a one-many relationship to an Exercise entity.

In my app, I start with a list of Workouts in a nav view pulled from core data.  Then I use a nav link to pass the selected Workout object to a details view that displays the properties of the Workout object.  The details view includes the workout name, date created, and a list of exercises tied to that workout.  The exercise list is loaded from the relationship property of the Workout object.

Next, I use a button to pass the Workout object to a sheet view that has a list of exercises.  The exercise list is a fetchrequest of the Exercise entity, and there is a checkmark next to each exercise in the list that has a relationship to the workout.  Each row in the list is an instance of another "row" view, and the entire row is a button.  The user can tap on row to add/remove it from the workout.

So far, this all works great. My problem is that the workout details view doesn't update when I use the exercise list sheet view to make changes to the workout's relationship to the exercise entity.  Core data does get updated, but the details view doesn't refresh the updated object from core data when the exercise sheet view is closed.

If I go back one step more to the parent view with the list of Workouts, and select that same Workout object again, now the details view refreshes with the correct exercise list from core data.

I think this is because the parent workout list is using a fetch request to get workout objects, and all the child views are just passing a single instance of the workout object down but not monitoring it for changes.  When I get back to the workout list, I guess fetch request is replacing the object instance with the latest data.

I want the details view to realize when the relationship property is changed in the exercise sheet view, and then update the Exercise list that appears on that details view with those changes.

How can I make this work? I've tried @ObservedObject on the Workout object that is getting passed through the view hierarchy, and I've tried managedObjectContext.refresh(Workout, mergeChanges: true) when the dismiss button on the sheet view is tapped, but nothing.

Any ideas?

//
//  WorkoutDetail.swift

import SwiftUI

struct WorkoutDetail: View {

    @Environment (\.managedObjectContext) var moc

    @ObservedObject var workout: Workout
    @State private var workoutDate: Date
    @State private var exerciseArray: [Exercise]
    @State private var workoutName: String
    @State private var showingAddScreen = false
    var fetchRequest: FetchRequest<Workout>

    static let setDateFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM d, y, h:mm a"
        return formatter
    }()

    init(workout: Workout) {
        self.workout = workout
        // Define the initial form field values
        _workoutName = .init(initialValue: workout.wrappedWorkoutName)
        _workoutDate = .init(initialValue: workout.wrappedWorkoutDate)
        _exerciseArray = .init(initialValue: workout.workoutExerciseArray)
        let workoutPredicate = NSPredicate(format: "workoutName == %@", workout.workoutName!)
        fetchRequest = FetchRequest<Workout>(entity: Workout.entity(), sortDescriptors: [], predicate: workoutPredicate)

    }

    var body: some View {
            Form {
                Section(header: Text("Workout Name")) {
                    TextField("Workout Name", text: $workoutName)
                    Text("Created \(workoutDate, formatter: Self.setDateFormat)")

                    Button("Save Changes") {
                        self.workout.setValue(self.workoutName, forKey: "workoutName")
                        try? self.moc.save()
                    }
                }
                Section(header: Text("Exercises")) {
                    Button(action: {self.showingAddScreen.toggle()}) {
                    HStack {
                        Image(systemName: "pencil")
                        Text("Add/Remove Exercises")}
                    }
                    List{
                        ForEach(exerciseArray, id:\ .self) { exercise in
                            VStack(alignment: .leading) {
                                NavigationLink(destination: ExerciseSet(exerciseSetExercise: exercise, exerciseSetWorkout: self.workout)) {
                                    WorkoutExercise(exercise: exercise)
                                }
                            }
                        }
                    }
                }
            }.navigationBarTitle("\(workoutName)")
            .sheet(isPresented: $showingAddScreen) {
                AddExerciseToWorkout(workout: self.workout).environment(\.managedObjectContext, self.moc)}
        }
}

//
//  AddExerciseToWorkout.swift

import SwiftUI

struct AddExerciseToWorkout: View {
    @ObservedObject var workout: Workout
    @State private var exerciseArray: [Exercise]
    @State private var workoutName: String
    var exerciseNameArray: [String] = []
    @State var selectedExercises: [String] = []
    @FetchRequest(entity: Type.entity(), sortDescriptors: [NSSortDescriptor(key:"typeName", ascending: true)]) var strengthExercises: FetchedResults<Type>
    @Environment(\.presentationMode) var presentationMode

    init(workout: Workout) {
        self.workout = workout
        _exerciseArray = .init(initialValue: workout.workoutExerciseArray)
        _workoutName = .init(initialValue: workout.wrappedWorkoutName)
    }

    var body: some View {
        VStack {

            Text("\(workoutName) exercises:")
                .font(.headline)
                .padding()
            List{
                ForEach(strengthExercises, id:\.self) { strengthExercise in
                    Section(header: Text(strengthExercise.wrappedTypeName)) {
                        ForEach(strengthExercise.typeExerciseArray, id: \.self) { exercise in
                            AddExerciseToWorkoutRow(workout: self.workout, exercise: exercise)

                        }
                    }
                }
            }
            Button("Done") {self.presentationMode.wrappedValue.dismiss()
            }
        }
    }
}

//
//  AddExerciseToWorkoutRow.swift

import SwiftUI
import CoreData

struct AddExerciseToWorkoutRow: View {
    @Environment(\.managedObjectContext) var moc
    let exercise: Exercise
    @ObservedObject var workout: Workout
    @State private var exerciseArray: [Exercise]
    @State private var isSelected: Bool = false

    init(workout: Workout, exercise: Exercise) {
        self.workout = workout
        self.exercise = exercise
        _exerciseArray = .init(initialValue: workout.workoutExerciseArray)
        if exerciseArray.contains(exercise) {
            _isSelected = .init(initialValue: true)
        } else {
            _isSelected = .init(initialValue: false)
        }
    }

    var body: some View {
        Button(action: {
            if self.exerciseArray.contains(self.exercise) {
                self.workout.removeFromWorkoutToExercise(self.exercise)
                self.isSelected = false
            } else {
                self.workout.addToWorkoutToExercise(self.exercise)
                self.isSelected = true
            }
            try? self.moc.save()
                self.moc.refresh(self.workout, mergeChanges: true)
                self.workout.didChangeValue(forKey: "workoutToExercise")
        }) {
            HStack {
                Text(exercise.wrappedExerciseName)
                Spacer()
                if self.isSelected {
                    Image(systemName: "checkmark")
                        .foregroundColor(.green)
                }
            }
        }
    }
}


来源: stackexchange

问:
Generating fibonacci number is C
I was practicing array in C. I have found a code mentioned bellow.

```<code>
int main(void)
{
    int  numbers[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int  i, j;

    **for (j = 0;  j < 10;  ++j)
        for (i = 0;  i < j;  ++i)
            numbers[j]  = numbers[j] +numbers[i];**

    for (j = 0;  j < 10;  ++j)
        printf("%i ", numbers[j]);

    printf("\n");

    return 0;
}
</code>```

I know that it's a silly question. If anyone help me to understand the Bold marked for loop, I would be very grateful. Thanks in advance.

答:
```<code>for (j = 0;  j < 10;  ++j)
    for (i = 0;  i < j;  ++i)
        numbers[j]  = numbers[j] +numbers[i];
</code>```

The above loop will target particular position of the array and will add all the numbers one by one from 0th position to selected position.

Eventually you are not generating the Fibonacci sequence.

```<code>j =0
       1, 0, 0, 0, 0, 0, 0, 0, 0, 0

j = 1
       1, 1, 0, 0, 0, 0, 0, 0, 0, 0

j = 2
       1, 1, 2, 0, 0, 0, 0, 0, 0, 0

j = 3
       1, 1, 2, 4, 0, 0, 0, 0, 0, 0

j = 4
       1, 1, 2, 4, 8, 0, 0, 0, 0, 0

...so on
</code>```

ContentLicense: CC BY-SA 4.0

Title: Generating fibonacci number is C

Body:
I was practicing array in C. I have found a code mentioned bellow.

int main(void)
{
    int  numbers[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int  i, j;

    **for (j = 0;  j < 10;  ++j)
        for (i = 0;  i < j;  ++i)
            numbers[j]  = numbers[j] +numbers[i];**

    for (j = 0;  j < 10;  ++j)
        printf("%i ", numbers[j]);

    printf("\n");

    return 0;
}

I know that it's a silly question. If anyone help me to understand the Bold marked for loop, I would be very grateful. Thanks in advance.

Body:
for (j = 0;  j < 10;  ++j)
    for (i = 0;  i < j;  ++i)
        numbers[j]  = numbers[j] +numbers[i];

The above loop will target particular position of the array and will add all the numbers one by one from 0th position to selected position.

Eventually you are not generating the Fibonacci sequence.

j =0
       1, 0, 0, 0, 0, 0, 0, 0, 0, 0

j = 1
       1, 1, 0, 0, 0, 0, 0, 0, 0, 0

j = 2
       1, 1, 2, 0, 0, 0, 0, 0, 0, 0

j = 3
       1, 1, 2, 4, 0, 0, 0, 0, 0, 0

j = 4
       1, 1, 2, 4, 8, 0, 0, 0, 0, 0

...so on


问:
Issue in connecting with LUIS platform from Python v4 botframework
I am trying to run the below github project  :-

Python Core Bot

in main_dialog.py below lines (70-73) are relevant:

```<code># Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
        intent, luis_result = await LuisHelper.execute_luis_query(
            self._luis_recognizer, step_context.context
        )
</code>```

Configured config.py with Luis app id ,key and hostname

When i run the python app :-
python app.py

and start chatbot emulator ,it doesn't recognizes the LUIS intent and i also get an error.

More description of error, i have provided in below link:

Chatbot v4 issue raised github

Steps to reproduce:
Configure config.py with Luis app id,key and host.
Run app using python app.py
Start chatbot emulator and open bot with http://localhost:3978/api/messages url.
Enter your message as per screenshot.

Case 1. Luis host id is configured with value starting with https:// i.e  https://XXXX.XXXX.XXX in config.py

Blow error occurs:
Error occurred in request., ConnectionError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: /southcXXX.api.XXXXX.microsoft.com/luis/v2.0/ap
ps/?log=true (Caused by NewConnectionError(': Failed to establish a
new connection: [Errno 11001] getaddrinfo failed'))

Case 2. When luis host is configured without https:// i.e XXXX.XXXX.XXXX

Then luis intents are not recognized in main_dialog.py . It finally goes to didnt_understand_message  part i.e Sorry, I didn't get that. Please try asking in a different way in chatbot (attached in screenshot)

```<code># Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
intent, luis_result = await LuisHelper.execute_luis_query(
    self._luis_recognizer, step_context.context
)

if intent == Intent.BOOK_FLIGHT.value and luis_result:
    # Show a warning for Origin and Destination if we can't resolve them.
    await MainDialog._show_warning_for_unsupported_cities(
        step_context.context, luis_result
    )

    # Run the BookingDialog giving it whatever details we have from the LUIS call.
    return await step_context.begin_dialog(self._booking_dialog_id, luis_result)

if intent == Intent.GET_WEATHER.value:
    get_weather_text = "TODO: get weather flow here"
    get_weather_message = MessageFactory.text(
        get_weather_text, get_weather_text, InputHints.ignoring_input
    )
    await step_context.context.send_activity(get_weather_message)

else:
    didnt_understand_text = (
        "Sorry, I didn't get that. Please try asking in a different way"
    )
    didnt_understand_message = MessageFactory.text(
        didnt_understand_text, didnt_understand_text, InputHints.ignoring_input
    )
    await step_context.context.send_activity(didnt_understand_message)

return await step_context.next(None)
</code>```

Please help.
Thanks in Advance.

答:
This issue is resolved Now.
Luis host format was added in config.py file was having https:// which was causing issue.
I just removed that from url and it worked fine for me.

https://xxx.xxx.xxx - Wrong format for this Python project.
xxxx.xxxx.xxx - Correct format.

Body:
I am trying to run the below github project  :-

Python Core Bot

in main_dialog.py below lines (70-73) are relevant:

# Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
        intent, luis_result = await LuisHelper.execute_luis_query(
            self._luis_recognizer, step_context.context
        )

Configured config.py with Luis app id ,key and hostname

When i run the python app :-
python app.py

and start chatbot emulator ,it doesn't recognizes the LUIS intent and i also get an error.

More description of error, i have provided in below link:

Chatbot v4 issue raised github

Steps to reproduce:
Configure config.py with Luis app id,key and host.
Run app using python app.py
Start chatbot emulator and open bot with http://localhost:3978/api/messages url.
Enter your message as per screenshot.

Case 1. Luis host id is configured with value starting with https:// i.e  https://XXXX.XXXX.XXX in config.py

Blow error occurs:
Error occurred in request., ConnectionError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: /southcXXX.api.XXXXX.microsoft.com/luis/v2.0/ap
ps/?log=true (Caused by NewConnectionError(': Failed to establish a
new connection: [Errno 11001] getaddrinfo failed'))

Case 2. When luis host is configured without https:// i.e XXXX.XXXX.XXXX

Then luis intents are not recognized in main_dialog.py . It finally goes to didnt_understand_message  part i.e Sorry, I didn't get that. Please try asking in a different way in chatbot (attached in screenshot)

# Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
intent, luis_result = await LuisHelper.execute_luis_query(
    self._luis_recognizer, step_context.context
)

if intent == Intent.BOOK_FLIGHT.value and luis_result:
    # Show a warning for Origin and Destination if we can't resolve them.
    await MainDialog._show_warning_for_unsupported_cities(
        step_context.context, luis_result
    )

    # Run the BookingDialog giving it whatever details we have from the LUIS call.
    return await step_context.begin_dialog(self._booking_dialog_id, luis_result)

if intent == Intent.GET_WEATHER.value:
    get_weather_text = "TODO: get weather flow here"
    get_weather_message = MessageFactory.text(
        get_weather_text, get_weather_text, InputHints.ignoring_input
    )
    await step_context.context.send_activity(get_weather_message)

else:
    didnt_understand_text = (
        "Sorry, I didn't get that. Please try asking in a different way"
    )
    didnt_understand_message = MessageFactory.text(
        didnt_understand_text, didnt_understand_text, InputHints.ignoring_input
    )
    await step_context.context.send_activity(didnt_understand_message)

return await step_context.next(None)

Please help.
Thanks in Advance.


问:
How to determine MySQL / MariaDB version for Maven dependency?
I'm writing a simple Maven project to access my MySQL / MariaDB database. In order to download the proper database connector jar file, I'm adding the following Maven dependency:

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>provided</scope>
</dependency>
</code>```

I've got that 5.1.47 version above "by chance", based on a previous project which already worked on my computer.

However, when I type mysql -V (capital V) on terminal to check my MySQL/MariaDB version, I get the following:

```<code>>mysql -V
mysql  Ver 15.1 Distrib 10.4.6-MariaDB, for Win64 (AMD64), source revision b8e655ce029a1f182602c9f12c3cc5931226eec2
</code>```

But that 10.4.6 version doesn't mean much to me in terms of determining a proper version to set up my Maven dependency.

What's the procedure to determine MySQL version for Maven dependency based on my local MySQL / MariaDB server?

答:
You can get the newest version from mvnrepository.

If you have the older version of mysql, you need to make sure, that the versions of the connector, jdbc, database etc. match. You can find this information in the mysql developer guide. The same thing applies to the compatibility for mariadb - check out the documentation.

Note, that the driver version depends not only on the version of the database, but also on java version.

Body:
I'm writing a simple Maven project to access my MySQL / MariaDB database. In order to download the proper database connector jar file, I'm adding the following Maven dependency:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>provided</scope>
</dependency>

I've got that 5.1.47 version above "by chance", based on a previous project which already worked on my computer.

However, when I type mysql -V (capital V) on terminal to check my MySQL/MariaDB version, I get the following:

>mysql -V
mysql  Ver 15.1 Distrib 10.4.6-MariaDB, for Win64 (AMD64), source revision b8e655ce029a1f182602c9f12c3cc5931226eec2

But that 10.4.6 version doesn't mean much to me in terms of determining a proper version to set up my Maven dependency.

What's the procedure to determine MySQL version for Maven dependency based on my local MySQL / MariaDB server?


问:
If Statement If A2 is Empty Dont Run Code - else run code if A2 has Data - Google Apps Script / GoogleSheets
I have tried to get this if statement to run as I am not yet experienced enough to know what I am doing wrong. (it runs perfectly if I manually run the script)

Expected result = if A2 has data - run the below code. if A2 is blank - dont run the code.

```<code>function IfStatement() {
var app = SpreadsheetApp;
var activeSheet = app.getActive().getActiveSheet();
var workingCell = activeSheet.getRange(2, 1).getValue();

if(workingCell === ""){
}

function kk() {
var sheet = SpreadsheetApp.getActive();
sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
sheet.getRange('D2').activate();
sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" &
JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');
addCheckboxToI2();
}}

Hoping I was close !
</code>```

答:
If you want to run the script of function kk() {###} when workingCell is not empty, how about this modification?

Modified script:

```<code>function IfStatement() {
  var app = SpreadsheetApp;
  var activeSheet = app.getActive().getActiveSheet();
  var workingCell = activeSheet.getRange(2, 1).getValue();
  if (workingCell === "") return;  // Modified

  var sheet = SpreadsheetApp.getActive();
  sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
  sheet.getRange('D2').activate();
  sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" & JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');
  addCheckboxToI2();
}
</code>```

if(workingCell === ""){} was modified to if (workingCell === "") return;.

function kk() { was removed.

By this modification, when the value of workingCell is not empty, the below script of if (workingCell === "") return; is run. When the value of workingCell is empty, the script is finished at if (workingCell === "") return;.

If I misunderstood your question and this was not the direction you want, I apologize.

Body:
I have tried to get this if statement to run as I am not yet experienced enough to know what I am doing wrong. (it runs perfectly if I manually run the script)

Expected result = if A2 has data - run the below code. if A2 is blank - dont run the code.

function IfStatement() {
var app = SpreadsheetApp;
var activeSheet = app.getActive().getActiveSheet();
var workingCell = activeSheet.getRange(2, 1).getValue();

if(workingCell === ""){
}

function kk() {
var sheet = SpreadsheetApp.getActive();
sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
sheet.getRange('D2').activate();
sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" &
JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');
addCheckboxToI2();
}}

Hoping I was close !

Body:
If you want to run the script of function kk() {###} when workingCell is not empty, how about this modification?

Modified script:

function IfStatement() {
  var app = SpreadsheetApp;
  var activeSheet = app.getActive().getActiveSheet();
  var workingCell = activeSheet.getRange(2, 1).getValue();
  if (workingCell === "") return;  // Modified

  var sheet = SpreadsheetApp.getActive();
  sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
  sheet.getRange('D2').activate();
  sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" & JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');
  addCheckboxToI2();
}

if(workingCell === ""){} was modified to if (workingCell === "") return;.

function kk() { was removed.

By this modification, when the value of workingCell is not empty, the below script of if (workingCell === "") return; is run. When the value of workingCell is empty, the script is finished at if (workingCell === "") return;.

If I misunderstood your question and this was not the direction you want, I apologize.


问:
How can I match an exact pattern with sed -n
I have a file test.txt

```<code>---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla
</code>```

And need this output with sed (just the line that matches the exact pattern)

```<code>kind: ClusterRole
metadata:
</code>```

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

```<code>kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla
</code>```

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

```<code>sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt
</code>```

Both of the above output to nothing what am I doing wrong?
just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema

答:
If you just need to search the exact multiple lines, then you can achieve it using pcregrep

```<code>pcregrep -M 'kind: ClusterRole(\n)metadata:' test.txt
</code>```

where -M, --multiline allow patterns to match more than one line.

More details can be found in this SO post.

Edit:

You can also use grep

```<code>grep -Pazo 'kind: ClusterRole\nmetadata:' test.txt
</code>```

Reference: this SO post

Body:
I have a file test.txt

---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla

And need this output with sed (just the line that matches the exact pattern)

kind: ClusterRole
metadata:

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt

Both of the above output to nothing what am I doing wrong?
just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema

Body:
If you just need to search the exact multiple lines, then you can achieve it using pcregrep

pcregrep -M 'kind: ClusterRole(\n)metadata:' test.txt

where -M, --multiline allow patterns to match more than one line.

More details can be found in this SO post.

Edit:

You can also use grep

grep -Pazo 'kind: ClusterRole\nmetadata:' test.txt

Reference: this SO post


问:
html canvas problems with context.drawImage()
I'm using canvas and i'm trying to draw an image to the canvas but it doesn't work. I found that I need to use eventListener but it didn't fix it. can someone tell me what's wrong.</p>

```<code>const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

const groundImg = new Image();
groundImg.src = "ground.png";

groundImg.addEventListener("load", startDraw());

function startDraw() {
    ctx.drawImage(groundImg, 0, 0, c.width, c.height);
}
</code>```

答:
change:

```<code>groundImg.addEventListener("load", startDraw());
</code>```

to:

```<code>groundImg.addEventListener("load", startDraw);
</code>```

Body:
I'm using canvas and i'm trying to draw an image to the canvas but it doesn't work. I found that I need to use eventListener but it didn't fix it. can someone tell me what's wrong.

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

const groundImg = new Image();
groundImg.src = "ground.png";

groundImg.addEventListener("load", startDraw());

function startDraw() {
    ctx.drawImage(groundImg, 0, 0, c.width, c.height);
}

Body:
change:

groundImg.addEventListener("load", startDraw());

to:

groundImg.addEventListener("load", startDraw);


问:
How to add a new key value pair to existing key value pair from list of dicts?
I have a dictionary with a parent-key and its value is a dict. I want to extract a key,val pair from a list of dict.

given:

```<code>{"Premier" : {}}
</code>```

I want to extract:

```<code> all_compseasons = content: [
    {
        label: "2019/20",
        id: 274
    },
    {
        label: "2018/19",
        id: 210
    }]
</code>```

So to get:

```<code>{"Premier" :
    {"2019/20" : 274,
    "2018/19" : 210
    }
}
</code>```

I can't seem to find a good way to do it. I've tried below given other examples of the problem, but doesn't work.

```<code>compseasons = {}
for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index]comp['label'] = comp['id']
</code>```

答:
You just made a mistake in how you declared compseasons and how you are accessing the value of premier key which is also a dictionary.

Declaring compseasons = {"Premier" : {}} will not give you KeyError when you are trying to access it via compseasons[index] since Premier has already been inserted as a key.

Second, since your value of Premier itself is a dictionary, you should access the inner key enclosed in [] which would translate to compseasons[index][comp['label']] = comp['id'].

```<code>all_compseasons = [
{
    'label': "2019/20",
    'id': 274
},
{
    'label': "2018/19",
    'id': 210
}]

compseasons = {"Premier" : {}}

for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index][comp['label']] = comp['id']
</code>```

Body:
I have a dictionary with a parent-key and its value is a dict. I want to extract a key,val pair from a list of dict.

given:

{"Premier" : {}}

I want to extract:

 all_compseasons = content: [
    {
        label: "2019/20",
        id: 274
    },
    {
        label: "2018/19",
        id: 210
    }]

So to get:

{"Premier" :
    {"2019/20" : 274,
    "2018/19" : 210
    }
}

I can't seem to find a good way to do it. I've tried below given other examples of the problem, but doesn't work.

compseasons = {}
for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index]comp['label'] = comp['id']

Body:
You just made a mistake in how you declared compseasons and how you are accessing the value of premier key which is also a dictionary.

Declaring compseasons = {"Premier" : {}} will not give you KeyError when you are trying to access it via compseasons[index] since Premier has already been inserted as a key.

Second, since your value of Premier itself is a dictionary, you should access the inner key enclosed in [] which would translate to compseasons[index][comp['label']] = comp['id'].

all_compseasons = [
{
    'label': "2019/20",
    'id': 274
},
{
    'label': "2018/19",
    'id': 210
}]

compseasons = {"Premier" : {}}

for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index][comp['label']] = comp['id']


问:
Create stored function to retrieve total amount between two dates
I create a stored function and just want to retrieve total amount by following query but ouput is null please let me know whats wrong in it</p>

```<code>DELIMITER $$

CREATE FUNCTION demo6(a DATE , b DATE)
RETURNS INT
DETERMINISTIC
BEGIN
    RETURN (SELECT SUM(`amount`) AS `total` FROM
`temp_sale` WHERE `transaction_date`
BETWEEN a AND b);
END$$

DELIMITER ;
</code>```

答:
If the function is returning NULL, then the query is returning NULL.  This query:

```<code>SELECT SUM(`amount`) AS `total`
FROM `temp_sale`
WHERE `transaction_date` BETWEEN a AND b;
</code>```

returns NULL whenever there are no rows that match the WHERE clause.  So, your result is probably due to either an empty table or having no rows match the conditions.

A secondary reason could be the presence of columns called a or b in temp_sale.  I strongly recommend giving function and stored procedure parameters prefixes to help avoid naming conflicts:

```<code>CREATE FUNCTION demo6 (
    in_date_first DATE,
    in_date_last DATE
) RETURNS INT DETERMINISTIC
BEGIN
    RETURN (SELECT SUM(ts.amount)
            FROM temp_sale ts
            WHERE ts.transaction_date BETWEEN in_date_first AND in_date_last);
END$$
</code>```

Body:
I create a stored function and just want to retrieve total amount by following query but ouput is null please let me know whats wrong in it

DELIMITER $$

CREATE FUNCTION demo6(a DATE , b DATE)
RETURNS INT
DETERMINISTIC
BEGIN
    RETURN (SELECT SUM(`amount`) AS `total` FROM
`temp_sale` WHERE `transaction_date`
BETWEEN a AND b);
END$$

DELIMITER ;

Body:
If the function is returning NULL, then the query is returning NULL.  This query:

SELECT SUM(`amount`) AS `total`
FROM `temp_sale`
WHERE `transaction_date` BETWEEN a AND b;

returns NULL whenever there are no rows that match the WHERE clause.  So, your result is probably due to either an empty table or having no rows match the conditions.

A secondary reason could be the presence of columns called a or b in temp_sale.  I strongly recommend giving function and stored procedure parameters prefixes to help avoid naming conflicts:

CREATE FUNCTION demo6 (
    in_date_first DATE,
    in_date_last DATE
) RETURNS INT DETERMINISTIC
BEGIN
    RETURN (SELECT SUM(ts.amount)
            FROM temp_sale ts
            WHERE ts.transaction_date BETWEEN in_date_first AND in_date_last);
END$$


问:
Is any ways to speedup work of Map.getOrElse(val, 0) on big tuple maps?
I has simple immutable Map in Scala:

```<code>// ... - mean and so on
val myLibrary = Map("qwe" -> 1.2, "qasd" -> -0.59, ...)
</code>```

And for that myMap i calling MyFind method which call getOrElse(val, 0):

```<code>def MyFind (srcMap: Map[String,Int], str: String): Int ={
    srcMap.getOrElse(str,0)
}

val res = MyFind(myLibrary, "qwe")
</code>```

Problem in that this method called several times for different input strings. E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

What you can advice to speedup that code?

Maybe use another type of Map?

Maybe another collection?

答:
E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

No, it won't. That's rather the point of Map in the first place. While it allows implementations which do require checking each value one-by-one (such as ListMap) they are very rarely used and by default when calling Map(...) you'll get a HashMap which doesn't. Its lookup is logarithmic time (with a large base), so basically when going from 100 to 10000 it doubles instead of increasing by 100 times.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

10000 is quite small.

Actually, look at http://www.lihaoyi.com/post/BenchmarkingScalaCollections.html#performance. You can also see that mutable maps are much faster. Note that this predates collection changes in Scala 2.13, so may have changed.

Body:
I has simple immutable Map in Scala:

// ... - mean and so on
val myLibrary = Map("qwe" -> 1.2, "qasd" -> -0.59, ...)

And for that myMap i calling MyFind method which call getOrElse(val, 0):

def MyFind (srcMap: Map[String,Int], str: String): Int ={
    srcMap.getOrElse(str,0)
}

val res = MyFind(myLibrary, "qwe")

Problem in that this method called several times for different input strings. E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

What you can advice to speedup that code?

Maybe use another type of Map?

Maybe another collection?


问:
how to trim whitespace between strings in selenium xpath python
I want to find elements containing name and age.

But Name can contain whitespace like "Jo hn", So I want to remove whitespace between strings.

So I made code below, but SyntaxError. How can I do this?

```<code>driver.find_elements_by_xpath('//*[@id="Nlist"]/section/ul/li/a/span[contains(text().replace(" ", ""),"' + NAME + '") and contains(.,"' + AGE + '")]')
</code>```

text().replace(" ", "") is Syntax Error. Is there any method?

I need to do this when find elements because speed.

答:
Here is the sample html used to trim the space(s) with in name and used contains to match the partial text.

   <!DOCTYPE html>

  s upputuri-100
  s upp uturi-100

```
</div>
</div>
</p>

<p>You can use <code>translate</code> method to replace the white space(s) with the desired char/empty. Below the xpath to get the span that contains <code>supputuri</code> and <code>100</code>.</p>

```//span[contains(translate(.,' ' ,''),'supputuri')][contains(.,'100')]
```

Body:
I want to find elements containing name and age.

But Name can contain whitespace like "Jo hn", So I want to remove whitespace between strings.

So I made code below, but SyntaxError. How can I do this?

driver.find_elements_by_xpath('//*[@id="Nlist"]/section/ul/li/a/span[contains(text().replace(" ", ""),"' + NAME + '") and contains(.,"' + AGE + '")]')

text().replace(" ", "") is Syntax Error. Is there any method?

I need to do this when find elements because speed.

Body:
Here is the sample html used to trim the space(s) with in name and used contains to match the partial text.

   <!DOCTYPE html>
<html>
  <body>
  <span>s upputuri-100</span>
  <span>s upp uturi-100</span>
   </body>
</html>

You can use translate method to replace the white space(s) with the desired char/empty. Below the xpath to get the span that contains supputuri and 100.

//span[contains(translate(.,' ' ,''),'supputuri')][contains(.,'100')]


问:
Changing the class name JS
I have this code on the page:

```<code><td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;"><button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button></td>
</code>```

I want to change the class name if there is a string "niedziela" in the "aria-label" attribute.
I wrote something, but unfortunately it doesn't work and I don't know what to do. My code:

```<code>var string = document.getElementsByClassName("CalendarDay CalendarDay--valid").aria-label,
    substring = "niedziela";

if (string.includes(substring)) {
    document.getElementsByClassName("CalendarDay CalendarDay--valid").className = "CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range";
}
</code>```

答:
Instead of targeting by class of the parent target the button with specified class using
document.querySelectorAll(). Then iterate the collection and check if the aria-label includes that specific keyword. If so then change the class of the parent using parentNode

let buttonDataAttr = document.querySelectorAll('.CalendarDay__button').forEach((item) => {
  let getDataLabel = item.getAttribute('aria-label');
  if (getDataLabel.includes('niedziela')) {
    item.parentNode.className = "CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range"
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.CalendarDay--blocked {
  border: 1px solid green;
}

.CalendarDay--blocked-out-of-range {
  border: 1px solid red;
}</code>```

    <button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>

```

Title: Changing the class name JS

Body:
I have this code on the page:

<button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>

I want to change the class name if there is a string "niedziela" in the "aria-label" attribute.
I wrote something, but unfortunately it doesn't work and I don't know what to do. My code:

var string = document.getElementsByClassName("CalendarDay CalendarDay--valid").aria-label,
    substring = "niedziela";

if (string.includes(substring)) {
    document.getElementsByClassName("CalendarDay CalendarDay--valid").className = "CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range";
}

Body:
Instead of targeting by class of the parent target the button with specified class using
document.querySelectorAll(). Then iterate the collection and check if the aria-label includes that specific keyword. If so then change the class of the parent using parentNode

let buttonDataAttr = document.querySelectorAll('.CalendarDay__button').forEach((item) => {
  let getDataLabel = item.getAttribute('aria-label');
  if (getDataLabel.includes('niedziela')) {
    item.parentNode.className = "CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range"
  }
})

.CalendarDay--blocked {
  border: 1px solid green;
}

.CalendarDay--blocked-out-of-range {
  border: 1px solid red;
}

<table>
  <tr>
    <td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;"><button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button></td>
  </tr>
</table>


问:
RoomProcessor compilation or a circular dependency
I've been struggling for days with and issue with Android Room component.

All I did was upgrade my Android studio from 3.3 to 3.4.1, this comes with changes to gradle etc that are done.
I've even tried going back to 3.3, but nothing is working.
I've have run with Run with --info or --debug option to try see more details but nothing gives me more info. Please help

```<code>e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/HotspotEntity.java:7: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public final class HotspotEntity implements android.os.Parcelable {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../ConditionEntity.java:7: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above".
public final class ConditionEntity implements android.os.Parcelable {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/AdLimits.java:6: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above"
public final class AdLimits {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/AdTarget.java:6: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above"
public final class AdTarget {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/AdUrl.java:6: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above"
public final class AdUrl {
             ^

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Compilation error. See log for more details
</code>```

Versions

```<code>Android Gradle:
3.4.1
Gradle version:
5.4.1
Android Room:
def room_version = "2.1.0-alpha06"
implementation 'androidx.room:room-runtime:' + room_version
kapt 'androidx.room:room-compiler:' + room_version
testImplementation 'androidx.room:room-testing:' + room_version
</code>```

----UPDATE----

Below was tried with room 2.1.0-rc01"which changed it to the same problem but for a different class:

```<code>AppDatabase.java:8: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public abstract class AppDatabase extends androidx.room.RoomDatabase {
</code>```

Grade File

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: "androidx.navigation.safeargs.kotlin"

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.cfl.surfstoked"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 19
        versionName "1.0.4"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            debuggable true
        }

        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    repositories {
        mavenCentral()
    }

    lintOptions {
        checkReleaseBuilds false
    }

    configurations {
        cleanedAnnotations
        compile.exclude group: 'org.jetbrains', module: 'annotations'
    }
}

dependencies {
    kapt 'com.google.dagger:dagger-android-processor:2.23.1'

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.0.2'

    def lifecycleVersion = "2.1.0-alpha02"
    implementation 'androidx.lifecycle:lifecycle-extensions:' + lifecycleVersion
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:' + lifecycleVersion
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha01'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
    kapt 'androidx.lifecycle:lifecycle-compiler:' + lifecycleVersion

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    //DI
    def koinVersion = "1.0.2"
    implementation 'org.koin:koin-android:' + koinVersion
    implementation 'org.koin:koin-androidx-scope:' + koinVersion
    implementation 'org.koin:koin-androidx-viewmodel:' + koinVersion

    //Navigation
//    def navigationVersion = "1.0.0-beta02"
//    implementation 'android.arch.navigation:navigation-fragment-ktx:' + navigationVersion
//    implementation 'android.arch.navigation:navigation-ui-ktx:' + navigationVersion

    def navigationVersion = "2.1.0-alpha01"
    implementation 'androidx.navigation:navigation-fragment-ktx:' + navigationVersion
    implementation 'androidx.navigation:navigation-ui-ktx:' + navigationVersion

    implementation 'org.greenrobot:eventbus:3.1.1'

    //Coroutines
    def corutinesVersion = "1.1.1"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:' + corutinesVersion
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:' + corutinesVersion

    //Database
    def room_version = "2.1.0-rc01"
    implementation 'androidx.room:room-runtime:' + room_version
    kapt 'androidx.room:room-compiler:' + room_version
//    implementation 'androidx.room:room-coroutines:' + room_version
    testImplementation 'androidx.room:room-testing:' + room_version

}

apply plugin: 'com.google.gms.google-services'
</code>```

app dependencies

```<code>debugCompileClasspath - Compile classpath for compilation 'debug' (target  (androidJvm)).
+--- org.jetbrains.kotlin:kotlin-android-extensions-runtime:{strictly 1.3.30} -> 1.3.30 (c)
+--- org.jetbrains.kotlin:kotlin-stdlib:{strictly 1.3.30} -> 1.3.30 (c)
+--- org.jetbrains.kotlin:kotlin-stdlib-common:{strictly 1.3.30} -> 1.3.30 (c)
+--- org.jetbrains.kotlin:kotlin-stdlib-jdk7:{strictly 1.3.30} -> 1.3.30 (c)
+--- androidx.core:core-ktx:{strictly 1.0.2} -> 1.0.2 (c)
+--- androidx.annotation:annotation:{strictly 1.1.0-rc01} -> 1.1.0-rc01 (c)
+--- androidx.core:core:{strictly 1.1.0-alpha05} -> 1.1.0-alpha05 (c)
+--- com.google.guava:listenablefuture:{strictly 9999.0-empty-to-avoid-conflict-with-guava} -> 9999.0-empty-to-avoid-conflict-with-guava (c)
+--- androidx.lifecycle:lifecycle-runtime:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-common:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.arch.core:core-common:{strictly 2.1.0-beta01} -> 2.1.0-beta01 (c)
+--- androidx.versionedparcelable:versionedparcelable:{strictly 1.1.0-alpha02} -> 1.1.0-alpha02 (c)
+--- androidx.collection:collection:{strictly 1.1.0-alpha03} -> 1.1.0-alpha03 (c)
+--- androidx.concurrent:concurrent-futures:{strictly 1.0.0-alpha02} -> 1.0.0-alpha02 (c)
+--- androidx.lifecycle:lifecycle-extensions:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.arch.core:core-runtime:{strictly 2.1.0-beta01} -> 2.1.0-beta01 (c)
+--- androidx.fragment:fragment:{strictly 1.1.0-alpha05} -> 1.1.0-alpha05 (c)
+--- androidx.viewpager:viewpager:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.customview:customview:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.loader:loader:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.lifecycle:lifecycle-livedata:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-livedata-core:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-viewmodel:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.activity:activity:{strictly 1.0.0-alpha05} -> 1.0.0-alpha05 (c)
+--- androidx.savedstate:savedstate:{strictly 1.0.0-alpha02} -> 1.0.0-alpha02 (c)
+--- androidx.lifecycle:lifecycle-process:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-service:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-viewmodel-ktx:{strictly 2.1.0-alpha02} -> 2.1.0-alpha02 (c)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-android:{strictly 1.1.1} -> 1.1.1 (c)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-core:{strictly 1.1.1} -> 1.1.1 (c)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-core-common:{strictly 1.1.1} -> 1.1.1 (c)
+--- androidx.appcompat:appcompat:{strictly 1.0.2} -> 1.0.2 (c)
+--- androidx.cursoradapter:cursoradapter:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.legacy:legacy-support-core-utils:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.documentfile:documentfile:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.localbroadcastmanager:localbroadcastmanager:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.print:print:{strictly 1.0.0} -> 1.0.0 (c)
...
+--- androidx.room:room-runtime:{strictly 2.1.0-rc01} -> 2.1.0-rc01 (c)
+--- androidx.room:room-common:{strictly 2.1.0-rc01} -> 2.1.0-rc01 (c)
+--- androidx.sqlite:sqlite-framework:{strictly 2.0.1} -> 2.0.1 (c)
+--- androidx.sqlite:sqlite:{strictly 2.0.1} -> 2.0.1 (c)
+--- com.jakewharton.timber:timber:{strictly 4.7.1} -> 4.7.1 (c)
+--- org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.3.30
|    \--- org.jetbrains.kotlin:kotlin-stdlib:1.3.30
|         \--- org.jetbrains.kotlin:kotlin-stdlib-common:1.3.30
+--- org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.30
...
+--- org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1 (*)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1 (*)
+--- androidx.room:room-runtime:2.1.0-rc01
|    +--- androidx.room:room-common:2.1.0-rc01
|    |    \--- androidx.annotation:annotation:1.1.0-rc01
|    +--- androidx.sqlite:sqlite-framework:2.0.1
|    |    +--- androidx.annotation:annotation:1.0.2 -> 1.1.0-rc01
|    |    \--- androidx.sqlite:sqlite:2.0.1
|    |         \--- androidx.annotation:annotation:1.0.2 -> 1.1.0-rc01
|    +--- androidx.sqlite:sqlite:2.0.1 (*)
|    +--- androidx.arch.core:core-runtime:2.0.1 -> 2.1.0-beta01 (*)
|    +--- androidx.core:core:1.0.0 -> 1.1.0-alpha05 (*)
|    \--- androidx.collection:collection:1.0.0 -> 1.1.0-alpha03 (*)
</code>```

答:
You must include the library:

```<code>implementation org.jetbrains:annotations-java5:19.0.0
</code>```

Because the code which is generated out of the annotations through the kapt plugin, uses org.jetbrains.annotations.NotNull annotation.

It you copy-paste the generated java class is your classpath, you will see the compilation error.

Cheers

Body:
I've been struggling for days with and issue with Android Room component.

All I did was upgrade my Android studio from 3.3 to 3.4.1, this comes with changes to gradle etc that are done.
I've even tried going back to 3.3, but nothing is working.
I've have run with Run with --info or --debug option to try see more details but nothing gives me more info. Please help

e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/HotspotEntity.java:7: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public final class HotspotEntity implements android.os.Parcelable {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../ConditionEntity.java:7: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above".
public final class ConditionEntity implements android.os.Parcelable {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/AdLimits.java:6: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above"
public final class AdLimits {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/AdTarget.java:6: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above"
public final class AdTarget {
             ^
e: /.../app/build/tmp/kapt3/stubs/debug/com/.../model/AdUrl.java:6: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor "same as above"
public final class AdUrl {
             ^

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Compilation error. See log for more details

Versions

Android Gradle:
3.4.1
Gradle version:
5.4.1
Android Room:
def room_version = "2.1.0-alpha06"
implementation 'androidx.room:room-runtime:' + room_version
kapt 'androidx.room:room-compiler:' + room_version
testImplementation 'androidx.room:room-testing:' + room_version

----UPDATE----

Below was tried with room 2.1.0-rc01"which changed it to the same problem but for a different class:

AppDatabase.java:8: error: [RoomProcessor:MiscError] androidx.room.RoomProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public abstract class AppDatabase extends androidx.room.RoomDatabase {

Grade File

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: "androidx.navigation.safeargs.kotlin"

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.cfl.surfstoked"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 19
        versionName "1.0.4"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            debuggable true
        }

        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    repositories {
        mavenCentral()
    }

    lintOptions {
        checkReleaseBuilds false
    }

    configurations {
        cleanedAnnotations
        compile.exclude group: 'org.jetbrains', module: 'annotations'
    }
}

dependencies {
    kapt 'com.google.dagger:dagger-android-processor:2.23.1'

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.0.2'

    def lifecycleVersion = "2.1.0-alpha02"
    implementation 'androidx.lifecycle:lifecycle-extensions:' + lifecycleVersion
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:' + lifecycleVersion
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha01'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
    kapt 'androidx.lifecycle:lifecycle-compiler:' + lifecycleVersion

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    //DI
    def koinVersion = "1.0.2"
    implementation 'org.koin:koin-android:' + koinVersion
    implementation 'org.koin:koin-androidx-scope:' + koinVersion
    implementation 'org.koin:koin-androidx-viewmodel:' + koinVersion

    //Navigation
//    def navigationVersion = "1.0.0-beta02"
//    implementation 'android.arch.navigation:navigation-fragment-ktx:' + navigationVersion
//    implementation 'android.arch.navigation:navigation-ui-ktx:' + navigationVersion

    def navigationVersion = "2.1.0-alpha01"
    implementation 'androidx.navigation:navigation-fragment-ktx:' + navigationVersion
    implementation 'androidx.navigation:navigation-ui-ktx:' + navigationVersion

    implementation 'org.greenrobot:eventbus:3.1.1'

    //Coroutines
    def corutinesVersion = "1.1.1"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:' + corutinesVersion
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:' + corutinesVersion

    //Database
    def room_version = "2.1.0-rc01"
    implementation 'androidx.room:room-runtime:' + room_version
    kapt 'androidx.room:room-compiler:' + room_version
//    implementation 'androidx.room:room-coroutines:' + room_version
    testImplementation 'androidx.room:room-testing:' + room_version

}

apply plugin: 'com.google.gms.google-services'

app dependencies

debugCompileClasspath - Compile classpath for compilation 'debug' (target  (androidJvm)).
+--- org.jetbrains.kotlin:kotlin-android-extensions-runtime:{strictly 1.3.30} -> 1.3.30 (c)
+--- org.jetbrains.kotlin:kotlin-stdlib:{strictly 1.3.30} -> 1.3.30 (c)
+--- org.jetbrains.kotlin:kotlin-stdlib-common:{strictly 1.3.30} -> 1.3.30 (c)
+--- org.jetbrains.kotlin:kotlin-stdlib-jdk7:{strictly 1.3.30} -> 1.3.30 (c)
+--- androidx.core:core-ktx:{strictly 1.0.2} -> 1.0.2 (c)
+--- androidx.annotation:annotation:{strictly 1.1.0-rc01} -> 1.1.0-rc01 (c)
+--- androidx.core:core:{strictly 1.1.0-alpha05} -> 1.1.0-alpha05 (c)
+--- com.google.guava:listenablefuture:{strictly 9999.0-empty-to-avoid-conflict-with-guava} -> 9999.0-empty-to-avoid-conflict-with-guava (c)
+--- androidx.lifecycle:lifecycle-runtime:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-common:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.arch.core:core-common:{strictly 2.1.0-beta01} -> 2.1.0-beta01 (c)
+--- androidx.versionedparcelable:versionedparcelable:{strictly 1.1.0-alpha02} -> 1.1.0-alpha02 (c)
+--- androidx.collection:collection:{strictly 1.1.0-alpha03} -> 1.1.0-alpha03 (c)
+--- androidx.concurrent:concurrent-futures:{strictly 1.0.0-alpha02} -> 1.0.0-alpha02 (c)
+--- androidx.lifecycle:lifecycle-extensions:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.arch.core:core-runtime:{strictly 2.1.0-beta01} -> 2.1.0-beta01 (c)
+--- androidx.fragment:fragment:{strictly 1.1.0-alpha05} -> 1.1.0-alpha05 (c)
+--- androidx.viewpager:viewpager:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.customview:customview:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.loader:loader:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.lifecycle:lifecycle-livedata:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-livedata-core:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-viewmodel:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.activity:activity:{strictly 1.0.0-alpha05} -> 1.0.0-alpha05 (c)
+--- androidx.savedstate:savedstate:{strictly 1.0.0-alpha02} -> 1.0.0-alpha02 (c)
+--- androidx.lifecycle:lifecycle-process:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-service:{strictly 2.2.0-alpha01} -> 2.2.0-alpha01 (c)
+--- androidx.lifecycle:lifecycle-viewmodel-ktx:{strictly 2.1.0-alpha02} -> 2.1.0-alpha02 (c)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-android:{strictly 1.1.1} -> 1.1.1 (c)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-core:{strictly 1.1.1} -> 1.1.1 (c)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-core-common:{strictly 1.1.1} -> 1.1.1 (c)
+--- androidx.appcompat:appcompat:{strictly 1.0.2} -> 1.0.2 (c)
+--- androidx.cursoradapter:cursoradapter:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.legacy:legacy-support-core-utils:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.documentfile:documentfile:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.localbroadcastmanager:localbroadcastmanager:{strictly 1.0.0} -> 1.0.0 (c)
+--- androidx.print:print:{strictly 1.0.0} -> 1.0.0 (c)
...
+--- androidx.room:room-runtime:{strictly 2.1.0-rc01} -> 2.1.0-rc01 (c)
+--- androidx.room:room-common:{strictly 2.1.0-rc01} -> 2.1.0-rc01 (c)
+--- androidx.sqlite:sqlite-framework:{strictly 2.0.1} -> 2.0.1 (c)
+--- androidx.sqlite:sqlite:{strictly 2.0.1} -> 2.0.1 (c)
+--- com.jakewharton.timber:timber:{strictly 4.7.1} -> 4.7.1 (c)
+--- org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.3.30
|    \--- org.jetbrains.kotlin:kotlin-stdlib:1.3.30
|         \--- org.jetbrains.kotlin:kotlin-stdlib-common:1.3.30
+--- org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.30
...
+--- org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1 (*)
+--- org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1 (*)
+--- androidx.room:room-runtime:2.1.0-rc01
|    +--- androidx.room:room-common:2.1.0-rc01
|    |    \--- androidx.annotation:annotation:1.1.0-rc01
|    +--- androidx.sqlite:sqlite-framework:2.0.1
|    |    +--- androidx.annotation:annotation:1.0.2 -> 1.1.0-rc01
|    |    \--- androidx.sqlite:sqlite:2.0.1
|    |         \--- androidx.annotation:annotation:1.0.2 -> 1.1.0-rc01
|    +--- androidx.sqlite:sqlite:2.0.1 (*)
|    +--- androidx.arch.core:core-runtime:2.0.1 -> 2.1.0-beta01 (*)
|    +--- androidx.core:core:1.0.0 -> 1.1.0-alpha05 (*)
|    \--- androidx.collection:collection:1.0.0 -> 1.1.0-alpha03 (*)

Body:
You must include the library:

implementation org.jetbrains:annotations-java5:19.0.0

Because the code which is generated out of the annotations through the kapt plugin, uses org.jetbrains.annotations.NotNull annotation.

It you copy-paste the generated java class is your classpath, you will see the compilation error.

Cheers


问:
c# .net mysql - Best way to find an updated row in one million row table
I query a MySQL table in my c# console app. Thousands of updates(row) are coming in all the times via another program and I want to propagate them, let's say for an easy way Console.WriteLine, in the fastest possible way (almost instantly). See diagram.

MYSQL to C# updates

Where do I do it in the most efficient/fastest way? On the MySQL Server? Or in my c# script?

If in my c# sript, do I use lists to compare old vs new row, or arrays? Any other way?

Any help is highly appreciated.

答:
Use triggers to write audit tables

There are some pretty good guides and questions on this like this: Creating Triggers to add the data into Audit Table

It does not contain timestamps which would be required for your case and it would also need a lot of space in your database to store all these changes


问:
How to solve unexpected Tor behaviour? User-agent and HTTPS protocol show my actual ip
I am trying to hide my ip adress by using Tor network.

I am using Tor expert bundle on windows.

I have run 2 tests to compare the different outputs.

I used two websites to detect the ip and the user-agent: ipecho.net and httpbin.org

First test results: call with HTTP protocol and default user-agent:

```<code>Ipecho found this ip: 199.249.230.64 (an expected Tor ip)
Httpbin found this ip: 199.249.230.64 (an expected Tor ip)
Ipecho found this user-agent: python-requests/2.22.0 (an expected default user-agent from requests)
Httpbin found this user-agent: python-requests/2.22.0 (an expected default user-agent from requests)
</code>```

But on the second test results: call with HTTP protocol and a specific user agent

```<code>Ipecho found this ip: <MY ACTUAL IP> (my own unexpected ip)
Httpbin found this ip: 199.249.230.64 (an expected Tor ip)
Ipecho found this user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 (an expected user-agent that we specified)
Httpbin found this user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 (an expected user-agent that we specified)
</code>```

I have two questions:

-Why ipecho.net and httpbin.org have different results on the second test?

-Why is my own ip showing up when I provide a user-agent in the header?

Here is the full code to reproduce these test results:

note: I have configured the torrc file to ControlPort 9051 and also changed HashedControlPassword.

```<code>from torrequest import TorRequest # to make requests in Tor
import bs4 # to parse the responses
import json # to parse the responses

# we set up our requests for Tor with TorRequest
with TorRequest(proxy_port = 9050, ctrl_port = 9051, password = '<your password>') as tr:

    # we set up a specific user-agent that we will use on some tests
    headers = {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}

    # First test: we call with HTTP protocol and no specific user-agent
    response_ipecho_ip = tr.get('http://ipecho.net/plain')
    response_httpbin_ip = tr.get('http://httpbin.org/ip')
    response_ipecho_agent = tr.get('http://ipecho.net/extra')
    response_httpbin_agent = tr.get('http://httpbin.org/user-agent')

    print('################ First test: we call with HTTP protocol and no specific user-agent ##############')
    print('Ipecho found this ip: {}'.format(response_ipecho_ip.text))
    response_httpbin_ip = json.loads(response_httpbin_ip.text)
    print('Httpbin found this ip: {}'.format(response_httpbin_ip['origin']))
    soup = bs4.BeautifulSoup(response_ipecho_agent.text,'html.parser')
    print('Ipecho found this user-agent: {}'.format(soup.find('tr').td.findNext('td').text))
    response_httpbin_agent = json.loads(response_httpbin_agent.text)
    print('Httpbin found this user-agent: {}\n'.format(response_httpbin_agent['user-agent']))

    # Second test: we call with HTTP protocol and a specific user agent
    response_ipecho_ip = tr.get('http://ipecho.net/plain', headers = headers)
    response_httpbin_ip = tr.get('http://httpbin.org/ip', headers = headers)
    response_ipecho_agent = tr.get('http://ipecho.net/extra', headers = headers)
    response_httpbin_agent = tr.get('http://httpbin.org/user-agent', headers = headers)

    print('################ Second test: we call HTTP protocol and a specific user agent ##############')
    print('Ipecho found this ip: {}'.format(response_ipecho_ip.text))
    response_httpbin_ip = json.loads(response_httpbin_ip.text)
    print('Httpbin found this ip: {}'.format(response_httpbin_ip['origin']))
    soup = bs4.BeautifulSoup(response_ipecho_agent.text,'html.parser')
    print('Ipecho found this user-agent: {}'.format(soup.find('tr').td.findNext('td').text))
    response_httpbin_agent = json.loads(response_httpbin_agent.text)
    print('Httpbin found this user-agent: {}\n'.format(response_httpbin_agent['user-agent']))
</code>```

Also, bonus tests:
I run the same tests but this time with HTTPS. My own ip is always showing up, no matter if it's ipecho.net or httpbin.org and no matter if I use default user-agent or a specific one.

答: Install "torrequest" from source. This bug has been solved, but maybe not released.</p>

Body:
I am trying to hide my ip adress by using Tor network.

I am using Tor expert bundle on windows.

I have run 2 tests to compare the different outputs.

I used two websites to detect the ip and the user-agent: ipecho.net and httpbin.org

First test results: call with HTTP protocol and default user-agent:

Ipecho found this ip: 199.249.230.64 (an expected Tor ip)
Httpbin found this ip: 199.249.230.64 (an expected Tor ip)
Ipecho found this user-agent: python-requests/2.22.0 (an expected default user-agent from requests)
Httpbin found this user-agent: python-requests/2.22.0 (an expected default user-agent from requests)

But on the second test results: call with HTTP protocol and a specific user agent

Ipecho found this ip: <MY ACTUAL IP> (my own unexpected ip)
Httpbin found this ip: 199.249.230.64 (an expected Tor ip)
Ipecho found this user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 (an expected user-agent that we specified)
Httpbin found this user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 (an expected user-agent that we specified)

I have two questions:

-Why ipecho.net and httpbin.org have different results on the second test?

-Why is my own ip showing up when I provide a user-agent in the header?

Here is the full code to reproduce these test results:

note: I have configured the torrc file to ControlPort 9051 and also changed HashedControlPassword.

from torrequest import TorRequest # to make requests in Tor
import bs4 # to parse the responses
import json # to parse the responses

# we set up our requests for Tor with TorRequest
with TorRequest(proxy_port = 9050, ctrl_port = 9051, password = '<your password>') as tr:

    # we set up a specific user-agent that we will use on some tests
    headers = {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}

    # First test: we call with HTTP protocol and no specific user-agent
    response_ipecho_ip = tr.get('http://ipecho.net/plain')
    response_httpbin_ip = tr.get('http://httpbin.org/ip')
    response_ipecho_agent = tr.get('http://ipecho.net/extra')
    response_httpbin_agent = tr.get('http://httpbin.org/user-agent')

    print('################ First test: we call with HTTP protocol and no specific user-agent ##############')
    print('Ipecho found this ip: {}'.format(response_ipecho_ip.text))
    response_httpbin_ip = json.loads(response_httpbin_ip.text)
    print('Httpbin found this ip: {}'.format(response_httpbin_ip['origin']))
    soup = bs4.BeautifulSoup(response_ipecho_agent.text,'html.parser')
    print('Ipecho found this user-agent: {}'.format(soup.find('tr').td.findNext('td').text))
    response_httpbin_agent = json.loads(response_httpbin_agent.text)
    print('Httpbin found this user-agent: {}\n'.format(response_httpbin_agent['user-agent']))

    # Second test: we call with HTTP protocol and a specific user agent
    response_ipecho_ip = tr.get('http://ipecho.net/plain', headers = headers)
    response_httpbin_ip = tr.get('http://httpbin.org/ip', headers = headers)
    response_ipecho_agent = tr.get('http://ipecho.net/extra', headers = headers)
    response_httpbin_agent = tr.get('http://httpbin.org/user-agent', headers = headers)

    print('################ Second test: we call HTTP protocol and a specific user agent ##############')
    print('Ipecho found this ip: {}'.format(response_ipecho_ip.text))
    response_httpbin_ip = json.loads(response_httpbin_ip.text)
    print('Httpbin found this ip: {}'.format(response_httpbin_ip['origin']))
    soup = bs4.BeautifulSoup(response_ipecho_agent.text,'html.parser')
    print('Ipecho found this user-agent: {}'.format(soup.find('tr').td.findNext('td').text))
    response_httpbin_agent = json.loads(response_httpbin_agent.text)
    print('Httpbin found this user-agent: {}\n'.format(response_httpbin_agent['user-agent']))

Also, bonus tests:
I run the same tests but this time with HTTPS. My own ip is always showing up, no matter if it's ipecho.net or httpbin.org and no matter if I use default user-agent or a specific one.


答:
var el = document.querySelector('.CalendarDay__button')
var string = el.getAttribute('aria-label')
var substring = 'niedziela'

if (string.includes(substring)) {
  el.parentNode.className = 'CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;">
  <button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>
</td></code>```

Title: Changing the class name JS

Body:
var el = document.querySelector('.CalendarDay__button')
var string = el.getAttribute('aria-label')
var substring = 'niedziela'

if (string.includes(substring)) {
  el.parentNode.className = 'CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range';
}

<td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;">
  <button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>
</td>


问:
Handling file download with gRPC on Android
I currently have a gRPC server which is sending chunks of a video file. My android application written in Kotlin uses coroutines for UI updates (on Dispatchers.MAIN) and for handling a unidirectional stream of chunks (on Dispatchers.IO). Like the following:

```<code>GlobalScope.launch(Dispatchers.Main) {
   viewModel.downloadUpdated().accept(DOWNLOAD_STATE.DOWNLOADING) // MAKE PROGRESS BAR VISIBLE

      GlobalScope.launch(Dispatchers.IO) {
         stub.downloadVideo(request).forEach {
                file.appendBytes(
                    it.data.toByteArray()
                )
            }
      }.join()
      viewModel.downloadUpdated().accept(DOWNLOAD_STATE.FINISHED) // MAKE PROGRESS BAR DISAPPEAR
   } catch (exception: Exception) {
      viewModel.downloadUpdated().accept(DOWNLOAD_STATE.ERROR) // MAKE PROGRESS BAR DISAPPEAR
      screenNavigator.showError(exception) // SHOW DIALOG
   }
}
</code>```

This works pretty well but I wonder if there is not a 'cleaner' way to handle downloads. I already know about DownloadManager but I feel like it only accepts HTTP queries and so I can't use my gRPC stub (I might be wrong, please tell me if so). I also checked WorkManager, and here is the same problem I do not know if this is the proper way of handling that case.

So, there are two questions here:

Is there a way to handle gRPC queries in a clean way, meaning that I can now when it starts, finishes, fails and that I can cancel properly?

If not, is there a better way to use coroutines for that ?

EDIT

For those interested, I believe I came up with a dummy algorithm for downloading while updating the progress bar (open to improvments):

```<code>suspend fun downloadVideo(callback: suspend (currentBytesRead: Int) -> Unit) {
   println("download")

   stub.downloadVideo(request).forEach {
      val data = it.data.toByteArray()

      file.appendBytes(data)
      callback(x) // Where x is the percentage of download
   }

    println("downloaded")
}

class Fragment : CoroutineScope { //NOTE: The scope is the current Fragment
    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = job

    fun onCancel() {
        if (job.isActive) {
            job.cancel()
        }
    }

    private suspend fun updateLoadingBar(currentBytesRead: Int) {
        println(currentBytesRead)
    }

    fun onDownload() {

        launch(Dispatchers.IO) {
            downloadVideo { currentBytes ->
                withContext(Dispatchers.Main) {

                    updateLoadingBar(currentBytes)

                    if (job.isCancelled)
                        println("cancelled !")
                }
            }
        }
    }
}
</code>```

For more info, please check: Introduction to coroutines

EDIT 2

As proposed in comments we could actually use Flows to handle this and it would give something like:

```<code>suspend fun foo(): Flow<Int> = flow {
   println("download")
   stub.downloadVideo(request).forEach {
      val data = it.data.toByteArray()

      file.appendBytes(data)
      emit(x) // Where x is the percentage of download
   }
   println("downloaded")
}

class Fragment : CoroutineScope {
    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = job

    fun onCancel() {
        if (job.isActive) {
            job.cancel()
        }
    }

    private suspend fun updateLoadingBar(currentBytesRead: Int) {
        println(currentBytesRead)
    }

    fun onDownload() {

        launch(Dispatchers.IO) {
            withContext(Dispatchers.Main) {
                foo()
                    .onCompletion { cause -> println("Flow completed with $cause") }
                    .catch { e -> println("Caught $e") }
                    .collect { current ->
                        if (job.isCancelled)
                            return@collect

                        updateLoadingBar(current)
                }
            }
        }
    }
}
</code>```

答:
gRPC can be many things so in that respect your question is unclear. Most importantly, it can be fully async and callback-based, which would mean it can be turned into a Flow that you can collect on the main thread. File writing, however, is blocking.

Your code seems to send the FINISHED signal right away, as soon as it has launched the download in the background. You should probably replace launch(IO) with withContext(IO).

Body:
I currently have a gRPC server which is sending chunks of a video file. My android application written in Kotlin uses coroutines for UI updates (on Dispatchers.MAIN) and for handling a unidirectional stream of chunks (on Dispatchers.IO). Like the following:

GlobalScope.launch(Dispatchers.Main) {
   viewModel.downloadUpdated().accept(DOWNLOAD_STATE.DOWNLOADING) // MAKE PROGRESS BAR VISIBLE

      GlobalScope.launch(Dispatchers.IO) {
         stub.downloadVideo(request).forEach {
                file.appendBytes(
                    it.data.toByteArray()
                )
            }
      }.join()
      viewModel.downloadUpdated().accept(DOWNLOAD_STATE.FINISHED) // MAKE PROGRESS BAR DISAPPEAR
   } catch (exception: Exception) {
      viewModel.downloadUpdated().accept(DOWNLOAD_STATE.ERROR) // MAKE PROGRESS BAR DISAPPEAR
      screenNavigator.showError(exception) // SHOW DIALOG
   }
}

This works pretty well but I wonder if there is not a 'cleaner' way to handle downloads. I already know about DownloadManager but I feel like it only accepts HTTP queries and so I can't use my gRPC stub (I might be wrong, please tell me if so). I also checked WorkManager, and here is the same problem I do not know if this is the proper way of handling that case.

So, there are two questions here:

Is there a way to handle gRPC queries in a clean way, meaning that I can now when it starts, finishes, fails and that I can cancel properly?

If not, is there a better way to use coroutines for that ?

EDIT

For those interested, I believe I came up with a dummy algorithm for downloading while updating the progress bar (open to improvments):

suspend fun downloadVideo(callback: suspend (currentBytesRead: Int) -> Unit) {
   println("download")

   stub.downloadVideo(request).forEach {
      val data = it.data.toByteArray()

      file.appendBytes(data)
      callback(x) // Where x is the percentage of download
   }

    println("downloaded")
}

class Fragment : CoroutineScope { //NOTE: The scope is the current Fragment
    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = job

    fun onCancel() {
        if (job.isActive) {
            job.cancel()
        }
    }

    private suspend fun updateLoadingBar(currentBytesRead: Int) {
        println(currentBytesRead)
    }

    fun onDownload() {

        launch(Dispatchers.IO) {
            downloadVideo { currentBytes ->
                withContext(Dispatchers.Main) {

                    updateLoadingBar(currentBytes)

                    if (job.isCancelled)
                        println("cancelled !")
                }
            }
        }
    }
}

For more info, please check: Introduction to coroutines

EDIT 2

As proposed in comments we could actually use Flows to handle this and it would give something like:

suspend fun foo(): Flow<Int> = flow {
   println("download")
   stub.downloadVideo(request).forEach {
      val data = it.data.toByteArray()

      file.appendBytes(data)
      emit(x) // Where x is the percentage of download
   }
   println("downloaded")
}

class Fragment : CoroutineScope {
    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = job

    fun onCancel() {
        if (job.isActive) {
            job.cancel()
        }
    }

    private suspend fun updateLoadingBar(currentBytesRead: Int) {
        println(currentBytesRead)
    }

    fun onDownload() {

        launch(Dispatchers.IO) {
            withContext(Dispatchers.Main) {
                foo()
                    .onCompletion { cause -> println("Flow completed with $cause") }
                    .catch { e -> println("Caught $e") }
                    .collect { current ->
                        if (job.isCancelled)
                            return@collect

                        updateLoadingBar(current)
                }
            }
        }
    }
}


问:
Posting object/keyvalue with file upload to asp.net core api
I have been trying to post a file with additonal information to asp.net core 3+ post api. If I send these params individually, it works. However, I want to send the required information at once.

My Model in ASP.Net Core 3.1

```<code>public class PostItem
{
   public string Title { get; set; }
   public IFormFile File { get; set; }
}
</code>```

The Post API

```<code>[HttpPost]
        public async Task<IActionResult> Post(PostItem item)
        {
            try
            {
                if (item == null)
                    return BadRequest();
                await Task.Delay(TimeSpan.FromMilliseconds(100));
                //Do Something here
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message + "Internal server error");
            }
        }
</code>```

Calling the API from Xamarin client

```<code>MultipartFormDataContent content = new MultipartFormDataContent();
var values = new[]
{
    new KeyValuePair<string, string>("Title", postItem.Title)
};
foreach(var keyValue in values)
{
      content.Add(new StringContent(keyValue.Value), keyValue.Key);
}

foreach (string file in imagePaths)
{
    byte[] byteArray = File.ReadAllBytes(file);
    content.Add(new ByteArrayContent(byteArray), "file", Path.GetFileName(file));
}
HttpClient client = new HttpClient();
var response = await client.PostAsync(Path.Combine(ApplicationConstants.apiUrl, "item/"), content);
//read response result as a string async into json var
var responsestr = response.Content.ReadAsStringAsync().Result;
</code>```

I am getting 415 error Unsupported Media Type

The question is how to send the required parameter from Xamarin Client
  or how to include FileUpload as part of an object and send it to the
  api?

答:
Decorate the input parameter in your post method with a [FromForm] tag to bind to the form.

```<code>public async Task<IActionResult> Post([FromForm] PostItem item)
{

}
</code>```

This is assuming that your PostItem class matches the form you are posting. Adding [FromForm] should at least fix the 415.

Body:
I have been trying to post a file with additonal information to asp.net core 3+ post api. If I send these params individually, it works. However, I want to send the required information at once.

My Model in ASP.Net Core 3.1

public class PostItem
{
   public string Title { get; set; }
   public IFormFile File { get; set; }
}

The Post API

[HttpPost]
        public async Task<IActionResult> Post(PostItem item)
        {
            try
            {
                if (item == null)
                    return BadRequest();
                await Task.Delay(TimeSpan.FromMilliseconds(100));
                //Do Something here
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message + "Internal server error");
            }
        }

Calling the API from Xamarin client

MultipartFormDataContent content = new MultipartFormDataContent();
var values = new[]
{
    new KeyValuePair<string, string>("Title", postItem.Title)
};
foreach(var keyValue in values)
{
      content.Add(new StringContent(keyValue.Value), keyValue.Key);
}

foreach (string file in imagePaths)
{
    byte[] byteArray = File.ReadAllBytes(file);
    content.Add(new ByteArrayContent(byteArray), "file", Path.GetFileName(file));
}
HttpClient client = new HttpClient();
var response = await client.PostAsync(Path.Combine(ApplicationConstants.apiUrl, "item/"), content);
//read response result as a string async into json var
var responsestr = response.Content.ReadAsStringAsync().Result;

I am getting 415 error Unsupported Media Type

The question is how to send the required parameter from Xamarin Client
  or how to include FileUpload as part of an object and send it to the
  api?

Body:
Decorate the input parameter in your post method with a [FromForm] tag to bind to the form.

public async Task<IActionResult> Post([FromForm] PostItem item)
{

}

This is assuming that your PostItem class matches the form you are posting. Adding [FromForm] should at least fix the 415.


问:
How do I display an animated gif in React Native?
How can I display an animated gif in react native.  This is what I've tried.

```<code><Image source={{uri: "loading"}} />
</code>```

It works fine with a .png file but when I use a .gif file it's blank. I read somewhere to try renaming the .gif to a .png but that just displays one frame of the animated gif with no animation.  Any ideas?

答:
import React,{useState} from 'react';

**step1 import from react narive  You Can Use (Image) Or (ImageBackground)  **

import { StyleSheet, Text, View ,ImageBackground} from 'react-native';

function LoadingUsers() {
    return(<View style={styles.LoadingView}>

**Step 2 require inside source ImageBackground **

<ImageBackground source={require('../assets/stickman.gif')} style={styles.Gif}><Text>Loading..</Text></ImageBackground>
</View>)
}

**Step 3 Set Width ANd height **

const styles = StyleSheet.create({
    LoadingView:{
        flex:1,
    },
    Gif:{
        flex:1,
        width:"100%",
        height:"100%",
        justifyContent:"center",
        alignItems:"center",
        backgroundColor:'#000',
    }

    });
    export default LoadingUsers ;```

Body:
How can I display an animated gif in react native.  This is what I've tried.

<Image source={{uri: "loading"}} />

It works fine with a .png file but when I use a .gif file it's blank. I read somewhere to try renaming the .gif to a .png but that just displays one frame of the animated gif with no animation.  Any ideas?