content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: I am getting the vscode error: "The editor could not be opened due to an unexpected error". How do I fix this? Basically I am making a discord bot on github codespaces (online vscode), and it was working for a while, but after I closed out of my tab, and re-opened it, it is giving me this error: This is the pictur...
I am getting the vscode error: "The editor could not be opened due to an unexpected error". How do I fix this?
Basically I am making a discord bot on github codespaces (online vscode), and it was working for a while, but after I closed out of my tab, and re-opened it, it is giving me this error: This is the picture of the error. I don't know what is causing this error. I tried creating a new codespace for the repo, but it still...
[ "Use vscode client. Check if the file path exists. Follow this document.\n" ]
[ 0 ]
[]
[]
[ "github", "github_codespaces", "python", "python_3.x", "visual_studio_code" ]
stackoverflow_0074496835_github_github_codespaces_python_python_3.x_visual_studio_code.txt
Q: Python/Tkinter: need code to define / import a widget as a class outside root window I have been wrestling for a very long time with the issue of creating a Tkinter gui in modular fashion using classes. While there are many examples on this site - and believe me, I have read them all - they have all been too compl...
Python/Tkinter: need code to define / import a widget as a class outside root window
I have been wrestling for a very long time with the issue of creating a Tkinter gui in modular fashion using classes. While there are many examples on this site - and believe me, I have read them all - they have all been too complex for me to understand. In particular, I could not work out how the imported modules coul...
[ "You can define the class in a separate module and then import it, but you will still want to initiate the button inside of your main window like you are doing now. After all the button does belong on the window.\nTo create a button class it would be similar to how you created the MainWindow...\nimport tkinter as ...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074513607_python_tkinter.txt
Q: How to parse and get specific data from a huge json file to implement search in python I have a json file with lot of information so I'm trying to just extract specific data where there is a position and I need to get the immediate name data, also trying to implement search in python. I'm uploading a part of sampl...
How to parse and get specific data from a huge json file to implement search in python
I have a json file with lot of information so I'm trying to just extract specific data where there is a position and I need to get the immediate name data, also trying to implement search in python. I'm uploading a part of sample json data from the file ex.json ` { "storables": [ { "columns": [ { ...
[ "import json\nwith open('ex.json', 'r') as f:\n data = json.load(f)\n\nNow you can access all json items just like you access any dictionary/object in python from data variable\n", "Your code may works, but you need to change the logic a little bit. Here is fast sketch of the solution:\nprevWasPosition = False...
[ 0, 0 ]
[]
[]
[ "arrays", "json", "parsing", "python" ]
stackoverflow_0074513435_arrays_json_parsing_python.txt
Q: Can't index through graph containing string values My goal im to be able to read the shortest distance between a specific building between all other buildings using the Dijkstra algorithm. I believe if I can fix the error, I will be able to complete my goal. The error below stops at a for loop, where it's trying t...
Can't index through graph containing string values
My goal im to be able to read the shortest distance between a specific building between all other buildings using the Dijkstra algorithm. I believe if I can fix the error, I will be able to complete my goal. The error below stops at a for loop, where it's trying to index through the vertices. I think it might have to d...
[ "changed to work with strings\"\nimport sys \n \nclass Graph(): \n \n def __init__(self, vertices): \n self.V = vertices \n self.graph = {}\n \n def min_distance(self,distance,traversed):\n min_index = 0 \n min_value = sys.maxsize\n for i in self.graph:\n if traversed[i] is False and min_...
[ 1 ]
[]
[]
[ "algorithm", "graph", "python" ]
stackoverflow_0074513489_algorithm_graph_python.txt
Q: Is there a way to find the position of my for loop variable in a integer list For example, num = [4, 6, 2, 5, 7] for i in num: for j in num: j = num[i+1] Is there a way to find if i is in the 0 position, 1 position, 2 position, ... so that I can make it were j = what position i is in +1 I also want to make i...
Is there a way to find the position of my for loop variable in a integer list
For example, num = [4, 6, 2, 5, 7] for i in num: for j in num: j = num[i+1] Is there a way to find if i is in the 0 position, 1 position, 2 position, ... so that I can make it were j = what position i is in +1 I also want to make it were if, lets say i was in position 1; if i == i+1: num.remove(i) I already tried...
[ "Yes, what you're looking for is the enumerate function, which takes in a list and gives you both the index and the value of each element in the list:\nnums = [4, 6, 2, 5, 7]\n\nfor index, value in enumerate(nums):\n print(index, value)\n\n# will print\n# (0, 4)\n# (1, 6)\n# (2, 2)\n# (3, 5)\n# (4, 7)\n\nSome extr...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074513681_python.txt
Q: Python get mouse x, y position on click Coming from IDL, I find it quite hard in python to get the x-y position of the mouse on a single left click using a method that is not an overkill as in tkinter. Does anyone know about a python package that contains a method simply returning x-y when the mouse is clicked (si...
Python get mouse x, y position on click
Coming from IDL, I find it quite hard in python to get the x-y position of the mouse on a single left click using a method that is not an overkill as in tkinter. Does anyone know about a python package that contains a method simply returning x-y when the mouse is clicked (similar to the cursor method in IDL)?
[ "There are a number of libraries you could use. Here are two third party ones:\nUsing PyAutoGui\nA powerful GUI automation library allows you to get screen size, control the mouse, keyboard and more.\nTo get the position you just need to use the position() function. Here is an example:\n>>>import pyautogui\n>>>py...
[ 21, 14, 3, 3, 2, 1, 1, 0 ]
[ "You all are making it too hard, its just as easy as:\nimport pyautogui as pg\n\npos = pg.position()\n\n# for x pos\nprint(pos[0])\n\n# for y pos\nprint(pos[1])\n\n" ]
[ -2 ]
[ "python", "python_2.7" ]
stackoverflow_0025848951_python_python_2.7.txt
Q: ValueError: No password or public key available I'm trying to connect to a remote MySQL database through an SSH Tunnel and deploying my code to Streamlit. When I try to do it, I get this error: File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 966, in __init__ (self.ssh_password, self.s...
ValueError: No password or public key available
I'm trying to connect to a remote MySQL database through an SSH Tunnel and deploying my code to Streamlit. When I try to do it, I get this error: File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 966, in __init__ (self.ssh_password, self.ssh_pkeys) = self._consolidate_auth( File "/home/ap...
[ "conn = db.connect(host=\"localhost\"), \nport=server.local_bind_port, \nuser=(\"db_username\"), \npasswd=(\"db_password\"), \ndb=(\"db_database\")\n\nBecause you have a closing parentheses on the first line, only the host argument is being passed to the...
[ 0 ]
[]
[]
[ "python", "ssh_tunnel", "streamlit" ]
stackoverflow_0074513690_python_ssh_tunnel_streamlit.txt
Q: Optimize conversion of numpy ndarray to string I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, t...
Optimize conversion of numpy ndarray to string
I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size ...
[ "One simple approach is to use tobytes on the numpy array. E.g.,\nimage = imageio.imread(filename)\n# Drop the alpha channel.\nif image.shape[2] == 4:\n image = image[..., :3]\n# Convert to bytes directly.\nbyte_image = image.tobytes()\n\nOn my machine, this gives a 250x speed up compared with converting to stri...
[ 2, 1 ]
[]
[]
[ "numpy", "python", "python_3.x", "python_imageio" ]
stackoverflow_0074513611_numpy_python_python_3.x_python_imageio.txt
Q: In Python code below, how can I immediately exit the code? I have been trying below this two days, but cannot make it work. I have tried except KeyboardInterrupt: sys.exit() exit() control+C , and so on. I have tried the code, but it terminates only after 30 seconds or 1 minute. It seems like "listener" in the co...
In Python code below, how can I immediately exit the code?
I have been trying below this two days, but cannot make it work. I have tried except KeyboardInterrupt: sys.exit() exit() control+C , and so on. I have tried the code, but it terminates only after 30 seconds or 1 minute. It seems like "listener" in the code makes the code complicated. I need to make the code terminate...
[ "The program won't exit while the click_thread is still running.\nIf the clicker knows that it's supposed to exit it can break the loop and return. Alternatively, if you mark the thread as a daemon:\nclick_thread = threading.Thread(target=clicker, daemon=True)\n\nthen it will exit when the main program exits.\nYou...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074511971_python.txt
Q: Is it possible somehow without refreshing the pages on Django to send a request via SSH to a virtual machine running Ubuntu? Good afternoon, I have a frequently asked question, for example, <button>Check</button> Is it possible somehow without refreshing the page to send a request via SSH to a virtual machine run...
Is it possible somehow without refreshing the pages on Django to send a request via SSH to a virtual machine running Ubuntu?
Good afternoon, I have a frequently asked question, for example, <button>Check</button> Is it possible somehow without refreshing the page to send a request via SSH to a virtual machine running Ubuntu? For example: The csgo server is on a permanent machine, it has possible options: IP: 192.168.44.122/94.32.143.84 PORT...
[ "So you want to execute a script/program on a machine (the virtual machine) from another (here your local machine).\n\nYes SSH is one way you can do that. Try ssh -p 44 test@192.168.44.122 \"csgoserver start\" (side note: I'm assuming here that the . in ./csgoserver start is the user's home directory. . means \"cur...
[ 0 ]
[]
[]
[ "django", "python", "ssh" ]
stackoverflow_0074513068_django_python_ssh.txt
Q: Python Error: 'float' object has no attribute 'replace' I am an R User that is trying to learn more about Python. I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser I was able to try an example over here: from ez_address_parser import AddressParse...
Python Error: 'float' object has no attribute 'replace'
I am an R User that is trying to learn more about Python. I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser I was able to try an example over here: from ez_address_parser import AddressParser ap = AddressParser() result = ap.parse("290 Bremner Blvd,...
[ "Looking at the code from the library, we have this method for parse in the AddressParser class, and then this function for tokenize that is called by parse\n# method of AddressParser\ndef parse(self, address):\n if not self.crf:\n raise RuntimeError(\"Model is not loaded\")\n\n tokens = to...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074513701_python.txt
Q: Run specific function for exactly 2 hours There is a function which is needed to run for 2 hours, Interrupting it manually after 2 hours is not desired in this case. What is the best practice to implement such a task? def fib(): sequence = [0,1] while True: sequence.append(sequence[-1]+sequence[-2]...
Run specific function for exactly 2 hours
There is a function which is needed to run for 2 hours, Interrupting it manually after 2 hours is not desired in this case. What is the best practice to implement such a task? def fib(): sequence = [0,1] while True: sequence.append(sequence[-1]+sequence[-2]) return sequence I know it is possible to...
[ "You can clean up the poll a bit by\nimport time\n\ndef fib():\n sequence = [0,1]\n end = time.time() + 2*60*60\n while time.time() < end:\n sequence.append(sequence[-1]+sequence[-2])\n return sequence\n\nThis adds the cost of time.time() on each loop, which can be significant - especially in thi...
[ 1 ]
[]
[]
[ "python", "python_3.x", "time" ]
stackoverflow_0074513792_python_python_3.x_time.txt
Q: Flask-SQLAlchemy raising: AttributeError: module 'psycopg2' has no attribute 'paramstyle' I'm running a generic (because I don't know enough to do anything beyond the basics) Flask-SQLAlchemy 3.0.2 setup on Python 3.10. Not sure what happened, but at some point it started throwing this error every time I tried to ...
Flask-SQLAlchemy raising: AttributeError: module 'psycopg2' has no attribute 'paramstyle'
I'm running a generic (because I don't know enough to do anything beyond the basics) Flask-SQLAlchemy 3.0.2 setup on Python 3.10. Not sure what happened, but at some point it started throwing this error every time I tried to query the db: AttributeError: module 'psycopg2' has no attribute 'paramstyle' I'm doing package...
[ "I uninstalled psycopg2 (and removed its requirement from the poetry lock file), and installed psycopg2-binary 2.9.5 manually. Now it works.\n" ]
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "psycopg2", "python", "sqlalchemy" ]
stackoverflow_0074513831_flask_flask_sqlalchemy_psycopg2_python_sqlalchemy.txt
Q: How to parse and get known individual elements, not characters, from a smiles string in Python In Python, I am trying to break a SMILES string into a list of valid SMILES elements. I wanted to ask if RDKit already has a method to do this kind of deconstruction of the SMILES string? I DO have created a list of vali...
How to parse and get known individual elements, not characters, from a smiles string in Python
In Python, I am trying to break a SMILES string into a list of valid SMILES elements. I wanted to ask if RDKit already has a method to do this kind of deconstruction of the SMILES string? I DO have created a list of valid SMILES elements separately. For example, I want to convert this string CC(Cl)c1ccn(C)c1 into this ...
[ "This can be accomplished by extending the following function (from Molecular Transformer):\nimport re\n\ndef smi_tokenizer(smi):\n \"\"\"\n Tokenize a SMILES molecule or reaction\n \"\"\"\n pattern = \"(\\[[^\\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\\(|\\)|\\.|=|#|-|\\+|\\\\\\\\|\\/|:|~|@|\\?|>|\\*|\\$|...
[ 1, 0 ]
[]
[]
[ "cheminformatics", "parsing", "python", "rdkit" ]
stackoverflow_0074205361_cheminformatics_parsing_python_rdkit.txt
Q: Python. flask, wfastCGI, and IIS - Very short url length limit (or something) I'm using Python 3.10.4 and Flask on a Windows 2016 Server with IIS and wfastCGI. I stripped down my Python script to bare minimum for testing: from flask import Flask, request, abort, render_template from functools import wraps app = F...
Python. flask, wfastCGI, and IIS - Very short url length limit (or something)
I'm using Python 3.10.4 and Flask on a Windows 2016 Server with IIS and wfastCGI. I stripped down my Python script to bare minimum for testing: from flask import Flask, request, abort, render_template from functools import wraps app = Flask(__name__, static_url_path='/dwapi') app.config["APPLICATION_ROOT"] = "/dwapi" ...
[ "In addition to iis settings, you can also set registry keys to tell HTTP.sys to allow longer URLs. By default, HTTP.sys permits 255 segments at a maximum length of 260 characters each. That 260 character limit was the cause of this issue.\nYou can change that setting in the registry. once you reboot, the url will...
[ 0 ]
[]
[]
[ "iis", "python", "wfastcgi" ]
stackoverflow_0074483997_iis_python_wfastcgi.txt
Q: Own dataset ValueError: Tensor conversion requested dtype string for Tensor with dtype float32 I'm trying to use my own dataset to train a GAN network. I'm having issues with loading my own dataset in .jpg format. I have existing jpg datasets that work, I can't see a difference in the jpg encoding between the work...
Own dataset ValueError: Tensor conversion requested dtype string for Tensor with dtype float32
I'm trying to use my own dataset to train a GAN network. I'm having issues with loading my own dataset in .jpg format. I have existing jpg datasets that work, I can't see a difference in the jpg encoding between the working and not working datasets. The photos are converted using a windows machine and renamed to 001.jp...
[ "I have got same error with you.\nI solve it: change the path name correctly.\nI guess in your case, you should check you \"path\" name in codes\nimg = tf.read_file(path)\n\n", "This sounds like a converting issue.\nI think you may have to call\n str(input)\non the input you are passing as filename. \n", "...
[ 1, 0, 0 ]
[]
[]
[ "image", "jpeg", "python", "tensorflow", "type_conversion" ]
stackoverflow_0051139028_image_jpeg_python_tensorflow_type_conversion.txt
Q: Genrate grid information file from MODIS HDFEOS data Is there a way to generate grid information (lat-lon) from the MODIS MCD19A2 files in python?. The file is downloaded from Link to the data file .In MATLAB it can be done using the following block code import matlab.io.hdf4.* import matlab.io.hdfeos.* % Open th...
Genrate grid information file from MODIS HDFEOS data
Is there a way to generate grid information (lat-lon) from the MODIS MCD19A2 files in python?. The file is downloaded from Link to the data file .In MATLAB it can be done using the following block code import matlab.io.hdf4.* import matlab.io.hdfeos.* % Open the HDF-EOS2 Grid file. FILE_NAME='MCD19A2.A2010010.h25v06.0...
[ "HDF-EOS Tools and Information Center Help was so nice to provide a script to deal with grid definition. This can be found here. In case the link is not working, here is the code:\n\"\"\"\nCopyright (C) 2014-2019 The HDF Group\nCopyright (C) 2014 John Evans\n\nThis example code illustrates how to access and visuali...
[ 0, 0 ]
[]
[]
[ "hdf", "matlab", "pyhdf", "python" ]
stackoverflow_0057990038_hdf_matlab_pyhdf_python.txt
Q: How can I draw a projectile arc on turtle graphics? I need help with learning how to draw a arc in turtle graphics. I would prefer a simple set of code that I can easily incorporate into my pre-existing code. I've tried to make an arc following online instructions but its not projectile, its more like a smiley fac...
How can I draw a projectile arc on turtle graphics?
I need help with learning how to draw a arc in turtle graphics. I would prefer a simple set of code that I can easily incorporate into my pre-existing code. I've tried to make an arc following online instructions but its not projectile, its more like a smiley face arc would be.
[ "This code keeps track of two variables, one called x_velocity, and the other called y_velocity. These variables represent the speed that the projectile is moving in x and y directions respectively. It then loops through a couple times, moving the turtle at those velocities and then applying gravity to the y_veloci...
[ 1 ]
[]
[]
[ "python", "python_3.9", "python_turtle", "turtle_graphics" ]
stackoverflow_0074513719_python_python_3.9_python_turtle_turtle_graphics.txt
Q: Selenium getting banned from cloudflare I am using selenium python but when I load my target page it gets banned. I find if I run this code while trying load page then everything getting fine. driver.service.stop() Cloudflare is accept my connection and my target page is loaded success. But still don't know how t...
Selenium getting banned from cloudflare
I am using selenium python but when I load my target page it gets banned. I find if I run this code while trying load page then everything getting fine. driver.service.stop() Cloudflare is accept my connection and my target page is loaded success. But still don't know how to deal with Cloudflare because when I resume ...
[ "When I run into this problem I usually use a library called \"cloudscraper\"\nRead more about it here: https://github.com/VeNoMouS/cloudscraper\n" ]
[ 2 ]
[]
[]
[ "cloudflare", "python", "selenium" ]
stackoverflow_0074513547_cloudflare_python_selenium.txt
Q: How do I fix indentation error when creating a class in Python? Every time I try to create a class, it gives me the IndentationError when I haven't even added indentations yet. I have tried restarting Jupyter and my PC and there is no luck. I have also tried using another notebook but still face the error. A: A...
How do I fix indentation error when creating a class in Python?
Every time I try to create a class, it gives me the IndentationError when I haven't even added indentations yet. I have tried restarting Jupyter and my PC and there is no luck. I have also tried using another notebook but still face the error.
[ "As the error shows, it is expecting an indented block after the class.\nSo add a statement in there, example:\nclass Animal():\n pass\n\n", "You should understand the basics of classes in python for this. It is working fine, the only thing is that your code is incomplete. After you declare a class, it is simp...
[ 2, 0 ]
[]
[]
[ "class", "python", "syntax_error" ]
stackoverflow_0074514050_class_python_syntax_error.txt
Q: BeautifulSoup - Scrape product and product variants and export it to csv I am trying to scrape this website products listing what I am trying to achieve here is grab all the info per product for example: product_name, price and their variants info as well like 10kg, 20kg, 3kg and their prices accordingly. I have s...
BeautifulSoup - Scrape product and product variants and export it to csv
I am trying to scrape this website products listing what I am trying to achieve here is grab all the info per product for example: product_name, price and their variants info as well like 10kg, 20kg, 3kg and their prices accordingly. I have search the html they don't provide all the info I am looking for but under scri...
[ "\nevery time I run that code the label_options column has always the same values which is the last one I am guessing\n\nAre you sure that they don't just all happen to have the same set of options? It shouldn't be repeating since you're clearing the list with labels = [] in the loop - although you can just append ...
[ 1 ]
[]
[]
[ "beautifulsoup", "csv", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074511414_beautifulsoup_csv_python_python_3.x_web_scraping.txt
Q: Weird list in python So I was trying to fetch member of my discord server using discord.py, using the guild.members I was iterating over it and it returned me the names of the members but then I printed it directly and I got something like this: [<Member id=102833403109497170 name='Xiaoling' discriminator='147' bo...
Weird list in python
So I was trying to fetch member of my discord server using discord.py, using the guild.members I was iterating over it and it returned me the names of the members but then I printed it directly and I got something like this: [<Member id=102833403109497170 name='Xiaoling' discriminator='147' bot=False nick=None guild=<G...
[ "Take a look at the class Member\nclass Member:\n def __init__(self,id,name,somethingElse=True):\n self.id = id\n self.name = name\n self.somethingElse = somethingElse\n\n def addExtraValue(self,extra):\n self.extra = extra\n \n def __repr__(self):\n return \"<id = {},...
[ 0 ]
[]
[]
[ "discord", "discord.py", "list", "python" ]
stackoverflow_0074513648_discord_discord.py_list_python.txt
Q: In python, can locateCenterOnScreen be used with region? There is a large picture including number 8. First, I want to detect the large picture as below: left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3) Second, if the large picture is detected, then I want to narrow down to find...
In python, can locateCenterOnScreen be used with region?
There is a large picture including number 8. First, I want to detect the large picture as below: left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3) Second, if the large picture is detected, then I want to narrow down to find the number 8. x, y = pyautogui.locateCenterOnScreen('number8...
[ "Yes locateCenterOnScreen can be used with region. That error you get is because pyautogui simply cannot find the object. And since there is no result, it cannot use iteration to assign variables to your x and y\nthis line here will never be true\nif x is None: \n\nBecause this line will throw an error if the objec...
[ 2 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0074513744_pyautogui_python.txt
Q: Why my tabula template does not output the data from PDF file when running through Python? I selected the area using Tabula as below in the app and created a template. The out put in web works. But when I do it via code below I get an error "The output file is empty". Area selection Code import tabula df...
Why my tabula template does not output the data from PDF file when running through Python?
I selected the area using Tabula as below in the app and created a template. The out put in web works. But when I do it via code below I get an error "The output file is empty". Area selection Code import tabula df = tabula.io.read_pdf_with_template(input_path="C:/Users/dnalaka/Desktop/DEF.2400-20221117.pdf",...
[ "I notice the out put format defining really doesn't work in the function. However, it does out put the data in JSON format. As we have it in a data frame we can simply save it to a csv file.\ndf[0].to_csv(csv_path)\n\n" ]
[ 0 ]
[]
[]
[ "python", "tabula", "tabula_py" ]
stackoverflow_0074485053_python_tabula_tabula_py.txt
Q: Adding flag according to a condition in Dataframes Suppose I have a dataframe that looks likes this-> ID time-A time-B time-C A 30 40 50 B NULL 60 50 C 30 20 50 I want to add a flag such that if time-A is NULL and time-B/time-c>=1 I put 'Y' flag otherwise I put 'N' Desired result-> ID tim...
Adding flag according to a condition in Dataframes
Suppose I have a dataframe that looks likes this-> ID time-A time-B time-C A 30 40 50 B NULL 60 50 C 30 20 50 I want to add a flag such that if time-A is NULL and time-B/time-c>=1 I put 'Y' flag otherwise I put 'N' Desired result-> ID time-A time-B time-C Flag A 30 40 50 N B NULL...
[ "Could try this one :D\nimport numpy as np\ndf['Flag'] = np.where((df['time-A'].isna() & (df['time-B']>df['time-C'])), 'Y', 'N')\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074514034_dataframe_numpy_pandas_python.txt
Q: How to vertically stack the results of a for loop to a 2D array? I've trained the CNN model to classify the images of 35 persons. To test the trained CNN model, I have used 70 images (2 from each person). The following for loop was written to predict the probabilities of the 70 images. I need the predicted probabi...
How to vertically stack the results of a for loop to a 2D array?
I've trained the CNN model to classify the images of 35 persons. To test the trained CNN model, I have used 70 images (2 from each person). The following for loop was written to predict the probabilities of the 70 images. I need the predicted probabilities of 70 images (70 * 35) to be assigned to the ndarray predicted_...
[ "A simplest way is to assign results directly to the array.\nactual_values_images = []\npredicted_values_images = []\npredicted_probabilities = np.empty((70, 35), int)\n\nfor index, testImage in enumerate(test_image_folder):\n img = folder_path+str(testImage)\n img = image.load_img(img, target_size=(64, 64))\...
[ 1 ]
[]
[]
[ "for_loop", "multidimensional_array", "numpy_ndarray", "python", "vstack" ]
stackoverflow_0074514008_for_loop_multidimensional_array_numpy_ndarray_python_vstack.txt
Q: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! when resuming training I saved a checkpoint while training on gpu. After reloading the checkpoint and continue training I get the following error: Traceback (most recent call last): File "main.py", line 1...
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! when resuming training
I saved a checkpoint while training on gpu. After reloading the checkpoint and continue training I get the following error: Traceback (most recent call last): File "main.py", line 140, in <module> train(model,optimizer,train_loader,val_loader,criteria=args.criterion,epoch=epoch,batch=batch) File "main.py", line...
[ "There might be an issue with the device parameters are on:\n\nIf you need to move a model to GPU via .cuda() , please do so before constructing optimizers for it. Parameters of a model after .cuda() will be different objects with those before the call.\nIn general, you should make sure that optimized parameters li...
[ 28, 3, 0, 0, 0, 0 ]
[]
[]
[ "deep_learning", "python", "pytorch", "runtime_error" ]
stackoverflow_0066091226_deep_learning_python_pytorch_runtime_error.txt
Q: How to control Newport controller model 8742 with python? I have the Newport New Focus Picomotor Controller/Driver, Model 8742, and it comes with software to control the motors. I want to be able to command the controller with python. There is a similar question here already but for some reason that code is not wo...
How to control Newport controller model 8742 with python?
I have the Newport New Focus Picomotor Controller/Driver, Model 8742, and it comes with software to control the motors. I want to be able to command the controller with python. There is a similar question here already but for some reason that code is not working for me. So far I have import serial as s from time import...
[ "The USB driver for 8742 / 8743 controllers does not expose an actual serial port. However, you can communicate using ASCII commands thru its USB endpoints on any operating system, which can be done with PyUSB. Here's an excellent starting point: https://github.com/bdhammel/python_newport_controller\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0045575568_python.txt
Q: How to run background tasks in python I'm developing a small web service with Flask which needs to run background tasks, preferably from a task queue. However, after googling the subject the only results were essentially Celery and Redis Queue, which apparently require separate queuing services and thus are optio...
How to run background tasks in python
I'm developing a small web service with Flask which needs to run background tasks, preferably from a task queue. However, after googling the subject the only results were essentially Celery and Redis Queue, which apparently require separate queuing services and thus are options that are far too heavy and convoluted to...
[ "import threading\nimport time\n\nclass BackgroundTasks(threading.Thread):\n def run(self,*args,**kwargs):\n while True:\n print('Hello')\n time.sleep(1)\n\nt = BackgroundTasks()\nt.start()\n\nAfter the while statement , you can put the code you want to run in background. Maybe delet...
[ 8, 5, 0 ]
[]
[]
[ "multithreading", "python", "python_3.x" ]
stackoverflow_0059850517_multithreading_python_python_3.x.txt
Q: tkinter Image is not displayed unless the mainloop() is called in the same class I am new to tkinter and encounter this strange behavior with the images. Please pay attention to the *.mainloop() in the code below. import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk class BaseWindow(tk.Tk)...
tkinter Image is not displayed unless the mainloop() is called in the same class
I am new to tkinter and encounter this strange behavior with the images. Please pay attention to the *.mainloop() in the code below. import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk class BaseWindow(tk.Tk): def __init__(self): super(BaseWindow, self).__init__() self.geom...
[ "I beginner at this stuff but I think you do need all of those .mainloop() because it updates the UI. But I am not sure. Hope you get more answers!\n", "Here i have some thing for you. You can add a single line in child Window class and your problem will be solved.\nclass ChildWindow(ttk.Frame):\ndef __init__(sel...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_imaging_library", "tkinter" ]
stackoverflow_0074510343_python_python_imaging_library_tkinter.txt
Q: Why am i getting "Name Error : name x is not defiened" in this program? # UNQ_C2 # GRADED FUNCTION: compute_gradient def compute_gradient(x, y, w, b): """ Computes the gradient for linear regression Args: x (ndarray): Shape (m,) Input to the model (Population of cities) y (ndarray): Shape (...
Why am i getting "Name Error : name x is not defiened" in this program?
# UNQ_C2 # GRADED FUNCTION: compute_gradient def compute_gradient(x, y, w, b): """ Computes the gradient for linear regression Args: x (ndarray): Shape (m,) Input to the model (Population of cities) y (ndarray): Shape (m,) Label (Actual profits for the cities) w, b (scalar): Parameters of ...
[ "Here, x must be your input which you have not specified anywhere. When you try to do a shape on something that has not even been set up/defined yet you encountered this error. Try something like assigning x = your_input_array/matrix etc before you do a shape on it.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074514182_python.txt
Q: How to split a 2D array into a list of smaller 2D arrays with overlapping? Python I want to split a 2D array x * y into some smaller 2D arrays which are N * N with overlapping and store these smaller arrays as values in a dictionary, the key will be the index of the top-left item in the larger array. From [[1,2,3,...
How to split a 2D array into a list of smaller 2D arrays with overlapping? Python
I want to split a 2D array x * y into some smaller 2D arrays which are N * N with overlapping and store these smaller arrays as values in a dictionary, the key will be the index of the top-left item in the larger array. From [[1,2,3,4], [5,6,7,8], [9,10,11,12]] To {(0,0):[[1,2],[5,6]], (0,1):[[2,3],[6,7]], (0,2):[[3...
[ "The operation you want to do is a sliding window.\nimport numpy as np\n\nA = np.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]\n])\n\nresult = dict(zip(\n [(i, j) for i in range(2) for j in range(3)],\n np.lib.stride_tricks.sliding_window_view(A, (2, 2)).reshape(-1, 2, 2).tolist()\...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074513892_arrays_numpy_python.txt
Q: how to round off a float i want to round off a float to 3 dp in python with 00 in the end if the float don't have 3 dp like 15.4 into 15.400 thank you. programme: x=round(15.4) result: 15.400 A: The "rounding" you are talking about can only be done if you convert the float to a string. This is usually only done...
how to round off a float
i want to round off a float to 3 dp in python with 00 in the end if the float don't have 3 dp like 15.4 into 15.400 thank you. programme: x=round(15.4) result: 15.400
[ "The \"rounding\" you are talking about can only be done if you convert the float to a string. This is usually only done for display purposes. In this case you can use a so-called f-string to do this formatting:\nx = 15.4\nprint(f\"{x:.3f}\")\n\n", "Hello its pretty simple you can do something like this\na=15.4\n...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074514179_python.txt
Q: I want to Remove the addition symbol from in-between the numbers using python and please find the below my code limit = int(input("Limit: ")) allvalue = "" count = 0 number = 0 while count < limit: number += 1 count += number allvalue += str(number) + " + " print(allvalue) This is my output 1 + 2 +...
I want to Remove the addition symbol from in-between the numbers using python and please find the below my code
limit = int(input("Limit: ")) allvalue = "" count = 0 number = 0 while count < limit: number += 1 count += number allvalue += str(number) + " + " print(allvalue) This is my output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + I want the + symbol only in between the numbers.Not to be in the last or the first.
[ "A likely solution is using \" + \".join(), which uses the string method on the \" + \" to collect the values together\n>>> values = \"1 2 3 4 5\".split()\n>>> \" + \".join(values)\n'1 + 2 + 3 + 4 + 5'\n\n", "limit = int(input(\"Limit: \"))\nallvalue = \"\"\ncount = 0\nnumber = 0\nwhile count < limit:\n number...
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074514064_python_python_3.x.txt
Q: Disapprove password if it contains exactly 4 digits (validation) I can't figure out how to modify my regex to make sure the password follows the last condition: at least 2 capital letters in a row doesn't have space symbols contains digits doesn't contain 4 consecutive digits {4} It currently disapproves the pas...
Disapprove password if it contains exactly 4 digits (validation)
I can't figure out how to modify my regex to make sure the password follows the last condition: at least 2 capital letters in a row doesn't have space symbols contains digits doesn't contain 4 consecutive digits {4} It currently disapproves the password if it has 4 and more digits but I need it to disapprove the pass...
[ "\nTo match exactly four digits, you can use at start ^ e.g. (?!(?:.*\\D)?\\d{4}(?!\\d)).\nThis requires start or a \\D non-digit before the 4 digits and disallows a digit after.\n(?=.*[A-Za-z]) looks redundant if you already require (?=.*[A-Z]{2,}) (2 upper).\n{2,} two or more is redundant. {2} would suffice and d...
[ 1 ]
[]
[]
[ "python", "regex", "validation" ]
stackoverflow_0074511690_python_regex_validation.txt
Q: How can I detect collision in pygame while using colliderect() to make an object disappear without using sprites? I have two classes that both create squares. One that puts squares randomly in the window and another that the user can control. I need to detect collision between them but I keep getting an error that...
How can I detect collision in pygame while using colliderect() to make an object disappear without using sprites?
I have two classes that both create squares. One that puts squares randomly in the window and another that the user can control. I need to detect collision between them but I keep getting an error that the I need a rect style object when I use the colliderect() function. I am pretty sure my drawings are rects but I mig...
[ "You do have a rectangle, but it's not a PyGame Rect. The collision functions can only be used with a Rect.\nThe Rect is really handy. The code doesn't need to store x, y, w, h ... all these can be put into a Rect:\nclass Player():\n def __init__(self):\n self.rect = pygame.Rect( 300, 300, 100, 100 )\...
[ 0 ]
[]
[]
[ "collision_detection", "pygame", "python" ]
stackoverflow_0074513106_collision_detection_pygame_python.txt
Q: Using Dataframes Column names within function I am just getting started with functions and want to try using them to streamline some of my code, but I run into a issue when trying to define a function to create different dataframes: def my_function(region): y = df_expert.loc[:,region] X['Price_24'] = df_ex...
Using Dataframes Column names within function
I am just getting started with functions and want to try using them to streamline some of my code, but I run into a issue when trying to define a function to create different dataframes: def my_function(region): y = df_expert.loc[:,region] X['Price_24'] = df_expert[region].shift(24) my_function("'Price_RE...
[ "'Price_REG1' == \"Price_REG1\" -> True\nso\nx['Price_REG1'] == x[\"Price_REG1\"] -> True\nso when you pass \"Price_REG1\" and use it as x[\"Price_REG1\"],\nthat the correct.\nbut if you pass \"'Price_REG1'\" that means you use it as x[\"'Price_REG1'\"]\nis incorrect.\n" ]
[ 0 ]
[]
[]
[ "function", "pandas", "python" ]
stackoverflow_0074510428_function_pandas_python.txt
Q: Fast way to convert string to numpy ndarray I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ...
Fast way to convert string to numpy ndarray
I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size ...
[ "remove incorrect indentation on this line:\nImg = np.asarray(stepThree)\n\nIt is inside the for loop and it should not\nAlso the code is doing innecesary conversion from byte to string to int instead of doing it directly byte to int, consider changing to the following which is shorter and faster\ndef BytesToImage2...
[ 1, 1 ]
[]
[]
[ "numpy", "python", "python_3.x", "python_imageio" ]
stackoverflow_0074512390_numpy_python_python_3.x_python_imageio.txt
Q: Is it possible to secure Tabs in my PySimpleGUI code? Dears, Is it possible to secure Tabs in my PySimpleGUI code ? Means that only 1st Tab can be kept accessible and the other ones request password: Knowing that I'm able to do that using Collapsible function as follows : def Collapsible(layout, key, title='', arr...
Is it possible to secure Tabs in my PySimpleGUI code?
Dears, Is it possible to secure Tabs in my PySimpleGUI code ? Means that only 1st Tab can be kept accessible and the other ones request password: Knowing that I'm able to do that using Collapsible function as follows : def Collapsible(layout, key, title='', arrows=(sg.SYMBOL_DOWN, sg.SYMBOL_UP), collapsed=False): ret...
[ "Information for a question here, IMO, it will be better.\n\nAdd everything required\nRemove everything not related.\nMost simple layout if GUI required.\n\nHere, just for how to set which tab accessible. tkinter code required here.\nimport PySimpleGUI as sg\n\naccessible = [0, 3]\n\nlayout = [[sg.TabGroup([[sg.Tab...
[ 0 ]
[]
[]
[ "passwords", "pysimplegui", "python", "security", "tabs" ]
stackoverflow_0074512833_passwords_pysimplegui_python_security_tabs.txt
Q: Playwright Python: Get Attribute inside Iframe I'm trying to get 'src' of iframe element using Playwright and Python. Here is the HTML I'm trying to access: <iframe title="IFRAME_NAME" src="https://www.data_I_want_TO_get.com"> </iframe> my goal is to grab 'src' attribute. here is what I've tried so far src=pa...
Playwright Python: Get Attribute inside Iframe
I'm trying to get 'src' of iframe element using Playwright and Python. Here is the HTML I'm trying to access: <iframe title="IFRAME_NAME" src="https://www.data_I_want_TO_get.com"> </iframe> my goal is to grab 'src' attribute. here is what I've tried so far src=page.frame_locator("IFRAME_NAME") print(src.inner_...
[ "Absent seeing the actual site, a traditional selection and get_attribute should be sufficient:\nfrom playwright.sync_api import sync_playwright\n\nwith sync_playwright() as p:\n browser = p.chromium.launch(headless=True)\n page = browser.new_page()\n page.set_content(\"\"\"\n <iframe title=\"IFRAME_NAM...
[ 1 ]
[]
[]
[ "playwright", "playwright_python", "python" ]
stackoverflow_0074508896_playwright_playwright_python_python.txt
Q: DashPlotly and Pandas choosing excel file via dropdown I have a folder with xlsx files. I want to use names of these files to populate the dropdown menu from dash plotly. I am stacked with what to begin from. I read files from folder, list and append. If I put df_list[0] or df_list[1] I can manually choose which e...
DashPlotly and Pandas choosing excel file via dropdown
I have a folder with xlsx files. I want to use names of these files to populate the dropdown menu from dash plotly. I am stacked with what to begin from. I read files from folder, list and append. If I put df_list[0] or df_list[1] I can manually choose which excel file to use for dataframe but how do I choose which fil...
[ "Here is a method that works:\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objects as go\nimport pandas as pd\nimport os\n\n# 1. first create sample Excel files\ndata1 = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]\ndata2 = [{'x': 10, 'y': -6}, {'x': -10, 'y': 8...
[ 0 ]
[]
[]
[ "pandas", "plotly", "plotly_dash", "python" ]
stackoverflow_0074513669_pandas_plotly_plotly_dash_python.txt
Q: Find all HTML tags and append target blank values using Python regular expression I want to find all <a href='https://example.com/'> references in a large file and append the target='_blank' rel='noopener noreferrer' option to the end of the tag, if it is missing. Roughly, I did the following: re.sub(r'<a href...
Find all HTML tags and append target blank values using Python regular expression
I want to find all <a href='https://example.com/'> references in a large file and append the target='_blank' rel='noopener noreferrer' option to the end of the tag, if it is missing. Roughly, I did the following: re.sub(r'<a href=([^>]+)', r'<a href=([^>]+)' + " target='_blank' rel='noopener noreferrer'", content) ...
[ "Try this: (*** If coding professionally, use the tool ti7 suggested.)\nimport re\ncontent = \"<a href='https://example.com/'>\"\nx = re.sub(r'(<a href=([^>]+))', r'\\1' + \" target='_blank' rel='noopener noreferrer'\", content)\nprint(x)\n\noutput:\n <a href='https://example.com/' target='_blank' rel='noopen...
[ 1, 0 ]
[]
[]
[ "append", "python" ]
stackoverflow_0074514366_append_python.txt
Q: i want to composite a data hourly with 4 years data i have hourly data from January 2018 - December 2021 i want to sum the data each hour for four years. i.e. in a day we have 2pm just one hour, right?.but, in 4 years(365*3+366=1461) we have 1461 hours. i want to sum a data in each hour (00.00 - 23.00) for four ye...
i want to composite a data hourly with 4 years data
i have hourly data from January 2018 - December 2021 i want to sum the data each hour for four years. i.e. in a day we have 2pm just one hour, right?.but, in 4 years(365*3+366=1461) we have 1461 hours. i want to sum a data in each hour (00.00 - 23.00) for four years. but i dont get the idea how to code. this is my code...
[ "Floor/truncate the timestamp to hour and format using strftime then groupby and sum:\ni = df.index.floor('H').strftime('%H:%M')\ndf.groupby(i).sum()\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074513634_pandas_python.txt
Q: In Python, what is the difference between df["row_name"] and df.loc["row_name"] I am trying to add another row to my data Frame When I use df["new_row"] = [5, True, "joe", 20] , I get the error ValueError: Length of values (4) does not match length of index (11) but if I use df.loc["new_row"] = [5, True, "joe", ...
In Python, what is the difference between df["row_name"] and df.loc["row_name"]
I am trying to add another row to my data Frame When I use df["new_row"] = [5, True, "joe", 20] , I get the error ValueError: Length of values (4) does not match length of index (11) but if I use df.loc["new_row"] = [5, True, "joe", 20], I can succesfully add a new row.
[ "To answer your question about the difference, in pandas, df[\"colname\"] is used to access a column of a given data frame.\nloc[r,c] is used to access specific cells within that data frame in the order of row and column. So, if you use df.loc[r], it will access the entire row.\nIn your case,df.loc['new_row'], crea...
[ 0 ]
[]
[]
[ "indexing", "pandas", "pandas_loc", "python" ]
stackoverflow_0074514469_indexing_pandas_pandas_loc_python.txt
Q: Palindrome LinkedList Leetcode challenge Given the following Leetcode challenge, Leet code challenge I have 2 questions: 1- I am confused about head =[1,2,3,4] in the question. To me, this looks like a whole linked list and not just a head. I would expect the head would be the first element in the input data array...
Palindrome LinkedList Leetcode challenge
Given the following Leetcode challenge, Leet code challenge I have 2 questions: 1- I am confused about head =[1,2,3,4] in the question. To me, this looks like a whole linked list and not just a head. I would expect the head would be the first element in the input data array. I think I am not sure how the head can equal...
[ "Point 1\nYou have the correct understanding. What whey mean in attached screenshot is that the \"head\" is pointing to the first element of the linked list.\nPoint 2\nThe problem is with the constructor. ListNode represents a single node and the corresponding contructor __init__(self, val=0, next=None) is expectin...
[ 0 ]
[]
[]
[ "class", "palindrome", "python" ]
stackoverflow_0074513928_class_palindrome_python.txt
Q: Django Conditional to remove css class if not on main url Im wondering if someone could help me figure this out; Working on a web app using the django framework and for my navbar, I have a css class that makes it transparent on the main page. This of course worked on a static website, but does not in django. How c...
Django Conditional to remove css class if not on main url
Im wondering if someone could help me figure this out; Working on a web app using the django framework and for my navbar, I have a css class that makes it transparent on the main page. This of course worked on a static website, but does not in django. How can i write an if statement to only apply this class on a specif...
[ "In Django, you can check active URL like this...\nI put code for if the home URL is active and then applied id=\"navbar\" else not.\n{% load static %}\n<header id=\"home\">\n <!-- Navbar -->\n <nav {% if request.resolver_match.url_name == 'home' %}id=\"navbar\"{% endif %} class=\"main-page\">\n <a hr...
[ 0 ]
[]
[]
[ "css", "django", "django_templates", "html", "python" ]
stackoverflow_0074510241_css_django_django_templates_html_python.txt
Q: How to place all files in python module to the same top level namespace? I have example python project with multiple files: src/common.py: def toint(x): return int(x) src/foo1.py: import common def add(a,b): return common.toint(a) + common.toint(b) src/foo2.py: import common def sub(a,b): return co...
How to place all files in python module to the same top level namespace?
I have example python project with multiple files: src/common.py: def toint(x): return int(x) src/foo1.py: import common def add(a,b): return common.toint(a) + common.toint(b) src/foo2.py: import common def sub(a,b): return common.toint(a)-common.toint(b) setup.py: from setuptools import setup setup (...
[ "Reference the python docs https://docs.python.org/2/tutorial/modules.html#intra-package-references for creating modules and project directory format. E.g. Modulename/ModuleFiles.py and existence of a __init__.py and __main__.py files. From __init__ you can import * or use relative/absolute imports.\n", "\nBut I ...
[ 0, 0 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0074341189_namespaces_python.txt
Q: Extract an array of numbers from a Python array Suppose I have a 10x10 Python array, M. I would like to extract the 3x3 array with the values of the rows [2,3,5], and columns [2,3,5]. How do I do this? I would like to obtain the equivalent of M[0:3,0:3] but using coordinates [2,3,5] instead of [0,1,2]. I have trie...
Extract an array of numbers from a Python array
Suppose I have a 10x10 Python array, M. I would like to extract the 3x3 array with the values of the rows [2,3,5], and columns [2,3,5]. How do I do this? I would like to obtain the equivalent of M[0:3,0:3] but using coordinates [2,3,5] instead of [0,1,2]. I have tried M[[2,3,5],[2,3,5]], but this produces three values,...
[ "You could .take() twice\n>>> a = np.arange(100).reshape(10,10)\n>>> a\narray([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],\n [40, 41, 42, 43, 44, 45, 46, 47, 48, ...
[ 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074514379_arrays_numpy_python.txt
Q: How to use conditional statement to map duplicates first and last with multiple columns in a dataframe? I am working with the following dataframe: issue_status market_phase trading_status is_and_mp market_state reason 0 10 0 B0 100 UNSCHEDULED_AU...
How to use conditional statement to map duplicates first and last with multiple columns in a dataframe?
I am working with the following dataframe: issue_status market_phase trading_status is_and_mp market_state reason 0 10 0 B0 100 UNSCHEDULED_AUCTION 1 20 0 200 CONTINUOUS_TRADING 2 40 ...
[ "UPDATE\nFollowing answer is updated after @PatrickChong 's updated logic:\n# df = pd.DataFrame(data=[[None,\"000\",\"CLOSED\"],[None,\"200\",\"CONTINUOUS_TRADING\"],[None,\"103\",\"None\"],[None,\"204\",\"UNSCHEDULED_AUCTION\"],[None,\"203\",\"UNSCHEDULED_AUCTION\"],[\"B0\",\"100\",\"UNSCHEDULED_AUCTION\"],[\"B1\"...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074509614_dataframe_pandas_python.txt
Q: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! in simple chatbot codes I made my first Korean chatbot program with python, pytorch and pycharm. It works in my local environment but so slow, So I want to move my codes to Google Colab to make it fast. But...
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! in simple chatbot codes
I made my first Korean chatbot program with python, pytorch and pycharm. It works in my local environment but so slow, So I want to move my codes to Google Colab to make it fast. But I have runtime error : two devices(cuda and cpu) works in same space. I looked for this error and found out that I should upload all of m...
[ "Replace token_ids, mask, label = samples with token_ids, mask, label = [t.to(device) for t in samples]\nThis is because the samples generated by the dataloader is on CPU instead of CUDA by default. You have to move them to CUDA before performing forward.\n" ]
[ 0 ]
[]
[]
[ "cpu", "gpu", "python", "pytorch" ]
stackoverflow_0074514534_cpu_gpu_python_pytorch.txt
Q: type object 'datetime.datetime' has no attribute 'datetime' I have gotten the following error: type object 'datetime.datetime' has no attribute 'datetime' On the following line: date = datetime.datetime(int(year), int(month), 1) Does anybody know the reason for the error? I imported datetime with from datetime ...
type object 'datetime.datetime' has no attribute 'datetime'
I have gotten the following error: type object 'datetime.datetime' has no attribute 'datetime' On the following line: date = datetime.datetime(int(year), int(month), 1) Does anybody know the reason for the error? I imported datetime with from datetime import datetime if that helps Thanks
[ "Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.\nYour error is probably based on the confusing naming of the module, and what either you or a ...
[ 333, 156, 23, 22, 6, 4, 3, 1, 1, 0, 0 ]
[ "The Problem Is That You Are Using The Tag\nfrom datetime\n\nI had The Same Problem You Need To use It Like This Instead\nimport datetime\n\n" ]
[ -3 ]
[ "datetime", "namespaces", "python" ]
stackoverflow_0012906402_datetime_namespaces_python.txt
Q: Convert a specific date into fiscal year in python I am trying to classified a specific date by fiscal year in python. My code is as follows. As you can see, the date I want to convert is 5/10/2017 which is in 2017 fiscal year, !pip install fiscalyear import fiscalyear fiscalyear.START_MONTH = 9 New_CF_Date='5/1...
Convert a specific date into fiscal year in python
I am trying to classified a specific date by fiscal year in python. My code is as follows. As you can see, the date I want to convert is 5/10/2017 which is in 2017 fiscal year, !pip install fiscalyear import fiscalyear fiscalyear.START_MONTH = 9 New_CF_Date='5/10/2017 12:00:00 AM' blank_pos=New_CF_Date.index(' 12:00:...
[ "The fiscalyear.FiscalDate() does not take the datetime.datetime object as an input, so you may want to explicitly create a new fiscalyear.FiscalDate object using the datetime object.\nimport datetime\nimport fiscalyear\n\nfiscalyear.setup_fiscal_calendar(start_month=9)\n\ninput_date='5/10/2017'\nNew_CF_Date = date...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074514495_python.txt
Q: How do I make my function work on negative numbers? repeat = "y" while repeat == "y": #First get the two integers from the user a = int(input("Enter the first integer: ")) b = int(input("Enter the second integer: ")) #Start the answer with 0 answer = 0 print("A", "B") print("---") ...
How do I make my function work on negative numbers?
repeat = "y" while repeat == "y": #First get the two integers from the user a = int(input("Enter the first integer: ")) b = int(input("Enter the second integer: ")) #Start the answer with 0 answer = 0 print("A", "B") print("---") print(a, b) #run loop until b is not zero while b...
[ "The issue is with the floor division b//2, when b is negative the result will be the lower integer, so -0.5 will be rounded to -1. To avoid it cast to an int a regular division b = int(b / 2).\nAfter removing duplicate code the while loop looks like that\nwhile b != 0:\n if b % 2 != 0:\n answer = answer ...
[ 0, 0 ]
[]
[]
[ "multiplication", "python" ]
stackoverflow_0074514540_multiplication_python.txt
Q: django MultiValueDictKeyError when trying to retrieve "type" I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here: <div class="p...
django MultiValueDictKeyError when trying to retrieve "type"
I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here: <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r ...
[ "You might try this as an alternative if you can't find the bug:\n#your Forms.py\nfrom django import forms\nmy_d_types=((\"accounts\",\"Accounts\"),(\"contacts\",\"Contacts\"),\n (\"membership\",\"Membership\"),(\"cg\",\"Community Group\"),\n (\"cgm\",\"Community Group Member\"),(\"so\",\"Sale...
[ 1 ]
[]
[]
[ "django", "python", "python_requests" ]
stackoverflow_0074463372_django_python_python_requests.txt
Q: Django: data from Views.py not displaying in HTML page My home.html in div where I called the { data } to display in HTML <div id= "main"> <h1> DATA SCRAPPER</h1> <h2>Header Data from html Page</h2> { data } </div> The local host shows But in terminal it is showing the scrapped data Views.py where de...
Django: data from Views.py not displaying in HTML page
My home.html in div where I called the { data } to display in HTML <div id= "main"> <h1> DATA SCRAPPER</h1> <h2>Header Data from html Page</h2> { data } </div> The local host shows But in terminal it is showing the scrapped data Views.py where def home(request): soup= None URL = 'https://www.abc.h...
[ "You're just missing some curly braces.\nYou need:\n{{ data }}\n\nnot\n{ data }\n\n", "For displaying variable data you have to use double bracket\n{{data}}\n\n", "\n\n<!doctype html>\n<html>\n<head>\n<title>code </title>\n</head>\n<body>\n<div id=\"main\">\n<h1> data </h1>\n<h2> header data from html </h2>\n{{...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074514579_django_django_models_django_templates_django_views_python.txt
Q: Importing modules from different folders I am following the pytest "Get Started" guide, and I just can't make it work. It seems to be something very elementary, but I just cant find it. The problem resides in importing modules from other folders, and, although I am following the official documentation, I cant make...
Importing modules from different folders
I am following the pytest "Get Started" guide, and I just can't make it work. It seems to be something very elementary, but I just cant find it. The problem resides in importing modules from other folders, and, although I am following the official documentation, I cant make it work Following PyPa and the official docum...
[ "It's a common issue in Python that the tests for a package cannot find the package itself.\nThe main reason for the issues is your working directory. You cannot just cd into the tests folder and run the tests. In fact, you need to be one level above your project folder, so you need to be in ex47_pypa/.. and then r...
[ 0 ]
[]
[]
[ "directory", "module", "pytest", "python" ]
stackoverflow_0074268066_directory_module_pytest_python.txt
Q: Standard way to embed version into Python package? Is there a standard way to associate version string with a Python package in such way that I could do the following? import foo print(foo.version) I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are s...
Standard way to embed version into Python package?
Is there a standard way to associate version string with a Python package in such way that I could do the following? import foo print(foo.version) I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that ...
[ "Not directly an answer to your question, but you should consider naming it __version__, not version.\nThis is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.\nUsually, __version__ is a string, but sometim...
[ 185, 160, 128, 34, 31, 15, 14, 11, 7, 6, 5, 5, 5, 5, 5, 1, 1, 1, 0 ]
[ "\nUse a version.py file only with __version__ = <VERSION> param in the file. In the setup.py file import the __version__ param and put it's value in the setup.py file like this:\nversion=__version__\nAnother way is to use just a setup.py file with version=<CURRENT_VERSION> - the CURRENT_VERSION is hardcoded.\n\nSi...
[ -1, -3, -3 ]
[ "package", "python", "string" ]
stackoverflow_0000458550_package_python_string.txt
Q: How to show Ag grid pop up menu above Quasar QDialog I am using Ag grid inside quasar QDialog. When the dialog is displayed and I click the column option menu, the Ag grid pop up menu appears behind QDialog, see the picture below: is there any way to make the ag grid pop up menu shows in the front of the QDialog?...
How to show Ag grid pop up menu above Quasar QDialog
I am using Ag grid inside quasar QDialog. When the dialog is displayed and I click the column option menu, the Ag grid pop up menu appears behind QDialog, see the picture below: is there any way to make the ag grid pop up menu shows in the front of the QDialog? For reference, I see this commmit in Aggrid code: https:/...
[ "I add the required css into the wp.css:\nwp.css = \"\"\"\n .ag-menu {z-index: 9999 !important;}\n \"\"\"\n\nreference:\nhttps://github.com/justpy-org/justpy/blob/master/jpcore/webpage.py#L52\nthe result looks like below, which shows the ag grid pop up menu above the quasar dialog.\n\n" ]
[ 0 ]
[]
[]
[ "ag_grid", "css", "justpy", "python", "quasar_framework" ]
stackoverflow_0074379959_ag_grid_css_justpy_python_quasar_framework.txt
Q: Check if an specific file available or not in a directory File_Name = "Invoice_Dmart" Folder-Name = "c:\Documents\Scripts\Bills" How to check if the specific filename exist in the "Folder-Name" with any extension, If Yes Get the full path in a variable. Code i have been using: import os.path if not os.path.Folder...
Check if an specific file available or not in a directory
File_Name = "Invoice_Dmart" Folder-Name = "c:\Documents\Scripts\Bills" How to check if the specific filename exist in the "Folder-Name" with any extension, If Yes Get the full path in a variable. Code i have been using: import os.path if not os.path.Folder-Name(File_Name): print("The File s% it's not created "%F...
[ "Before, you should fix the syntax of the variable Folder-Name to Folder_Name.\nI guess you can solve the problem by simply adding the two strings through a slash, and using the function os.path.exists() like:\nimport os.path\n\nFile_Name = \"Invoice_Dmart\"\nFolder_Name = \"c:\\Documents\\Scripts\\Bills\"\n\npath ...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074444773_python_python_3.x.txt
Q: pyautogui throws me error message. How can I fix my code? It gives me error message like below. How can I fix this? Traceback (most recent call last): File "c:\Users\jayjeo\tempCodeRunnerFile.py", line 3, in <module> x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8) TypeError: cannot unpack...
pyautogui throws me error message. How can I fix my code?
It gives me error message like below. How can I fix this? Traceback (most recent call last): File "c:\Users\jayjeo\tempCodeRunnerFile.py", line 3, in <module> x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8) TypeError: cannot unpack non-iterable NoneType object I made a code as below. I think ...
[ "This was changed in version 0.9.41. After that point, if the window is not found, it raises an exception. Before that point, it returns None. So, you need:\npt = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)\nif not pt:\n print(\"Not Detected\")\n pyautogui.click(1280,720)\nelse:\n x, y ...
[ 5 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0074514720_pyautogui_python.txt
Q: Predict new data based on previously clustered set I have a large set of binary data that I need to cluster. For example [[0 1 1 0 ... 0 1 0 1 ], [1 0 1 1 ... 0 0 1 1 ], ... [0 0 1 0 ... 1 0 1 1 ]] From what I've read, the best clustering algorithms for binary data are hierarchical such as agglomerative clust...
Predict new data based on previously clustered set
I have a large set of binary data that I need to cluster. For example [[0 1 1 0 ... 0 1 0 1 ], [1 0 1 1 ... 0 0 1 1 ], ... [0 0 1 0 ... 1 0 1 1 ]] From what I've read, the best clustering algorithms for binary data are hierarchical such as agglomerative clustering. So I implemented that using scikit. I have a v...
[ "When you want to predict, use a classifier, not clustering.\nHere, the most appropriate classifier would likely be a 1NN classifier. For performance reasons I'd choose DT or SVM instead though.\n", "For the followers, you can see the relevant posts:\n\nscikit-learn: Predicting new points with DBSCAN\nWhy k-means...
[ 0, 0 ]
[]
[]
[ "cluster_analysis", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0055983983_cluster_analysis_machine_learning_python_scikit_learn.txt
Q: How do I remove second row from the column name in pandas? How do I remove the row that says "UN member states"? A: You can use droplevel to completely remove a multi-index level: df.columns = df.columns.droplevel(1)
How do I remove second row from the column name in pandas?
How do I remove the row that says "UN member states"?
[ "You can use droplevel to completely remove a multi-index level:\ndf.columns = df.columns.droplevel(1)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074514741_dataframe_jupyter_notebook_pandas_python.txt
Q: handling infinite supply in minimum cost flow problem I got a typical problem about minimum cost flow problem. I'm given a dataset # node : {pos, demand} nodes_dict = {1: {'pos': (0, 0, 1), 'demand': 'NA'}, 2: {'pos': (0, 3, 1), 'demand': 'NA'}, 3: {'pos': (0, 6, 1), 'demand': 'NA'}, 4: {'pos': (4, 0, 1), 'demand'...
handling infinite supply in minimum cost flow problem
I got a typical problem about minimum cost flow problem. I'm given a dataset # node : {pos, demand} nodes_dict = {1: {'pos': (0, 0, 1), 'demand': 'NA'}, 2: {'pos': (0, 3, 1), 'demand': 'NA'}, 3: {'pos': (0, 6, 1), 'demand': 'NA'}, 4: {'pos': (4, 0, 1), 'demand': 1}, 5: {'pos': (4, 3, 1), 'demand': 2}, 6: {'pos': (4, 6,...
[ "This feature is not implemented in networkx version 2.8 (might be implemented in the future).\nOne thing that comes to mind is that if you are working with a special case of 'infinite supply' nodes that each have a single connection (like in the post), then you can work out a solution by solving for all feasible s...
[ 1 ]
[]
[]
[ "graph", "logistics", "networkx", "python" ]
stackoverflow_0074514546_graph_logistics_networkx_python.txt
Q: How to prevent the repetition of code suggest for Python in VSCode? I am using VSCode for writing Python code in a Jupyter Notebook. The relevant extensions installed are Python, Pylance and Jupyter. The problem occurs when I am coding, VSCode will give two same suggestion in the box. It looks like this: Problem H...
How to prevent the repetition of code suggest for Python in VSCode?
I am using VSCode for writing Python code in a Jupyter Notebook. The relevant extensions installed are Python, Pylance and Jupyter. The problem occurs when I am coding, VSCode will give two same suggestion in the box. It looks like this: Problem How can I remove the duplicated code suggestion?
[ "Upgrade Jupyter extension to pre-release version.\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "pylance", "python", "visual_studio_code" ]
stackoverflow_0074499443_jupyter_notebook_pylance_python_visual_studio_code.txt
Q: Transform Pandas column to get a key value pair in a column post group by My DataFrame: Col X Col Y ID Value A a 'r' 3 A a 'b' 2 A a 'c' 1 B b 'd' 5 B b 's' 6 B b 'd' 7 Output required: Co...
Transform Pandas column to get a key value pair in a column post group by
My DataFrame: Col X Col Y ID Value A a 'r' 3 A a 'b' 2 A a 'c' 1 B b 'd' 5 B b 's' 6 B b 'd' 7 Output required: Col X Col Y Out A a {'r':3, 'b':2, 'c':1} B b {...
[ "Use GroupBy.apply with lambda function:\ndf['ID'] = df['ID'].str.strip(\"'\")\n\ndf1 = (df.groupby(['Col X', 'Col Y'])[['ID','Value']]\n .apply(lambda x: dict(x.to_numpy()))\n .reset_index(name='Out'))\nprint (df1)\n Col X Col Y Out\n0 A a {'r': 3, 'b': 2, 'c': 1}\n1 ...
[ 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074514826_pandas_python.txt
Q: Error : strptime() argument 1 must be str, not int I am trying to substract two times and getting an error. In below total error is coming up if result[0]['outTime'] != None: type = "bothPunchDone" FMT = '%H:%M:%S' total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT) I...
Error : strptime() argument 1 must be str, not int
I am trying to substract two times and getting an error. In below total error is coming up if result[0]['outTime'] != None: type = "bothPunchDone" FMT = '%H:%M:%S' total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT) I tried but not able to solve the issue.
[ "from datetime import datetime\n\nresult = datetime.now().strftime(\"%H:%M:%S\")\n\nif result != None:\n type = \"bothPunchDone\"\n \nFMT = '%H:%M:%S'\ntotal= datetime.strptime(result, FMT) - datetime.strptime(result, FMT)\n\nprint(total)\n\nis working for me. Try to check the type of result[0]['outTime']\n" ...
[ 0 ]
[]
[]
[ "django", "python", "time" ]
stackoverflow_0074514820_django_python_time.txt
Q: Python Pandas rows merging different column values include Binary or Yes or No values Column1 Column2 Column3 Eswar IT Yes Eswar Admin No Column1 Column2 Column3 Eswar IT,Admin No I need this as Where Yes/No becomes No Or 1/0 become 0 A: You can aggreagte values by join and min, it working for Yes/...
Python Pandas rows merging different column values include Binary or Yes or No values
Column1 Column2 Column3 Eswar IT Yes Eswar Admin No Column1 Column2 Column3 Eswar IT,Admin No I need this as Where Yes/No becomes No Or 1/0 become 0
[ "You can aggreagte values by join and min, it working for Yes/No and 1/0 values very well:\ndf1 = (df.groupby('Column1', as_index=False)\n .agg(Column2=('Column2', ','.join), Column3=('Column3', 'min')))\nprint (df1)\n Column1 Column2 Column3\n0 Eswar IT,Admin No\n\n\nprint (df)\n Column1 Column...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074514827_pandas_python.txt
Q: Pandas Column Content Editing I was wondering what method is best for changing contents in the whole column in my dataframe. Part of my dataframe has the column "Percentage" and the contents in that column labeled as "#%". Here, I want to adjust the whole column from percentage to decimal numbers. For instance, 80...
Pandas Column Content Editing
I was wondering what method is best for changing contents in the whole column in my dataframe. Part of my dataframe has the column "Percentage" and the contents in that column labeled as "#%". Here, I want to adjust the whole column from percentage to decimal numbers. For instance, 80% to 0.80 and 42% to 0.42. What wou...
[ "df['DataFrame Column'] = df['DataFrame Column'].str[:-1].astype(float)/100\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074514865_dataframe_pandas_python.txt
Q: i want to do Maxzero function in Python Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero. This question was originally made for java but i wo...
i want to do Maxzero function in Python
Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero. This question was originally made for java but i would like to do it in python still i cant solv...
[ "This should do the trick:\ndef odd_right(a):\n return [i for i in a if i%2 != 0]\n\ndef zeroMax(l):\n for i, v in enumerate(l[:]):\n if v == 0:\n temp_list = odd_right(l[i:])\n rep = max(temp_list) if temp_list else 0 \n l[i] = rep\n return l\n\nAlthough stackoverfl...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074514760_list_python.txt
Q: zip dict converts a integer list to a string while creating a JSON file I am trying to save a JSON file from a dataframe. Sample data: import pandas as pd import json df Metric Value 0 Line1 10% off 1 Line2 15% off 2 Line3 20% off 3 Line4 25% off 4 L...
zip dict converts a integer list to a string while creating a JSON file
I am trying to save a JSON file from a dataframe. Sample data: import pandas as pd import json df Metric Value 0 Line1 10% off 1 Line2 15% off 2 Line3 20% off 3 Line4 25% off 4 Line5 30% off 5 revenueXaxis ['Week 1', 'Week 2', 'Week 3', 'We...
[ "If string starting by [ convert values to lists by ast.literal_eval only for filtered rows:\nimport ast\n\nm = df['Value'].str.startswith('[')\ndf.loc[m, 'Value'] = df.loc[m, 'Value'].apply(ast.literal_eval)\n\nLast create dictionary:\nprint (df.set_index('Metric')['Value'].to_dict())\n\nprint (dict(zip(df.iloc[:,...
[ 1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074513906_json_pandas_python.txt
Q: How to check specific file and run another python script I want to use watchdog for monitoring specific filename in directory for run specific python script. for example: First, I want to use watchdog for monitor all of .avi file. If name of .avi file in path (C:/User/AAxxx/video/) is : ABxxx_11.avi, I want to run...
How to check specific file and run another python script
I want to use watchdog for monitoring specific filename in directory for run specific python script. for example: First, I want to use watchdog for monitor all of .avi file. If name of .avi file in path (C:/User/AAxxx/video/) is : ABxxx_11.avi, I want to run ABxxx_11.py If name of .avi file in path (C:/User/BBxxx/video...
[ "I can't get your code to run, so I hardcoded the values. Just check for the modified and created files, get the file name and execute the python script accordingly.\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n\nclass Watcher:\n DIRECTORY_TO_WATCH ...
[ 0 ]
[]
[]
[ "python", "watchdog" ]
stackoverflow_0074514273_python_watchdog.txt
Q: Is there a vim plugin for Python that will check if a non-existant object is called from a package? I have been using the flake 8 python extension, which when ran will tell me whether a variable is not defined, if there are too many white spaces, etc. But flake8 will not produce an error if I call a nonexistent ob...
Is there a vim plugin for Python that will check if a non-existant object is called from a package?
I have been using the flake 8 python extension, which when ran will tell me whether a variable is not defined, if there are too many white spaces, etc. But flake8 will not produce an error if I call a nonexistent object from some package. For example, the following will not produce an error with flake8: import numpy as...
[ "Install pylint then create a vim map to run it from within vim.\nnnoremap <leader>l :!python3 -m pylint % <bar> grep no-member<cr>\n\nNotes: I'm using <leader>l but it could be anything else. Also, <bar> grep no-member will only output the error you're looking for. Remove it to see other pylint warnings.\n" ]
[ 0 ]
[]
[]
[ "plugins", "python", "vim" ]
stackoverflow_0074435856_plugins_python_vim.txt
Q: how read a specific sheet from a CSV file using read_csv() function of pandas library by passing sheet name as an argument? i want to read a csv file with the file name, when i pass the sheet name as an argument i am getting an error message. i tried the following code and it did not work. import pandas as pd df =...
how read a specific sheet from a CSV file using read_csv() function of pandas library by passing sheet name as an argument?
i want to read a csv file with the file name, when i pass the sheet name as an argument i am getting an error message. i tried the following code and it did not work. import pandas as pd df = pd.read_csv('file_name.csv',sheet_name='sheet 1',header = 1) The error message is " read_csv() got an unexpected keyword argumen...
[ "I think you should use excel_parse instead of parse_CSV , because CSV is a comma separated text file, which does not contain multiple sheets.\nxls = pd.ExcelFile('path_to_file.xls')\nsheet1 = xls.parse(0)\n\n# above will give you first sheet\n\nsheet1 = xls.parse(1)\n\n#This will give you second sheet\n\n" ]
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074515076_csv_pandas_python.txt
Q: Python Pandas Plot graphs in percentage I have data of States and Classes as below. I am trying to plot the total, and different percentages using matplotlib. data = [['FL', 2], ['AR', 0], ['CA', 0], ['CA', 1], ['AR', 1], ['FL', 0], ['CA', 0], ['CA', 1], ['AR', 2], ['FL', 1], ['AR', 0], ['FL', 2], ['CA', ...
Python Pandas Plot graphs in percentage
I have data of States and Classes as below. I am trying to plot the total, and different percentages using matplotlib. data = [['FL', 2], ['AR', 0], ['CA', 0], ['CA', 1], ['AR', 1], ['FL', 0], ['CA', 0], ['CA', 1], ['AR', 2], ['FL', 1], ['AR', 0], ['FL', 2], ['CA', 1], ['FL', 1], ['AR', 1], ['AR', 2], ['AR', 1...
[ "I assume your terms are defined like these.\n\nState level percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for the class C and all states)\nClass level percentage of a state S and a class C = 100 * (count of records for the state S and the class ...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074495984_matplotlib_pandas_plot_python.txt
Q: How can I write an mltable artifact from python to a local folder? I am using the mltable library on an AzureML notebook. I can successufully load a local csv file as an mltable: from mltable import from_delimited_files paths = [{'file': "dati_estra_test.csv"}] dati = from_delimited_files(paths) And I can view it...
How can I write an mltable artifact from python to a local folder?
I am using the mltable library on an AzureML notebook. I can successufully load a local csv file as an mltable: from mltable import from_delimited_files paths = [{'file': "dati_estra_test.csv"}] dati = from_delimited_files(paths) And I can view it as a pandas dataframe: Is there a way to write this artifact as an MLT...
[ "Use the below code block to get the file downloaded.\nfrom azureml.core import Workspace, Dataset\n\nsubscription_id = ‘subscription'\nresource_group = ‘your RG’\nworkspace_name = 'nov21'\n\nworkspace = Workspace(subscription_id, resource_group, workspace_name)\n\ndataset = Dataset.get_by_name(workspace, name='chu...
[ 0 ]
[]
[]
[ "azure", "azure_machine_learning_service", "azure_sdk", "python" ]
stackoverflow_0074507558_azure_azure_machine_learning_service_azure_sdk_python.txt
Q: Python decode not converting to string I am attempting to read a string from serial line using the code below, python keeps attaching the b' prefix and newline or return suffixes despite my telling it to convert to regular code and strip those out. Also, even if I send the text for 'FORWARD' to the device, it wil...
Python decode not converting to string
I am attempting to read a string from serial line using the code below, python keeps attaching the b' prefix and newline or return suffixes despite my telling it to convert to regular code and strip those out. Also, even if I send the text for 'FORWARD' to the device, it will not recognize the response. Why wont pytho...
[ "Hello I think decode('UTF-8') might help. I am working with binary data as well and you should specify which form you want it to be decoded to.\nb'test'.decode('utf-8') == 'test' -> True\nIf the problem roots in that your string is binary which contains binary string, such as b'b\"test\"' then you can solve it wit...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074511607_python_python_3.x.txt
Q: How to submit an HTML dropdown list using FastAPI? How do I submit the value selected from a dropdown list using FastAPI and HTML template? Here is my code for the app thus far: from fastapi import FastAPI, Request, Form from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(di...
How to submit an HTML dropdown list using FastAPI?
How do I submit the value selected from a dropdown list using FastAPI and HTML template? Here is my code for the app thus far: from fastapi import FastAPI, Request, Form from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates/") @app.get('/') def read_form(): ...
[ "You need to make sure to include the action attribute in the form, which specifies where to send the form-data when a form is submitted (see W3schools <form> tag docs as well). Also, in the <select> element that is used to create the drop-down list, make sure to use the same name used to define the Form parameter ...
[ 0 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0074504161_fastapi_python.txt
Q: Tensorboard scalar plotting with epoch number on the horizontal axis I am new to TensorFlow, and I recently started to play around a little bit with data visualization using Tensorboard. I was wondering if it is possible to convert the horizontal axis of the monitoring scalars (I monitor accuracy and loss on train...
Tensorboard scalar plotting with epoch number on the horizontal axis
I am new to TensorFlow, and I recently started to play around a little bit with data visualization using Tensorboard. I was wondering if it is possible to convert the horizontal axis of the monitoring scalars (I monitor accuracy and loss on train and validation) to show epoch number instead of iteration number. the onl...
[ "Yes, you can do this by passing the epoch number to the global_step parameter of the add_summary() method:\nsummary_writer = tf.summary.FileWriter(log_dir)\n\nmy_summary = session.run(my_summary_op, feed_dict)\nsummary_writer.add_summary(my_summary, global_step=epoch_number)\n\n", "One workaround is using add_sc...
[ 4, 0 ]
[]
[]
[ "python", "tensorboard", "tensorflow" ]
stackoverflow_0046017070_python_tensorboard_tensorflow.txt
Q: extracting all tables using tabula While reading a pdf file using df = tabula.read_pdf(pdf_file, pages=‘all’) —> displays all tables from all pages. but when converting into a Pandas dataframe using tables = pd.DataFrame(pdf_file, pages = ‘all’, lattice = ‘True’)[0])—> display only the table on the first page. A:...
extracting all tables using tabula
While reading a pdf file using df = tabula.read_pdf(pdf_file, pages=‘all’) —> displays all tables from all pages. but when converting into a Pandas dataframe using tables = pd.DataFrame(pdf_file, pages = ‘all’, lattice = ‘True’)[0])—> display only the table on the first page.
[ "The df that you receive from tabula should be in the form of a list.\nI also think that if you want to use pandas and tabula together the syntax should be something like below,\ndf = pandas.DataFrame(tabula.read_pdf(pdffile, pages ='all')[0])\n\nIf you want to utilize what you've gotten from tabula, you can also c...
[ 0 ]
[]
[]
[ "python", "tabula_py", "text_extraction" ]
stackoverflow_0074515191_python_tabula_py_text_extraction.txt
Q: ScrapeTube package for Youtube is not Working? I tried to extract all youtube videoid from a channel. It was working fine last week suddenly its not working from yesterday. In fact its not throwing any errors. Kindly help! #scrape all the videos links import scrapetube link=[] videos = scrapetube.get_channel("UCPX...
ScrapeTube package for Youtube is not Working?
I tried to extract all youtube videoid from a channel. It was working fine last week suddenly its not working from yesterday. In fact its not throwing any errors. Kindly help! #scrape all the videos links import scrapetube link=[] videos = scrapetube.get_channel("UCPXnayBvF7ynbG_I3VOTgIg") for video in videos: str...
[ "It was a bug in a consent line in youtube that is fixed in version 2.3.1 of scrapetube. I suggest you uninstall any version <= 2.3.0 and install the latest one. That should do it.\n" ]
[ 2 ]
[]
[]
[ "python", "scrape", "youtube" ]
stackoverflow_0074356652_python_scrape_youtube.txt
Q: Keras models diferent results after loading pretrained weights After successfully training a model, and saving the weights with a checkpoint, when I reload the weights with the load_weights function and run an evaluate, I get results as if the network was loaded with the original weights. I have tried to run the e...
Keras models diferent results after loading pretrained weights
After successfully training a model, and saving the weights with a checkpoint, when I reload the weights with the load_weights function and run an evaluate, I get results as if the network was loaded with the original weights. I have tried to run the eval on the train and valid sets, to rule out that it is a problem of...
[ "If i remove the 'Shuffe = False' in the test data_generator works perfectly fine.\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074457385_keras_python_tensorflow.txt
Q: pyspark filter the value of a column to assign a new column In python, you can write A filter and assign a value to a new column by using df.loc[df["A"].isin([1,2,3]),"newColumn"] ="numberType". How does this work in pyspark? A: FYI, in Python there is no such thing as DataFrame. The code you showed above are Pa...
pyspark filter the value of a column to assign a new column
In python, you can write A filter and assign a value to a new column by using df.loc[df["A"].isin([1,2,3]),"newColumn"] ="numberType". How does this work in pyspark?
[ "FYI, in Python there is no such thing as DataFrame. The code you showed above are Pandas syntax - a Python library written for data analysis and manipulation.\nFor your problem, you can use when, lit and col from pyspark.sql.functions to achieve this.\nfrom pyspark.sql.functions import when, lit, col\n\ndf1 = df.w...
[ 0, 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074515285_pyspark_python.txt
Q: how can i do a variables in python this is my problem and the photo of it i have no idea why it didn't work A: Avoid this by selecting 'Auto Save' Option in File Menu of VS Code A: I think it's not just about saving files automatically. Usually, we use CamelCase or _ For example, pythonVariables or python_vari...
how can i do a variables in python
this is my problem and the photo of it i have no idea why it didn't work
[ "Avoid this by selecting 'Auto Save' Option in File Menu of VS Code\n", "I think it's not just about saving files automatically.\nUsually, we use CamelCase or _\nFor example, pythonVariables or python_variables.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "variables", "visual_studio_code" ]
stackoverflow_0074513416_python_variables_visual_studio_code.txt
Q: applying conditions basis the value in column to create new tag Existing Dataframe : Id created_by A A A 123 B X B B Expected Dataframe : Id created_by status A A category_1 A 123 category_2 B X category_3 B B ...
applying conditions basis the value in column to create new tag
Existing Dataframe : Id created_by A A A 123 B X B B Expected Dataframe : Id created_by status A A category_1 A 123 category_2 B X category_3 B B category_1 I am looking to create a status tag basis the condition ...
[ "Problem is in second condition, there is necessary add filtering non X values in created_by:\nconditions = [\n df['Id'] == df['created_by'], \n (df['Id'] != df['created_by']) & (df['created_by'] != 'X'),\n (df['Id'] != df['created_by']) & (df['created_by'] == 'X')\n\n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074515519_dataframe_pandas_python.txt
Q: How to access package level variable Suppose i have package named src src - __init__.py - app.py __init__.py ___version__ = '0.1.0' import os ENTRY_DIR = os.path.dirname(__file__) BASE_DIR = os path.dirname(ENTRY_DIR) DATA_DIR = os.path.join(BASE_DIR, 'data') how can i ...
How to access package level variable
Suppose i have package named src src - __init__.py - app.py __init__.py ___version__ = '0.1.0' import os ENTRY_DIR = os.path.dirname(__file__) BASE_DIR = os path.dirname(ENTRY_DIR) DATA_DIR = os.path.join(BASE_DIR, 'data') how can i access the variable DATA_DIR in app.py I t...
[ "The __init__.py file is used to define how your package looks for an other one so you cannot do what you are trying to do since you are inside.\nYou can create a cfg.py like this :\n# cfg.py\n\nimport os\n\nENTRY_DIR = os.path.dirname(__file__)\nBASE_DIR = os path.dirname(ENTRY_DIR)\nDATA_DIR = os.path.join(BASE_D...
[ 2 ]
[ "it seems like you are referencing wrong path for that variable.\nimport the file in app.py\nthen you will be able to use variables from that file in same package.\nuse underscore with file name\nimport init\nprint(DATA_DIR)\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074515105_python.txt
Q: Looal Dynamo db insert validation exception error I am learning to use dynamodb and am getting An error occurred (ValidationException) when calling the TransactWriteItems operation: One of the required keys was not given a value when trying to run my mock test to insert a value. I am trying to create a mock test. ...
Looal Dynamo db insert validation exception error
I am learning to use dynamodb and am getting An error occurred (ValidationException) when calling the TransactWriteItems operation: One of the required keys was not given a value when trying to run my mock test to insert a value. I am trying to create a mock test. I am clearly missing something and don't understand. Th...
[ "Every one of the items you try to Put must have its key attributes - in your case that is the \"email\" attribute - set. But it seems one of your calls used the name \"pk\" instead of \"email\", I guess a copy-pasto.\nYou also mention \"pk\" in the ConditionExpression - that's a typo too?\n" ]
[ 0 ]
[]
[]
[ "amazon_dynamodb", "python" ]
stackoverflow_0074514455_amazon_dynamodb_python.txt
Q: error putting paths in the function () in python im trying to run this code but I have an error when I put the path in the function the path turns grey and I have a red line under it, maybe someone can help me with that? import shutil from pathlib import Path from xml.etree import ElementTree as ET def contains_d...
error putting paths in the function () in python
im trying to run this code but I have an error when I put the path in the function the path turns grey and I have a red line under it, maybe someone can help me with that? import shutil from pathlib import Path from xml.etree import ElementTree as ET def contains_drone(path): tree = ET.parse(path.as_posix()) root =...
[ "Assuming the paths you define are your src and dst paths, your function definition should look like this, with corrected indentation and function definition:\ndef move_drone_files(src, dst):\n src, dst = Path(src), Path(dst)\n for path in src.iterdir():\n if path.suffix == '.xml' and contains_drone(pat...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074515410_python.txt
Q: Depth Estimation from Disparity Map I'm trying estimate the depth of a point from the disparity map. To start with, I did the stereo calibration and rectified the images, and proceeded to find the disparity map. I used the StereoSGBM in OpenCV. Since disparity refers to the distance between two corresponding point...
Depth Estimation from Disparity Map
I'm trying estimate the depth of a point from the disparity map. To start with, I did the stereo calibration and rectified the images, and proceeded to find the disparity map. I used the StereoSGBM in OpenCV. Since disparity refers to the distance between two corresponding points in the left and right image of a stereo...
[ "Check if your camera parameters fx, fy, Cx, Cy are in line with the spatial dimension of the images.\n" ]
[ 0 ]
[]
[]
[ "depth", "disparity_mapping", "opencv", "python" ]
stackoverflow_0071134338_depth_disparity_mapping_opencv_python.txt
Q: Excel data not sorting the type decimal.Decimal I have a view where i export data the numerical data but when i sort the data it is not getting sorted as the excel is not considering the values as numerical data how can i convert them to numerical data in order to display the data in numerical format and make the ...
Excel data not sorting the type decimal.Decimal
I have a view where i export data the numerical data but when i sort the data it is not getting sorted as the excel is not considering the values as numerical data how can i convert them to numerical data in order to display the data in numerical format and make the sorting work.i have a function which gets the data he...
[ "you should wrap the data in float or int class types\ne.g.\ndef get_output_value(self, key, value, neutral=None):\n display = value\n if value is None and not user.is_active:\n return 0, 0\n\n if value is None:\n return float(f\"{Decimal('.00')}\"), float(f\"{Decimal('.00...
[ 0 ]
[]
[]
[ "django", "excel", "python", "python_3.x" ]
stackoverflow_0074515592_django_excel_python_python_3.x.txt
Q: Value returned by property method in django not getting stored in database. How to make this possible? In my models.py file I have a property method which returns a value and I need to store that value in the database field. ` class bug(models.Model): ...... ....... id_of_bug = models.CharField(max_len...
Value returned by property method in django not getting stored in database. How to make this possible?
In my models.py file I have a property method which returns a value and I need to store that value in the database field. ` class bug(models.Model): ...... ....... id_of_bug = models.CharField(max_length=20, blank= False, null= False) @property def bug_id(self): bugid = "BUG{:03d}".form...
[ "I would try use a property setter that updates the table value:\nclass bug(models.Model):\n ......\n .......\n id_of_bug = models.CharField(max_length=20, blank= False, null= False)\n \n @property\n def bug_id(self):\n bugid = \"BUG{:03d}\".format(self.pk)\n self.id_of_bug = bugid\n...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0074515304_django_django_models_django_views_python.txt
Q: Passing Arguments to Spyder for debugging file I want to pass arguments in Spyder IDE with IPython to debug the file but the input arguments passing will be different Driver.py -in "C:\Desktop\" -out "C:\Desktop\" -f 65 -f2 64 How can i pass the arguments, so that i can be able to debug the file. A: Go to run > ...
Passing Arguments to Spyder for debugging file
I want to pass arguments in Spyder IDE with IPython to debug the file but the input arguments passing will be different Driver.py -in "C:\Desktop\" -out "C:\Desktop\" -f 65 -f2 64 How can i pass the arguments, so that i can be able to debug the file.
[ "Go to run > configure \nTick command line options and type in the arguments in the space.\n", "I think I know what you are looking for.\nFor my function, I have several arguments, to pass multiple arguments on spyder to debug I pass debugfile('filePath', args='--argN1=argV1 --argN2=argV2', wdir='coreFolderPath')...
[ 5, 0 ]
[]
[]
[ "python", "spyder" ]
stackoverflow_0053628850_python_spyder.txt
Q: pandas.json_normalize sending Not Implemented Error I have below line in my data pipeline code which takes json array and normalizes it using pandas.json_normalize df = pd.json_normalize(reviews, sep='_') Now when reviews is getting null or None, it has suddenly started failing. What should be done here? I tried ...
pandas.json_normalize sending Not Implemented Error
I have below line in my data pipeline code which takes json array and normalizes it using pandas.json_normalize df = pd.json_normalize(reviews, sep='_') Now when reviews is getting null or None, it has suddenly started failing. What should be done here? I tried writing all the data that review receives in a for loop, ...
[ "Which version of pandas are you using?\nIf you get the error AttributeError: module 'pandas' has oo attribute 'json_normalize' after inserting from pandas import json_normalize it may be due to the version you are using.\nYou have to downgrade the pandas to the version before 1.0.3. Since you need to import the js...
[ 0 ]
[]
[]
[ "dataframe", "json_normalize", "pandas", "python" ]
stackoverflow_0074515659_dataframe_json_normalize_pandas_python.txt
Q: Changing metadata when uploading file to s3 with python I have an html file that I am uploading to s3 using python. For some reason, s3 adds a system defined metadata saying that the file Content-Type is "binary/octet-stream": I need to change this value to "text/html". I can do it manually, but I want it to be d...
Changing metadata when uploading file to s3 with python
I have an html file that I am uploading to s3 using python. For some reason, s3 adds a system defined metadata saying that the file Content-Type is "binary/octet-stream": I need to change this value to "text/html". I can do it manually, but I want it to be done automatically when I upload the file. I tried the followi...
[ "Use MetadataDirective parameter:\nbucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata, MetadataDirective='REPLACE')\n\nMetadataDirective -- Specifies whether the metadata is copied from the source object or replaced with metadata provided in the request ('COPY' | 'REPLACE').\nS3 - Boto3 Docs\n", ...
[ 3, 0 ]
[]
[]
[ "amazon_s3", "bots", "python", "python_3.x" ]
stackoverflow_0064911004_amazon_s3_bots_python_python_3.x.txt
Q: Is there a prefab python function out there that turns only integer floats into ints? I would like to turn float integers (123.0) into ints (123). What I would like the function to do: Input: 2.1 Output: Exception, cannot turn float into int Input: 2.0 Output: 2 Using int() on a float seems to just be math.floor()...
Is there a prefab python function out there that turns only integer floats into ints?
I would like to turn float integers (123.0) into ints (123). What I would like the function to do: Input: 2.1 Output: Exception, cannot turn float into int Input: 2.0 Output: 2 Using int() on a float seems to just be math.floor() and that is not what I'm looking for.
[ "You can check if after you use int() it the same value as the float\ndef convert(num):\n if num == int(num):\n return int(num)\n raise Exception('Cannot turn float into int')\n\nAs a side note, using int() is not exactly as using math.floor(), try with negative numbers. What is the difference between ...
[ 3, 3, 2 ]
[]
[]
[ "floating_point", "python", "python_3.x" ]
stackoverflow_0074515645_floating_point_python_python_3.x.txt
Q: Sending email with Sendgrid using data from a csv I am trying to send out an email using Sendgrid and adding data from a csv into the body of the email. I can do this process with smtplib but now I need to do it using sendgrid. import os import pandas as pd from sendgrid import SendGridAPIClient from sendgrid.help...
Sending email with Sendgrid using data from a csv
I am trying to send out an email using Sendgrid and adding data from a csv into the body of the email. I can do this process with smtplib but now I need to do it using sendgrid. import os import pandas as pd from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail db = pd.read_csv('changes.csv', d...
[ "Use following two functions:\n def read_csv_for_email(final_path=None):\n \"\"\" send_csv_email\n Send final generated CSV file\n :return:\n \"\"\"\n final_path = \"sample/path/to.csv\"\n df = pd.read_csv(final_path, dtype=str, na_filter=True, index_col=False)\n res = send_email_with_csv(\n ...
[ 0 ]
[]
[]
[ "csv", "python", "sendgrid" ]
stackoverflow_0060011210_csv_python_sendgrid.txt
Q: Groupby/aggregation shows groups which were supposed to be filtered out before I have a pandas DataFrame with a column Size, on which I filter first and then group by and count records per group. The result contains also rows for the groups which were filtered out before, but with a count of 0: ( df[df["Size"]...
Groupby/aggregation shows groups which were supposed to be filtered out before
I have a pandas DataFrame with a column Size, on which I filter first and then group by and count records per group. The result contains also rows for the groups which were filtered out before, but with a count of 0: ( df[df["Size"].isin(("XXS", "XS", "S", "M", "L", "XL", "XXL"))] .groupby("Size") .agg( ...
[ "Sometimes it helps to wait a weekend and think about on Monday again:\nThe behavior occurred due to categorical datatype of Size column:\n>>> df.dtypes\n\nSize category\n...\n\n>>> df[\"Size\"].unique()\n\n['S', 'M', 'L', 'XL', 'XXL', 'XS', 'XXS']\nCategories (80, object): ['100 CM', '105 CM', ...
[ 1 ]
[ "df[df[\"Size\"].isin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])]\n .groupby(\"Size\")\n .agg(\n count=(\"OID\", \"count\"),\n )\n .sort_values(\"count\", ascending=False)\n\n====================================================\nisin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"...
[ -3 ]
[ "group_by", "pandas", "python" ]
stackoverflow_0074491161_group_by_pandas_python.txt
Q: I tried to created dictionary in dictionary but I struggled I tried to created a get_dict function that takes a parameter as a filename and then creates and returns a dictionary which contains key is the number of the product code and has value is a dictionary that contains key is a string of sizes (S, M, L, or XL...
I tried to created dictionary in dictionary but I struggled
I tried to created a get_dict function that takes a parameter as a filename and then creates and returns a dictionary which contains key is the number of the product code and has value is a dictionary that contains key is a string of sizes (S, M, L, or XL), and value is the number of the product. enter image descriptio...
[ "def get_dict(file_name): \n\nd={}\nwith open(file_name) as f:\n for line in f:\n line = line.strip()\n alist = line.split()\n if not alist[0] in d:\n d[alist[0]] = {alist[1]: alist[2]}\n else:\n d[alist[0]].update({alist[1]: alist[2]})\nprint(d)\n\nYou have to ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074515569_python.txt
Q: What is the logical error for this Python program to generate all possible unique ways to represent n=3 as sum of positive integers? Python program to generate all possible unique ways to represent n=3 as sum of positive integers: def fun(): res=[] a=[] def backtracking(n): if(n==0): ...
What is the logical error for this Python program to generate all possible unique ways to represent n=3 as sum of positive integers?
Python program to generate all possible unique ways to represent n=3 as sum of positive integers: def fun(): res=[] a=[] def backtracking(n): if(n==0): res.append(a) print(res) return if(n<0): return for i in range(1,n+1): a...
[ "You are appending the list a directly to the res, you should be appending a copy of the list a instead. List is passed by reference, so in the end, your res has 4 references to the same list which is empty. To get a copy of the list you have different options - list.copy() , copy.copy() method, or just slicing lis...
[ 0 ]
[]
[]
[ "dynamic_programming", "python", "recursive_backtracking" ]
stackoverflow_0074515786_dynamic_programming_python_recursive_backtracking.txt
Q: How can I set the time zone in Dockerfile using gliderlabs/alpine:3.3 My Dockerfile is: FROM gliderlabs/alpine:3.3 RUN set -x \ && buildDeps='\ python-dev \ py-pip \ build-base \ ' \ && apk --update add python py-lxml py-mysqldb $buildDeps \ && rm -rf /var/cache/apk/* \ ...
How can I set the time zone in Dockerfile using gliderlabs/alpine:3.3
My Dockerfile is: FROM gliderlabs/alpine:3.3 RUN set -x \ && buildDeps='\ python-dev \ py-pip \ build-base \ ' \ && apk --update add python py-lxml py-mysqldb $buildDeps \ && rm -rf /var/cache/apk/* \ && mkdir -p /app ENV INSTALL_PATH /app ENV TZ=Asia/Shanghai WORKDIR $INSTAL...
[ "The usual workaround is to mount /etc/localtime, as in issue 3359\n$ docker run --rm busybox date\nThu Mar 20 04:42:02 UTC 2014\n$ docker run --rm -v /etc/localtime:/etc/localtime:ro busybox date\nThu Mar 20 14:42:20 EST 2014\n$ FILE=$(mktemp) ; echo $FILE ; echo -e \"Europe/Brussels\" > $FILE ; docker run --rm -...
[ 7, 6, 0, 0 ]
[]
[]
[ "docker", "dockerfile", "python" ]
stackoverflow_0034972521_docker_dockerfile_python.txt
Q: Return integer or string instead of None from a JMESPath query Is there a way to return an integer or a string instead of None? I know that I can do an additional check like: item = {"SX": {"BX": 1}} value = jmespath.search("SX.BX", item) if jmespath.search("SX.BX", item) else 0 but the condition is very long an...
Return integer or string instead of None from a JMESPath query
Is there a way to return an integer or a string instead of None? I know that I can do an additional check like: item = {"SX": {"BX": 1}} value = jmespath.search("SX.BX", item) if jmespath.search("SX.BX", item) else 0 but the condition is very long and I would like to make it easier.
[ "You can build that logic in your JMESPath query:\nSX.BX || `0`\n\nGiven the empty JSON:\n{}\n\nWould yield you 0, as you are excepting it.\n\nSo, you Python code becomes:\nvalue = jmespath.search(\"SX.BX || `0`\", item)\n\n" ]
[ 1 ]
[]
[]
[ "jmespath", "python" ]
stackoverflow_0074514745_jmespath_python.txt