Sunday, November 28, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to define optional element in regex pattern with quanteda's kwic?

Posted: 28 Nov 2021 02:57 PM PST

I am struggling to 'translate' a regex expression from stringi/stringr to quanteda's kwic function.

How can I get all instances of "Jane Mayer", regardless of whether she has a middle name or not. Note that I don't have a list of all existing middle names in the data. So defining multiple patterns (one for each middle name) wouldn't be possible.

Many thanks!

library(quanteda)  library(tidyverse)  txt <- c("this is Jane Alexandra Mayer",            "this is Jane Mayer",           "this is Jane Eli Mayer",            "this is Jane Burger")    txt_token <- tokens(txt)    my_pattern <- c("Jane .* Mayer")  kwic(txt_token, pattern=phrase(my_pattern), valuetype = "regex")  #> Keyword-in-context with 2 matches.                                                 #>  [text1, 3:5] this is | Jane Alexandra Mayer |   #>  [text3, 3:5] this is |    Jane Eli Mayer    |    my_pattern <- c("Jane .? Mayer")  kwic(txt_token, pattern=phrase(my_pattern), valuetype = "regex")  #> Keyword-in-context with 2 matches.                                                 #>  [text1, 3:5] this is | Jane Alexandra Mayer |   #>  [text3, 3:5] this is |    Jane Eli Mayer    |    my_pattern <- c("Jane.* Mayer")  kwic(txt_token, pattern=phrase(my_pattern), valuetype = "regex")  #> Keyword-in-context with 1 match.                                       #>  [text2, 3:4] this is | Jane Mayer |    my_pattern <- c("Jane . Mayer")  kwic(txt_token, pattern=phrase(my_pattern), valuetype = "regex")  #> Keyword-in-context with 2 matches.                                                 #>  [text1, 3:5] this is | Jane Alexandra Mayer |   #>  [text3, 3:5] this is |    Jane Eli Mayer    |          With `stringr` I'll would simply use: str_extract(txt, regex("Jane.* Mayer"))  #> [1] "Jane Alexandra Mayer" "Jane Mayer"           "Jane Eli Mayer"        #> [4] NA  

Created on 2021-11-28 by the reprex package (v2.0.1)

How to create an Android 12 color adaptive Icon pack?

Posted: 28 Nov 2021 02:57 PM PST

Can anyone help me find a script or tutorial on how to make a dynamic icon pack for Android 12 that changes icon color based on the wallpaper and dark mode?

how to iterate over a list using one liner msl?

Posted: 28 Nov 2021 02:56 PM PST

i have a list , and a tuple (start,end,interval) i am trying to iterate over the list and return the elements that are in list from start to end with interval steps . for example:

cutt [1,2,3,4,77,8,7] (1,5,2);  val it = [2,4,8] : int list;  

the problem is that i want to write a function that does this using one line only which means no recursic function and no if condition also no pattern matching

i began by thinking i can cutt the list first only to elements between start and end using :

fun cutt list1 (start,end,interval) = List.drop(List.take(list1 ,end+1),start);  

and now i want to use maybe foldl or foldr to only get elements in interval jumps , my problem is how to iterate over the list ?

How do I filter only numbers that contains decimal greater than .00 in python/pandas?

Posted: 28 Nov 2021 02:56 PM PST

How do I filter only numbers that contains decimal greater than .00 in python/pandas?

