Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
10
43.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
33.7k
response_k
stringlengths
0
40.5k
62,671,521
I have a use case where I have to write 5000 records into dynamoDB table in one shot. I am using **batchSave** api of DynamoDBMapper Library. it can write upto 25 records in one go. can I pass the list of 5000 records to it and it will internally convert them into batch of 25 records and write to dynamodb table or I will have to handle this thing in my code using conditional some logic and will pass only 25 records to batchSave?
2020/07/01
[ "https://Stackoverflow.com/questions/62671521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13436208/" ]
According to the [batchSave documentation](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/datamodeling/AbstractDynamoDBMapper.html#batchSave-java.lang.Iterable-), batchSave(): > > Saves the objects given using one or more calls to the AmazonDynamoDB.batchWriteItem > > > Indeed, it splits up the items you give it into appropriately-sized batches (25 items) and writes them using the DynamoDB `BatchWriteItem` operation. You can see the code that does this in `batchWrite()` in [DynamoDBMapper.java](https://github.com/aws/aws-sdk-java/blob/master/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.java): ```java /** The max number of items allowed in a BatchWrite request */ static final int MAX_ITEMS_PER_BATCH = 25; // Break into chunks of 25 items and make service requests to DynamoDB for (final StringListMap<WriteRequest> batch : requestItems.subMaps(MAX_ITEMS_PER_BATCH, true)) { List<FailedBatch> failedBatches = writeOneBatch(batch, config.getBatchWriteRetryStrategy()); ... ```
Here are the methods I use in order to achieve this end. I manage to do it, by first chucking the dataArray into small arrays (of length 25): ``` const queryChunk = (arr, size) => { const tempArr = [] for (let i = 0, len = arr.length; i < len; i += size) { tempArr.push(arr.slice(i, i + size)); } return tempArr } const batchWriteManyItems = async (tableName, itemObjs, chunkSize = 25) => { return await Promise.all(queryChunk(itemObjs, chunkSize).map(async chunk => { await dynamoDB.batchWriteItem({RequestItems: {[tableName]: chunk}}).promise() })) } ```
62,671,533
I have a function `modify` as follows: ```py list_with_chunks = [['hi','hello','how are you?'],['i','am','fine'],['what','about you?','.']] flatten_list = ['hi','hello',...] empty_list = [] # building the function to convert our sentences in list_with_chunks into another form: def modify(sentence): # do stuff here # returning the result and appending them in empty_list return empty_list.append(sentence*2) ``` I call the function as below: ```py for i in flatten_list: modify(i) ``` But, I want to send each sentence directly from `list_with_chunks` instead of flattening it and append the result in `empty_list`. How do I do that? TIA.
2020/07/01
[ "https://Stackoverflow.com/questions/62671533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13830386/" ]
I don't understand the question entirely! But is this what you looking for: ``` for x in list_with_chunks: for y in x: modify(y) ``` You just need to iterate every element inside list again in order to add them in the empty list.
Use a nested loop through list\_with\_chunks. ``` for i in range(len(list_with_chunks)): for j in range(len(list_with_chunks[i])): modify(list_with_chunks[i][j], top_n=5) ```
62,671,547
I've been trying to add secrets to my docker container using docker-compose secrets without any luck. Using this `docker-compose.yml` the secret is mounted under `/run/secrets/my_secret` as an empty directory, not as a file: ``` version: '3.7' services: main: build: context: ./ secrets: - my_secret secrets: my_secret: file: first_secret.txt ``` I have tried to explicitly define the target and source ``` main: ... secrets: - source: my_secret target: /usr/local/secrets/custom_location ``` but it still gets added as an empty directory, why is that? I'm aware of the limitations of using secrets in docker-compose without docker swarm and simply want to use secrets as a semantic way to define secrets.
2020/07/01
[ "https://Stackoverflow.com/questions/62671547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6482408/" ]
Apparently the ability to use secrets in docker-compose is still a work in progress (thus, doesn't work). But you may be able to use a workaround using a Dockerfile. There's an in depth tutorial about how to do this here: <https://pythonspeed.com/articles/build-secrets-docker-compose/>
Remove the container (`docker container rm …`), then run `docker compose up` again. Source: <https://github.com/docker/compose/issues/4865#issuecomment-468644938> (worked for me).
62,671,551
I am rotating a model. When I click start button it starts from `0` `start = animateAssembly` I am trying to resume from `width`. What ever value of `width` will be there my animation will start from there. `resume = resumeAssembly` but width variable returning as `NaN` inside frame. and not getting passed into `resumeAssembly` ``` animateAssembly: function() { var element = document.getElementById("myBar"); this.width = 1; clearInterval(this.interval); this.interval = setInterval(frame, 100); //here my width shows number console.log(typeof this.width); function frame() { if (this.width >= 100) { console.log(typeof this.width); clearInterval(this.interval); } else { this.width++; console.log(typeof parseInt(this.width)); console.log(typeof this.width); //here it shows as NaN element.style.width = parseInt(this.width) + '%'; element.innerHTML = parseInt(this.width) + "%"; } } }, pauseAssembly: function() { clearInterval(this.interval); this.tweening.stop(); }, resumeAssembly: function() { var element = document.getElementById("myBar"); element.style.width = this.width + '%'; element.innerHTML = this.width + "%"; }, ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12090556/" ]
Apparently the ability to use secrets in docker-compose is still a work in progress (thus, doesn't work). But you may be able to use a workaround using a Dockerfile. There's an in depth tutorial about how to do this here: <https://pythonspeed.com/articles/build-secrets-docker-compose/>
Remove the container (`docker container rm …`), then run `docker compose up` again. Source: <https://github.com/docker/compose/issues/4865#issuecomment-468644938> (worked for me).
62,671,553
i know this question has been asked similarly quite often, but I can't seeem to find an answer that I'm satisfied with. I want do learn this "right" from the start. ```cs string [] list = {"foo", "bar", "foo"}; for(int i = 0; i<list.Length;i++) { try { //begin sql transaction if(!list[i].Equals("foo")) throw new Exception("foo exception"); else { //save stuff into DB Console.WriteLine(list[i]); //commit transaction here } } catch(Exception ex) { Console.WriteLine(ex.Message); //rollback transaction here } Console.WriteLine("Next record"); } ``` I've tested the code in the following fiddle <https://dotnetfiddle.net/0nftFD> and now my questions: If i were to handle files in a for loop analog to the above example and if one of them had an IO exception for example, i would log it, email to admin, etc. and then continue with the next file. As far as i can see it would work like this, would this be good/bad practise? I'd like to learn this properly right away :) EDIT: Because i failed to mention this before, I would also get specific exceptions. Ressources i failed to see before: 1. similar question: <https://forums.asp.net/t/1943641.aspx?How+do+I+continue+after+an+exception+is+caught+> 2. .net site: <https://learn.microsoft.com/de-de/dotnet/csharp/programming-guide/exceptions/using-exceptions>
2020/07/01
[ "https://Stackoverflow.com/questions/62671553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393675/" ]
Depending on the requirements you might be able to separate the data processing and error handling: * Iterate through the files * In case of exception capture into enough information into a List, Dictionary to be able process later * After looping through all the object loop through the errors For example: ``` string[] list = {"foo", "bar", "foo"}; var errors = new Dictionary<string, ExceptionDispatchInfo>(); for(int i = 0; i < list.Length; i++) { try { if(!list[i].Equals("foo")) throw new Exception("foo exception"); else Console.WriteLine(list[i]); } catch(Exception ex) { var edi = ExceptionDispatchInfo.Capture(ex); errors.Add($"{list[i]}_{i}", edi); } Console.WriteLine("Next record"); } foreach(var error in errors) { //Process error and throw the original exception if needed //error.Value.Throw(); } ```
Your example is how to handle it, though you may wish to catch only specific exceptions and not all. In some cases you may want to exit the processing due to speicific exceptions - for instance - if your database is not reachable then no need to keep going through all the files only to find it fails on each iteration. In that example you could nest the loop in a try catch also such that it may catch exception types that are thrown which you specifically wish to be terminal to the loop processing. An example of it being nested is shown below. ``` try { for(int i=0; i < 100; i++) { try { //do something } catch(IOException ex) { } } } catch(SecurityException sex) { } ``` Incidentally - you might also consider that you can batch the database (depending how many files you might be processing) and make your changes in one go. That's a performance trade-off you might wish to consider.
62,671,590
I have a list, `list_df`, and I'd like to add a column using `mutate` to each element within the list to reflect which element it is located in. ``` df1 <- tibble(M = words[sample(1:length(words), 10)], N = rnorm(10, 3, 3)) df2 <- tibble(M = words[sample(1:length(words), 10)], N = rnorm(10, 3, 3)) df3 <- tibble(M = words[sample(1:length(words), 10)], N = rnorm(10, 3, 3)) list_df <- list(df1, df2, df3) ``` I can't seem to find a function that can extract the element names, similar to `rownames()`. I think the code would have to involve map( ~ mutate(.))? The third element in my end output would look like this: ``` [[3]] # A tibble: 10 x 3 M N page <chr> <dbl> <dbl> 1 really 9.86 3 2 son 3.34 3 3 fair 0.660 3 4 local 0.664 3 5 out 3.76 3 6 high 6.62 3 7 condition 5.24 3 8 cat 1.03 3 9 meaning 3.39 3 10 account -0.702 3 ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11485370/" ]
You can use `imap` : ``` library(dplyr) library(purrr) imap(list_df, ~.x %>% mutate(page = .y)) ``` Or `Map` in base R : ``` Map(cbind, list_df, page = seq_along(list_df)) ```
Perhaps an onther option... create the list with `tibble::lst()`, this automatically adds the objectname to the names of the list ``` tibble::lst(df1,df2,df3) ``` results in: ``` $df1 # A tibble: 10 x 2 M N <chr> <dbl> 1 shoot 1.76 2 house 3.50 3 compare 3.61 4 garden 5.40 5 colleague 2.33 6 park 1.65 7 rather 2.50 8 sick 4.74 9 role 9.83 10 electric -1.42 $df2 # A tibble: 10 x 2 M N <chr> <dbl> 1 unless 0.683 2 due -2.72 3 particular 5.26 4 minister 3.05 5 germany 2.21 6 employ 0.185 7 wood -0.537 8 street 3.43 9 without -0.629 10 tie 4.66 $df3 # A tibble: 10 x 2 M N <chr> <dbl> 1 lunch -0.624 2 million 2.49 3 double 5.74 4 appoint 3.18 5 television -3.36 6 saturday 1.60 7 respect 5.12 8 allow 4.55 9 comment 1.47 10 suit 4.49 ``` If you later want to rowbind the list together, you can usee a function like `data.table::rbindlist()` to extract the list-element's names to a column with the `idcol`-argument. ``` data.table::rbindlist( tibble::lst(df1,df2,df3), idcol = "df_name" ) ``` results in ``` # df_name M N # 1: df1 shoot 1.7580908 # 2: df1 house 3.4973056 # 3: df1 compare 3.6061300 # 4: df1 garden 5.3983339 # 5: df1 colleague 2.3278449 # 6: df1 park 1.6549181 # 7: df1 rather 2.4975684 # 8: df1 sick 4.7351671 # 9: df1 role 9.8348196 # 10: df1 electric -1.4212905 # 11: df2 unless 0.6831733 # 12: df2 due -2.7249668 # 13: df2 particular 5.2616224 # 14: df2 minister 3.0530140 # 15: df2 germany 2.2128920 # 16: df2 employ 0.1850958 # 17: df2 wood -0.5370465 # 18: df2 street 3.4334869 # 19: df2 without -0.6292031 # 20: df2 tie 4.6573207 # 21: df3 lunch -0.6241718 # 22: df3 million 2.4854351 # 23: df3 double 5.7427438 # 24: df3 appoint 3.1819854 # 25: df3 television -3.3639328 # 26: df3 saturday 1.6013188 # 27: df3 respect 5.1175062 # 28: df3 allow 4.5501064 # 29: df3 comment 1.4678056 # 30: df3 suit 4.4915864 # df_name M N ```
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
It would be better if you just maintain a `List` of `Task` instances and sort that `List`. You can use one of the following options to sort a `List` of `Task` instances: 1. Implementing Comparable Interface 2. Using Comparator Implementing Comparable Interface --------------------------------- To implement `Comparable` interface, you must override `compareTo` method in `Task` class. Since you want to sort Tasks based on `date` instance field, you can just return the result of date comparison. Here's how you should override `compareTo()` method to sort Tasks in ascending order based on `date` instance field. ``` @Override public int compareTo(Task o) { return this.date.compareTo(o.date); } ``` Since `Date` class already implements `Comparable` interface, you can just call `compareTo` method to compare two `Date` instances. Now to sort the list of tasks, call `sort` method of `Collections` class. ``` Collections.sort(taskList); ``` [Here's a version of your code](https://pastebin.com/4RvuJe2M) that implements `Comparable` interface and sorts the tasks using `date` instance field Using Comparator ---------------- There are more than one ways to sort objects using a `Comparator` interface: * Create a separate class that implements `Comparator` interface * Use anonymous class or use lambda expression * Use static methods of Comparator interface ### Create a separate class that implements Comparator interface You can create a class that implements `Comparator` interface and then override `compare` function. Implementation of `compare` function will be same as that of `compareTo` function implemented above by implementing `Comparable` interface. ``` class TaskComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } } ``` To sort the task list, you have two options: 1. Use `sort` function of `Collections` class and pass an instacne of `TaskComparator` class as a second argument ``` Collections.sort(taskList, new TaskComparator()); ``` 2. Use `sort` method of `List` interface ``` taskList.sort(new TaskComparator()); ``` [Here's a version of your code](https://pastebin.com/Pgyr6Yka) that creates a separate comparator class to sort the tasks using `date` instance field ### Use anonymous class or use lambda expression Instead of creating a separate class to implement `Comparator` interface, you can use an anonymous class ``` Collections.sort(taskList, new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { // code to compare Task objects } }); ``` or ``` taskList.sort(new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } }); ``` Java 8 introduced lambda expressions, you can replace anonymous class with lambda expression to make your code concise ``` Collections.sort(taskList, (o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` or ``` taskList.sort((o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` [Here's a version of your code](https://pastebin.com/gmMJWipB) that uses lambda expression to implement `Comparator` interface ### Use static methods of Comparator interface You can also use static method named `comparing` of `Comparator` interface. It will return a comparator that will be used for sorting. ``` Collections.sort(taskList, Comparator.comparing(Task::getDate)); ``` or ``` taskList.sort(Comparator.comparing(Task::getDate)); ``` [Here's a version of your code](https://pastebin.com/9mJRrnRV) that uses `Comparator.comparing` method to sort the tasks using `date` instance field For details on how to implement `Comparable` or `Comparator` interfaces, see: * [Comparable vs Comparator in Java](https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/) * [Java Comparable interface](https://www.javatpoint.com/Comparable-interface-in-collection-framework) * [Java Comparator Interface](https://www.javatpoint.com/Comparator-interface-in-collection-framework)
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
You can sort `List` use `sort` method with custom `Comparator` ``` list.sort(Comparator.comparing(Task::getDate).reversed()); ``` But I think you have to use another collection. `PriorityQueue` feet better than `ArrayList`. ``` Queue<Task> queue = new PriorityQueue<>(Comparator.comparing(...)); ```
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
Since creating TaskList and sorting based on dates solution is already provided by **@Amongalen**. I will provide a different approach with better **Time complexity**. Since Sorting a collection can be **O(nlogn)**. It is not a good idea to sort after every time you add an element to the list. Instead you can maintain a `PriorityQueue` of Task Object and compare them based on date and add `Task` objects to that `PriorityQueue`. Now you don't need to call sort, just `iterate` over the `queue` and display the result. ``` PriorityQueue<Task> queue = new PriorityQueue<>((o1,o2)-> o1.getDate.comapreTo(o2.getDate)); // Add task object to the queue queue.add(myTaskObject); //iterate and display when asked Iterator<Task> it = queue.iterator(); while(it.hasNext()) { System.out.println(it.next().toString()); } ``` Note: adding task object to queue is O(logn) So this will improve time of your solution
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
It would be better if you just maintain a `List` of `Task` instances and sort that `List`. You can use one of the following options to sort a `List` of `Task` instances: 1. Implementing Comparable Interface 2. Using Comparator Implementing Comparable Interface --------------------------------- To implement `Comparable` interface, you must override `compareTo` method in `Task` class. Since you want to sort Tasks based on `date` instance field, you can just return the result of date comparison. Here's how you should override `compareTo()` method to sort Tasks in ascending order based on `date` instance field. ``` @Override public int compareTo(Task o) { return this.date.compareTo(o.date); } ``` Since `Date` class already implements `Comparable` interface, you can just call `compareTo` method to compare two `Date` instances. Now to sort the list of tasks, call `sort` method of `Collections` class. ``` Collections.sort(taskList); ``` [Here's a version of your code](https://pastebin.com/4RvuJe2M) that implements `Comparable` interface and sorts the tasks using `date` instance field Using Comparator ---------------- There are more than one ways to sort objects using a `Comparator` interface: * Create a separate class that implements `Comparator` interface * Use anonymous class or use lambda expression * Use static methods of Comparator interface ### Create a separate class that implements Comparator interface You can create a class that implements `Comparator` interface and then override `compare` function. Implementation of `compare` function will be same as that of `compareTo` function implemented above by implementing `Comparable` interface. ``` class TaskComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } } ``` To sort the task list, you have two options: 1. Use `sort` function of `Collections` class and pass an instacne of `TaskComparator` class as a second argument ``` Collections.sort(taskList, new TaskComparator()); ``` 2. Use `sort` method of `List` interface ``` taskList.sort(new TaskComparator()); ``` [Here's a version of your code](https://pastebin.com/Pgyr6Yka) that creates a separate comparator class to sort the tasks using `date` instance field ### Use anonymous class or use lambda expression Instead of creating a separate class to implement `Comparator` interface, you can use an anonymous class ``` Collections.sort(taskList, new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { // code to compare Task objects } }); ``` or ``` taskList.sort(new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } }); ``` Java 8 introduced lambda expressions, you can replace anonymous class with lambda expression to make your code concise ``` Collections.sort(taskList, (o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` or ``` taskList.sort((o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` [Here's a version of your code](https://pastebin.com/gmMJWipB) that uses lambda expression to implement `Comparator` interface ### Use static methods of Comparator interface You can also use static method named `comparing` of `Comparator` interface. It will return a comparator that will be used for sorting. ``` Collections.sort(taskList, Comparator.comparing(Task::getDate)); ``` or ``` taskList.sort(Comparator.comparing(Task::getDate)); ``` [Here's a version of your code](https://pastebin.com/9mJRrnRV) that uses `Comparator.comparing` method to sort the tasks using `date` instance field For details on how to implement `Comparable` or `Comparator` interfaces, see: * [Comparable vs Comparator in Java](https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/) * [Java Comparable interface](https://www.javatpoint.com/Comparable-interface-in-collection-framework) * [Java Comparator Interface](https://www.javatpoint.com/Comparator-interface-in-collection-framework)
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
You can sort `List` use `sort` method with custom `Comparator` ``` list.sort(Comparator.comparing(Task::getDate).reversed()); ``` But I think you have to use another collection. `PriorityQueue` feet better than `ArrayList`. ``` Queue<Task> queue = new PriorityQueue<>(Comparator.comparing(...)); ```
62,671,598
I have created a To-Do-List program where one of the actions requires the program to list all tasks input by the user in ascending order of the date that they fall on. Output example: ``` Tasks listed in ascending order (earliest first): TaskName, 20/04/2020, time, location, duration, category TaskName, 18/07/2020, time, location, duration, category TaskName, 09/08/2020, time, location, duration, category TaskName, 21/12/2020, time, location, duration, category ``` So far, with the code that I have, the tasks that the user input all list, but they don't list in ascending order of the date of each task. Here is my code so far: ``` public void sortTasks() { System.out.println("Sorted tasks by date (earliest first): "); Collections.sort(currentList); currentList.forEach(System.out::println); } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062972/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
Since creating TaskList and sorting based on dates solution is already provided by **@Amongalen**. I will provide a different approach with better **Time complexity**. Since Sorting a collection can be **O(nlogn)**. It is not a good idea to sort after every time you add an element to the list. Instead you can maintain a `PriorityQueue` of Task Object and compare them based on date and add `Task` objects to that `PriorityQueue`. Now you don't need to call sort, just `iterate` over the `queue` and display the result. ``` PriorityQueue<Task> queue = new PriorityQueue<>((o1,o2)-> o1.getDate.comapreTo(o2.getDate)); // Add task object to the queue queue.add(myTaskObject); //iterate and display when asked Iterator<Task> it = queue.iterator(); while(it.hasNext()) { System.out.println(it.next().toString()); } ``` Note: adding task object to queue is O(logn) So this will improve time of your solution
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
It would be better if you just maintain a `List` of `Task` instances and sort that `List`. You can use one of the following options to sort a `List` of `Task` instances: 1. Implementing Comparable Interface 2. Using Comparator Implementing Comparable Interface --------------------------------- To implement `Comparable` interface, you must override `compareTo` method in `Task` class. Since you want to sort Tasks based on `date` instance field, you can just return the result of date comparison. Here's how you should override `compareTo()` method to sort Tasks in ascending order based on `date` instance field. ``` @Override public int compareTo(Task o) { return this.date.compareTo(o.date); } ``` Since `Date` class already implements `Comparable` interface, you can just call `compareTo` method to compare two `Date` instances. Now to sort the list of tasks, call `sort` method of `Collections` class. ``` Collections.sort(taskList); ``` [Here's a version of your code](https://pastebin.com/4RvuJe2M) that implements `Comparable` interface and sorts the tasks using `date` instance field Using Comparator ---------------- There are more than one ways to sort objects using a `Comparator` interface: * Create a separate class that implements `Comparator` interface * Use anonymous class or use lambda expression * Use static methods of Comparator interface ### Create a separate class that implements Comparator interface You can create a class that implements `Comparator` interface and then override `compare` function. Implementation of `compare` function will be same as that of `compareTo` function implemented above by implementing `Comparable` interface. ``` class TaskComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } } ``` To sort the task list, you have two options: 1. Use `sort` function of `Collections` class and pass an instacne of `TaskComparator` class as a second argument ``` Collections.sort(taskList, new TaskComparator()); ``` 2. Use `sort` method of `List` interface ``` taskList.sort(new TaskComparator()); ``` [Here's a version of your code](https://pastebin.com/Pgyr6Yka) that creates a separate comparator class to sort the tasks using `date` instance field ### Use anonymous class or use lambda expression Instead of creating a separate class to implement `Comparator` interface, you can use an anonymous class ``` Collections.sort(taskList, new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { // code to compare Task objects } }); ``` or ``` taskList.sort(new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } }); ``` Java 8 introduced lambda expressions, you can replace anonymous class with lambda expression to make your code concise ``` Collections.sort(taskList, (o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` or ``` taskList.sort((o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` [Here's a version of your code](https://pastebin.com/gmMJWipB) that uses lambda expression to implement `Comparator` interface ### Use static methods of Comparator interface You can also use static method named `comparing` of `Comparator` interface. It will return a comparator that will be used for sorting. ``` Collections.sort(taskList, Comparator.comparing(Task::getDate)); ``` or ``` taskList.sort(Comparator.comparing(Task::getDate)); ``` [Here's a version of your code](https://pastebin.com/9mJRrnRV) that uses `Comparator.comparing` method to sort the tasks using `date` instance field For details on how to implement `Comparable` or `Comparator` interfaces, see: * [Comparable vs Comparator in Java](https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/) * [Java Comparable interface](https://www.javatpoint.com/Comparable-interface-in-collection-framework) * [Java Comparator Interface](https://www.javatpoint.com/Comparator-interface-in-collection-framework)
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
You can sort `List` use `sort` method with custom `Comparator` ``` list.sort(Comparator.comparing(Task::getDate).reversed()); ``` But I think you have to use another collection. `PriorityQueue` feet better than `ArrayList`. ``` Queue<Task> queue = new PriorityQueue<>(Comparator.comparing(...)); ```
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
First of all you need to store `Task` objects not `String` in your list. Usually you can pass a `Comparator` to `Collections.sort`. ``` Collections.sort(tasks, Comparator.reverseOrder()); ``` In order for that to work properly you have to make `Task` an implementation of `Comparable`, the way you compare the fields of the object depend on your specific task, here you can provide implementation for ascending comparison, and than reverse it by `reverseOrder` method. ``` class Task implements Comparable<Task> { ... @Override public int compareTo(Task task) { return Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .compare(this, task); } } ``` Alternately, you can create and pass to `sort` a more sophisticated `Comparator` object, without `Task` being a `Comparable` object. Note though, that this approach makes code less reusable. ``` Collections.sort(tasks, Comparator .comparing(Task::getTitle) .thenComparing(Task::getDate) .reverseOrder() ); ``` Also consider using `SortedSet` or `PriorityQueue` instead of `List` for your task in order to avoid explicit sorting and reduce algorithmic complexity
Since creating TaskList and sorting based on dates solution is already provided by **@Amongalen**. I will provide a different approach with better **Time complexity**. Since Sorting a collection can be **O(nlogn)**. It is not a good idea to sort after every time you add an element to the list. Instead you can maintain a `PriorityQueue` of Task Object and compare them based on date and add `Task` objects to that `PriorityQueue`. Now you don't need to call sort, just `iterate` over the `queue` and display the result. ``` PriorityQueue<Task> queue = new PriorityQueue<>((o1,o2)-> o1.getDate.comapreTo(o2.getDate)); // Add task object to the queue queue.add(myTaskObject); //iterate and display when asked Iterator<Task> it = queue.iterator(); while(it.hasNext()) { System.out.println(it.next().toString()); } ``` Note: adding task object to queue is O(logn) So this will improve time of your solution
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
It would be better if you just maintain a `List` of `Task` instances and sort that `List`. You can use one of the following options to sort a `List` of `Task` instances: 1. Implementing Comparable Interface 2. Using Comparator Implementing Comparable Interface --------------------------------- To implement `Comparable` interface, you must override `compareTo` method in `Task` class. Since you want to sort Tasks based on `date` instance field, you can just return the result of date comparison. Here's how you should override `compareTo()` method to sort Tasks in ascending order based on `date` instance field. ``` @Override public int compareTo(Task o) { return this.date.compareTo(o.date); } ``` Since `Date` class already implements `Comparable` interface, you can just call `compareTo` method to compare two `Date` instances. Now to sort the list of tasks, call `sort` method of `Collections` class. ``` Collections.sort(taskList); ``` [Here's a version of your code](https://pastebin.com/4RvuJe2M) that implements `Comparable` interface and sorts the tasks using `date` instance field Using Comparator ---------------- There are more than one ways to sort objects using a `Comparator` interface: * Create a separate class that implements `Comparator` interface * Use anonymous class or use lambda expression * Use static methods of Comparator interface ### Create a separate class that implements Comparator interface You can create a class that implements `Comparator` interface and then override `compare` function. Implementation of `compare` function will be same as that of `compareTo` function implemented above by implementing `Comparable` interface. ``` class TaskComparator implements Comparator<Task> { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } } ``` To sort the task list, you have two options: 1. Use `sort` function of `Collections` class and pass an instacne of `TaskComparator` class as a second argument ``` Collections.sort(taskList, new TaskComparator()); ``` 2. Use `sort` method of `List` interface ``` taskList.sort(new TaskComparator()); ``` [Here's a version of your code](https://pastebin.com/Pgyr6Yka) that creates a separate comparator class to sort the tasks using `date` instance field ### Use anonymous class or use lambda expression Instead of creating a separate class to implement `Comparator` interface, you can use an anonymous class ``` Collections.sort(taskList, new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { // code to compare Task objects } }); ``` or ``` taskList.sort(new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o1.getDate().compareTo(o2.getDate()); } }); ``` Java 8 introduced lambda expressions, you can replace anonymous class with lambda expression to make your code concise ``` Collections.sort(taskList, (o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` or ``` taskList.sort((o1, o2) -> o1.getDate().compareTo(o2.getDate())); ``` [Here's a version of your code](https://pastebin.com/gmMJWipB) that uses lambda expression to implement `Comparator` interface ### Use static methods of Comparator interface You can also use static method named `comparing` of `Comparator` interface. It will return a comparator that will be used for sorting. ``` Collections.sort(taskList, Comparator.comparing(Task::getDate)); ``` or ``` taskList.sort(Comparator.comparing(Task::getDate)); ``` [Here's a version of your code](https://pastebin.com/9mJRrnRV) that uses `Comparator.comparing` method to sort the tasks using `date` instance field For details on how to implement `Comparable` or `Comparator` interfaces, see: * [Comparable vs Comparator in Java](https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/) * [Java Comparable interface](https://www.javatpoint.com/Comparable-interface-in-collection-framework) * [Java Comparator Interface](https://www.javatpoint.com/Comparator-interface-in-collection-framework)
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
You can sort `List` use `sort` method with custom `Comparator` ``` list.sort(Comparator.comparing(Task::getDate).reversed()); ``` But I think you have to use another collection. `PriorityQueue` feet better than `ArrayList`. ``` Queue<Task> queue = new PriorityQueue<>(Comparator.comparing(...)); ```
62,671,602
I have two parameters (page\_number, paze\_size) which I want to use Any one can help me? I am a new to asp.net MVC.
2020/07/01
[ "https://Stackoverflow.com/questions/62671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11623901/" ]
Your current approach to the problem makes it hard to achieve what you want. You have a list of Strings and want to parse some fragment of them and sort based on that. It is possible but you can make it much simplier. You already got a dedicated class to represent your `Task`. You should keep a `List` of `Task`s then, not their String representations. When you have a `List<Task>`, there are couple of ways to sort it. You can either implement `Comparable` in your class or use a `Comparator`. You could do something like that: ``` currentList.sort(Comparator.comparing(Task::getDate)) ``` Or (depending on desired order) ``` currentList.sort(Comparator.comparing(Task::getDate).reversed()) ``` And then you use `getItem()` only when you want to print the results (such method is usually called `toString()`).
Since creating TaskList and sorting based on dates solution is already provided by **@Amongalen**. I will provide a different approach with better **Time complexity**. Since Sorting a collection can be **O(nlogn)**. It is not a good idea to sort after every time you add an element to the list. Instead you can maintain a `PriorityQueue` of Task Object and compare them based on date and add `Task` objects to that `PriorityQueue`. Now you don't need to call sort, just `iterate` over the `queue` and display the result. ``` PriorityQueue<Task> queue = new PriorityQueue<>((o1,o2)-> o1.getDate.comapreTo(o2.getDate)); // Add task object to the queue queue.add(myTaskObject); //iterate and display when asked Iterator<Task> it = queue.iterator(); while(it.hasNext()) { System.out.println(it.next().toString()); } ``` Note: adding task object to queue is O(logn) So this will improve time of your solution
62,671,605
I am playing with SVG and I am stumped by something. I am trying to make the pink square into a diamond by using `skew` and `rotate`. However I am getting strange behaviour that I cannot figure out how to overcome. [![svg circles](https://i.stack.imgur.com/yzbuk.png)](https://i.stack.imgur.com/yzbuk.png) Adding the `skew`, gets me the diamond effect I want, but then I need to rotate and reposition it so it lines up with the circles. `<rect x="126" y="0" width="40" height="40"fill="pink" transform="skewY(10)" />` [![skewed](https://i.stack.imgur.com/l7a6D.png)](https://i.stack.imgur.com/l7a6D.png) However, when I apply rotation `transform="rotate(45)"` to the `rect`, it doesn't rotate "in-place", but rotates [I think] relative from the corner of the page. `<rect x="126" y="0" width="40" height="40"fill="pink" transform="skewY(10)" />` [![circle svg rotation](https://i.stack.imgur.com/dGQpG.png)](https://i.stack.imgur.com/dGQpG.png) Does anyone know how I can freely rotate and skew this rectangle (in SVG and not CSS or anything) without it moving around so wildly and awkwardly ? ```html <h1>Shapes</h1> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <circle cx="20" cy="20" r="20" fill="blue" stroke="red" ></circle> <circle cx="62" cy="20" r="20" fill="yellow" stroke="red" ></circle> <circle cx="104" cy="20" r="20" fill="blue" stroke="red" ></circle> <rect x="126" y="0" width="40" height="40"fill="pink"/> <circle cx="188" cy="20" r="20" fill="green" stroke="red" ></circle> </svg> ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675976/" ]
Simplest is to use transform-origin and transform-box ```css rect { transform-origin: center; transform-box: fill-box; } ``` ```html <h1>Shapes</h1> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <circle cx="20" cy="20" r="20" fill="blue" stroke="red" ></circle> <circle cx="62" cy="20" r="20" fill="yellow" stroke="red" ></circle> <circle cx="104" cy="20" r="20" fill="blue" stroke="red" ></circle> <rect transform="rotate(45)" x="126" y="0" width="40" height="40"fill="pink"/> <circle cx="188" cy="20" r="20" fill="green" stroke="red" ></circle> </svg> ```
```html <h1>Shapes</h1> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <circle cx="21" cy="21" r="20" fill="blue" stroke="red"></circle> <circle cx="63" cy="21" r="20" fill="yellow" stroke="red"></circle> <circle cx="105" cy="21" r="20" fill="blue" stroke="red"></circle> <rect x="154" y="0" width="40" height="40" fill="pink" transform="rotate(45, 154, 0)"/> <circle cx="203" cy="21" r="20" fill="green" stroke="red"></circle> </svg> ``` This can be done using `rotate`. For rotate * First argument is the angle of rotation i.e. 45 degrees. * Second argument is the x offset about which the `rect` is to be rotated and is calculated as follows: ``` x = (border_width_of_circle_1 * 2 + radius_of_circle_1 * 2) + (border_width_of_circle_2 * 2 + radius_of_circle_2 * 2) + (border_width_of_circle_3 * 2 + radius_of_circle_3 * 2) + 1/2 * diagonal_of_square = (2 + 40) + (2 + 40) + (2 + 40) + (1/2 * sqrt(40^2 + 40^2)) = 42 + 42 + 42 + (1/2 * sqrt(3200)) = (42 * 3) + (1/2 * 56) = 126 + 28 = 154 ``` * Third argument is the y offset about which the `rect` is to be rotated, which in our case will be `0`.
62,671,616
I am new to Angular and for practice i want to make a small application where a user can log in just with his username at first. In order to do so i would like to store the logged in user if the backend returns http status 200. But i can't get the http status of my request. I already looked up several posts here and on other sites, but all those solutions don't seem to work for me. My Angular Version is: 8.2.14 Here is my login service: ``` import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpErrorResponse, } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; import { User } from '../model/User'; @Injectable({ providedIn: 'root', }) export class LoginService { constructor(private http: HttpClient) {} loginUrl = 'login'; httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }), }; login(user: User) { const request = this.http .post(this.loginUrl, user, this.httpOptions) .pipe(catchError(this.handleError)); return request; } private handleError(error: HttpErrorResponse) { console.log('handleError Method'); console.log('Errorcode', error.status); if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}` ); } // return an observable with a user-facing error message return throwError('Something bad happened; please try again later.'); } } ``` And this is the Login Component calling the service: ``` import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { LoginService } from 'src/app/services/login.service'; import { User } from '../../../model/User'; @Component({ selector: 'app-login-component', templateUrl: './login-component.component.html', styleUrls: ['./login-component.component.css'], }) export class LoginComponent implements OnInit { loginForm: FormGroup; loading = false; submitted = false; returnUrl: string; user: User; // loginService: LoginService; constructor(private loginService: LoginService) {} ngOnInit() {} login(username: string, password: string) { const dummyUser = { username, password }; this.loginService.login(dummyUser).subscribe((data) => { console.log('data', data); this.user = data; console.log('user', this.user); }); } } ``` **Edit**: With the answer of Mari Mbiru and this post <https://stackoverflow.com/a/47761516/12360845> i was able to solve this question. I actually tried to set `observe:'response'` before but i didn't put it into `httpOptions` but in `HttpHeaders` which didn't work. My working post request looks like this now: ``` login(user: User) { const request = this.http .post<User>( `${this.loginUrl}`, { username: user.username, password: user.password }, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response', } ) .pipe(catchError(this.handleError)); return request; } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12360845/" ]
The HttpClient allows you to view the full response instead of just the body by adding `{observe: 'response'}` to your request options. This will return a HttpResponse object that has the body, headers, status, url etc. So the httpOptions should be: ``` httpOptions = { observe:'response' headers: new HttpHeaders({ 'Content-Type': 'application/json', }), }; ``` And in the subscription : ``` this.loginService.login(dummyUser).subscribe((res) => { console.log('response', res); this.user = res.body; console.log('user', this.user); }); ```
Don't convert the response to JSON then you can find it here HTTP.post(’.....’).subscribe( (res) => res[’status’], (err) =>.....);
62,671,617
I'm trying to connect to a postgresql database on my local machine from databricks using a JDBC connection. There are several useful posts in stackoverflow. I'm following the procedure mentioned in the documentation in [spark.apache.org](https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html) and [databricks](https://docs.databricks.com/data/data-sources/sql-databases.html#python-example) website. also these posts : [1](https://stackoverflow.com/questions/62624059/getting-error-on-connecting-to-a-local-sql-server-database-to-databricks-via-jdb/62624144#62624144) , [2](https://stackoverflow.com/questions/20825734/postgresql-connection-refused-check-that-the-hostname-and-port-are-correct-an) & [3](https://stackoverflow.com/questions/16904997/connection-refused-pgerror-postgresql-and-rails) In RStudio I can connect to postgresql database via this script : ``` # Define data base credential ---- psql <- DBI::dbDriver("PostgreSQL") con <- dbConnect( psql, dbname = 'mydbname', host = 'hostname', port = 5444, user = 'username', password = 'password') ``` I am trying to connect postgresql via JDBC to databricks. I used two approaches: ``` # method 1 jdbcHostname = "hostname" jdbcDatabase = "mydbname" jdbcPort = 5444 jdbcUrl = "jdbc:postgresql://{0}:{1}/{2}".format(jdbcHostname, jdbcPort, jdbcDatabase) connectionProperties = { "user" : "username", "password" : "password", "driver" : "org.postgresql.Driver" } pushdown_query = "SELECT * FROM mytable" df = spark.read.jdbc(url=jdbcUrl, table= pushdown_query , properties=connectionProperties) ``` and this one ``` #method2 jdbcDF = spark.read \ .format("jdbc") \ .option("url", "jdbc:postgresql://hostname:5444/mydbname") \ .option("dbtable", "SELECT * FROM schema.mytable") \ .option("user", "username") \ .option("password", "password")\ .load() ``` but I am getting error on both tries like this : ``` Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections ``` I couldn't understand why it tries to connect to `localhost:5432` when I specified `localhost:5444`?
2020/07/01
[ "https://Stackoverflow.com/questions/62671617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7996904/" ]
I'm able to connecting to Azure Database for PostgreSQL server to Databricks via JDBC connection. **You may try the below steps:** **Prerequisites:** Azure Database for PostgreSQL server => JDBC Connection String > > jdbc:postgresql://{server\_name}.postgres.database.azure.com:5432/{your\_database}?user={Admin\_username}&password={your\_password}&sslmode=require > > > [![enter image description here](https://i.stack.imgur.com/8pE7B.png)](https://i.stack.imgur.com/8pE7B.png) **Step 1:** Connection Information ``` driver = "org.postgresql.Driver" url = "jdbc:postgresql://cheprapostgresql.postgres.database.azure.com:5432/postgres?user=chepra@cheprapostgresql&password=XXXXXXXXXXXXXX&sslmode=require" dbname = "postgres" dbtable = "inventory" ``` **Step 2:** Reading the data ``` jdbcDF = spark.read \ .format("jdbc") \ .option("driver", driver)\ .option("url", url)\ .option("dbname", dbname) \ .option("dbtable", dbtable)\ .load() ``` [![enter image description here](https://i.stack.imgur.com/y7FO6.png)](https://i.stack.imgur.com/y7FO6.png) **Reference:** This [notebook](https://docs.databricks.com/_static/notebooks/data-import/jdbc.html) shows you how to load data from JDBC databases using Spark SQL.
Check the following file in intelij "**application.properties**" for example: specifically: Username, Password, Port(this case: 5432) and make sure you actually created the database by its name(this case: 'student') before and its consist with this lines for example: ``` spring.datasource.url=jdbc:postgresql://localhost:5432/student spring.datasource.username= spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect = `org.hibernate.dialect.PostgreSQLDialect` spring.jpa.properties.hibernate.format_sql = true server.error.include-message=always ```
62,671,641
Our project is using dataproc, and I have checked for service account that is indicated in master and worker compute engines that it has required permissions for my bucket storage. Nevertheless, in log viewer I have seen following: > > (gsutil) Failed to create the default configuration. Ensure your have the correct permissions on: [/home/.config/gcloud/configurations]. Could not create directory [/home/.config/gcloud/configurations]: Permission denied. Please verify that you have permissions to write to the parent directory. > > > What can I do to fix this issue? I should download some file from this bucket and using gsutil to do that. PS: I have tried using action.sh to find out logged in user which results in nothing. PS2: We are using SparkSession for this operation.
2020/07/01
[ "https://Stackoverflow.com/questions/62671641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9234341/" ]
I'm able to connecting to Azure Database for PostgreSQL server to Databricks via JDBC connection. **You may try the below steps:** **Prerequisites:** Azure Database for PostgreSQL server => JDBC Connection String > > jdbc:postgresql://{server\_name}.postgres.database.azure.com:5432/{your\_database}?user={Admin\_username}&password={your\_password}&sslmode=require > > > [![enter image description here](https://i.stack.imgur.com/8pE7B.png)](https://i.stack.imgur.com/8pE7B.png) **Step 1:** Connection Information ``` driver = "org.postgresql.Driver" url = "jdbc:postgresql://cheprapostgresql.postgres.database.azure.com:5432/postgres?user=chepra@cheprapostgresql&password=XXXXXXXXXXXXXX&sslmode=require" dbname = "postgres" dbtable = "inventory" ``` **Step 2:** Reading the data ``` jdbcDF = spark.read \ .format("jdbc") \ .option("driver", driver)\ .option("url", url)\ .option("dbname", dbname) \ .option("dbtable", dbtable)\ .load() ``` [![enter image description here](https://i.stack.imgur.com/y7FO6.png)](https://i.stack.imgur.com/y7FO6.png) **Reference:** This [notebook](https://docs.databricks.com/_static/notebooks/data-import/jdbc.html) shows you how to load data from JDBC databases using Spark SQL.
Check the following file in intelij "**application.properties**" for example: specifically: Username, Password, Port(this case: 5432) and make sure you actually created the database by its name(this case: 'student') before and its consist with this lines for example: ``` spring.datasource.url=jdbc:postgresql://localhost:5432/student spring.datasource.username= spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect = `org.hibernate.dialect.PostgreSQLDialect` spring.jpa.properties.hibernate.format_sql = true server.error.include-message=always ```
62,671,655
Suppose I have a dataframe that has date and ID column. This is a time series data set. So i need to generate a time series identifier for this dataframe. That is, I need to add a value corresponding to each unique set. Is there a way to do this ? ``` df = pd.DataFrame({'Date':[2012-01-01, 2012-01-01, 2012-01-01, 2012-01-02, 2012-01-02, 2012-01-03, 2012-01-03, 2012-01-03, 2012-01-04, 2012-01-01, 2012-01-04], 'Id':[1,2,3,4,5,6,7,8,9,10,11]}) print(df) ``` Output: ``` Date Id 2012-01-01 1 2012-01-01 2 2012-01-01 3 2012-01-02 4 2012-01-02 5 2012-01-03 6 2012-01-03 7 2012-01-03 8 2012-01-04 9 2012-01-01 10 2012-01-04 11 ``` I need to order the dates according to its uniqueness like ``` Date Id TimeID 2012-01-01 1 0 2012-01-02 4 0 2012-01-03 6 0 2012-01-04 9 0 2012-01-01 2 1 2012-01-02 5 1 2012-01-03 7 1 2012-01-04 11 1 2012-01-01 3 2 2012-01-03 8 2 2012-01-01 10 3 ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845475/" ]
Use [`GroupBy.cumcount`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html) with [`DataFrame.sort_values`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html): ``` df['TimeID'] = df.groupby('Date').cumcount() df = df.sort_values('TimeID') print (df) Date Id TimeID 0 2012-01-01 1 0 3 2012-01-02 4 0 5 2012-01-03 6 0 8 2012-01-04 9 0 1 2012-01-01 2 1 4 2012-01-02 5 1 6 2012-01-03 7 1 10 2012-01-04 11 1 2 2012-01-01 3 2 7 2012-01-03 8 2 9 2012-01-01 10 3 ```
First, convert the string dates to datetimes with `pd.to_datetime()`. Then, use `groupby()` and `.cumcount()` as per [this solution](https://stackoverflow.com/questions/37997668/pandas-number-rows-within-group-in-increasing-order): ``` import pandas as pd df = pd.DataFrame({'Date': ['2012-01-01','2012-01-01','2012-01-01','2012-01-02', '2012-01-02','2012-01-03','2012-01-03','2012-01-03','2012-01-04','2012-01-01','2012-01-04'], 'Id': [1,2,3,4,5,6,7,8,9,10,11]}) # strictly, you can read in a datetime as a datetime at pd.read_csv() time df['Date'] = pd.to_datetime(df['Date']) ```
62,671,668
If I am using the tensorflow version of huggingface transformer, how do I freeze the weights of the pretrained encoder so that only the weights of the head layer are optimized? For the PyTorch implementation, it is done through ``` for param in model.base_model.parameters(): param.requires_grad = False ``` Would like to do the same for tensorflow implementation.
2020/07/01
[ "https://Stackoverflow.com/questions/62671668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732618/" ]
Found a way to do it. Freeze the base model BEFORE compiling it. ``` model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased") model.layers[0].trainable = False model.compile(...) ```
Alternatively: ``` model.bert.trainable = False ```
62,671,668
If I am using the tensorflow version of huggingface transformer, how do I freeze the weights of the pretrained encoder so that only the weights of the head layer are optimized? For the PyTorch implementation, it is done through ``` for param in model.base_model.parameters(): param.requires_grad = False ``` Would like to do the same for tensorflow implementation.
2020/07/01
[ "https://Stackoverflow.com/questions/62671668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732618/" ]
Found a way to do it. Freeze the base model BEFORE compiling it. ``` model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased") model.layers[0].trainable = False model.compile(...) ```
After digging this thread [1](https://github.com/huggingface/transformers/issues/400) up, I think the following codes won't hurt for TF2. Even though it may be redundant in a specific case. ``` model = TFBertModel.from_pretrained('./bert-base-uncase') for layer in model.layers: layer.trainable=False for w in layer.weights: w._trainable=False ```
62,671,668
If I am using the tensorflow version of huggingface transformer, how do I freeze the weights of the pretrained encoder so that only the weights of the head layer are optimized? For the PyTorch implementation, it is done through ``` for param in model.base_model.parameters(): param.requires_grad = False ``` Would like to do the same for tensorflow implementation.
2020/07/01
[ "https://Stackoverflow.com/questions/62671668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732618/" ]
Found a way to do it. Freeze the base model BEFORE compiling it. ``` model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased") model.layers[0].trainable = False model.compile(...) ```
``` model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') for _layer in model: if _layer.name == 'distilbert': print(f"Freezing model layer {_layer.name}") _layer.trainable = False print(_layer.name) print(_layer.trainable) --- Freezing model layer distilbert distilbert False <---------------- pre_classifier True classifier True dropout_99 True Model: "tf_distil_bert_for_sequence_classification_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_99 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 592,130 Non-trainable params: 66,362,880 <----- ``` Without freezing. ``` Model: "tf_distil_bert_for_sequence_classification_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_59 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 66,955,010 Non-trainable params: 0 ``` Please change from TFDistilBertForSequenceClassification to TFBertForSequenceClassification accordingly. To do so, first run `model.summary` to verify the base name. For TFDistilBertForSequenceClassification, it is `distilbert`.
62,671,668
If I am using the tensorflow version of huggingface transformer, how do I freeze the weights of the pretrained encoder so that only the weights of the head layer are optimized? For the PyTorch implementation, it is done through ``` for param in model.base_model.parameters(): param.requires_grad = False ``` Would like to do the same for tensorflow implementation.
2020/07/01
[ "https://Stackoverflow.com/questions/62671668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732618/" ]
After digging this thread [1](https://github.com/huggingface/transformers/issues/400) up, I think the following codes won't hurt for TF2. Even though it may be redundant in a specific case. ``` model = TFBertModel.from_pretrained('./bert-base-uncase') for layer in model.layers: layer.trainable=False for w in layer.weights: w._trainable=False ```
Alternatively: ``` model.bert.trainable = False ```
62,671,668
If I am using the tensorflow version of huggingface transformer, how do I freeze the weights of the pretrained encoder so that only the weights of the head layer are optimized? For the PyTorch implementation, it is done through ``` for param in model.base_model.parameters(): param.requires_grad = False ``` Would like to do the same for tensorflow implementation.
2020/07/01
[ "https://Stackoverflow.com/questions/62671668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732618/" ]
``` model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') for _layer in model: if _layer.name == 'distilbert': print(f"Freezing model layer {_layer.name}") _layer.trainable = False print(_layer.name) print(_layer.trainable) --- Freezing model layer distilbert distilbert False <---------------- pre_classifier True classifier True dropout_99 True Model: "tf_distil_bert_for_sequence_classification_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_99 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 592,130 Non-trainable params: 66,362,880 <----- ``` Without freezing. ``` Model: "tf_distil_bert_for_sequence_classification_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_59 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 66,955,010 Non-trainable params: 0 ``` Please change from TFDistilBertForSequenceClassification to TFBertForSequenceClassification accordingly. To do so, first run `model.summary` to verify the base name. For TFDistilBertForSequenceClassification, it is `distilbert`.
Alternatively: ``` model.bert.trainable = False ```
62,671,669
I am currently trying to compare an array of times with current time and execute certain code. ``` import os import datetime as dt t1 = dt.time(hour=12, minute=45) t2 = dt.time(hour=12, minute=47) timetable = [t1, t2] for i in timetable: if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute: print("Its working...") else: print ("time is now changed") ``` Currently giving the format like above for specific times. I tried entering time as string like `timetable = ["12:45", "12:50"]` or integer as `timetable = [(12),(45),(12),(50)]` but all methods give me different errors.
2020/07/01
[ "https://Stackoverflow.com/questions/62671669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829406/" ]
Found a way to do it. Freeze the base model BEFORE compiling it. ``` model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased") model.layers[0].trainable = False model.compile(...) ```
Alternatively: ``` model.bert.trainable = False ```
62,671,669
I am currently trying to compare an array of times with current time and execute certain code. ``` import os import datetime as dt t1 = dt.time(hour=12, minute=45) t2 = dt.time(hour=12, minute=47) timetable = [t1, t2] for i in timetable: if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute: print("Its working...") else: print ("time is now changed") ``` Currently giving the format like above for specific times. I tried entering time as string like `timetable = ["12:45", "12:50"]` or integer as `timetable = [(12),(45),(12),(50)]` but all methods give me different errors.
2020/07/01
[ "https://Stackoverflow.com/questions/62671669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829406/" ]
Found a way to do it. Freeze the base model BEFORE compiling it. ``` model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased") model.layers[0].trainable = False model.compile(...) ```
After digging this thread [1](https://github.com/huggingface/transformers/issues/400) up, I think the following codes won't hurt for TF2. Even though it may be redundant in a specific case. ``` model = TFBertModel.from_pretrained('./bert-base-uncase') for layer in model.layers: layer.trainable=False for w in layer.weights: w._trainable=False ```
62,671,669
I am currently trying to compare an array of times with current time and execute certain code. ``` import os import datetime as dt t1 = dt.time(hour=12, minute=45) t2 = dt.time(hour=12, minute=47) timetable = [t1, t2] for i in timetable: if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute: print("Its working...") else: print ("time is now changed") ``` Currently giving the format like above for specific times. I tried entering time as string like `timetable = ["12:45", "12:50"]` or integer as `timetable = [(12),(45),(12),(50)]` but all methods give me different errors.
2020/07/01
[ "https://Stackoverflow.com/questions/62671669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829406/" ]
Found a way to do it. Freeze the base model BEFORE compiling it. ``` model = TFBertForSequenceClassification.from_pretrained("bert-base-uncased") model.layers[0].trainable = False model.compile(...) ```
``` model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') for _layer in model: if _layer.name == 'distilbert': print(f"Freezing model layer {_layer.name}") _layer.trainable = False print(_layer.name) print(_layer.trainable) --- Freezing model layer distilbert distilbert False <---------------- pre_classifier True classifier True dropout_99 True Model: "tf_distil_bert_for_sequence_classification_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_99 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 592,130 Non-trainable params: 66,362,880 <----- ``` Without freezing. ``` Model: "tf_distil_bert_for_sequence_classification_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_59 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 66,955,010 Non-trainable params: 0 ``` Please change from TFDistilBertForSequenceClassification to TFBertForSequenceClassification accordingly. To do so, first run `model.summary` to verify the base name. For TFDistilBertForSequenceClassification, it is `distilbert`.
62,671,669
I am currently trying to compare an array of times with current time and execute certain code. ``` import os import datetime as dt t1 = dt.time(hour=12, minute=45) t2 = dt.time(hour=12, minute=47) timetable = [t1, t2] for i in timetable: if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute: print("Its working...") else: print ("time is now changed") ``` Currently giving the format like above for specific times. I tried entering time as string like `timetable = ["12:45", "12:50"]` or integer as `timetable = [(12),(45),(12),(50)]` but all methods give me different errors.
2020/07/01
[ "https://Stackoverflow.com/questions/62671669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829406/" ]
After digging this thread [1](https://github.com/huggingface/transformers/issues/400) up, I think the following codes won't hurt for TF2. Even though it may be redundant in a specific case. ``` model = TFBertModel.from_pretrained('./bert-base-uncase') for layer in model.layers: layer.trainable=False for w in layer.weights: w._trainable=False ```
Alternatively: ``` model.bert.trainable = False ```
62,671,669
I am currently trying to compare an array of times with current time and execute certain code. ``` import os import datetime as dt t1 = dt.time(hour=12, minute=45) t2 = dt.time(hour=12, minute=47) timetable = [t1, t2] for i in timetable: if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute: print("Its working...") else: print ("time is now changed") ``` Currently giving the format like above for specific times. I tried entering time as string like `timetable = ["12:45", "12:50"]` or integer as `timetable = [(12),(45),(12),(50)]` but all methods give me different errors.
2020/07/01
[ "https://Stackoverflow.com/questions/62671669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829406/" ]
``` model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') for _layer in model: if _layer.name == 'distilbert': print(f"Freezing model layer {_layer.name}") _layer.trainable = False print(_layer.name) print(_layer.trainable) --- Freezing model layer distilbert distilbert False <---------------- pre_classifier True classifier True dropout_99 True Model: "tf_distil_bert_for_sequence_classification_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_99 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 592,130 Non-trainable params: 66,362,880 <----- ``` Without freezing. ``` Model: "tf_distil_bert_for_sequence_classification_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= distilbert (TFDistilBertMain multiple 66362880 _________________________________________________________________ pre_classifier (Dense) multiple 590592 _________________________________________________________________ classifier (Dense) multiple 1538 _________________________________________________________________ dropout_59 (Dropout) multiple 0 ================================================================= Total params: 66,955,010 Trainable params: 66,955,010 Non-trainable params: 0 ``` Please change from TFDistilBertForSequenceClassification to TFBertForSequenceClassification accordingly. To do so, first run `model.summary` to verify the base name. For TFDistilBertForSequenceClassification, it is `distilbert`.
Alternatively: ``` model.bert.trainable = False ```
62,671,692
I have a tuple- `('name@mail.com',)`. I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
2020/07/01
[ "https://Stackoverflow.com/questions/62671692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845570/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,692
I have a tuple- `('name@mail.com',)`. I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
2020/07/01
[ "https://Stackoverflow.com/questions/62671692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845570/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,692
I have a tuple- `('name@mail.com',)`. I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
2020/07/01
[ "https://Stackoverflow.com/questions/62671692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845570/" ]
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,692
I have a tuple- `('name@mail.com',)`. I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
2020/07/01
[ "https://Stackoverflow.com/questions/62671692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845570/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
62,671,692
I have a tuple- `('name@mail.com',)`. I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
2020/07/01
[ "https://Stackoverflow.com/questions/62671692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845570/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,692
I have a tuple- `('name@mail.com',)`. I want to unpack it to get 'name@mail.com'. How can I do so? I am new to Python so please excuse.
2020/07/01
[ "https://Stackoverflow.com/questions/62671692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845570/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,707
This is my Dockerfile. also you can see the image of Dockerfile ``` #Dockerfile # Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ ``` #Dcokerfile image [1]: <https://i.stack.imgur.com/DvcAD.png> When i run this file it gives me error. I run this file using command (>docker build .) on ubuntu 18.04 for the testing simple django project.
2020/07/01
[ "https://Stackoverflow.com/questions/62671707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11323523/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,707
This is my Dockerfile. also you can see the image of Dockerfile ``` #Dockerfile # Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ ``` #Dcokerfile image [1]: <https://i.stack.imgur.com/DvcAD.png> When i run this file it gives me error. I run this file using command (>docker build .) on ubuntu 18.04 for the testing simple django project.
2020/07/01
[ "https://Stackoverflow.com/questions/62671707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11323523/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,707
This is my Dockerfile. also you can see the image of Dockerfile ``` #Dockerfile # Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ ``` #Dcokerfile image [1]: <https://i.stack.imgur.com/DvcAD.png> When i run this file it gives me error. I run this file using command (>docker build .) on ubuntu 18.04 for the testing simple django project.
2020/07/01
[ "https://Stackoverflow.com/questions/62671707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11323523/" ]
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,707
This is my Dockerfile. also you can see the image of Dockerfile ``` #Dockerfile # Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ ``` #Dcokerfile image [1]: <https://i.stack.imgur.com/DvcAD.png> When i run this file it gives me error. I run this file using command (>docker build .) on ubuntu 18.04 for the testing simple django project.
2020/07/01
[ "https://Stackoverflow.com/questions/62671707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11323523/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
62,671,707
This is my Dockerfile. also you can see the image of Dockerfile ``` #Dockerfile # Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ ``` #Dcokerfile image [1]: <https://i.stack.imgur.com/DvcAD.png> When i run this file it gives me error. I run this file using command (>docker build .) on ubuntu 18.04 for the testing simple django project.
2020/07/01
[ "https://Stackoverflow.com/questions/62671707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11323523/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,707
This is my Dockerfile. also you can see the image of Dockerfile ``` #Dockerfile # Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ ``` #Dcokerfile image [1]: <https://i.stack.imgur.com/DvcAD.png> When i run this file it gives me error. I run this file using command (>docker build .) on ubuntu 18.04 for the testing simple django project.
2020/07/01
[ "https://Stackoverflow.com/questions/62671707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11323523/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,716
I submit new version in app store connect, they reject the version ,I upload new version from Xcode and it is successfully uploaded. but when i go to the rejected version in app store connect and want to add the new build , it is not appear , only the rejected build appear, any one knows why?? i try upload new version many times , so now there are many uploaded versions , which not appear in app store connect!
2020/07/01
[ "https://Stackoverflow.com/questions/62671716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386253/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,716
I submit new version in app store connect, they reject the version ,I upload new version from Xcode and it is successfully uploaded. but when i go to the rejected version in app store connect and want to add the new build , it is not appear , only the rejected build appear, any one knows why?? i try upload new version many times , so now there are many uploaded versions , which not appear in app store connect!
2020/07/01
[ "https://Stackoverflow.com/questions/62671716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386253/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,716
I submit new version in app store connect, they reject the version ,I upload new version from Xcode and it is successfully uploaded. but when i go to the rejected version in app store connect and want to add the new build , it is not appear , only the rejected build appear, any one knows why?? i try upload new version many times , so now there are many uploaded versions , which not appear in app store connect!
2020/07/01
[ "https://Stackoverflow.com/questions/62671716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386253/" ]
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,716
I submit new version in app store connect, they reject the version ,I upload new version from Xcode and it is successfully uploaded. but when i go to the rejected version in app store connect and want to add the new build , it is not appear , only the rejected build appear, any one knows why?? i try upload new version many times , so now there are many uploaded versions , which not appear in app store connect!
2020/07/01
[ "https://Stackoverflow.com/questions/62671716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386253/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
62,671,716
I submit new version in app store connect, they reject the version ,I upload new version from Xcode and it is successfully uploaded. but when i go to the rejected version in app store connect and want to add the new build , it is not appear , only the rejected build appear, any one knows why?? i try upload new version many times , so now there are many uploaded versions , which not appear in app store connect!
2020/07/01
[ "https://Stackoverflow.com/questions/62671716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386253/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,716
I submit new version in app store connect, they reject the version ,I upload new version from Xcode and it is successfully uploaded. but when i go to the rejected version in app store connect and want to add the new build , it is not appear , only the rejected build appear, any one knows why?? i try upload new version many times , so now there are many uploaded versions , which not appear in app store connect!
2020/07/01
[ "https://Stackoverflow.com/questions/62671716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386253/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,728
I have a data in very weird form: [image of data in list format](https://i.stack.imgur.com/YPS3n.png) How would I convert this list into image? I tried using PIL but it didn't work: ``` array = np.array(aList, dtype=np.uint8) image = Image.fromarray(array) image.save('output.png') ``` I got following error: ``` KeyError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2648 typekey = (1, 1) + shape[2:], arr["typestr"] -> 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: KeyError: ((1, 1, 256, 256, 3), '|u1') During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-39-c48b139b22e6> in <module> 1 array = np.array(list_of_arrays, dtype=np.uint8) ----> 2 image = Image.fromarray(array) 3 image.save('output.png') /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: -> 2651 raise TypeError("Cannot handle this data type") 2652 else: 2653 rawmode = mode TypeError: Cannot handle this data type ``` Any help will be greatly appreciated :)
2020/07/01
[ "https://Stackoverflow.com/questions/62671728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845507/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,728
I have a data in very weird form: [image of data in list format](https://i.stack.imgur.com/YPS3n.png) How would I convert this list into image? I tried using PIL but it didn't work: ``` array = np.array(aList, dtype=np.uint8) image = Image.fromarray(array) image.save('output.png') ``` I got following error: ``` KeyError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2648 typekey = (1, 1) + shape[2:], arr["typestr"] -> 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: KeyError: ((1, 1, 256, 256, 3), '|u1') During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-39-c48b139b22e6> in <module> 1 array = np.array(list_of_arrays, dtype=np.uint8) ----> 2 image = Image.fromarray(array) 3 image.save('output.png') /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: -> 2651 raise TypeError("Cannot handle this data type") 2652 else: 2653 rawmode = mode TypeError: Cannot handle this data type ``` Any help will be greatly appreciated :)
2020/07/01
[ "https://Stackoverflow.com/questions/62671728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845507/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,728
I have a data in very weird form: [image of data in list format](https://i.stack.imgur.com/YPS3n.png) How would I convert this list into image? I tried using PIL but it didn't work: ``` array = np.array(aList, dtype=np.uint8) image = Image.fromarray(array) image.save('output.png') ``` I got following error: ``` KeyError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2648 typekey = (1, 1) + shape[2:], arr["typestr"] -> 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: KeyError: ((1, 1, 256, 256, 3), '|u1') During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-39-c48b139b22e6> in <module> 1 array = np.array(list_of_arrays, dtype=np.uint8) ----> 2 image = Image.fromarray(array) 3 image.save('output.png') /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: -> 2651 raise TypeError("Cannot handle this data type") 2652 else: 2653 rawmode = mode TypeError: Cannot handle this data type ``` Any help will be greatly appreciated :)
2020/07/01
[ "https://Stackoverflow.com/questions/62671728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845507/" ]
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
A tuple is just like a list but static, so just do : ``` ('name@mail.com',)[0] ```
62,671,728
I have a data in very weird form: [image of data in list format](https://i.stack.imgur.com/YPS3n.png) How would I convert this list into image? I tried using PIL but it didn't work: ``` array = np.array(aList, dtype=np.uint8) image = Image.fromarray(array) image.save('output.png') ``` I got following error: ``` KeyError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2648 typekey = (1, 1) + shape[2:], arr["typestr"] -> 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: KeyError: ((1, 1, 256, 256, 3), '|u1') During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-39-c48b139b22e6> in <module> 1 array = np.array(list_of_arrays, dtype=np.uint8) ----> 2 image = Image.fromarray(array) 3 image.save('output.png') /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: -> 2651 raise TypeError("Cannot handle this data type") 2652 else: 2653 rawmode = mode TypeError: Cannot handle this data type ``` Any help will be greatly appreciated :)
2020/07/01
[ "https://Stackoverflow.com/questions/62671728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845507/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
62,671,728
I have a data in very weird form: [image of data in list format](https://i.stack.imgur.com/YPS3n.png) How would I convert this list into image? I tried using PIL but it didn't work: ``` array = np.array(aList, dtype=np.uint8) image = Image.fromarray(array) image.save('output.png') ``` I got following error: ``` KeyError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2648 typekey = (1, 1) + shape[2:], arr["typestr"] -> 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: KeyError: ((1, 1, 256, 256, 3), '|u1') During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-39-c48b139b22e6> in <module> 1 array = np.array(list_of_arrays, dtype=np.uint8) ----> 2 image = Image.fromarray(array) 3 image.save('output.png') /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: -> 2651 raise TypeError("Cannot handle this data type") 2652 else: 2653 rawmode = mode TypeError: Cannot handle this data type ``` Any help will be greatly appreciated :)
2020/07/01
[ "https://Stackoverflow.com/questions/62671728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845507/" ]
``` tu = ('name@mail.com',) str = tu[0] print(str) #will return 'name@mail.com' ``` A tuple is a sequence type, which means the elements can be accessed by their indices.
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,728
I have a data in very weird form: [image of data in list format](https://i.stack.imgur.com/YPS3n.png) How would I convert this list into image? I tried using PIL but it didn't work: ``` array = np.array(aList, dtype=np.uint8) image = Image.fromarray(array) image.save('output.png') ``` I got following error: ``` KeyError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2648 typekey = (1, 1) + shape[2:], arr["typestr"] -> 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: KeyError: ((1, 1, 256, 256, 3), '|u1') During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-39-c48b139b22e6> in <module> 1 array = np.array(list_of_arrays, dtype=np.uint8) ----> 2 image = Image.fromarray(array) 3 image.save('output.png') /opt/conda/lib/python3.7/site-packages/PIL/Image.py in fromarray(obj, mode) 2649 mode, rawmode = _fromarray_typemap[typekey] 2650 except KeyError: -> 2651 raise TypeError("Cannot handle this data type") 2652 else: 2653 rawmode = mode TypeError: Cannot handle this data type ``` Any help will be greatly appreciated :)
2020/07/01
[ "https://Stackoverflow.com/questions/62671728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845507/" ]
The full syntax for unpacking use the syntax for tuple literal so you can use ``` tu = ('name@mail.com',) (var,) = tu ``` The following simplified syntax is allowed ``` var, = tu ```
The prettiest way to get the first element and the last element of an `iterable` object like `tuple`, `list`, etc. would be to use the `*` feature not same as the `*` operator. ```py my_tup = ('a', 'b', 'c',) # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:] # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. # This will result in no exceptions if you have only 1 element in the tuple. my_tup = ('a',) # This still works # Last element *other_els, last_el = my_tup # First element first_el, *other_els = my_tup # other_els is [] here ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try this: ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let [key, value] of Object.entries(checkObj)) { // console.log(`${key}: ${value}`); if(value>=2){ objToArray.push(value); } } console.log(objToArray); ```
try this: I hope you got it .. ``` let checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; let objToArray = []; for (let values of Object.values(checkObj)) { console.log(values); if (values >=2 ) { objToArray.push(values) } } ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try with `Object.values(checkObj).filter(x => x >= 2);`. 1. Get array of all values with `Object.values(checkObj)`. 2. Filter array and get value >= 2 with `.filter(x => x >= 2)`. **If you want to use `for ... in` loop** then it iterates over `key` so you can get value with `obj[key]`. As you have declared `for (let values in checkObj)` `values` object will hold `key` of `checkObj`. So you can access value with `checkObj[values]`. Check output below. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; // Approach 1 let result = Object.values(checkObj).filter(x => x >= 2); console.log(result); // Approach 2 const objToArray = []; for (let values in checkObj) { if (checkObj[values] >= 2) { objToArray.push(checkObj[values]); } } console.log(objToArray); ```
Try this ``` const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; let objToArray = []; objToArray = Object.values(checkObj).filter(elem => elem >= 2); console.log(objToArray); ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try with `Object.values(checkObj).filter(x => x >= 2);`. 1. Get array of all values with `Object.values(checkObj)`. 2. Filter array and get value >= 2 with `.filter(x => x >= 2)`. **If you want to use `for ... in` loop** then it iterates over `key` so you can get value with `obj[key]`. As you have declared `for (let values in checkObj)` `values` object will hold `key` of `checkObj`. So you can access value with `checkObj[values]`. Check output below. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; // Approach 1 let result = Object.values(checkObj).filter(x => x >= 2); console.log(result); // Approach 2 const objToArray = []; for (let values in checkObj) { if (checkObj[values] >= 2) { objToArray.push(checkObj[values]); } } console.log(objToArray); ```
``` const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; //changing the loop into a foreach loop that iterates over the keys Object.keys(checkObj).forEach((key => { if (checkObj[key]) { objToArray.push(checkObj[key]) } })) ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try with `Object.values(checkObj).filter(x => x >= 2);`. 1. Get array of all values with `Object.values(checkObj)`. 2. Filter array and get value >= 2 with `.filter(x => x >= 2)`. **If you want to use `for ... in` loop** then it iterates over `key` so you can get value with `obj[key]`. As you have declared `for (let values in checkObj)` `values` object will hold `key` of `checkObj`. So you can access value with `checkObj[values]`. Check output below. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; // Approach 1 let result = Object.values(checkObj).filter(x => x >= 2); console.log(result); // Approach 2 const objToArray = []; for (let values in checkObj) { if (checkObj[values] >= 2) { objToArray.push(checkObj[values]); } } console.log(objToArray); ```
Is this you wanted? The for...in statement iterates over all enumerable properties of an object that are keyed, it should be key rather than values. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let key in checkObj) { if (checkObj[key] >= 2) { objToArray.push(checkObj[key]) } } console.log(objToArray) ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try with `Object.values(checkObj).filter(x => x >= 2);`. 1. Get array of all values with `Object.values(checkObj)`. 2. Filter array and get value >= 2 with `.filter(x => x >= 2)`. **If you want to use `for ... in` loop** then it iterates over `key` so you can get value with `obj[key]`. As you have declared `for (let values in checkObj)` `values` object will hold `key` of `checkObj`. So you can access value with `checkObj[values]`. Check output below. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; // Approach 1 let result = Object.values(checkObj).filter(x => x >= 2); console.log(result); // Approach 2 const objToArray = []; for (let values in checkObj) { if (checkObj[values] >= 2) { objToArray.push(checkObj[values]); } } console.log(objToArray); ```
try this: I hope you got it .. ``` let checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; let objToArray = []; for (let values of Object.values(checkObj)) { console.log(values); if (values >=2 ) { objToArray.push(values) } } ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Is this you wanted? The for...in statement iterates over all enumerable properties of an object that are keyed, it should be key rather than values. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let key in checkObj) { if (checkObj[key] >= 2) { objToArray.push(checkObj[key]) } } console.log(objToArray) ```
``` const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; //changing the loop into a foreach loop that iterates over the keys Object.keys(checkObj).forEach((key => { if (checkObj[key]) { objToArray.push(checkObj[key]) } })) ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try this ``` const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; let objToArray = []; objToArray = Object.values(checkObj).filter(elem => elem >= 2); console.log(objToArray); ```
``` const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; //changing the loop into a foreach loop that iterates over the keys Object.keys(checkObj).forEach((key => { if (checkObj[key]) { objToArray.push(checkObj[key]) } })) ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try this: ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let [key, value] of Object.entries(checkObj)) { // console.log(`${key}: ${value}`); if(value>=2){ objToArray.push(value); } } console.log(objToArray); ```
``` const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; //changing the loop into a foreach loop that iterates over the keys Object.keys(checkObj).forEach((key => { if (checkObj[key]) { objToArray.push(checkObj[key]) } })) ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Try with `Object.values(checkObj).filter(x => x >= 2);`. 1. Get array of all values with `Object.values(checkObj)`. 2. Filter array and get value >= 2 with `.filter(x => x >= 2)`. **If you want to use `for ... in` loop** then it iterates over `key` so you can get value with `obj[key]`. As you have declared `for (let values in checkObj)` `values` object will hold `key` of `checkObj`. So you can access value with `checkObj[values]`. Check output below. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; // Approach 1 let result = Object.values(checkObj).filter(x => x >= 2); console.log(result); // Approach 2 const objToArray = []; for (let values in checkObj) { if (checkObj[values] >= 2) { objToArray.push(checkObj[values]); } } console.log(objToArray); ```
Try this: ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let [key, value] of Object.entries(checkObj)) { // console.log(`${key}: ${value}`); if(value>=2){ objToArray.push(value); } } console.log(objToArray); ```
62,671,735
I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let values in checkObj) { if (Object.values(checkObj) >=2 ) { objToArray.push(checkObj.values()) } } console.log(objToArray); ``` So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].
2020/07/01
[ "https://Stackoverflow.com/questions/62671735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206932/" ]
Is this you wanted? The for...in statement iterates over all enumerable properties of an object that are keyed, it should be key rather than values. ```js const checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; const objToArray = []; for (let key in checkObj) { if (checkObj[key] >= 2) { objToArray.push(checkObj[key]) } } console.log(objToArray) ```
try this: I hope you got it .. ``` let checkObj = { oddNum: 1, evenNum: 2, foundNum: 5, randomNum: 18 }; let objToArray = []; for (let values of Object.values(checkObj)) { console.log(values); if (values >=2 ) { objToArray.push(values) } } ```
62,671,770
I am getting error as "Failed to perform fetch" while doing maven clean install. While same thing is working in Intellij of other people. i have checked the Maven settings.xml and other configuration, it's same as other teammates but unable to figure out the root cause.Also, I am able to log into my Bitbucket account. Following is the stack trace while getting the build error: ``` org.eclipse.jgit.api.errors.TransportException: https:SomeBitbucketURL/project.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:254) at pl.project13.maven.git.JGitProvider.fetch (JGitProvider.java:352) at pl.project13.maven.git.JGitProvider.getAheadBehind (JGitProvider.java:339) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$17 (GitDataProvider.java:174) at pl.project13.maven.git.GitDataProvider.lambda$memoize$23 (GitDataProvider.java:272) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$18 (GitDataProvider.java:175) at pl.project13.maven.git.GitDataProvider.maybePut (GitDataProvider.java:255) at pl.project13.maven.git.GitDataProvider.loadGitData (GitDataProvider.java:175) at pl.project13.maven.git.GitCommitIdMojo.loadGitDataWithJGit (GitCommitIdMojo.java:604) at pl.project13.maven.git.GitCommitIdMojo.loadGitData (GitCommitIdMojo.java:563) at pl.project13.maven.git.GitCommitIdMojo.execute (GitCommitIdMojo.java:458) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) Caused by: org.eclipse.jgit.errors.TransportException: https:SomeBitbucketURL/project.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.transport.TransportHttp.connect (TransportHttp.java:537) at org.eclipse.jgit.transport.TransportHttp.openFetch (TransportHttp.java:362) at org.eclipse.jgit.transport.FetchProcess.executeImp (FetchProcess.java:138) at org.eclipse.jgit.transport.FetchProcess.execute (FetchProcess.java:124) at org.eclipse.jgit.transport.Transport.fetch (Transport.java:1271) at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:243) at pl.project13.maven.git.JGitProvider.fetch (JGitProvider.java:352) at pl.project13.maven.git.JGitProvider.getAheadBehind (JGitProvider.java:339) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$17 (GitDataProvider.java:174) at pl.project13.maven.git.GitDataProvider.lambda$memoize$23 (GitDataProvider.java:272) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$18 (GitDataProvider.java:175) at pl.project13.maven.git.GitDataProvider.maybePut (GitDataProvider.java:255) at pl.project13.maven.git.GitDataProvider.loadGitData (GitDataProvider.java:175) at pl.project13.maven.git.GitCommitIdMojo.loadGitDataWithJGit (GitCommitIdMojo.java:604) at pl.project13.maven.git.GitCommitIdMojo.loadGitData (GitCommitIdMojo.java:563) at pl.project13.maven.git.GitCommitIdMojo.execute (GitCommitIdMojo.java:458) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12964338/" ]
Maybe you can find the workaround through : <https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/421> With 3.0.0 we got two new properties (git.local.branch.ahead / git.local.branch.behind) that pretty much are only correct when using a git pull prior. This git pull might cause such transport exceptions (and requires internet). With the 3.0.1 there will be a more clear offline option. The real fix would be that we have the plugin work in offline mode unless specified. When a user operates in offline mode and consumes the mentioned options this plugin would generate a warning. ``` <build> <plugins> <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> <configuration> <offline>true</offline> </configuration> </plugin> </plugins> </build> ``` or another way ``` <configuration> <excludeProperties> <excludeProperty>^git.local.branch.*$</excludeProperty> </excludeProperties> </configuration> ```
Looks like you are pulling artifacts from private artifactory. You need to provide the artifactory username and password. Or if you are using jgitflow-maven-plugin then something like this is needed ``` <plugin> <groupId>external.atlassian.jgitflow</groupId> <artifactId>jgitflow-maven-plugin</artifactId> <version>1.0-m5.1</version> <configuration> <username>${git.user}</username> <password>${git.password}</password> </configuration> </plugin> ```
62,671,770
I am getting error as "Failed to perform fetch" while doing maven clean install. While same thing is working in Intellij of other people. i have checked the Maven settings.xml and other configuration, it's same as other teammates but unable to figure out the root cause.Also, I am able to log into my Bitbucket account. Following is the stack trace while getting the build error: ``` org.eclipse.jgit.api.errors.TransportException: https:SomeBitbucketURL/project.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:254) at pl.project13.maven.git.JGitProvider.fetch (JGitProvider.java:352) at pl.project13.maven.git.JGitProvider.getAheadBehind (JGitProvider.java:339) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$17 (GitDataProvider.java:174) at pl.project13.maven.git.GitDataProvider.lambda$memoize$23 (GitDataProvider.java:272) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$18 (GitDataProvider.java:175) at pl.project13.maven.git.GitDataProvider.maybePut (GitDataProvider.java:255) at pl.project13.maven.git.GitDataProvider.loadGitData (GitDataProvider.java:175) at pl.project13.maven.git.GitCommitIdMojo.loadGitDataWithJGit (GitCommitIdMojo.java:604) at pl.project13.maven.git.GitCommitIdMojo.loadGitData (GitCommitIdMojo.java:563) at pl.project13.maven.git.GitCommitIdMojo.execute (GitCommitIdMojo.java:458) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) Caused by: org.eclipse.jgit.errors.TransportException: https:SomeBitbucketURL/project.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.transport.TransportHttp.connect (TransportHttp.java:537) at org.eclipse.jgit.transport.TransportHttp.openFetch (TransportHttp.java:362) at org.eclipse.jgit.transport.FetchProcess.executeImp (FetchProcess.java:138) at org.eclipse.jgit.transport.FetchProcess.execute (FetchProcess.java:124) at org.eclipse.jgit.transport.Transport.fetch (Transport.java:1271) at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:243) at pl.project13.maven.git.JGitProvider.fetch (JGitProvider.java:352) at pl.project13.maven.git.JGitProvider.getAheadBehind (JGitProvider.java:339) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$17 (GitDataProvider.java:174) at pl.project13.maven.git.GitDataProvider.lambda$memoize$23 (GitDataProvider.java:272) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$18 (GitDataProvider.java:175) at pl.project13.maven.git.GitDataProvider.maybePut (GitDataProvider.java:255) at pl.project13.maven.git.GitDataProvider.loadGitData (GitDataProvider.java:175) at pl.project13.maven.git.GitCommitIdMojo.loadGitDataWithJGit (GitCommitIdMojo.java:604) at pl.project13.maven.git.GitCommitIdMojo.loadGitData (GitCommitIdMojo.java:563) at pl.project13.maven.git.GitCommitIdMojo.execute (GitCommitIdMojo.java:458) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12964338/" ]
To update the answer from @Paul-Li, this bug has been fixed but the maven dependency has changed from `pl.project13.maven:git-commit-id-plugin` (any version starting from `3.0.0`) to `io.github.git-commit-id:git-commit-id-maven-plugin:5.0.0`. No need to use the offline mode anymore. In `org.springframework.boot:spring-boot-starter-parent:2.6.3` (the latest so far), we can still find `pl.project13.maven:git-commit-id-plugin` in the plugin management. To make it work on my projects having `spring-boot-starter-parent` as parent, I copied from the parent the `<executions>` and `<configuration>` like that: ``` <plugin> <groupId>io.github.git-commit-id</groupId> <artifactId>git-commit-id-maven-plugin</artifactId> <version>${git-commit-id-maven-plugin.version}</version> <executions> <execution> <goals> <goal>revision</goal> </goals> </execution> </executions> <configuration> <verbose>true</verbose> <dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat> <generateGitPropertiesFile>true</generateGitPropertiesFile> <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename> </configuration> </plugin> ```
Looks like you are pulling artifacts from private artifactory. You need to provide the artifactory username and password. Or if you are using jgitflow-maven-plugin then something like this is needed ``` <plugin> <groupId>external.atlassian.jgitflow</groupId> <artifactId>jgitflow-maven-plugin</artifactId> <version>1.0-m5.1</version> <configuration> <username>${git.user}</username> <password>${git.password}</password> </configuration> </plugin> ```
62,671,770
I am getting error as "Failed to perform fetch" while doing maven clean install. While same thing is working in Intellij of other people. i have checked the Maven settings.xml and other configuration, it's same as other teammates but unable to figure out the root cause.Also, I am able to log into my Bitbucket account. Following is the stack trace while getting the build error: ``` org.eclipse.jgit.api.errors.TransportException: https:SomeBitbucketURL/project.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:254) at pl.project13.maven.git.JGitProvider.fetch (JGitProvider.java:352) at pl.project13.maven.git.JGitProvider.getAheadBehind (JGitProvider.java:339) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$17 (GitDataProvider.java:174) at pl.project13.maven.git.GitDataProvider.lambda$memoize$23 (GitDataProvider.java:272) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$18 (GitDataProvider.java:175) at pl.project13.maven.git.GitDataProvider.maybePut (GitDataProvider.java:255) at pl.project13.maven.git.GitDataProvider.loadGitData (GitDataProvider.java:175) at pl.project13.maven.git.GitCommitIdMojo.loadGitDataWithJGit (GitCommitIdMojo.java:604) at pl.project13.maven.git.GitCommitIdMojo.loadGitData (GitCommitIdMojo.java:563) at pl.project13.maven.git.GitCommitIdMojo.execute (GitCommitIdMojo.java:458) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) Caused by: org.eclipse.jgit.errors.TransportException: https:SomeBitbucketURL/project.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.transport.TransportHttp.connect (TransportHttp.java:537) at org.eclipse.jgit.transport.TransportHttp.openFetch (TransportHttp.java:362) at org.eclipse.jgit.transport.FetchProcess.executeImp (FetchProcess.java:138) at org.eclipse.jgit.transport.FetchProcess.execute (FetchProcess.java:124) at org.eclipse.jgit.transport.Transport.fetch (Transport.java:1271) at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:243) at pl.project13.maven.git.JGitProvider.fetch (JGitProvider.java:352) at pl.project13.maven.git.JGitProvider.getAheadBehind (JGitProvider.java:339) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$17 (GitDataProvider.java:174) at pl.project13.maven.git.GitDataProvider.lambda$memoize$23 (GitDataProvider.java:272) at pl.project13.maven.git.GitDataProvider.lambda$loadGitData$18 (GitDataProvider.java:175) at pl.project13.maven.git.GitDataProvider.maybePut (GitDataProvider.java:255) at pl.project13.maven.git.GitDataProvider.loadGitData (GitDataProvider.java:175) at pl.project13.maven.git.GitCommitIdMojo.loadGitDataWithJGit (GitCommitIdMojo.java:604) at pl.project13.maven.git.GitCommitIdMojo.loadGitData (GitCommitIdMojo.java:563) at pl.project13.maven.git.GitCommitIdMojo.execute (GitCommitIdMojo.java:458) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12964338/" ]
Maybe you can find the workaround through : <https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/421> With 3.0.0 we got two new properties (git.local.branch.ahead / git.local.branch.behind) that pretty much are only correct when using a git pull prior. This git pull might cause such transport exceptions (and requires internet). With the 3.0.1 there will be a more clear offline option. The real fix would be that we have the plugin work in offline mode unless specified. When a user operates in offline mode and consumes the mentioned options this plugin would generate a warning. ``` <build> <plugins> <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> <configuration> <offline>true</offline> </configuration> </plugin> </plugins> </build> ``` or another way ``` <configuration> <excludeProperties> <excludeProperty>^git.local.branch.*$</excludeProperty> </excludeProperties> </configuration> ```
To update the answer from @Paul-Li, this bug has been fixed but the maven dependency has changed from `pl.project13.maven:git-commit-id-plugin` (any version starting from `3.0.0`) to `io.github.git-commit-id:git-commit-id-maven-plugin:5.0.0`. No need to use the offline mode anymore. In `org.springframework.boot:spring-boot-starter-parent:2.6.3` (the latest so far), we can still find `pl.project13.maven:git-commit-id-plugin` in the plugin management. To make it work on my projects having `spring-boot-starter-parent` as parent, I copied from the parent the `<executions>` and `<configuration>` like that: ``` <plugin> <groupId>io.github.git-commit-id</groupId> <artifactId>git-commit-id-maven-plugin</artifactId> <version>${git-commit-id-maven-plugin.version}</version> <executions> <execution> <goals> <goal>revision</goal> </goals> </execution> </executions> <configuration> <verbose>true</verbose> <dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat> <generateGitPropertiesFile>true</generateGitPropertiesFile> <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename> </configuration> </plugin> ```
62,671,780
I'm trying to process DB migrations during application startup in a Azure-hosted web API. However, no matter where I try to put it, I get the exception: `ObjectDisposedException: Cannot access a disposed object.` I gather that this is because I'm wrapping the context Migrate call in a "using" statement during the wrong part of the injection process. But I'm not sure where it should be located. I've consulted the following articles: * [ASP - Core Migrate EF Core SQL DB on Startup](https://stackoverflow.com/questions/37780136/asp-core-migrate-ef-core-sql-db-on-startup) * <https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup> * <https://blog.rsuter.com/automatically-migrate-your-entity-framework-core-managed-database-on-asp-net-core-application-start/> And have tried the following migration locations: ``` public Startup(IConfiguration appSettings) { using var dbContext = new MyContext(); dbContext.Database.Migrate(); } ``` This produced the ObjectDisposedException on MyContext. So I tried removing it from the constructor and adding it to services and injecting it into the configure call (per the first and second articles): ``` public Startup(IConfiguration appSettings) { } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MyContext>(); [...] } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyContext dbcontext) { [...] dbcontext.Database.Migrate(); } ``` This also produced the ObjectDisposedException on MyContext. So I tried changing how the configure method access the context service (per the third article): ``` public Startup(IConfiguration appsettings) { } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MyContext>(); [...] } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { [...] using var serviceScope = app.ApplicationServices .GetRequiredService<IServiceScopeFactory>() .CreateScope(); using var context = serviceScope.ServiceProvider .GetService<MyDbContext>(); context.Database.Migrate(); } ``` Which still produced the ObjectDisposedException on MyContext. I would appreciate any help in understanding what I'm doing wrong trying to implement this EF Core migration! Thanks!
2020/07/01
[ "https://Stackoverflow.com/questions/62671780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1652327/" ]
If you understand the security risks of using a connection string with permissions to alter the database schema and you understand problems that can occur when multiple instances of your app try to migrate the database at the same time... You can do it in Program.Main. If you're using Microsoft.Extensions.Hosting, it would look like this: ```cs public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); db.Database.Migrate(); } host.Run(); } ``` You could also consider adding an admin page that requires the user to be authenticated before clicking a button to migrate the database.
Thus is an updated solution for the latest EF Core version. ```cs public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var migrator = db.Database.GetService<IMigrator>(); migrator.Migrate(); } host.Run(); } ```
62,671,805
I'm trying to make an obligatory Todo app to help with my React learning . The behavior I'm going for is multiple Todo lists, where you select a todo name and the list of todo items for that show. Select a different name list and it's list todo items show, etc (like wunderlist/msft todo). It's using static json where each item has a child array. I'm realizing I have no idea how to update the text in the nested array and I can't seem to find any relevant examples of this. Will someone show me how this is done or point me in the right direction? In my POC on codesandbox each todo has a button where all I'd like to do (for now) is change the text to 'changed' when clicking on the button. Basically I'd like to do this: ``` todoData[selectedIndex].TodoList[index].Title = 'Changed; ``` But the es6/react way using the spread operator Here's a POC : <https://codesandbox.io/s/zealous-lovelace-xtexr?file=/src/App.js> My data looks like this: ``` const TodoData = [ { "Id": 1, "Title": "Groceries", "TodoList": [ { "Id": 1, "Title": "Apples", "IsChecked": false }, { "Id": 2, "Title": "Oranges", "IsChecked": false }, { "Id": 3, "Title": "Bananas", "IsChecked": true } ] }, { "Id": 2, "Title": "Daily Tasks", "TodoList": [{ "Id": 11, "Title": "Clean Kitchen", "IsChecked": false }, { "Id": 12, "Title": "Feed Pets", "IsChecked": false }, { "Id": 13, "Title": "Do Stuff", "IsChecked": false }] }, { "Id": 3, "Title": "Hardware Store", "TodoList": [] }, { "Id": 4, "Title": "Costco", "TodoList": [{ "Id": 21, "Title": "Diapers", "IsChecked": false }, { "Id": 22, "Title": "Cat Food", "IsChecked": false }, { "Id": 23, "Title": "Apples", "IsChecked": false }, { "Id": 24, "Title": "Bananas", "IsChecked": false }] }, { "Id": 5, "Title": "Work", "TodoList": [ { "Id": 34, "Title": "TPS Reports", "IsChecked": true } ] } ] export default TodoData; ``` And the code: ``` function App() { const [todoData, setTodoData] = useState([]); const [selectedIndex, setSelectedIndex] = useState(0); useEffect(() => { setTodoData(TodoData); }, []); const addSelectedIndex = (index) => { setSelectedIndex(index); } const handleInputChange = (todoItem, todoItemIndex) => { const target = todoItem; const value = target.type === 'checkbox' ? target.checked : target.value; }; const handleTextChange = (item, index) => { const updatedTitle = 'Changed'; //Not sure what to do here } return ( <div className="App"> <ul className="pointer"> {todoData.map((todo, todoIndex) => ( <li key={todo.Id} onClick={() => addSelectedIndex(todoIndex)}> {todo.Title + ' (' + todo.TodoList.length + ')'} </li> ))} </ul> <ul> {todoData[selectedIndex] && todoData[selectedIndex].TodoList.map((todoItem, todoItemIndex) => ( <li key={todoItem.Id}> <input type="checkbox" id="gridCheck" checked={todoItem.IsChecked} onChange={() => { handleInputChange(todoItem, todoItemIndex) }} /> <label htmlFor="gridCheck"> {todoItem.Title} </label> <button onClick={() => handleTextChange(todoItem, todoItemIndex)}>Change</button> </li> ))} </ul> </div> ); } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13784014/" ]
If you understand the security risks of using a connection string with permissions to alter the database schema and you understand problems that can occur when multiple instances of your app try to migrate the database at the same time... You can do it in Program.Main. If you're using Microsoft.Extensions.Hosting, it would look like this: ```cs public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); db.Database.Migrate(); } host.Run(); } ``` You could also consider adding an admin page that requires the user to be authenticated before clicking a button to migrate the database.
Thus is an updated solution for the latest EF Core version. ```cs public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var migrator = db.Database.GetService<IMigrator>(); migrator.Migrate(); } host.Run(); } ```
62,671,850
In default, android using the `Theme.AppCompat.Light.DarkActionBar` theme and the status bar text is white, how to change it to black?
2020/07/01
[ "https://Stackoverflow.com/questions/62671850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9768260/" ]
actually you could change the color of statusbar for Api >= 19 inside the style of value-v19 put : ``` <?xml version="1.0" encoding="utf-8"?> <resources> <style name="AppTheme" parent="MaterialDrawerTheme.Light"> <!-- Customize your theme here. --> <item name="android:windowNoTitle">true</item> <item name="android:windowTranslucentStatus">true</item> ..... </style> </resources> ```
Thanks @mohosyny for advising to introduce the material theme, I fix my problem by using the below AppTheme. ``` <resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:windowLightStatusBar" tools:targetApi="m">true</item> </style> </resources> ```
62,671,872
I have a need to define a standalone patch as YAML. More specifically, I want to do the following: ``` kubectl patch serviceaccount default -p '{"imagePullSecrets": [{"name": "registry-my-registry"}]}' ``` The catch is I can't use `kubectl patch`. I'm using a GitOps workflow with flux, and that resource I want to patch is a default resource created outside of flux. In other terms, I need to do the same thing as the command above but with `kubectl apply` only: ``` kubectl apply patch.yaml ``` I wasn't able to figure out if you can define such a patch. **The key bit is that I can't predict the name of the default secret token on a new cluster (as the name is random, i.e. `default-token-uudge`)**
2020/07/01
[ "https://Stackoverflow.com/questions/62671872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018084/" ]
> > * Fields set and deleted from Resource Config are merged into Resources by `Kubectl apply`: > * If a Resource already exists, Apply updates the Resources by merging the > local Resource Config into the remote Resources > * Fields removed from the Resource Config will be deleted from the remote Resource > > > You can learn more about [Kubernetes Field Merge Semantics](https://kubectl.docs.kubernetes.io/pages/app_management/field_merge_semantics.html). * If your limitation is not knowing the secret `default-token-xxxxx` name, no problem, just keep that field out of your yaml. * As long as the yaml has enough fields to identify the target resource (name, kind, namespace) it will add/edit the fields you set. * I created a cluster (minikube in this example, but it could be any) and retrieved the current default serviceAccount: ``` $ kubectl get serviceaccount default -o yaml apiVersion: v1 kind: ServiceAccount metadata: creationTimestamp: "2020-07-01T14:51:38Z" name: default namespace: default resourceVersion: "330" selfLink: /api/v1/namespaces/default/serviceaccounts/default uid: a9e5ff4a-8bfb-466f-8873-58c2172a5d11 secrets: - name: default-token-j6zx2 ``` * Then, we create a yaml file with the content's that we want to add: ``` $ cat add-image-pull-secrets.yaml apiVersion: v1 kind: ServiceAccount metadata: name: default namespace: default imagePullSecrets: - name: registry-my-registry ``` * Now we apply and verify: ``` $ kubectl apply -f add-image-pull-secrets.yaml serviceaccount/default configured $ kubectl get serviceaccount default -o yaml apiVersion: v1 imagePullSecrets: - name: registry-my-registry kind: ServiceAccount metadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"v1","imagePullSecrets":[{"name":"registry-my-registry2"}],"kind":"ServiceAccount","metadata":{"annotations":{},"name":"default","namespace":"default"}} creationTimestamp: "2020-07-01T14:51:38Z" name: default namespace: default resourceVersion: "2382" selfLink: /api/v1/namespaces/default/serviceaccounts/default uid: a9e5ff4a-8bfb-466f-8873-58c2172a5d11 secrets: - name: default-token-j6zx2 ``` As you can see, the ImagePullPolicy was added to the resource. I hope it fits your needs. If you have any further questions let me know in the comments.
Let say, your service account YAML looks like bellow: ```sh $ kubectl get sa demo -o yaml apiVersion: v1 kind: ServiceAccount metadata: name: demo namespace: default secrets: - name: default-token-uudge ``` Now, you want to add or change the `imagePullSecrets` for that service account. To do so, edit the YAML file and add `imagePullSecrets`. ```yaml apiVersion: v1 kind: ServiceAccount metadata: name: demo namespace: default secrets: - name: default-token-uudge imagePullSecrets: - name: myregistrykey ``` And finally, apply the changes: ```sh $ kubectl apply -f service-account.yaml ```
62,671,896
I try to run and get the age from the date in a table but end up with error "ORA-00923: FROM keyword not found where expected". This is my first time run in apex oracle shipping table ``` ship_id ship_date SEL0001 12/6/2015 SEL0002 01/5/2016 ``` sql code ``` select ship_id, YEAR(ship_date) AS [BirthDate], YEAR(GETDATE()) AS [ThisYear], YEAR(GETDATE()) -YEAR(ship_date) AS Age from shipping ``` expected output ``` ship_id BirthDate ThisYear Age SEL0001 12/6/2015 2020 5 SEL0002 01/5/2016 2020 4 ``` Is there any way to get the age? I try to use datediff but I am not expert in that. Thank you.
2020/07/01
[ "https://Stackoverflow.com/questions/62671896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9143271/" ]
You should use `extract` in Oracle, here is the [demo](http://sqlfiddle.com/#!4/7747e/5). ``` select ship_id, TO_CHAR(ship_date , 'MM/DD/YYYY') as BirthDate, extract(YEAR from sysdate) as ThisYear, extract(YEAR from sysdate) - extract(YEAR from ship_date) as Age from shipping ``` output: ``` *---------------------------------------* | SHIP_ID BIRTHDATE THISYEAR AGE | *---------------------------------------* | SEL0001 12/06/2015 2020 5 | | SEL0002 01/05/2016 2020 4 | *---------------------------------------* ```
Use `extract` to get year or month value, and for age use the `months\_between' to get the no.of months then calc age. ``` select ship_id, to_char(ship_date,'DD/MM/YYYY') "BirthDate", extract(year from SYSDATE) ThisYear, months_between(sydate,ship_date)/12 as Age_inYears from shipping ```
62,671,924
I am facing a problem since I added the sendmail configuration in the .env file of my shopware folder. [![enter image description here](https://i.stack.imgur.com/q6AN2.png)](https://i.stack.imgur.com/q6AN2.png) See the above picture, If we click on "**Order with compulsory payment of the costs**", the page will start loading until the mail arrives in the inbox of the email address attached to the order. Which means that this page will load for like 5minutes. Is there a way to shorter this time lapse OR to configure shopware so that he doesn't wait until the mail is sent? Here is my mail config in .env file : ***MAILER\_URL=sendmail://emakers.be***
2020/07/01
[ "https://Stackoverflow.com/questions/62671924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512609/" ]
You should use `extract` in Oracle, here is the [demo](http://sqlfiddle.com/#!4/7747e/5). ``` select ship_id, TO_CHAR(ship_date , 'MM/DD/YYYY') as BirthDate, extract(YEAR from sysdate) as ThisYear, extract(YEAR from sysdate) - extract(YEAR from ship_date) as Age from shipping ``` output: ``` *---------------------------------------* | SHIP_ID BIRTHDATE THISYEAR AGE | *---------------------------------------* | SEL0001 12/06/2015 2020 5 | | SEL0002 01/05/2016 2020 4 | *---------------------------------------* ```
Use `extract` to get year or month value, and for age use the `months\_between' to get the no.of months then calc age. ``` select ship_id, to_char(ship_date,'DD/MM/YYYY') "BirthDate", extract(year from SYSDATE) ThisYear, months_between(sydate,ship_date)/12 as Age_inYears from shipping ```
62,671,933
I have no sample and I'd like to compute the variance, mean, median, and mode of a distribution which I only have a vector with it's density and a vector with it's support. Is there an easy way to compute this statistics in R with this information? Suppose that I only have the following information: ``` Support Density sum(Density) == 1 #TRUE length(Support)==length(Density)# TRUE ```
2020/07/01
[ "https://Stackoverflow.com/questions/62671933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11837637/" ]
You have to do weighted summations F.e., starting with @Johann example ``` set.seed(312345) x = rnorm(1000, mean=10, sd=1) x_support = density(x)$x x_density = density(x)$y plot(x_support, x_density) mean(x) ``` prints ``` [1] 10.00558 ``` and what, I believe, you're looking for ``` m = weighted.mean(x_support, x_density) ``` computes mean as weighted mean of values, producing output ``` 10.0055796130192 ``` There are `weighted.sd`, `weighted.sum` functions which should help you with other quantities you're looking for. Plot [![enter image description here](https://i.stack.imgur.com/i5LHC.png)](https://i.stack.imgur.com/i5LHC.png)
If you don't need a mathematical solution, and an empirical one is all right, you can achieve a pretty good approximation by sampling. Let's generate some data: ``` set.seed(6854684) x = rnorm(50,mean=10,sd=1) x_support = density(x)$x x_density = density(x)$y # see our example: plot(x_support, x_density ) # the real mean of x mean(x) ``` Now to 'reverse' the process we generate a large sample from that density distribution: ``` x_sampled = sample(x = x_support, 1000000, replace = T, prob = x_density) # get the statistics mean(x_sampled) median(x_sampled) var(x_sampled) etc... ```
62,671,936
I'm currently getting the error > > 'String cannot represent value: { year: { low: 2020, high: 0 }, month: { low: 7, high: 0 }, day: { low: 1, high: 0 }, hour: { low: 7, high: 0 }, minute: { low: 35, high: 0 }, second: { low: 45, high: 0 }, nanosecond: { low: 914000000, high: 0 }, timeZoneOffsetSeconds: { low: 0, high: 0 }, timeZoneId: null }' > > > which is caused by one of my properties being stored as `datetime()`. What would be the way to convert this into a string? I am using the neo4j-driver from npm
2020/07/01
[ "https://Stackoverflow.com/questions/62671936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6554121/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,936
I'm currently getting the error > > 'String cannot represent value: { year: { low: 2020, high: 0 }, month: { low: 7, high: 0 }, day: { low: 1, high: 0 }, hour: { low: 7, high: 0 }, minute: { low: 35, high: 0 }, second: { low: 45, high: 0 }, nanosecond: { low: 914000000, high: 0 }, timeZoneOffsetSeconds: { low: 0, high: 0 }, timeZoneId: null }' > > > which is caused by one of my properties being stored as `datetime()`. What would be the way to convert this into a string? I am using the neo4j-driver from npm
2020/07/01
[ "https://Stackoverflow.com/questions/62671936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6554121/" ]
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,936
I'm currently getting the error > > 'String cannot represent value: { year: { low: 2020, high: 0 }, month: { low: 7, high: 0 }, day: { low: 1, high: 0 }, hour: { low: 7, high: 0 }, minute: { low: 35, high: 0 }, second: { low: 45, high: 0 }, nanosecond: { low: 914000000, high: 0 }, timeZoneOffsetSeconds: { low: 0, high: 0 }, timeZoneId: null }' > > > which is caused by one of my properties being stored as `datetime()`. What would be the way to convert this into a string? I am using the neo4j-driver from npm
2020/07/01
[ "https://Stackoverflow.com/questions/62671936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6554121/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
62,671,961
I have a sparksession which I currently create like so: ``` spark = SparkSession.builder.master("local").appName("myapp").getOrCreate() ``` I would like to set the working directory of the spark master. It is currently using /tmp and I would like to use something else. I noticed there is a config(..) option, could I do something like: ``` spark = SparkSession.builder.master("local").appName("myapp").config("option", "value").getOrCreate() ``` Is there a list of options that are available somewhere? Should it be done in a different way?
2020/07/01
[ "https://Stackoverflow.com/questions/62671961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1648641/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,961
I have a sparksession which I currently create like so: ``` spark = SparkSession.builder.master("local").appName("myapp").getOrCreate() ``` I would like to set the working directory of the spark master. It is currently using /tmp and I would like to use something else. I noticed there is a config(..) option, could I do something like: ``` spark = SparkSession.builder.master("local").appName("myapp").config("option", "value").getOrCreate() ``` Is there a list of options that are available somewhere? Should it be done in a different way?
2020/07/01
[ "https://Stackoverflow.com/questions/62671961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1648641/" ]
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,961
I have a sparksession which I currently create like so: ``` spark = SparkSession.builder.master("local").appName("myapp").getOrCreate() ``` I would like to set the working directory of the spark master. It is currently using /tmp and I would like to use something else. I noticed there is a config(..) option, could I do something like: ``` spark = SparkSession.builder.master("local").appName("myapp").config("option", "value").getOrCreate() ``` Is there a list of options that are available somewhere? Should it be done in a different way?
2020/07/01
[ "https://Stackoverflow.com/questions/62671961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1648641/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
62,671,978
I use GPU for training a model with transfer learning from Inception v3. Weights='imagenet'. The convolution base is frozen and dense layers on top are used for 10 classes classification for MNIST digit recognition. The code is the following: ``` from keras.preprocessing import image datagen=ImageDataGenerator( #rescale=1./255, preprocessing_function=tf.keras.applications.inception_v3.preprocess_input, featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) zoom_range = 0.1, # Randomly zoom image width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=False, # randomly flip images vertical_flip=False) train_generator=datagen.flow_from_directory( train_path, target_size=(224, 224), color_mode="rgb", class_mode="categorical", batch_size=86, interpolation="bilinear", ) test_generator=datagen.flow_from_directory( test_path, target_size=(224, 224), color_mode="rgb", class_mode="categorical", batch_size=86, interpolation="bilinear", ) #Import pre-trained model InceptionV3 from keras.applications import InceptionV3 #Instantiate convolutional base conv_base = InceptionV3(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # 3 = number of channels in RGB pictures #Forbid training of conv part conv_base.trainable=False #Build model model=Sequential() model.add(conv_base) model.add(Flatten()) model.add(Dense(256,activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) # Define the optimizer optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) # Compile the model model.compile(optimizer=optimizer,loss="categorical_crossentropy",metrics=['accuracy'] ) history = model.fit_generator(train_generator, epochs = 1, validation_data = test_generator, verbose = 2, steps_per_epoch=60000 // 86) #, callbacks=[learning_rate_reduction]) ``` The obtained training rate was 1 epoch/hour (even after reducing lr to 0.001), when I used rescale=1./255 for data generator. After searching for answers, I found that the cause my be in not appropriate form for input. When I tried to use preprocessing\_function=tf.keras.applications.inception\_v3.preprocess\_input, I received a message after 30 min of training: ``` Epoch 1/1 /usr/local/lib/python3.6/dist-packages/keras/utils/data_utils.py:616: UserWarning: The input 1449 could not be retrieved. It could be because a worker has died. UserWarning) /usr/local/lib/python3.6/dist-packages/keras/utils/data_utils.py:616: UserWarning: The input 614 could not be retrieved. It could be because a worker has died. UserWarning) ``` What is wrong with the model? Thanks in advance.
2020/07/01
[ "https://Stackoverflow.com/questions/62671978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9349225/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,978
I use GPU for training a model with transfer learning from Inception v3. Weights='imagenet'. The convolution base is frozen and dense layers on top are used for 10 classes classification for MNIST digit recognition. The code is the following: ``` from keras.preprocessing import image datagen=ImageDataGenerator( #rescale=1./255, preprocessing_function=tf.keras.applications.inception_v3.preprocess_input, featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) zoom_range = 0.1, # Randomly zoom image width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=False, # randomly flip images vertical_flip=False) train_generator=datagen.flow_from_directory( train_path, target_size=(224, 224), color_mode="rgb", class_mode="categorical", batch_size=86, interpolation="bilinear", ) test_generator=datagen.flow_from_directory( test_path, target_size=(224, 224), color_mode="rgb", class_mode="categorical", batch_size=86, interpolation="bilinear", ) #Import pre-trained model InceptionV3 from keras.applications import InceptionV3 #Instantiate convolutional base conv_base = InceptionV3(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # 3 = number of channels in RGB pictures #Forbid training of conv part conv_base.trainable=False #Build model model=Sequential() model.add(conv_base) model.add(Flatten()) model.add(Dense(256,activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) # Define the optimizer optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) # Compile the model model.compile(optimizer=optimizer,loss="categorical_crossentropy",metrics=['accuracy'] ) history = model.fit_generator(train_generator, epochs = 1, validation_data = test_generator, verbose = 2, steps_per_epoch=60000 // 86) #, callbacks=[learning_rate_reduction]) ``` The obtained training rate was 1 epoch/hour (even after reducing lr to 0.001), when I used rescale=1./255 for data generator. After searching for answers, I found that the cause my be in not appropriate form for input. When I tried to use preprocessing\_function=tf.keras.applications.inception\_v3.preprocess\_input, I received a message after 30 min of training: ``` Epoch 1/1 /usr/local/lib/python3.6/dist-packages/keras/utils/data_utils.py:616: UserWarning: The input 1449 could not be retrieved. It could be because a worker has died. UserWarning) /usr/local/lib/python3.6/dist-packages/keras/utils/data_utils.py:616: UserWarning: The input 614 could not be retrieved. It could be because a worker has died. UserWarning) ``` What is wrong with the model? Thanks in advance.
2020/07/01
[ "https://Stackoverflow.com/questions/62671978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9349225/" ]
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,978
I use GPU for training a model with transfer learning from Inception v3. Weights='imagenet'. The convolution base is frozen and dense layers on top are used for 10 classes classification for MNIST digit recognition. The code is the following: ``` from keras.preprocessing import image datagen=ImageDataGenerator( #rescale=1./255, preprocessing_function=tf.keras.applications.inception_v3.preprocess_input, featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) zoom_range = 0.1, # Randomly zoom image width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=False, # randomly flip images vertical_flip=False) train_generator=datagen.flow_from_directory( train_path, target_size=(224, 224), color_mode="rgb", class_mode="categorical", batch_size=86, interpolation="bilinear", ) test_generator=datagen.flow_from_directory( test_path, target_size=(224, 224), color_mode="rgb", class_mode="categorical", batch_size=86, interpolation="bilinear", ) #Import pre-trained model InceptionV3 from keras.applications import InceptionV3 #Instantiate convolutional base conv_base = InceptionV3(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # 3 = number of channels in RGB pictures #Forbid training of conv part conv_base.trainable=False #Build model model=Sequential() model.add(conv_base) model.add(Flatten()) model.add(Dense(256,activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) # Define the optimizer optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) # Compile the model model.compile(optimizer=optimizer,loss="categorical_crossentropy",metrics=['accuracy'] ) history = model.fit_generator(train_generator, epochs = 1, validation_data = test_generator, verbose = 2, steps_per_epoch=60000 // 86) #, callbacks=[learning_rate_reduction]) ``` The obtained training rate was 1 epoch/hour (even after reducing lr to 0.001), when I used rescale=1./255 for data generator. After searching for answers, I found that the cause my be in not appropriate form for input. When I tried to use preprocessing\_function=tf.keras.applications.inception\_v3.preprocess\_input, I received a message after 30 min of training: ``` Epoch 1/1 /usr/local/lib/python3.6/dist-packages/keras/utils/data_utils.py:616: UserWarning: The input 1449 could not be retrieved. It could be because a worker has died. UserWarning) /usr/local/lib/python3.6/dist-packages/keras/utils/data_utils.py:616: UserWarning: The input 614 could not be retrieved. It could be because a worker has died. UserWarning) ``` What is wrong with the model? Thanks in advance.
2020/07/01
[ "https://Stackoverflow.com/questions/62671978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9349225/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
62,671,985
My initial matrix looks like the following (but my matrix is huge) ``` A NA A A A D D B NA B C NA C A NA A B B D C A NA A A NA A D NA D D A A A C NA C C NA C ``` ``` structure(c("A", "A", "D", NA, NA, NA, "A", "A", "D", "A", "B", "D", "A", "B", "A", "D", "D", "A", "D", "C", "A", "B", "A", "C", NA, NA, NA, "B", "A", "C", "C", "A", "C", NA, NA, NA, "C", "A", "C"), .Dim = c(3L, 13L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13"))) ``` I want to substitute the NA with the letters surroundings (left and right), if they are the same, that is, I want something like this: ``` A A A A A D D B B B C C C A A A B B D C A A A A A A D D D D A A A C C C C C C ``` ``` structure(c("A", "A", "D", "A", "A", "D", "A", "A", "D", "A", "B", "D", "A", "B", "A", "D", "D", "A", "D", "C", "A", "B", "A", "C", "B", "A", "C", "B", "A", "C", "C", "A", "C", "C", "A", "C", "C", "A", "C"), .Dim = c(3L, 13L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13"))) ``` So, if both surrounding letters are the same, I would change the NA to the surrounding letter, otherwise, I would keep the NA. Any ideas? Thank you very much.
2020/07/01
[ "https://Stackoverflow.com/questions/62671985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12682304/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,985
My initial matrix looks like the following (but my matrix is huge) ``` A NA A A A D D B NA B C NA C A NA A B B D C A NA A A NA A D NA D D A A A C NA C C NA C ``` ``` structure(c("A", "A", "D", NA, NA, NA, "A", "A", "D", "A", "B", "D", "A", "B", "A", "D", "D", "A", "D", "C", "A", "B", "A", "C", NA, NA, NA, "B", "A", "C", "C", "A", "C", NA, NA, NA, "C", "A", "C"), .Dim = c(3L, 13L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13"))) ``` I want to substitute the NA with the letters surroundings (left and right), if they are the same, that is, I want something like this: ``` A A A A A D D B B B C C C A A A B B D C A A A A A A D D D D A A A C C C C C C ``` ``` structure(c("A", "A", "D", "A", "A", "D", "A", "A", "D", "A", "B", "D", "A", "B", "A", "D", "D", "A", "D", "C", "A", "B", "A", "C", "B", "A", "C", "B", "A", "C", "C", "A", "C", "C", "A", "C", "C", "A", "C"), .Dim = c(3L, 13L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13"))) ``` So, if both surrounding letters are the same, I would change the NA to the surrounding letter, otherwise, I would keep the NA. Any ideas? Thank you very much.
2020/07/01
[ "https://Stackoverflow.com/questions/62671985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12682304/" ]
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,985
My initial matrix looks like the following (but my matrix is huge) ``` A NA A A A D D B NA B C NA C A NA A B B D C A NA A A NA A D NA D D A A A C NA C C NA C ``` ``` structure(c("A", "A", "D", NA, NA, NA, "A", "A", "D", "A", "B", "D", "A", "B", "A", "D", "D", "A", "D", "C", "A", "B", "A", "C", NA, NA, NA, "B", "A", "C", "C", "A", "C", NA, NA, NA, "C", "A", "C"), .Dim = c(3L, 13L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13"))) ``` I want to substitute the NA with the letters surroundings (left and right), if they are the same, that is, I want something like this: ``` A A A A A D D B B B C C C A A A B B D C A A A A A A D D D D A A A C C C C C C ``` ``` structure(c("A", "A", "D", "A", "A", "D", "A", "A", "D", "A", "B", "D", "A", "B", "A", "D", "D", "A", "D", "C", "A", "B", "A", "C", "B", "A", "C", "B", "A", "C", "C", "A", "C", "C", "A", "C", "C", "A", "C"), .Dim = c(3L, 13L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13"))) ``` So, if both surrounding letters are the same, I would change the NA to the surrounding letter, otherwise, I would keep the NA. Any ideas? Thank you very much.
2020/07/01
[ "https://Stackoverflow.com/questions/62671985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12682304/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
62,671,988
I am currently working on a Spring Boot REST application with Spring Security. My workplace use Auth0 (external third-party service providing user management) for their authentication and have requested me to implement it in this application. Authentication occurs in the front end application written in React. The frontend application shows a login form and sends the username and password to Auth0, Auth0 verifies the credentials and returns a JWT token when the user is validated. After this, the frontend application will call the REST services from my application passing a JWT token in the `Authorize` header. Using an Auth0 plugin, Spring Security verifies this token and the request is allowed to execute. I have tested this much to be working as expected. The code is as follows: ``` import java.util.Arrays; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import com.auth0.spring.security.api.JwtWebSecurityConfigurer; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ @Value(value = "${auth0.apiAudience}") private String apiAudience; @Value(value = "${auth0.issuer}") private String issuer; @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080")); configuration.setAllowedMethods(Arrays.asList("GET","POST")); configuration.setAllowCredentials(true); configuration.addAllowedHeader("Authorization"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); JwtWebSecurityConfigurer //Auth0 provided class performs per-authentication using JWT token .forRS256(apiAudience, issuer) .configure(http) .authorizeRequests() .antMatchers(HttpMethod.GET, "/Test/public").permitAll() .antMatchers(HttpMethod.GET, "/Test/authenticated").authenticated(); } } ``` Now, once this authentication is done, I have observed that the principal in the security context gets updated with user id from Auth0. I have verified this by this code snippet: ``` Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String name = authentication.getName(); // Returns the Auth0 user id. ``` The next step I expect to do is to use this user id to match the user with roles and permissions in my existing database schema. Therefore, I need to implement a custom authorization mechanism that plugs into Spring Security as well. In other words the user's roles must be loaded into the security context shortly after the (pre)authentication is done. How do I implement this? Is there some class that I need to extend or implement some interface?
2020/07/01
[ "https://Stackoverflow.com/questions/62671988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1586108/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,988
I am currently working on a Spring Boot REST application with Spring Security. My workplace use Auth0 (external third-party service providing user management) for their authentication and have requested me to implement it in this application. Authentication occurs in the front end application written in React. The frontend application shows a login form and sends the username and password to Auth0, Auth0 verifies the credentials and returns a JWT token when the user is validated. After this, the frontend application will call the REST services from my application passing a JWT token in the `Authorize` header. Using an Auth0 plugin, Spring Security verifies this token and the request is allowed to execute. I have tested this much to be working as expected. The code is as follows: ``` import java.util.Arrays; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import com.auth0.spring.security.api.JwtWebSecurityConfigurer; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ @Value(value = "${auth0.apiAudience}") private String apiAudience; @Value(value = "${auth0.issuer}") private String issuer; @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080")); configuration.setAllowedMethods(Arrays.asList("GET","POST")); configuration.setAllowCredentials(true); configuration.addAllowedHeader("Authorization"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); JwtWebSecurityConfigurer //Auth0 provided class performs per-authentication using JWT token .forRS256(apiAudience, issuer) .configure(http) .authorizeRequests() .antMatchers(HttpMethod.GET, "/Test/public").permitAll() .antMatchers(HttpMethod.GET, "/Test/authenticated").authenticated(); } } ``` Now, once this authentication is done, I have observed that the principal in the security context gets updated with user id from Auth0. I have verified this by this code snippet: ``` Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String name = authentication.getName(); // Returns the Auth0 user id. ``` The next step I expect to do is to use this user id to match the user with roles and permissions in my existing database schema. Therefore, I need to implement a custom authorization mechanism that plugs into Spring Security as well. In other words the user's roles must be loaded into the security context shortly after the (pre)authentication is done. How do I implement this? Is there some class that I need to extend or implement some interface?
2020/07/01
[ "https://Stackoverflow.com/questions/62671988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1586108/" ]
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,671,988
I am currently working on a Spring Boot REST application with Spring Security. My workplace use Auth0 (external third-party service providing user management) for their authentication and have requested me to implement it in this application. Authentication occurs in the front end application written in React. The frontend application shows a login form and sends the username and password to Auth0, Auth0 verifies the credentials and returns a JWT token when the user is validated. After this, the frontend application will call the REST services from my application passing a JWT token in the `Authorize` header. Using an Auth0 plugin, Spring Security verifies this token and the request is allowed to execute. I have tested this much to be working as expected. The code is as follows: ``` import java.util.Arrays; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import com.auth0.spring.security.api.JwtWebSecurityConfigurer; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ @Value(value = "${auth0.apiAudience}") private String apiAudience; @Value(value = "${auth0.issuer}") private String issuer; @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080")); configuration.setAllowedMethods(Arrays.asList("GET","POST")); configuration.setAllowCredentials(true); configuration.addAllowedHeader("Authorization"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); JwtWebSecurityConfigurer //Auth0 provided class performs per-authentication using JWT token .forRS256(apiAudience, issuer) .configure(http) .authorizeRequests() .antMatchers(HttpMethod.GET, "/Test/public").permitAll() .antMatchers(HttpMethod.GET, "/Test/authenticated").authenticated(); } } ``` Now, once this authentication is done, I have observed that the principal in the security context gets updated with user id from Auth0. I have verified this by this code snippet: ``` Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String name = authentication.getName(); // Returns the Auth0 user id. ``` The next step I expect to do is to use this user id to match the user with roles and permissions in my existing database schema. Therefore, I need to implement a custom authorization mechanism that plugs into Spring Security as well. In other words the user's roles must be loaded into the security context shortly after the (pre)authentication is done. How do I implement this? Is there some class that I need to extend or implement some interface?
2020/07/01
[ "https://Stackoverflow.com/questions/62671988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1586108/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
62,672,000
I have a `pandas` dateframe like the following, with `DATETIME` as index: ``` ID Val1 Val2 DATETIME 2019-01-18 10:35:00 A 482.84387 439.67942 2019-01-18 10:35:00 B -5.30216 20.22247 2019-01-18 10:40:00 A -790.63989 -810.00000 2019-01-18 10:40:00 B 257.00000 270.55490 2019-01-18 10:45:00 A 10.54820 5.64659 2019-01-18 10:45:00 B -85.50000 -89.00000 ``` Note that the `DATETIME` is repeated for `ID`s. My goal is to convert it to something like the following (with column names changed based on ID, if possible): ``` A_Val1 A_Val2 B_Val1 B_Val2 DATETIME 2019-01-18 10:35:00 482.84387 439.67942 -5.30216 20.22247 2019-01-18 10:40:00 -790.63989 -810.00000 257.00000 270.55490 2019-01-18 10:45:00 10.54820 5.64659 -85.50000 -89.00000 ``` I used `pandas.pivot` but it didn't work. `df_2= df_1.pivot(index=df_1.index, columns='ID', values=['Val1', 'Val2'])` error is: ``` "DatetimeIndex(['2019-01-18 10:35:00', '2019-01-18 10:35:00',\n ....],\n dtype='datetime64[ns]', name='DATETIME', freq=None) not in index" ``` I'm not sure where to go from there. Thanks in advance if you can help.
2020/07/01
[ "https://Stackoverflow.com/questions/62672000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5937757/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,672,000
I have a `pandas` dateframe like the following, with `DATETIME` as index: ``` ID Val1 Val2 DATETIME 2019-01-18 10:35:00 A 482.84387 439.67942 2019-01-18 10:35:00 B -5.30216 20.22247 2019-01-18 10:40:00 A -790.63989 -810.00000 2019-01-18 10:40:00 B 257.00000 270.55490 2019-01-18 10:45:00 A 10.54820 5.64659 2019-01-18 10:45:00 B -85.50000 -89.00000 ``` Note that the `DATETIME` is repeated for `ID`s. My goal is to convert it to something like the following (with column names changed based on ID, if possible): ``` A_Val1 A_Val2 B_Val1 B_Val2 DATETIME 2019-01-18 10:35:00 482.84387 439.67942 -5.30216 20.22247 2019-01-18 10:40:00 -790.63989 -810.00000 257.00000 270.55490 2019-01-18 10:45:00 10.54820 5.64659 -85.50000 -89.00000 ``` I used `pandas.pivot` but it didn't work. `df_2= df_1.pivot(index=df_1.index, columns='ID', values=['Val1', 'Val2'])` error is: ``` "DatetimeIndex(['2019-01-18 10:35:00', '2019-01-18 10:35:00',\n ....],\n dtype='datetime64[ns]', name='DATETIME', freq=None) not in index" ``` I'm not sure where to go from there. Thanks in advance if you can help.
2020/07/01
[ "https://Stackoverflow.com/questions/62672000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5937757/" ]
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
Since DateTime returns a bunch of neo4 int style stuff e.g. ``` DateTime { year: Integer { low: 2020, high: 0 }, month: Integer { low: 7, high: 0 }, day: Integer { low: 1, high: 0 }, hour: Integer { low: 8, high: 0 }, minute: Integer { low: 48, high: 0 }, second: Integer { low: 18, high: 0 }, nanosecond: Integer { low: 833000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } ``` I am converting the field with .toString() ``` export function convertDateToString ( date) : string { const date_values = []; for (const key in date) { const cursor = date[key]; if (cursor) { date_values.push(cursor.toString()); } } const the_date = new Date(...date_values as [number, number, number, number, number, number]); return the_date.toUTCString(); } ```
62,672,000
I have a `pandas` dateframe like the following, with `DATETIME` as index: ``` ID Val1 Val2 DATETIME 2019-01-18 10:35:00 A 482.84387 439.67942 2019-01-18 10:35:00 B -5.30216 20.22247 2019-01-18 10:40:00 A -790.63989 -810.00000 2019-01-18 10:40:00 B 257.00000 270.55490 2019-01-18 10:45:00 A 10.54820 5.64659 2019-01-18 10:45:00 B -85.50000 -89.00000 ``` Note that the `DATETIME` is repeated for `ID`s. My goal is to convert it to something like the following (with column names changed based on ID, if possible): ``` A_Val1 A_Val2 B_Val1 B_Val2 DATETIME 2019-01-18 10:35:00 482.84387 439.67942 -5.30216 20.22247 2019-01-18 10:40:00 -790.63989 -810.00000 257.00000 270.55490 2019-01-18 10:45:00 10.54820 5.64659 -85.50000 -89.00000 ``` I used `pandas.pivot` but it didn't work. `df_2= df_1.pivot(index=df_1.index, columns='ID', values=['Val1', 'Val2'])` error is: ``` "DatetimeIndex(['2019-01-18 10:35:00', '2019-01-18 10:35:00',\n ....],\n dtype='datetime64[ns]', name='DATETIME', freq=None) not in index" ``` I'm not sure where to go from there. Thanks in advance if you can help.
2020/07/01
[ "https://Stackoverflow.com/questions/62672000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5937757/" ]
This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else. ``` import { DateTime } from 'neo4j-driver'; /** * Convert neo4j date objects in to a parsed javascript date object * @param dateString - the neo4j date object * @returns Date */ const parseDate = (neo4jDateTime: DateTime): Date => { const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime; const date = new Date( year.toInt(), month.toInt() - 1, // neo4j dates start at 1, js dates start at 0 day.toInt(), hour.toInt(), minute.toInt(), second.toInt(), nanosecond.toInt() / 1000000 // js dates use milliseconds ); return date; }; ``` console.log output to compare dates - ``` DateTime { year: Integer { low: 2021, high: 0 }, month: Integer { low: 9, high: 0 }, day: Integer { low: 6, high: 0 }, hour: Integer { low: 15, high: 0 }, minute: Integer { low: 41, high: 0 }, second: Integer { low: 30, high: 0 }, nanosecond: Integer { low: 184000000, high: 0 }, timeZoneOffsetSeconds: Integer { low: 0, high: 0 }, timeZoneId: null } 2021-09-06T15:41:30.184Z ```
Look at neo4j.types.DateTime. ``` const datetime= new Date() const dateToNeo = neo4j.types.DateTime.fromStandardDate(datetime); ```
62,672,014
Hi I am trying to add some values from TextFormField to ListView when click on enter key . But getting the error setState() or markNeedsBuild() called during build My code is below . ``` class ScanBarcode extends StatefulWidget { @override _ScanBarcodeState createState() => _ScanBarcodeState(); } class _ScanBarcodeState extends State<ScanBarcode> { List<String> litems = []; final TextEditingController eCtrl = new TextEditingController(); @override Widget build(BuildContext ctxt) { return new Scaffold( appBar: new AppBar(title: new Text("Dynamic Demo"),), body: new Column( children: <Widget>[ new TextFormField( controller: eCtrl, maxLines: null, autovalidate: true, textInputAction: TextInputAction.none, // ignore: missing_return validator: (value) { if (value.isEmpty==false) { // if(eCtrl.text.trim()!='') { if (value.contains('\n')) { debugPrint(value); litems.add(value); // Append Text to the list eCtrl.clear(); // Clear the Text area setState(() {}); } } // } }, decoration: InputDecoration( border: InputBorder.none, hintText: 'Enter a search term' ), ), new Expanded( child: new ListView.builder ( itemCount: litems.length, itemBuilder: (BuildContext ctxt, int Index) { return new Text(litems[Index]); } ) ) ], ) ); } } ``` I am getting below error. ``` setState() or markNeedsBuild() called during build ``` if commented ``` setState() ``` it is working fine but the values are not added to list view .. Any help will be appreciated.
2020/07/01
[ "https://Stackoverflow.com/questions/62672014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1567706/" ]
You can copy paste run full code below You can use `addPostFrameCallback` code snippet ``` WidgetsBinding.instance.addPostFrameCallback((_) { setState(() {}); }); ``` working demo [![enter image description here](https://i.stack.imgur.com/YLzt0.gif)](https://i.stack.imgur.com/YLzt0.gif) full code ``` import 'package:flutter/material.dart'; class ScanBarcode extends StatefulWidget { @override _ScanBarcodeState createState() => _ScanBarcodeState(); } class _ScanBarcodeState extends State<ScanBarcode> { List<String> litems = []; final TextEditingController eCtrl = TextEditingController(); @override Widget build(BuildContext ctxt) { return Scaffold( appBar: AppBar( title: Text("Dynamic Demo"), ), body: Column( children: <Widget>[ TextFormField( controller: eCtrl, maxLines: null, autovalidate: true, textInputAction: TextInputAction.none, // ignore: missing_return validator: (value) { if (value.isEmpty == false) { // if(eCtrl.text.trim()!='') { if (value.contains('\n')) { debugPrint(value); litems.add(value); // Append Text to the list eCtrl.clear(); // Clear the Text area WidgetsBinding.instance.addPostFrameCallback((_) { setState(() {}); }); } } // } }, decoration: InputDecoration( border: InputBorder.none, hintText: 'Enter a search term'), ), Expanded( child: ListView.builder( itemCount: litems.length, itemBuilder: (BuildContext ctxt, int Index) { return Text(litems[Index]); })) ], )); } } void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: ScanBarcode(), ); } } ```
**Chunhunghan's** solution is a valid solution and still works. But, in my case, it's the future build & the stream builder. What I did is, I directly assigned the Future to a FutureBuilder, which gets called every time when the build() is called, which causes the Future method to re-call & reload my UI every time I touched/typed on a TextField/TextFormField. **The Solution:** Create a Future object & assign the Future method to that future object, then assign the future object to the FutureBuilder widget. **The Code:** ``` late Future _dataFuture; @override void initState() { super.initState(); _stream = _leadDatabase.listenLeads(); _dataFuture = _fetchData(); } //inside build() FutureBuilder(future: _dataFuture, builder:context, dataSnapshot) { //logics } ``` The same solution is applicable for StreamBuilder.
62,672,050
I want to popup iframe src(domain) when script load. I code simple code but it does not working. ``` <html> <title>Iframe load</title> <iframe src="https://evil.com/" id="site" width="800px" heigth="700px"></iframe> <script> var siteD = document.getElementById("site"); alert(siteD); </script> </html> ``` When page load its only showing me `[object HTMLIFrameElement]`. But i want to show in popup `evil.com` from src. I hope you understand my question.
2020/07/01
[ "https://Stackoverflow.com/questions/62672050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7486765/" ]
The cause: `alert()` wants to show a string, which is why it applies `toString()` to its parameter, and that does not render any of the properties of the object. You need to use `alert(siteD.src);` instead: ```js var siteD = document.getElementById("site"); alert(siteD.src); ``` ```html <iframe src="https://evil.com/" id="site" width="800px" heigth="700px"></iframe> ```
There's a simple answer to your question, `siteD` has a property `src` which you need to be alerting instead of `siteD` on its own. Here is an example with src as property: <https://codepen.io/dwaynehulsman/pen/rNxYYWQ>
62,672,089
Let's say I got this array ```js const items = ["foo", "bar", "baz"]; ``` and I got this object ```js const _obj = { foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3], moo: [1, 2, 3], tee: [1, 2, 3] }; ``` I would like to have all the object keys removed which are **not** present in the `items` array. So the result should be: ```js const _newObj = { foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3] } ``` As you can see, the properties `moo` and `tee` are not present in the object anymore, since they are not items of the array. I will use it like this: ```js const [obj, setObj] = useState({ foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3], moo: [1, 2, 3], tee: [1, 2, 3] }); const update = () => { setObj(prevObj => { // the magic should happen here return { ...prevObj }; }); } ``` **How would I accomplish this..?**
2020/07/01
[ "https://Stackoverflow.com/questions/62672089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10546688/" ]
You could map new entries and get a new object from it. ```js const items = ["foo", "bar", "baz"], object = { foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3], moo: [1, 2, 3], tee: [1, 2, 3] }, result = Object.fromEntries(items.map(key => [key, object[key]])); console.log(result); ``` A version which keeps the same object reference. ```js const items = ["foo", "bar", "baz"], object = { foo: [1, 2, 3], bar: [1, 2, 3], baz: [1, 2, 3], moo: [1, 2, 3], tee: [1, 2, 3] }; Object .keys(object) .filter(key => !items.includes(key)) .forEach(Reflect.deleteProperty.bind(null, object)); console.log(object); ```
Maybe using reduce: ```js const _newObj = Object.entries(_obj).reduce((acc, el) => { const [key, value] = el; if(items.includes(key)){ acc[key] = value; } return acc; },{}); ```