Create Python Enum referencing a list with TkImages Posted: 07 Apr 2022 11:12 AM PDT I've got a couple of Images in a folder and each of these gets resized and turnded into a Image for Tkinter. I want to use these images in other python scripts as a enum. This is how i create the Images. ''' import os from PIL import Image, ImageTk from enum import Enum #Resize All Images and turn them into TkImages def ResizeImages(): PieceImages = [] for images in os.listdir('Resources'): cImage = Image.open('Resources/' + images) cImage = cImage.resize((80, 80), Image.ANTIALIAS) PieceImages.append(ImageTk.PhotoImage(cImage)) return PieceImages #Called from outside to create PNGS list AFTER Tkinter.Tk() was called def InitializeImages(): global PNGS PNGS = ResizeImages() #This is the part where I'm lost class Black(Enum): global PNGS Queen = PNGS[3] King = PNGS[4] Tower = PNGS[5] ''' I want to create a Tkinter Button with these images on like this: ''' #PieceImages is the .py file above import PieceImages import Black form tkinter import * root = Tk() root.geometry('800x800') someButton = tk.Button(root, image=Black.Tower).place(x=100, y=100) ''' My Question is: Is it even possible to create enums of this type and if so, how? Thanks to everyone who takes his time for this :) |
handle checked exception in RxJava 2 Posted: 07 Apr 2022 11:12 AM PDT I have some issue when I try to catch exception. I have some method like this (legacy method) : public String myLegacyMethod throws MyException() { //do something or throw MyException in case of error } and I need to send a Single of this part and my solution is: public Single<String> reactiveMethod() { try { String s = myLegacyMethod(); return Single.just(s); } catch (Exception e) { //log exception return Single.error(e); } } are there a way to handle an exception in reactive way? or maybe transform reactiveMethod in non-blocking code? thanks for your answers. |
matching two elements of two arrays in react Posted: 07 Apr 2022 11:12 AM PDT I need to match two elements of two arrays in react, it's like matching exercises. the problem is that i don't even understand the logic and i don't have any idea. I have 2 arrays, an array of questions and an array of answers which are inside div, so when i click on a question i can choose the matching answer by clicking on it. this what i've tried so far const [selectedQuestion, setSelectedQuestion] = useState(); const [selectedAnswer , setSelectedAnswer] = useState(); const [couple , setCouple] = useState(); const [matches , setMatches] = useState([]); The idea is that after generating a couple i will add it to the matches array, but i have to test first if a couple if generated and that he has a question and an answer, second thing. In the case when user clicks question and clicks another question we have to replace the qestion choosen. please help i'm new to react and i'm struggling |
Prevent a string with from being cast to an int with try/catch Posted: 07 Apr 2022 11:12 AM PDT I am using try/catch exception to sore a vector of strings and I want to prevent it from converting a string like "157cm" from being converted to an int. It removes the "cm" part. Is there anyway to prevent this? My code: for (int v = 0; v < values.data.size(); v++) { try { int value = std::stod(values.data.at(v)); values.areints2.push_back(value); } catch (std::exception& e) { string x; x = values.data.at(v); values.notints2.push_back(x); } } |
the function get dose not work with plot in r? Posted: 07 Apr 2022 11:11 AM PDT having this: set.seed(2015-04-13) d = data.frame(x =seq(1,10), n1 = c(0,0,1,2,3,4,4,5,6,6), logp = signif(-log10(runif(10)), 2))> i=1 This works fine barplot(d$n1,main=NA,col='grey40', axes=F,border=NA,space=0)> but with get, i got error barplot(d$get(paste0("n",i)),main=NA,col='grey40', axes=F,border=NA,space=0) Error in h(simpleError(msg, call)) : attempt to apply non-function or with paste0 barplot(d$paste0("n",i),main=NA,col='grey40', axes=F,border=NA,space=0) Error in h(simpleError(msg, call)) : |
E-mail piping with e-mail forwarder does not work Posted: 07 Apr 2022 11:11 AM PDT I have a simple email pipe script. But I need a copy of the incoming e-mail going to another e-mailadress. Unfortunately I do not receive the e-mail as I wanted. Can somebody please help me? Thanks in advance! The code; #!/usr/bin/php -q <?php $email_msg = ''; // the content of the email that is being piped $email_addr = 'sales@flensmuts.nl'; // where the email will be sent $subject = 'Piped:'; // the subject of the email being sent // open a handle to the email $fh = fopen("php://stdin", "r"); // read through the email until the end while (!feof($fh)){ $email_msg .= fread($fh, 1024); } fclose($fh); // send a copy of the email to your account mail($email_addr, $subject, "Piped Email: ".$email_msg); ?> |
Trying to add data to different dictionaries and print one then another Posted: 07 Apr 2022 11:11 AM PDT I am trying to create two different dictionaries with my code, then, print them separately. I've been messing with the update() function but nothing is working, here is my code. def readTempData(filename): with open(filename, 'r') as f: for line in f.readlines(): day, high, low = line.split(',') high = int(high) low = int(low) day = int(day) highs = dict.update({'Day: {}, High: {}'}.format(day, high)) lows = dict.update({'Day: {}, Low: {}'}.format(day, low)) print(highs) print(lows) readTempData(input("Enter file name:")) AttributeError: 'set' object has no attribute 'format' Thank you in advance for any help! |
How can I do a transition from one node to other? The "always" option does not appear, and I'm not know js code to put there Posted: 07 Apr 2022 11:11 AM PDT |
Question about natural language processing Posted: 07 Apr 2022 11:11 AM PDT I am working on a graduation project related to "Aspect extraction (AE)". I'm pretty confused about POS taging, syntax tree, grammar rules, and other low-level NLP stuff. I need a reference that teaches me these things in detail, so if any of you know I hope you don't mind me? I know my question is not about programming directly and this may not agree with the site, but I really need to. |
MEAN Stack, Heroku, and TailwindCSS | Website is showing a blank screen Posted: 07 Apr 2022 11:11 AM PDT I'm building a website using the MEAN stack (TailwindCSS for the CSS styling) and deploying it on Heroku. The website is blank: https://bitesizedtreasures.herokuapp.com/ Could someone assist? Link to Github code: https://github.com/BiteSizedtreasures/website/tree/heroku-deploy tailwind.config.js module.exports = { content: ['./src/**/*.{html,js}', './node_modules/tw-elements/dist/js/**/*.js' ], theme: { colors: { 'blue': '#1fb6ff', 'purple': '#7e5bef', 'lite-pink': '#F7DAD9', 'orange': '#ff7849', 'green': '#13ce66', 'yellow': '#ffc82c', 'gray-dark': '#273444', 'gray': '#8492a6', 'gray-light': '#d3dce6', 'bluesign': '#007AFF', blue: colors.blue, yellow: colors.amber, gray: colors.slate, white: colors.white, }, fontFamily: { sans: ['Graphik', 'sans-serif'], serif: ['Salsa', 'serif'], }, fontSize: { 'xs': '.75rem', 'sm': '.875rem', 'tiny': '.875rem', 'base': '1rem', 'lg': '1.125rem', 'xl': '1.25rem', '2xl': '1.5rem', '3xl': '1.875rem', '4xl': '2.25rem', '5xl': '3rem', '6xl': '4rem', '7xl': '5rem', }, }, plugins: [ require('tw-elements/dist/plugin') ] }; angular.json "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "angular-src": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" }, "@schematics/angular:application": { "strict": true } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "outputPath": "dist/angular-src", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "customWebpackConfig": { "path": "webpack.config.js" }, "inlineStyleLanguage": "scss", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "3mb", "maximumError": "6mb" }, { "type": "anyComponentStyle", "maximumWarning": "3mb", "maximumError": "6kb" } ], "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "outputHashing": "all" }, "development": { "buildOptimizer": false, "optimization": false, "vendorChunk": true, "extractLicenses": false, "sourceMap": true, "namedChunks": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-builders/custom-webpack:dev-server", "configurations": { "production": { "browserTarget": "angular-src:build:production" }, "development": { "browserTarget": "angular-src:build:development" } }, "defaultConfiguration": "development" }, "extract-i18n": { "builder": "ngx-build-plus:extract-i18n", "options": { "browserTarget": "angular-src:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "inlineStyleLanguage": "scss", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] } } } } }, "defaultProject": "angular-src" } server.js if(server_port == 8080) { app.use(express.static(path.join(__dirname + "/public/"))); app.get("/*", (req, res) => { const fullPath = path.join(__dirname, "/public/index.html"); console.log(" Fetching from.. " + fullPath); res.sendFile(fullPath); }); } else { app.use(express.static(path.join(__dirname + "/angular-src/dist/angular-src"))); // Used for deployment app.get("/*", (req, res) => { const fullPath = path.join(__dirname,"/angular-src/dist/angular-src/index.html"); console.log(" Fetching from.. " + fullPath); res.sendFile(fullPath); }); } // Start Server app.listen(server_port, () => { if(server_port == 8080) { // development status console.log(`Listening at http://${process.env.HOST_NAME}:${server_port}`); } else { // deployment status console.log("Server listening on port " + server_port); } }); |
Execute two functions inside map function javascript Posted: 07 Apr 2022 11:12 AM PDT I have this await Promise.all( activeSupporters.map(async (item: Transactions) => { return EmailPayment.confirmedSupport(item); }) ); } But I also want EmailPayment.confirmedSupportCollaborator(item); to execute inside that map function. Can I do that? |
how to get image last launched time using awscli or boto3 Posted: 07 Apr 2022 11:10 AM PDT using the AWS console on the ami page I can see an attribute called Last launched time that shows the last time an instance was launched with this image (i assume) I try to get this attribute using the describe-images ec2 API but it doesn't show it as far as I can tell. is there any way to get this information using code? |
Iterate over list in Python using for loop Posted: 07 Apr 2022 11:11 AM PDT The below is my script in main.py which I was hoping would return "true", but doesn't seem to register anything: main.py import config business_number = int(678) for company in config.companies: if int(company.business_id) == business_number: print("True") config.py: companies: [Company] = [ Company("ABC", "345", 3.00, 10.00, 200.00), Company("DEF", "678", 5.00, 10.00, 500.00) ] company .py class Company: name = None business_id = None max_share_price = None min_total = None max_total = None def __init__(self, name, business_id, max_share_price, min_total, max_total): self.name = name self.business_id = business_id self.max_share_price = max_share_price self.min_total = min_total self.max_total = max_total |
How can I seamlessly and descretely communicate new URI launch parameters to a currently running application in Windows? Posted: 07 Apr 2022 11:11 AM PDT Case: Click a URL in the browser and a video game that is currently running on user's desktop can ingest that data and do something. I've been working on this for some time, but I don't know if I'm on the right path. What I currently have: A clickable URI in a webpage that can have different arguments for the client to recieve. The URI scheme is registered in Windows. When clicking URI in the browser it will launch a c++ console 'launcher' or 'bridge' app that is already installed on the user's PC. This 'launcher' is a middle-man that parses the URI arguments and communicates them to the main 'user' app (a video game) via IPC named pipes. How do I: In terms of UX, make the whole process descrete and seamless? Specifically, I need to: Keep launcher hidden from the user - no pop-up. Needs to be only capable of running a single instance, even when invoked with new URI parameters. Do I just exit the current and create a new one? User can click another URI in the webpage and the launcher will process the new arguments without displaying itself to the user. Tech constraints: Windows. Preferably needs to be C++. C# could be a possibily. Existing example: Zoom conferencing software appears to works similar to this. Clicking a URL in the browser launches a 'launcher' which starts the main app to video conference. Closing that 'launcher' will minimize it into the system tray. Clicking on a new link while the launcher is running does not start a new launcher, but it does start a new meeting. How does something like this normally work? |
How to draw 2 histograms in 1 table? Posted: 07 Apr 2022 11:12 AM PDT I was planning to combine these 2 histograms under 1 table. Also they need to be side by side, i.e., data cannot overlap each other. df.hist(column='oq_len', bins = 25, color = 'blue') df.hist(column='cq_len', bins = 25, color = 'red') plt.show() enter image description here enter image description here |
Fix aspect ratio of a scatter plot with an image Posted: 07 Apr 2022 11:12 AM PDT I've to plot multiple scatter and table in a grid space and I'm having a couple of issues with the relative position but most important with defining and maintaining the aspect ratio of the scatter plot. I've written a script with "fake" data on it to describe my problem and a minimum "not working" example below. What I have is a dataframe with x, and y positions of objects, and what I want to do is to put the corresponding image below. Since the image can have an arbitrary aspect ratio I need to read the aspect ratio and construct the scatter plot in that way but I'm unable to make it work. Another problem is connected with the invert_xaxis and invert_yaxis that don't work (I need that command since the scatter data are inverted. I've used the following commands, and as far as I've understood each of them should block the aspect ratio of the scatter plot to the same ratio of the figure but they do not work. The aspect ratio becomes corrected only when the figure is plotted but that eliminates the effect of axis inversion. I've had a similar problem with setting the aspect ratio of plots without the addition of a figure, sometimes it worked but not with tight_layout. It is obvious that I'm missing something important....but I'm unable to figure it out. This is the fake data code: ############################################################################### # fake data #general data aspect ratio image_height= 5 #4270 image_width = 10 # 8192 pix2scale = 0.3125 data_AR = image_height / image_width #random data generation data_width = image_width* pix2scale data_height = image_height * pix2scale data1x = np.random.uniform(-data_width/2, data_width/2, size=(40)) data1y = np.random.uniform(-data_height/2, data_height/2, size=(40)) data2x = np.random.uniform(-data_width/2, data_width/2, size=(40)) data2y = np.random.uniform(-data_height/2,data_height/2, size=(40)) temp_df1 = pd.DataFrame([data1x,data1y,['random1']*40],index = ['x','y','label']).T temp_df2 = pd.DataFrame([data2x,data2y,['random2']*40],index = ['x','y','label']).T df = pd.concat([temp_df1,temp_df2],axis = 0, ignore_index = True) del temp_df1, temp_df2 #sample image generation of variable aspect ratio img_size = (image_height, image_width) R_layer = np.ones(shape= img_size)*0.50 G_layer = np.ones(shape= img_size)*0.50 B_layer = np.ones(shape= img_size)*0.50 A_layer = np.ones(shape= img_size) img = np.dstack([R_layer,G_layer,B_layer,A_layer]) #add a mark at the top left of the image for k in range(0,3): for i in range(0,int(image_width*0.2*data_AR)): for j in range(0,int(image_width*0.2)): img[i,j,k] = 0 #add a mark at the center of the image # get center coordinates of the image center = [[2, 4], [2, 5]] for k in range(0,3): for point in center: if k == 0: img[point[0],point[1],k] = 1 else: img[point[0],point[1],k] = 0 #show image fig, ax = plt.subplots() ax.imshow(img) ############################################################################### this is the code that generates the image: #%% # sample code # at this point Iìve already loaded the image, the pix2scale value # and the df containing data points #read image aspect ratio img_AR = img.shape[0]/img.shape[1] pixel_width = img.shape[1] pixel_height = img.shape[0] # each pixel correspond to 0.3125 unit (mm) pix2scale = 0.3125 #define image position #the center of the image need to be placed at (0,0) #bottom left corner left = - (pixel_width * pix2scale)/2 bottom = - (pixel_height * pix2scale)/2 right = left + (pixel_width * pix2scale) top = bottom + (pixel_height * pix2scale) extent = [left,right,bottom,top] #figure definition figure_width = 15 #inch figure_AR = 1 scatter_AR = img_AR #initialize figure fig_s= plt.figure(figsize = (figure_width,figure_width*figure_AR)) gs = plt.GridSpec (3,3) #scatter plot in ax1 ax1 = fig_s.add_subplot(gs[:2,:2]) g = sns.scatterplot( data = df, x = 'x', y = 'y', hue = 'label', ax =ax1 ) ax1.invert_xaxis() ax1.invert_yaxis() #resize the figure box box = ax1.get_position() ax1.set_position([box.x0,box.y0,box.width*0.4,box.width*0.4*scatter_AR]) ax1.legend(loc = 'center left', bbox_to_anchor = (1,0.5)) ax1.set_title('Inclusions Scatter Plot') ax1.set_aspect(scatter_AR) #plt image ax1.imshow(img,extent = extent) #scatter plot ax2 = fig_s.add_subplot(gs[2,:2]) g = sns.scatterplot( data = df, x = 'x', y = 'y', hue = 'label', ax =ax2 ) #resize the figure box box = ax2.get_position() ax2.set_position([box.x0,box.y0,box.width*0.4,box.width*0.4*scatter_AR]) ax2.legend(loc = 'center left', bbox_to_anchor = (1,0.5)) ax2.set_title('Inclusions Scatter Plot') ax2.set_aspect(scatter_AR) ax2.imshow(img,extent = extent) #scatter plot ax3 = fig_s.add_subplot(gs[1,2]) g = sns.scatterplot( data = df, x = 'x', y = 'y', hue = 'label', ax =ax3 ) #resize the figure box box = ax3.get_position() ax3.set_position([box.x0,box.y0,box.width*0.4,box.width*0.4*scatter_AR]) ax3.legend(loc = 'center left', bbox_to_anchor = (1,0.5)) ax3.set_title('Inclusions Scatter Plot') ax3.set_aspect(scatter_AR) ax3.imshow(img,extent = extent) #add suptitle to figure fig_s.suptitle('my title',fontsize= 22) fig_s.subplots_adjust(top=0.85) # #make it fancy for i in range(3): fig_s.tight_layout() plt.pause(0.2) I've plotted multiple grid because I wanted to test the tight_layout(). [enter image description here][2] |
JAVA: Different console output in normal and debugging modes using try-catch Posted: 07 Apr 2022 11:12 AM PDT I'm a novice in Java, trying to understand behaviour of JVM. Well, I have a simple code: public class MyClass { public static void main(String[] args) { System.out.println(anotherMethod(5)); System.out.println(anotherMethod(0)); } private static Integer anotherMethod(int x) { try { return 10 / x; } catch (ArithmeticException e) { e.printStackTrace(); return 0; } } } In normal mode it returns in console: 2 0 java.lang.ArithmeticException: / by zero at MyClass.anotherMethod(MyClass.java:9) at MyClass.main(MyClass.java:4) But in debugging mode it returns (and I think this is more correctly): 2 java.lang.ArithmeticException: / by zero at MyClass.anotherMethod(MyClass.java:9) at MyClass.main(MyClass.java:4) 0 I placed breakpoint in line "System.out.println(anotherMethod(5));" Please, would you be able to explain why the output differs between each other? From my perspective it should be the same and correspond to the second output mentioned in my question. Thank you so much in advance! |
VBA set range syntax Posted: 07 Apr 2022 11:12 AM PDT I have tried variations of whatever I could find so far, but no luck. Does anyone notice an error in my syntax? I get the error "Run-time error '1004': Method 'Range' of object '_Global" failed. Here is the snippet of code I am referring to: Sub newVariable() Dim a As Range Set a = Range(".Cells(1,1), .Cells(5,1)") End Sub |
On a Laravel 'update' function, how to parse a JSON object, and store it with a ForEach loop Posted: 07 Apr 2022 11:11 AM PDT I am using the Laravel framework to work with my MySQL database, and currently want to update my database from a JSON object, that will be sent from somewhere else. Currently, I have it the same as my 'Store' function, which is obviously not going to work, because it will update everything, or refuse to work because it is missing information. This is the for each I have currently, it does not work, but I am not experienced with how it is best to parse a JSON with a for-each, then store it. public function update(Request $request,$student) { $storeData = User::find($student); foreach ($request as $value) { $storeData-> username = $value; } Here is my store function, with all the info that the front-end team may send in a JSON format. $storeData->username=$request->input('username'); $storeData->password=$request->input('password'); $storeData->email=$request->input('email'); $storeData->location=$request->input('location'); $storeData->role=DB::table('users')->where('user_id', $student)->value('role'); $storeData->devotional_id=$request->input('devotional_id'); $storeData->gift_id=$request->input('gift_id'); $storeData->save(); return dd("Info Recieved"); |
Issues with FileReader and Java GUI/jForm Posted: 07 Apr 2022 11:12 AM PDT I am trying to make a smaller version of Pwned Passwords (https://haveibeenpwned.com/Passwords) for my Ap comp sci project. Everything is goo besides 2 things: (Issue 1) (image of my code to show better) I have this below my jForm source code which declares each button/etc and what they do. I get this error though: "Illegal static declaration in inner class PassCheck.check. I do not now how to resolve this issue. The second issue is using FileReader and Buffered Reader. I want the program to read the text inputted from the jForm and compare it to a file which has a list of commonly used passwords. How can I do this? Here is my code so far of just practicing with FR and BR: import java.io.*; public class MainFileReader { public static void main(String[] args) throws Exception{ String refpass, input; input = "1234"; FileReader fr = new FileReader("C:\\Users\\tcoley\\Downloads\\207pass.txt"); BufferedReader br = new BufferedReader(fr); while((input = br.readLine()) != null){ refpass = br.readLine(); And I stopped here. I apologize as Java is not my strong suit but any help is much appreciated! |
Can I send files one by one to the client with Flask? Posted: 07 Apr 2022 11:11 AM PDT Let's say I have a lot of images and it takes 1 hour to loop through them. I want to send to the client the images that suit a condition. I don't want to send all of them at the same time because the client will have to wait 1 hour to get the images. I want to send the images one at a time, as soon as each image passed the condition. The code below won't send any file to the client because the object created by send_file needs to be returned. Of course, if I return the object, only the first file will be sent. @app.route('/img_process', methods=['POST']) def img_process(): for file in files: if condition: send_file(photo_path, mimetype='image/jpg') |
How to display code "< />" as plain text in React? Posted: 07 Apr 2022 11:12 AM PDT I want to display < /> as plain text on my react page. I tried <code> </code> and I have also tried using < > but it doesn't work. Does anyone know how to do it? Many thanks |
What does this mean "if (!(i % 10) && i)" Posted: 07 Apr 2022 11:12 AM PDT What does this line of code mean, I found this in this piece of code: void simple_print_buffer(char *buffer, unsigned int size) { unsigned int i; i = 0; while (i < size) { if (i % 10) { printf(" "); } if (!(i % 10) && i) { printf("\n"); } printf("0x%02x", buffer[i]); i++; } printf("\n"); } |
Seems like I have lots of space outside of the boot disk but I can't install packages - how do I clear space? Ubuntu GCloud VM Posted: 07 Apr 2022 11:12 AM PDT Here is the output of df -H . I keep deleting caches and tmp directories but the problem keeps resurfacing. Any tips on how I might clear out more space? My home directory is only taking up 3GB - including Python packages and so on, not sure where the 104GB is being taken up. I deleted snapd earlier because all the loop devices were full with vnode tables; any time I try to install a package, for instance, xdiskusage , I get the error ` After this operation, 525 MB of additional disk space will be used. E: You don't have enough free space in /var/cache/apt/archives/... df -H Filesystem Size Used Avail Use% Mounted on /dev/root 104G 104G 0 100% / devtmpfs 180G 0 180G 0% /dev tmpfs 180G 0 180G 0% /dev/shm tmpfs 36G 3.6G 33G 10% /run tmpfs 5.3M 0 5.3M 0% /run/lock tmpfs 180G 0 180G 0% /sys/fs/cgroup /dev/sda15 110M 5.5M 104M 5% /boot/efi tmpfs 36G 0 36G 0% /run/user/2002 |
Source Generator Testing Posted: 07 Apr 2022 11:11 AM PDT I'm trying to develop a source generator that I can theoretically add to my projects, and for the given project have it find classes that are marked up with a specific attribute, and then build a corresponding generated file for each. I've set up unit tests that effectively use GeneratorDriver to instantiate and run generators and evaluate their output. Problem Classes exist in a secondary project referenced from the test project. The compilation does not appear to include syntaxTree's for the other project. I've tried calling CreateCompilation with a simple program.cs body, and calling .AddReferences(MetadataReference.CreateFromFile(typeof(User).Assembly.Location) , and then passing that to the in driver. At runtime, my syntax trees are still all the same (perhaps because I assume that reference is treated like an assembly reference. I assume in normal situations, generators will run with the context of projects they are referenced from as an Analyzer , but for the purposes of my unit testing, is there a way I can effectively set the compilation to be another project, or reference another project (such that when I walk the different syntax trees, I can access those classes marked with attributes in an external assembly)? |
parse json file to Pydntic model Posted: 07 Apr 2022 11:12 AM PDT I created a model of Pydantic. But it does not convert and outputs an error Please tell me,what is wrong. classDTO : from pydantic import BaseModel,Field from typing import List,Dict from datetime import date class OurBaseModel(BaseModel): pass #class Config: #orm_mode = True class SessionSubjectDTO(OurBaseModel): edu_year: int semester_type: str class MarkDTO(OurBaseModel): semester_number: int subject_name: str control_type: str mark: str # or int session_subject: SessionSubjectDTO #= Field(None, alias="SessionSubjectDTO") class MarksDTO(OurBaseModel): __root__: List[MarkDTO] class AttestationDTO(BaseModel): subject_name: str value: int attestation_start_date: date class AttestationsDTO(OurBaseModel): __root__: List[AttestationDTO] class DebtDTO(OurBaseModel): semester_number: int subject_name: str control_type: str session_subject: SessionSubjectDTO #= Field(None, alias="SessionSubjectDTO") class DebtsDTO(OurBaseModel): __root__: List[DebtDTO] class SkipDTO(OurBaseModel): valid: int no_valid: int attestation_start_date: date class SkipsDTO(OurBaseModel): __root__: List[SkipDTO] class StudentDTO(OurBaseModel): uid: str marks: MarksDTO attestations: AttestationsDTO debts: DebtsDTO skips: SkipsDTO class StudentsDTO(OurBaseModel): __root__: List[StudentDTO] example.json : [ { "uid": "61c689ac-98a1-11e9-8198-4ccc6a2d123b", "marks": [ { "semester_number": 1, "subject_name": "454", "control_type": "5", "mark": "3.", "date": "2019-12-27", "session_subject": { "id": 4228, "edu_year": 2019, "semester_type": "1" } } ], "attestations": [ { "subject_name": "133", "value": 2, "attestation_start_date": "2019-10-07", "attestation_end_date": "2019-10-12" } ], "debts": [ { "semester_number": 4, "subject_name": "323", "control_type": "12", "session_subject": { "id": 22856, "edu_year": 2020, "semester_type": "20" } } ], "skips": [ { "valid": null, "no_valid": null, "attestation_start_date": "2020-03-09", "attestation_end_date": "2020-03-14" } ] } ] main.py : students = pydantic.parse_file_as(path='192.json', type_=classDTO.StudentsDTO) Errors: Traceback (most recent call last): File "main.py", line 73, in <module> students = pydantic.parse_file_as(path='192.json', type_=classDTO.StudentsDTO) File "pydantic\tools.py", line 60, in pydantic.tools.parse_file_as File "pydantic\tools.py", line 38, in pydantic.tools.parse_obj_as File "pydantic\main.py", line 331, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 424 validation errors for ParsingModel[StudentsDTO] __root__ -> __root__ -> 0 -> attestations -> __root__ -> 18 -> value none is not an allowed value (type=type_error.none.not_allowed) __root__ -> __root__ -> 0 -> attestations -> __root__ -> 19 -> value none is not an allowed value (type=type_error.none.not_allowed) __root__ -> __root__ -> 0 -> attestations -> __root__ -> 20 -> value none is not an allowed value (type=type_error.none.not_allowed) ... __root__ -> __root__ -> 16 -> skips -> __root__ -> 1 -> no_valid none is not an allowed value (type=type_error.none.not_allowed) I tried to solve the problem with Custom Root Types: Pydantic models can be defined with a custom root type by declaring the field. __root__ The root type can be any type supported by pydantic, and is specified by the type hint on the __root__ field. The root value can be passed to the model __init__ via the __root__ keyword argument, or as the first and only argument to parse_obj . |
I cannot generate the ECDSA public key from her private key sequentially Posted: 07 Apr 2022 11:11 AM PDT I cannot generate the public keys in sequence. output :./keysgo.go:33:33: cannot use PrivateKey (type []byte) as type string in argument to Public Thank you so much for your help important to keep this part: func Public(PrivateKey string) (publicKey string) { var e ecdsa.PrivateKey e.D, _ = new(big.Int).SetString(PrivateKey, 16) e.PublicKey.Curve = secp256k1.S256() e.PublicKey.X, e.PublicKey.Y = e.PublicKey.Curve.ScalarBaseMult(e.D.Bytes()) return fmt.Sprintf("%x", elliptic.MarshalCompressed(secp256k1.S256(), e.X, e.Y)) i tried this package main import ( "crypto/ecdsa" "crypto/elliptic" "fmt" "math/big" "github.com/ethereum/go-ethereum/crypto/secp256k1" ) func Public(PrivateKey string) (publicKey string) { var e ecdsa.PrivateKey e.D, _ = new(big.Int).SetString(PrivateKey, 16) e.PublicKey.Curve = secp256k1.S256() e.PublicKey.X, e.PublicKey.Y = e.PublicKey.Curve.ScalarBaseMult(e.D.Bytes()) return fmt.Sprintf("%x", elliptic.MarshalCompressed(secp256k1.S256(), e.X, e.Y)) } func main() { count, one := big.NewInt(1), big.NewInt(1) count.SetString("9404625697166532776746648320380374280100293470930272690489102837043110636674",10) PrivateKey := make([]byte, 32) for { count.Add(count, one) copy(PrivateKey[32-len(count.Bytes()):], count.Bytes()) fmt.Printf("%x\n",Public(PrivateKey)) } } } |
Pure JavaScript Datepicker displays calendar only once to never do it again in a Shopify cart page Posted: 07 Apr 2022 11:11 AM PDT To achieve greater performance with our Shopify store, we decided to minimize use of jQuery across the site. In cartpage, I added a pure JavaScript datepicker that sometimes displays the calendar just once and never afterwards. I ensured only one version of jQuery loads in the theme, thinking multiple instances from other Shopify apps might be causing this issue. But even with a single jQuery instance being loaded now in the theme, the issue still persists. I don't see any console errors. Please add a product to the cart and go to the cart page to see this issue by clicking the date picker. Below is the link to the preview theme. Following is the datepicker code for pickaday plugin. <div class="cart-attribute__field"> <p> <label for="ship_date">Ordering early? Pick a future ship date here:</label> <input id="ship_date" type="text" name="attributes[ship_date]" value="{{ cart.attributes.ship_date }}" /> </p> </div> <p class="shipping-text">If you are placing an order with <b>a future ship date</b> that <u>also</u> includes multiple addresses please email <a href="mailto:support@packedwithpurpose.gifts" target="_blank">support@packedwithpurpose.gifts</a> upon placing your order to confirm your preferred ship date.</p> <!-- Added 11162020 --> <p class="shipping-text">Please note that specifying a date above ensures your gift is packaged and shipped on that date. <b>This is not a delivery date.</b> As we work with third party shipping agencies, your delivery date is subject to the specific carrier selected as well as your shipping destination. Please find our estimated shipping transit times for all regions of the US <strong><a href="https://packedwithpurpose.gifts/shipping-returns/" target="_blank" style="text-decoration: underline;">here</a></strong>.</p> <script type="text/javascript"> (function() { var disabledDays = ["2022-12-23","2022-12-24","2022-12-25","2022-12-30","2022-12-31","2023-1-1"]; var minDate = new Date(); var maxDate = new Date(); maxDate.setDate((maxDate.getDate()) + 60); minDaysToShip = 2; // Default minimum days if (minDate.getDay() == 5) { // Friday. Set min day to Tuesday. 4 days from now. minDaysToShip = 4; } else if (minDate.getDay() == 6) { // Saturday. Set min day to Tuesday. 3 days from now. minDaysToShip = 3; } minDate.setDate(minDate.getDate() + minDaysToShip); var picker = new Pikaday( { field: document.getElementById('ship_date'), format: 'MM/DD/YYYY', disableWeekends: 'true', toString(date, format) { // you should do formatting based on the passed format, // but we will just return 'D/M/YYYY' for simplicity const day = ("0" + date.getDate()).slice(-2); // Get two digit month ("0" + (this.getMonth() + 1)).slice(-2) const month = ("0" + (date.getMonth() + 1)).slice(-2); const year = date.getFullYear(); return `${month}/${day}/${year}`; }, parse(dateString, format) { // dateString is the result of `toString` method const parts = dateString.split('/'); const day = parseInt(parts[0], 10); const month = parseInt(parts[1], 10) - 1; const year = parseInt(parts[2], 10); return new Date(year, month, day); }, firstDay: 0, minDate: minDate, maxDate: maxDate, disableDayFn: function(inputDate) { // Disable national holidays var formattedDate = inputDate.getFullYear() + '-' + (inputDate.getMonth() + 1) + '-' + inputDate.getDate(); return ((disabledDays.indexOf(formattedDate) == -1) ? false : true); } }); })(); </script> |
Mongoose with TypesScript slows down VSCode code completion Posted: 07 Apr 2022 11:11 AM PDT I have seen that Mongoose supports TS. I have followed their official getting started guide: https://mongoosejs.com/docs/typescript.html And since then, my code completion are very slow - unless I remove this package. |
Ordinal numbers replacement Posted: 07 Apr 2022 11:12 AM PDT I am currently looking for the way to replace words like first, second, third,...with appropriate ordinal number representation (1st, 2nd, 3rd). I have been googling for the last week and I didn't find any useful standard tool or any function from NLTK. So is there any or should I write some regular expressions manually? Thanks for any advice |
No comments:
Post a Comment