dct = {'Lineitem price':[4.00,5.65,1.22,8.00,10.78,7.00,2.85]  

Basically I would like to keep only the numbers 5.65, 1.22, 10.78 , 2.85 , this would be for a muuch larger dataframe, so this dictionary is just to summarize my problem...

How do I locate or generate the .NET source files for AWS CDK

Posted: 28 Nov 2021 02:56 PM PST

I'm trying to get the .NET source code, not the TypeScript source code. I've googled for quite a while and tried to dig through the main source code repository for documentation on this. Not finding answers.

What are the drawbacks of changing an internal python method?

Posted: 28 Nov 2021 02:55 PM PST

I believe I've gotten into a bad habit recently when working with python. Sometimes, an internal method doesn't have all of the features I want, so I redefine the method locally. For example, I wanted to use the filter() method to search for methods in a module.

items=(x if 'query' in x.lower() else False for x in dir(module))  

which returns a huge list. I wanted to filter this down with filter(), but the method seemed weirdly limited. The initial solution was:

items_filtered=filter(lambda x: x,items)  print([x for x in items_filtered.__iter__()])  

Which seems like more lines than I want. Also I didn't like that iter() wipes the array clean, which is frustrating for notebook environments like Jupiter. I redefined the filter method as:

_filter = filter  class filter(_filter):    def __init__(self,*args,**kwargs):      _filter.__init__(*args,**kwargs)      itr = self.__iter__      self.values = [x for x in self.__iter__()]      self.__itr__ = itr  

which allows the one liner to be

items=filter(lambda x,(x if 'query' in x.lower() else False for x in dir(module))).values  

This is obviously not the 'right' way to handle these situations, but will it break anything when used in the wrong way?

Can't get PHP to work on Mac Os 12 -- it shows the code when opening Safari

Posted: 28 Nov 2021 02:55 PM PST

I am trying to set up PHP on my Macbook M1 Air, and it won't work. I have followed every step of this guide, and when I run info.php on Safari, I can read the actual code instead of seeing PHP info:

https://getgrav.org/blog/macos-monterey-apache-multiple-php-versions

Slow startup when extracting thumbnails from UDP live stream using FFMpeg

Posted: 28 Nov 2021 02:54 PM PST

I'm running the following command using FFMpeg to extract an image every 1 second from a UDP stream:

ffmpeg -i "udp://224.1.2.123:9001" -s 256x144 -vf fps=1 -update 1 test.jpg -y

This works well, but it takes about 5 seconds to actually start producing images. Is there any way to lower the startup time?

The UDP stream uses mpegts format and is encoded with H264/AAC.

Thanks!

PHP Regex the nested section based on defined parent

Posted: 28 Nov 2021 02:56 PM PST

I am trying to match a nested content section of the config based on the alias.

I have the base prototype working for matching single aliases over here: https://regex101.com/r/1vwKsx/1 (section correctly matched to: 'template_path_stack' =>)

HOWEVER, I want to select a section (which is re-used in the file) based on the section container. In the link above, I need to only match the section which is inside: controllers => factories.

The problem is that the regex matches both (the correct one and the one from the outside). https://regex101.com/r/IrV0SN/1

Current regex:

('factories' => )(\[((?>[^\[\]]++|(?2))*)\])  

Showing favicon while compiling with parcel

Posted: 28 Nov 2021 02:56 PM PST

I'm attempting to declare a favicon on my webapp which is compiled with parcel. From my project directory, my icon is located in static/icon.ico.

Using this in the head of my HTML did not display the icon.

<link rel="shortcut icon" href="/static/icon.ico">    

This StackOverflow post says I need to use parcel-plugin-static-files-copy with some settings in package.json to get it to compile properly, so I installed it in my project directory, and then added this to my package.json

  "staticFiles": {      "staticPath": [        {          "staticPath": "static/icon.ico",          "watcherGlob": "**"        }      ]    }  

I'm not returning any errors, but the icon doesn't display and I do get this warning when trying to open with Chrome after compiling with Parcel.

localhost/:1 Each dictionary in the list "icons" should contain a non-empty UTF8 string field "type".  localhost/:1 Each dictionary in the list "icons" should contain a non-empty UTF8 string field "type".  localhost/:1 Each dictionary in the list "icons" should contain a non-empty UTF8 string field "type".  localhost/:1 Each dictionary in the list "icons" should contain a non-empty UTF8 string field "type".  

What could be causing this?

How would I correctly format my blackjack python script because right now it is not how I want it [closed]

Posted: 28 Nov 2021 02:54 PM PST

In my script, the code runs properly and everything but it doesn't truly work like blackjack. When I run it, it prints out my 2 randomly assigned cards, then I have to hit or stay, but the problem is that in blackjack you're supposed to be able to see one of your opponent's cards before you choose to hit or stand. How could I incorporate this into my script?If it helps more copy and paste my script into python

from random import choice      def total(hand):      aces = hand.count(11)      t = sum(hand)      if t > 21 and aces > 0:          while aces > 0 and t > 21:                t -= 10              aces -= 1      return t    two=[]  cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]        while True:      player = []      player.append(choice(cards))      player.append(choice(cards))      playerbust = False      compbust = False          while True:          tp = total(player)          print ("You has these cards %s and your value is %d" % (player, tp))          if tp > 21:              print ("You busted!")              playerbust = True              break          elif tp == 21:              print ("\a nice you got a blackjack")              break          else:              hs = input("hit or stand (h or s): ").lower()              if 'h' in hs:                  player.append(choice(cards))              else:                  break          while True:          comp = []          comp.append(choice(cards))          comp.append(choice(cards))          while True:              tc = total(comp)                              if tc < 18:                  comp.append(choice(cards))              else:                  break          print ("the computer has %s which means they have %d" % (comp, tc))              if tc > 21:              print ("The computer busted")              compbust = True              if playerbust == False:                  print ("You win")            elif tc > tp:              print ("The computer wins!")          elif tc == tp:              print ("It's a draw!")          elif tp > tc:              if playerbust == False:                  print ("You wins!")                elif compbust == False:                  print ("The computer wins!")            break      print        exit = input("Press Enter to play again or no to quit ").lower()      if 'no' in exit:          break      print    print  print ("Thanks for playing")  

How to add an arrayList to this child class?

Posted: 28 Nov 2021 02:57 PM PST

Context - So there are two classes that uses inheritance. The EmployeeService is the parent class and the EmployeeInfo is the child class.

What do I need help with - So I am trying to insert an arrayList to the parent class that combines the information of the experience and position and makes a new arrayList called serviceList.

And when I call a super() in the child class, I should be able to call the arrayList rather than the String variables (experience, position).

To put it short, I should basically be able to pass an arrayList as the third parameter in the child class employeeInfo method instead of String experience or String position

Parent class -

public class EmployeeService () {      private String experience;      private String position;            public EmployeeService (String experience, String position) {          this.setExperience (experience);          this.setPosition(position);      }            public String getExperience() {          return experience;      }        public void setExperience(String experience) {          this.experience = experience;      }            public String getPosition() {          return position;      }        public void setPosition(String position) {          this.position = position;      }            public String toString() {          return "Experience - " + experience + "Position" + " - " + position;      }        }    

Child class -

public class EmployeeInfo () {      private String firstName;      private String address;            public EmployeeInfo (String firstName, String address,String experience, String position) {          super(experience, position);          this.setFirstName (firstName);          this.setAddress(address);      }            public String getFirstName() {          return firstName;      }        public void setFirstName(String firstName) {          this.firstName = firstName;      }            public String getAddress() {          return address;      }        public void setAddress(String address) {          this.address = address;      }            public String toString() {          return "Name - " + firstName + "Address" + " - " + address + super.toString();      }  }  

R: Count number of times B follows A using dplyr

Posted: 28 Nov 2021 02:55 PM PST

I have a data.frame of monthly averages of radon measured over a few months. I have labeled each value either "below" or "above" a threshold and would like to count the number of times the average value does: "below to above", "above to below", "above to above" or "below to below".

df <- data.frame(value = c(130, 200, 240, 230, 130),                   level = c("below", "above","above","above", "below"))  

A bit of digging into Matlab answer on here suggests that we could use the Matrix package:

require(Matrix)  sparseMatrix(i=c(2,2,2,1), j=c(2,2,2))  

Produces this result which I can't yet interpret.

[1,] | |  [2,] | .  

Any thoughts about a tidyverse method?

How to reduce a string by another string in Python?

Posted: 28 Nov 2021 02:56 PM PST

I would like to remove all characters from a first string s1 exactly the number of times they appear in another string s2, i.e. if s1 = "AAABBBCCCCCCD" and s2 = "ABBCCC" then the result should be s = "AABCCCD".

The following rather crude code can achieve this:

def reduce_string(s1, s2):      s = s1      for c in s2:          if c in s:              s = s.replace(c, "", 1)      return(s)    # examples  reduce_string("AAABBBCCCCCCD", "ABBCCC")  reduce_string("AAABBBCCCCCCD", "ABBCCCE")  

My question is, can the same be achieved by clever use of some built-in function or at least in a more elegant way? Thank you for all your answers!

python select the dataframe column with the oldest date for each user

Posted: 28 Nov 2021 02:57 PM PST

This question seems super easy but I just can't figure it out.

I have the following dataframe:

watched_df = pd.DataFrame([['Love Death Robots', '2016-01-29 14:04:22', 'Anna'],                      ['James Bond', '2016-02-29 14:04:22', 'Anna'],                     ['Lord of the Rings', '2016-09-29 14:04:22', 'BoB'],                      ['The Hobbit', '2016-10-29 14:04:22', 'Anna'],                     ['Beauty and the Beast', '2016-06-29 14:04:22', 'BoB']],                     columns=['Title', 'Date', 'Profile_Name'])  watched_df.head()  

For each user I want to know what is the 'Title' of the first movie the 'Profile_Name' has watched and on what 'date' it was.

So the wanted result is:

wanted_df = pd.DataFrame([['Love Death Robots', '2016-01-29 14:04:22', 'Anna'],                      ['Beauty and the Beast', '2016-06-29 14:04:22', 'BoB']],                     columns=['Title', 'Date', 'Profile_Name'])  wanted_df.head()  

I managed to get a dataframe that is indexed by the 'Profile_Name' and the respective oldest dates. But I cannot manage to add the 'Title' to the dataframe

C++ Weird File Line Read

Posted: 28 Nov 2021 02:56 PM PST

I'm new to C++ programming and trying to figure out a weird line read behavior when reading a line from a text file. For this specific program, I have to wait for the user to press enter before reading the next line.

If I hard code the file name, the file read starts at line 1 as expected:

#include <iostream>  #include <fstream>  using namespace std;    int main(void) {     ifstream in_file;     in_file.open("test.txt");       // read line by line     string line;       while (getline(in_file, line)) {        cout << line;        cin.get();     }       in_file.close();     return 0;  }  

I compile with g++ -Wall -std=c++14 test1.cpp -o test1 and get:

$ ./test  This is line one.  **user presses enter**  This is line two.  **user presses enter**  This is line three.  etc. etc.  

But when I add in the option to have the user type in a file name, the line read starts at line 2:

#include <iostream>  #include <fstream>  using namespace std;    int main(void) {     string filename;     cin >> filename;          ifstream in_file;     in_file.open(filename);       // read line by line     string line;       while (getline(in_file, line)) {        cout << line;        cin.get();     }       in_file.close();     return 0;  }  

The same compile command gives me:

$ ./test2  test.txt  This is line two.  **user presses enter**  This is line three.  **user presses enter**  This is line four.  etc. etc.  

Am I missing something here? I have no idea why it starts reading at line 2 when I add in the code to specify a file name. Am I not finishing the cin statement properly or something?

Thanks!

LazyVStack - row onAppear is called early

Posted: 28 Nov 2021 02:56 PM PST

I have a LazyVStack, with lots of rows. Code:

struct ContentView: View {      var body: some View {          ScrollView {              LazyVStack {                  ForEach(0 ..< 100) { i in                      Text("Item: \(i + 1)")                          .onAppear {                              print("Appeared:", i + 1)                          }                  }              }          }      }  }  

Only about 40 rows are visible on the screen initially, yet onAppear is triggered for 77 rows. Why is this, why is it called before it is actually visible on the screen? I don't see why SwiftUI would have to 'preload' them.

Is there a way to fix this, or if this is intended, how can I accurately know the last visible item (accepting varying row heights)?

Python Logging Equal Length String of Log Level

Posted: 28 Nov 2021 02:55 PM PST

When using the logging module in python, displaying the logging level makes them all different lengths. With using a formatting string of "[%(levelname)s] - %(message)s", the log file looks like this:

[DEBUG] - Message  [INFO] - Message  [WARNING] - Message  [ERROR] - Message  [CRITICAL] - Message  

However, I would really like it if the log levels took up the same amount of space. Is there a way to make the output look similar to this:

[  DBUG  ] - Message  [  INFO  ] - Message  [  WARN  ] - Message  [  EROR  ] - Message  [CRITICAL] - Message  

Whether that entails shortening the level names, or just adding padding to the sides of the names doesn't really matter to me. Just some way of getting everything to line up after the level name is what I'm after.

How to arrange plots in specific positions on a grid in R?

Posted: 28 Nov 2021 02:56 PM PST

I am trying to plot multiple plots (of different sizes) onto a grid, using specific coordinates. To do this, I am creating a treemap using the treemap package to get coordinates and then, using these coordinates, Im trying to place my individual plots. Hopefully my example below will explain better my problem.

To begin, I create some barplots and then, I create a treemap, like so:

library(ggplot2)  library(treemap)  #create data  df <- data.frame(var1 = c("A", "B", "C"),               var2 = runif(3),               var3 = runif(3),               var4 = runif(3),               size = c(10, 5, 3),               labels = c(1:3))  # Basic barplot  p1 <- ggplot(data=df, aes(x=var1, y=var2)) +     geom_bar(stat="identity")  p2 <- ggplot(data=df, aes(x=var1, y=var3)) +     geom_bar(stat="identity")  p3 <- ggplot(data=df, aes(x=var1, y=var4)) +    geom_bar(stat="identity")    #create treemap  tm <- treemap(df,         index = "labels",         vSize = "size",         palette = "Set2")  

If we take a look at the treemap object tm, we can see that it provides the coordinates of the treemap shown below, where x0, y0, w, and h are the coordinates.

> tm$tm    labels vSize vColor stdErr vColorValue level        x0    y0         w     h   color  1      1    10      1     10          NA     1 0.0000000 0.000 0.5555556 1.000 #66C2A5  2      2     5      1      5          NA     1 0.5555556 0.375 0.4444444 0.625 #FC8D62  3      3     3      1      3          NA     1 0.5555556 0.000 0.4444444 0.375 #8DA0CB  

treemap

So, what Im trying to do is to take my three barplots p1,p2,and p3 and place them into the treemap so that p1 will be in position 1 of the treemap.... p2 will be in position 2 etc...

For clarity, My desired result would look something like this: treemap of plots

Any suggestions as to how I could do this? I tried using the patchwork package but ran into issues of the plots overlapping... but im open to suggestions using any package (eg gridExtra or just ggplot)

EDIT to clarify things a little, as per the answer given by Peter below in relation to the patchwork package, I cant manually input the coordinates as the plot layout (I was originally using the area function in patchwork and inputting the coordinates of the treemap into the area function). But, as mentioned in the comments below, if I have numerous barplots, and the size and shape of the treemap changes, then I cant manually input the layout values. I am trying to find a way to automate the process

Impoting specific Class from a Python module with `importlib`

Posted: 28 Nov 2021 02:54 PM PST

How would one go about importing a specific Class from a Python module using its path?

I need to import a specific Class from a Python file using the file path.
I have no control over the file and its completely outside of my package.


file.py:

class Wanted(metaclass=MyMeta):      ...    class Unwanted(metaclass=MyMeta):      ...  

The Metaclass implementation is not relavant here,
however, I will point out that its part of my package and I have full contol over it.

import example:

spec = importlib.util.spec_from_file_location(name='Wanted', location="path_to_module/mudule.py")  module = importlib.util.module_from_spec(spec)  spec.loader.exec_module(module)  

This works, and Wanted is imported.
The problem is that Unwanted is also imported.
Infact, as long as there ANY srt value given for name(including empty string)
both Wanted & Unwanted are imported from the module.

This has the same effect as in the example before, where both Wanted & Unwanted are imported:
importlib.util.spec_from_file_location(name='random string', location="path_to_module/mudule.py")

I'm not looking for a specific solution using importlib
and any reasonable way will do.
I will point out that I dont have a need of using the Class when its imported,
I only need the import to happen and my Metaclass will take care of the rest.

sorting odd number in a new array, output problem

Posted: 28 Nov 2021 02:57 PM PST

to store odd numbers from a user inputed array(arr) in a new array(arr1), then printing. run and see output first

#include <stdio.h>  int main()  {      int i;      int arr1[100];      int arr[5] = {2, 3, 8, 9, 11};      for (i = 0; i <= 5; i++)      {          for (int x = 1; x < 12; x++)          {              if (x == arr[i])              {                  arr1[i] = arr[i];              }              x += 1;          }      }      for (i = 0; i < 5; i++)      {          printf("%d\n", arr1[i]);      }        return 0;  }  

Making a histogram from Json data

Posted: 28 Nov 2021 02:55 PM PST

I have data in JSON format that looks something like this

{     "ts": 1393631983,     "visitor_uuid": "ade7e1f63bc83c66",     "visitor_source": "external",     "visitor_device": "browser",     "visitor_useragent": "Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.16",     "visitor_ip": "b5af0ba608ab307c",     "visitor_country": "BR",     "visitor_referrer": "53c643c16e8253e7",     "env_type": "reader",     "env_doc_id": "140222143932-91796b01f94327ee809bd759fd0f6c76",     "event_type": "pagereadtime",     "event_readtime": 1010,     "subject_type": "doc",     "subject_doc_id": "140222143932-91796b01f94327ee809bd759fd0f6c76",     "subject_page": 3  } {      "ts": 1393631983,      "visitor_uuid": "232eeca785873d35",      "visitor_source": "internal",      "visitor_device": "browser",      "visitor_useragent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36",      "visitor_ip": "fcf9c67037f993f0",      "visitor_country": "MX",      "visitor_referrer": "63765fcd2ff864fd",      "env_type": "stream",      "env_ranking": 10,      "env_build": "1.7.118-b946",      "env_name": "explore",      "env_component": "editors_picks",      "event_type": "impression",      "subject_type": "doc",      "subject_doc_id": "100713205147-2ee05a98f1794324952eea5ca678c026",      "subject_page": 1  }  

My task requires me to find subject_doc_id that matches an input from user and then display a histogram showing the countries in which that document has been viewed.

I have been able to read through the data that with my code and I am also familiar with how to plot a histogram but I need help on how to count the countries and display that in the histogram.

For example here in the data above "visitor_country":"MX" and "visitor_country":"BR" exist so I want the count of each country.

Any ideas on how I can achieve that?

memcpy() is faster than "direct" memory access?

Posted: 28 Nov 2021 02:54 PM PST

I need to compute the MD5 hash of a large (e.g. several GB) block of memory.

Data is already loaded in memory. And physical RAM is bigger than data, so nothing is swapped out (presumably). Consequently, the most straight-forward approach is to simply pass the base address and the total size of the memory block into a single invocation of the md5_update() function and that's it. But I found this solution to be rather slow!

By a lot of testing, I found that stepping trough the memory block, with a step size of 8 Byte (64-Bit), and using memcpy() to "load" small chunks (8 byte each) from that memory block into a local variable of type uint64_t, which then are passed individually into repeated calls of md5_update(), is actually a whole lot faster! I mean like 5+ times faster.

So, can anybody explain to me: How can it be that, even with the "overhead" of the additional copy operations (and also many more small md5_update() invocations), the memcpy() approach still appears to be many times faster than the simple "direct" (linear) memory access?

My first idea was that memcpy() may do some "smart" prefetching to get chunks of bytes more quickly from RAM into CPU cache, whereas md5_update() interneally just iterates over the given memory range in a byte-by-byte fashion. So I changed my "stepping" loop to not use memcpy() but instead pass 8 byte chunks "directly" from the memory block into md5_update(). Additionally I added _mm_preftech() to prefetch each chunk before it is passed into md5_update() function. But this came out exactly as slow as passing the whole block into md5_update() at once!

Only with the memcpy() and an additional local variable as "buffer" I can get a huge speed up.


Original "slow" version:

void test(const uint8_t *const data, const size_t size, uint8_t *const digest)  {      md5_context_t ctx;      md5_init(&ctx);      md5_update(&ctx, data, size);      memcpy(digest, md5_finalize(&ctx), 16U);  }  

"Fast" version with memcpy():

void test2(const uint8_t *const data, const size_t size, uint8_t* const digest)  {      const uint8_t* p;      uint64_t temp;      md5_context_t ctx;      const uint8_t* const end = data + size;      md5_init(&ctx);      for (p = data; p < end; p += sizeof(uint64_t))      {          memcpy(&temp, p, sizeof(uint64_t));          md5_update(&ctx, (const uint8_t*)&temp, sizeof(uint64_t));      }      memcpy(digest, md5_finalize(&ctx), 16U);  }  

Please assume that the above sample code is called with a pointer to the base address and the size of a large block of memory that is already allocated in the RAM (heap space).

Note: Tested with VS2022 as well as VS2017. Always in "Release" mode (/O2). It was tested on my main develpment machine with Windows 11 and also on an older Windows 8.1 machine.

Note #2: I used the delta of clock() before/after whole computation to compare speeds.


[UPDATE] Please see a full example here:

Sample output:

Computing hash #1, please wait...  Done.    4591E000A32043C6EBF7E63647786C9B  Time #1: 844582                    <-- direct memory access    Computing hash #2, please wait...  Done.    4591E000A32043C6EBF7E63647786C9B  Time #2: 123811 (0.15)             <-- with memcpy(), about ~6x faster!  

Accessing objects with same id

Posted: 28 Nov 2021 02:55 PM PST

For the sake of reproducibility im reusing an object multiple times rather than creating a new one,

Im adding the Factory object into the main Layout and using the remove button i can remove the added object,

But if i add 2 or more objects into the Layout the remove function only works for the last added object

So is there any mechanism that can generate a unique id for an object which can be then used to delete it

Code

from kivymd.app import MDApp  from kivy.lang import Builder  from kivy.factory import Factory     kv='''    <Image_1@BoxLayout>:        orientation:'vertical'      id:img_1         Image:          source:"/storage/emulated/0/Download/download (37).jpeg"      Button:          text:"remove"          on_press:app.remove()             BoxLayout:      orientation:'vertical'                                      GridLayout:          cols:1          id:sc_grid                    Button:              size_hint:None,None               text:"add"              on_press:                  app.add_1()                                          '''    class MyApp(MDApp):            def build(self):          return Builder.load_string(kv)            def add_1(self):          self.Image_1=Factory.Image_1()          self.root.ids.sc_grid.add_widget(self.Image_1)      def remove(self):          self.root.ids.sc_grid.remove_widget(self.Image_1)            MyApp().run()  

Is it possible to make v-for variables dynamic in vue?

Posted: 28 Nov 2021 02:57 PM PST

<div class="col-3" v-for="n in 5"  :key="n">        <h3>Table {{n}}</h3>        <draggable class="list-group" :list="`list${n}`" group="people" @change="log">          <div            class="list-group-item"            v-for="`(element, index) in list${n}`"            :key="element.name"          >            {{ element.name }} {{ index }}          </div>        </draggable>      </div>  

Why can't I set the v-for or :list as a concatenated string? Is there any way around this?

Full code:

<template>    <div class="row">      <component      v-for="(component, index) in components"      :key="index"      :is="component"    />      <div class="col-3" v-for="n in listNumber"  :key="n">        <h3>Table {{n}}</h3>        <draggable class="list-group" :list="list${n}" group="people" @change="log">          <div            class="list-group-item"            v-for="(element, index) in list${n}"            :key="element.name"          >            {{ element.name }} {{ index }}          </div>        </draggable>      </div>      </div>  </template>    <script>  import draggable from "vuedraggable";  let id = 1;  export default {    name: "two-lists",    display: "Two Lists",    order: 1,    components: {      draggable,      list:[],    },    data() {      return {                list1: [          { name: "John", id: 1 },          { name: "Joao", id: 2 },          { name: "Jean", id: 3 },          { name: "Gerard", id: 4 }        ]        },        {        list2: [          { name: "Juan", id: 5 },          { name: "Edgard", id: 6 },          { name: "Johnson", id: 7 }        ],            listNumber: 3,      }    },    created(){        console.log(this.list);      },    methods: {            add: function() {        this.list.push({ name: "Juan" });      },      replace: function() {        this.list = [{ name: "Edgard" }];      },      clone: function(el) {        return {          name: el.name + " cloned"        };      },      }  };  </script>  

Using A* with target ouside graph

Posted: 28 Nov 2021 02:57 PM PST

My goal is to find the shortest path between A and B but B might be outside of the known graph. Currently my cost function works perfectly and heuristics function is 3D euclidean.

To solve the problem of target might be outside of the graph, I've tried to exit the algorithm when priority value stopped changing a certain time but that didn't worked. The algorithm spitted out a random path.

The reason why I don't select a node that is closest to the target is that if I select that algorithm will try to reach that point for certain. In my application I will rerun the algorithm when new information comes (i.e. update to the graph that might include the target).

So what I need is to find a path that is closest to target outside graph with least cost. I don't expect a code or whatsoever as an answer but any comment on how this kind of problem might be solved is greatly appreciated.

Below, I've added my A* implementation, PriorityQueue is just an wrapper for heapq.

def a_star_search(mesh, start, goal):      frontier = PriorityQueue()      frontier.put(start, 0)      came_from = {}      cost_so_far = {}      came_from[start] = None      cost_so_far[start] = 0        while not frontier.empty():          current = frontier.get()            if current == goal:              break            for i, next in enumerate(list(mesh.neighbors(current))):              new_cost = cost_so_far[current] + mesh.cost(current, next)              if next not in cost_so_far or new_cost < cost_so_far[next]:                  cost_so_far[next] = new_cost                  priority = new_cost + mesh.heuristic(next, goal) / mesh.unit                  frontier.put(next, priority)                  came_from[next] = current        return came_from, cost_so_far  

Example result when target is inside graph Example result when target is inside graph

How to run @Async method inside the @Scheduled one

Posted: 28 Nov 2021 02:54 PM PST

I have read many questions and answers about using @Scheduled with @Async in Spring but no one resolves my problem and my asynchronous method still runs single-threaded. So here is my Configuration class:

@EnableScheduling  @EnableAsync  @Configuration  @RequiredArgsConstructor  public class SchedulerConfiguration {        private final ThreadPoolProperties threadPoolProperties;        @Bean      public TaskExecutor commonTaskExecutor() {          ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();          taskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize()); // 10          taskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize()); // 20          taskExecutor.setQueueCapacity(threadPoolProperties.getQueueCapacity()); // 5          taskExecutor.setThreadNamePrefix("TEST");          taskExecutor.initialize();          return taskExecutor;      }  }  

Then we have a bean with the @Scheduled method:

@Component  @RequiredArgsConstructor  public class ScheduledTask {        private final ConfirmReservationTask confirmReservationTask;        @Scheduled(cron = "${booking.scheduler.confirmReservationsCron}")      public void process() {          confirmReservationTask.confirmReservations();      }  }  

And finally, another bean (to avoid self-injection and proxy problems with asynchronous processing) with @Async method:

@Log4j2  @Component  @RequiredArgsConstructor  public class ConfirmReservationTask {        private final ReservationService reservationService;        @Async("commonTaskExecutor")      public void confirmReservations() {      ...      }  }  

unfortunately, this solution works in only one thread, however, the method uses the correct ThreadExecutor. How to solve it?

How to install RStudio on Raspberry Pi(RaspbianOS)

Posted: 28 Nov 2021 02:55 PM PST

How to install RStudio on RaspbianOS?!! I have tried Ubuntu MATE 64 and 32 bit but neither work! Even wget or using the installer (by installer I mean Pi-gpk-dbus-service) or nothing works! It says something like Failed to install because some package is missing. But I do have have R-Base and it works on neither Ubuntu or RaspbianOS! So I can infer the issue is with my Raspberry Pi. But how do I solve this issue? How to actually install RStudio on a Raspberry Pi(RaspbianOS)? Please let me know if it is even possible to install RStudio on a Raspberry Pi.

Spring feature OutputCapture does not work in valid spring boot version

Posted: 28 Nov 2021 02:57 PM PST

I cannot use the feature with OutputCapture within JUnit testing. I want to use this feature to see some log messages. If I tried to include the class package org.springframework.book.test.rule.OutputCapture in IDEA it shows me warn message "No suggestions". So that I am not able to access to outputCapture class (even test package is not visible).

As I found out on this website this class is supported since version 1.3. However I am using correct spring boot version 1.5.

import org.junit.Rule;  import org.junit.Test;  import org.springframework.boot.test.rule.OutputCapture; THIS IS NOT RECOGNIZED    import static org.hamcrest.Matchers.*;  import static org.junit.Assert.*;    public class MyTest {        @Rule      public OutputCapture capture = new OutputCapture();        @Test      public void testName() throws Exception {          System.out.println("Hello World!");          assertThat(capture.toString(), containsString("World"));      }    }  

What is wrong?

Django modelform NOT required field

Posted: 28 Nov 2021 02:55 PM PST

I have a form like this:

class My_Form(ModelForm):      class Meta:          model = My_Class          fields = ('first_name', 'last_name' , 'address')  

How can I put the address field as optional?

No comments:

Post a Comment