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: How to know what python version a package is compatible with I tried to install an old version of a python package and got the Could not find a version that satisfies the requirement... error. I am confident that the package and the specified version do exist, and I have learned that this problem often occurs whe...
How to know what python version a package is compatible with
I tried to install an old version of a python package and got the Could not find a version that satisfies the requirement... error. I am confident that the package and the specified version do exist, and I have learned that this problem often occurs when the package is incompatible with the python version. How do I fi...
[ "You can look up the package on the Python Package Index and scroll down to the \"Meta\" section in the left sidebar. This shows the Python version required by the package. As you do not specify the package you are looking for, I will use numpy as an example. For the current version of numpy, the following informat...
[ 3, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0066627014_pip_python.txt
Q: Sweeping over multiple configurations I'm interested in using hydra to run some experiments over various datasets. Following the documentation found here, I've set up my conf directory as follows conf ├── config.yaml ├── dataset │   ├── experiment_1_0.yaml │   ├── experiment_2_0.yaml │   ├── experiment_2_1.yaml │...
Sweeping over multiple configurations
I'm interested in using hydra to run some experiments over various datasets. Following the documentation found here, I've set up my conf directory as follows conf ├── config.yaml ├── dataset │   ├── experiment_1_0.yaml │   ├── experiment_2_0.yaml │   ├── experiment_2_1.yaml │   ├── experiment_3_0.yaml │   ├── experime...
[ "I believe the answer is to add the --multirun flag like\npython main.py --multirun\n\nand the experiments seem to run as expected\n" ]
[ 1 ]
[]
[]
[ "hydra", "python" ]
stackoverflow_0074365658_hydra_python.txt
Q: Creating netcdf file from csv using xarray with 3d var I'm trying to transform a csv file with year, lat, long and pressure into a 3 dimensional netcdf pressure(time, lat, long). However, my list is with duplicate values ​​as below: year,lon,lat,pressure 1/1/00,79.4939,34.4713,11981569640 1/1/01,79.4939,34.4713,11...
Creating netcdf file from csv using xarray with 3d var
I'm trying to transform a csv file with year, lat, long and pressure into a 3 dimensional netcdf pressure(time, lat, long). However, my list is with duplicate values ​​as below: year,lon,lat,pressure 1/1/00,79.4939,34.4713,11981569640 1/1/01,79.4939,34.4713,11870476671 1/1/02,79.4939,34.4713,11858633008 1/1/00,77.9513,...
[ "The requested task is not directly possible with this data -- it's not on regular horizontal grid but rather data collected from different points.\nHere is the plot:\n\nSo, to make it to the regular grid, one should interpolate, but as the density of the data in some region is really high and in other region rathe...
[ 1, 1 ]
[]
[]
[ "csv", "netcdf", "python", "python_xarray" ]
stackoverflow_0074354665_csv_netcdf_python_python_xarray.txt
Q: How can I stop if the number is <= 0? I'm trying to stop my program when the Warrior are Priest are both with 0 or < 0 or the vampire goes to 0 our < 0 if not they will not advance for the next round and just finish the battle that way, and set up a winner. while (warrior[0] and priest[0]) > 0 or vampire[0] > 0: #...
How can I stop if the number is <= 0?
I'm trying to stop my program when the Warrior are Priest are both with 0 or < 0 or the vampire goes to 0 our < 0 if not they will not advance for the next round and just finish the battle that way, and set up a winner. while (warrior[0] and priest[0]) > 0 or vampire[0] > 0: #Loop until all of the group die or the enem...
[ "Change the while condition to:\n while (warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0:\n\nWe added parenthesis Because precedence of logical 'and' is greater than the logical 'or'.\nIf warrior[0]>0 is true it does not consider whether vampire[0]>0 condition at all.\n" ]
[ 1 ]
[ "Seems like you need parentheses.\nwhile ((warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0): #Loop until all of the group die or the enemy dies\n execute_turn() #Execute the turn\nelse: #someone died\n break\n\n" ]
[ -2 ]
[ "python", "python_3.x" ]
stackoverflow_0074365736_python_python_3.x.txt
Q: self-hosted runner, Windows, Environment variables, savin paths I'm trying to calculate paths for a pip install from a internal devpi server. I'm running a self-hosted runner on a Windows server virtual machine. I'm trying to install the latest PIP package to the tool directory by calculating the path as follows; ...
self-hosted runner, Windows, Environment variables, savin paths
I'm trying to calculate paths for a pip install from a internal devpi server. I'm running a self-hosted runner on a Windows server virtual machine. I'm trying to install the latest PIP package to the tool directory by calculating the path as follows; - name: pip install xmlcli env: MYTOOLS: ${{ r...
[ "You need to append to $env:GITHUB_ENV, or you can set the script execution engine on your run action.\nWhen using shell pwsh, then you can use:\n\"{environment_variable_name}={value}\" >> $env:GITHUB_ENV\n\nWhen using shell powershell\n\"{environment_variable_name}={value}\" | Out-File -FilePath $env:GITHUB_ENV -E...
[ 0, 0 ]
[]
[]
[ "action", "environment_variables", "github", "pip", "python" ]
stackoverflow_0074351726_action_environment_variables_github_pip_python.txt
Q: How to change the label in display_list of a field in the model in django admin I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page. How to set the label to be used in the list_display admin page ? A: It might be ...
How to change the label in display_list of a field in the model in django admin
I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page. How to set the label to be used in the list_display admin page ?
[ "It might be possible that you use verbose_name the wrong way, and that you should use help_text=… [Django-doc] instead:\nfrom django.db import models\n\n\nclass MyModel(models.Model):\n name = models.CharField(\n max_length=64,\n help_text='here some long help text that this is about filling in th...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0074365266_django_django_admin_python.txt
Q: error when using time in rolling function pandas I am trying to calculate mean i.e moving average every 10sec of data; lets say 1 to 10sec, and 11sec to 20sec etc. Is below right for this? I am getting error when using "60sec" in rolling function, I think it may be due to the "ltt" column which is of type string, ...
error when using time in rolling function pandas
I am trying to calculate mean i.e moving average every 10sec of data; lets say 1 to 10sec, and 11sec to 20sec etc. Is below right for this? I am getting error when using "60sec" in rolling function, I think it may be due to the "ltt" column which is of type string, I am converting it to datetime, but still the error is...
[ "i don't know how to exactly implement this in your code but i had a kind of similar problem where i had to group each day into 4 hour timeslots. so an approach might be something like this:\npandas_df.groupby([pandas_df['ltt'].dt.hour, pandas_df['ltt'].dt.minute, (pandas_df['ltt'].dt.second / 10).astype(int)]).las...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074365692_pandas_python.txt
Q: Reading data from a text file into a list I'm trying to read some data from a text file I created into a list, but keep getting the "TypeError: 'str' object is not callable" error when i try to do this. Here is the code class Weather(): """ Weather Class """ def __init__(self,weather = ''): self.wea...
Reading data from a text file into a list
I'm trying to read some data from a text file I created into a list, but keep getting the "TypeError: 'str' object is not callable" error when i try to do this. Here is the code class Weather(): """ Weather Class """ def __init__(self,weather = ''): self.weather= weather def rome_weather(self, we...
[ "Line 111 should be as follows.\nrome.append(float(line))\n\nThe problem was the () brackets that was causing python to try and call line when it was in fact a string.\n", "As has been previously said (and read by the error) you're trying to call a string, which is not callable. Simply remove the brackets on 'lin...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074365734_python.txt
Q: Get item from set python I have a set which contains objects which I have the __eq__ and __hash__ functions defined for. I would like to be able to check if an object with the same hash is in the set and if it is in the set to return the object from the set as I need the reference to the object. class SetObject():...
Get item from set python
I have a set which contains objects which I have the __eq__ and __hash__ functions defined for. I would like to be able to check if an object with the same hash is in the set and if it is in the set to return the object from the set as I need the reference to the object. class SetObject(): def __init__( sel...
[ "Instead of using a set, use a dictionary where the keys and values are the same element. Then you can look use the value as a key and return the element.\nx = SetObject(1,2,3)\ny = SetObject(4,5,6)\n\nobject_set = dict([(x, x),(y, y)])\n\nprint(f\"{object_set=}\")\n\nz = SetObject(1,2,7)\nprint(f\"{z=}\")\nif z in...
[ 5, 2 ]
[]
[]
[ "python", "set" ]
stackoverflow_0074322894_python_set.txt
Q: How to run Scrapy in a while loop So Im doing a project scraping different websites using multiple spiders. I want to make it so that the spiders run again when the user says "Yes" when asked to continue. keyword = input("enter keyword: ") page_range = input("enter page range: ") flag = True while flag: proc...
How to run Scrapy in a while loop
So Im doing a project scraping different websites using multiple spiders. I want to make it so that the spiders run again when the user says "Yes" when asked to continue. keyword = input("enter keyword: ") page_range = input("enter page range: ") flag = True while flag: process = CrawlProcess() process.crawl(c...
[ "Method 1:\nscrapy creates Reactor which can't be reused after stop but if you will run Crawler in separated process then new process will have to create new Reactor.\nimport multiprocessing\n\ndef run_crawler(keyword, page_range):\n process = CrawlProcess()\n process.crawl(crawler1, keyword, page_range)\n pr...
[ 1, 0, 0 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0070289996_python_scrapy_web_scraping.txt
Q: Jupyter notebook and vscode I create new ec2 for jupyter server and i'm running jupyter lab with back-ground so i can access jupyter lab in browser. However, i want to edit my ipynb file in vscode but in vscode i can connect jupyter server but i can't see directories or read files in ec2. I tried over and over to ...
Jupyter notebook and vscode
I create new ec2 for jupyter server and i'm running jupyter lab with back-ground so i can access jupyter lab in browser. However, i want to edit my ipynb file in vscode but in vscode i can connect jupyter server but i can't see directories or read files in ec2. I tried over and over to connect the server and see the di...
[ "remote ssh is the standard approach. you would need to SSH to your EC2 from vscode, then you can browse and run notebooks.\n\nIn vscode, go to extensions and install \"Remote - SSH\" & \"Remote - SSH: Editing Configuration Files\"\nOpen command palette (cmd/ctrl + shift + P) and type \"show remote explorer\"\nAdd ...
[ 1, 0 ]
[]
[]
[ "jupyter", "python", "visual_studio_code" ]
stackoverflow_0070119013_jupyter_python_visual_studio_code.txt
Q: I'm trying to convert this string of numbers to integer and read from a text file import statistics def main(): with open('Grades.txt', mode='w') as Grades: Grade = input("Please enter student grades. " ) #Gets Input from User Grades.write(str(Grade) + '\n') #Has the student grades written into the Grade...
I'm trying to convert this string of numbers to integer and read from a text file
import statistics def main(): with open('Grades.txt', mode='w') as Grades: Grade = input("Please enter student grades. " ) #Gets Input from User Grades.write(str(Grade) + '\n') #Has the student grades written into the Grades text file and has each of them on a new line. with open('Grades.txt', mode='r') ...
[ "I don't usually feel good about doing homework for others, but in this case I think you did give it a fair try.\nHere's how your code should look. I have eliminated the write/read from file, and just split the user's input directly. I store the numbers in a single list, and then do the statistics on that list.\n...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074365423_python_python_3.x.txt
Q: Plotly Express: Writing image not working, processes for several minutes until Keyboard Interrupted Attempting to save a figure to my computer, and no matter what I try, it just does not work! Here's what I'm exactly trying to save, and the code block just continues to "run" until I Keyboard Interrupt. import plot...
Plotly Express: Writing image not working, processes for several minutes until Keyboard Interrupted
Attempting to save a figure to my computer, and no matter what I try, it just does not work! Here's what I'm exactly trying to save, and the code block just continues to "run" until I Keyboard Interrupt. import plotly.express as px import plotly.io as pio pio.renderers.default = 'notebook_connected' fig = px.box(df, y ...
[ "try:\npio.write_image(fig, 'boxplot_generated/image.png')\n\n" ]
[ 0 ]
[]
[]
[ "plotly", "plotly_express", "python" ]
stackoverflow_0074365953_plotly_plotly_express_python.txt
Q: Disable joblib.memory caching globally during unittest I use the joblib.Memory module to cache some functions within several modules. The cache is initialized within modules and classes separately. Module1: memory = Memory(location='/cache/') @memory.cache def heavy_function(...) ..... Module2: memory = Memor...
Disable joblib.memory caching globally during unittest
I use the joblib.Memory module to cache some functions within several modules. The cache is initialized within modules and classes separately. Module1: memory = Memory(location='/cache/') @memory.cache def heavy_function(...) ..... Module2: memory = Memory(location='/cache/') @memory.cache def heavy_function2(...)...
[ "One work-around is to set a flag or an environment variable when running tests. Then check for these flags before initializing the Memory:\nModule1\nimport os\nmemflag = os.environ.get('UNITTESTING', False)\nmemory = Memory(location= None if memflag else '/cache/')\n@memory.cache\ndef heavy_function(...)\n .......
[ 3, 1, 1 ]
[]
[]
[ "caching", "joblib", "python", "unit_testing" ]
stackoverflow_0053318600_caching_joblib_python_unit_testing.txt
Q: Uploading to anonfiles API with curl in python I want to upload to anonfiles using the requests module. Code runs but the files don't appear on the website. Here's my code so far: import requests files = { 'file': ('file.txt', open('file.txt', 'rb')), } requests = requests.post('https://api.anonfiles.com/uplo...
Uploading to anonfiles API with curl in python
I want to upload to anonfiles using the requests module. Code runs but the files don't appear on the website. Here's my code so far: import requests files = { 'file': ('file.txt', open('file.txt', 'rb')), } requests = requests.post('https://api.anonfiles.com/upload/?token=mytoken', files=files) Any ideas as to wh...
[ "You use wrong URL - it has to be without / at the end.\nhttps://api.anonfiles.com/upload\n\nAnd it seems it works also without token\nimport requests\n\nfiles = {\n 'file': ('file.txt', open('file.txt', 'rb')),\n}\n\nurl = 'https://api.anonfiles.com/upload'\nresponse = requests.post(url, files=files)\n\ndata = ...
[ 1, 0 ]
[]
[]
[ "curl", "post", "python", "python_requests" ]
stackoverflow_0071243221_curl_post_python_python_requests.txt
Q: How can I make turtle check for color? Say I had a turtle moving forward until it touches black, and if it does, it turns by 90 degrees. How would I go about programming this in python? How can I make turtle check for a certain color? A: I don't believe python-turtle has color detection, instead another way you ...
How can I make turtle check for color?
Say I had a turtle moving forward until it touches black, and if it does, it turns by 90 degrees. How would I go about programming this in python? How can I make turtle check for a certain color?
[ "I don't believe python-turtle has color detection, instead another way you can try is to stop and turn 90 degrees when the turtle has moved forward for a certain amount.\nSimilar stackoverflow question:\n(\"Is there a way to check if turtle is touching a color?\")\n" ]
[ 0 ]
[]
[]
[ "colors", "python", "python_3.x", "python_turtle" ]
stackoverflow_0074365647_colors_python_python_3.x_python_turtle.txt
Q: gettext: FileNotFoundError: [Errno 2] No translation file found for domain: 'base' It seems that I am unable to get my GNU gettext utility to work properly, despite closely following both documentation and online resources. My folder structure is the following: / |- src | |- __init__.py | |- main.py |- local...
gettext: FileNotFoundError: [Errno 2] No translation file found for domain: 'base'
It seems that I am unable to get my GNU gettext utility to work properly, despite closely following both documentation and online resources. My folder structure is the following: / |- src | |- __init__.py | |- main.py |- locales |- ru |- LC_MESSAGES |- base.mo |- base....
[ "I've managed to solve my problem by doing the combination of the following, not sure which exact thing has helped:\n\nSpecifying the absolute path with pathlib.Path(__file__).resolve().parents[1] / \"locale\" instead of a simple string with a dot.\n\nNot overwriting the underscore after install - from gettext impo...
[ 0 ]
[]
[]
[ "gettext", "gnu", "python" ]
stackoverflow_0074336201_gettext_gnu_python.txt
Q: Python Selenium .send_keys() doesn't work after element changes class I am trying to input the name of the city that I want to depart from into Google Flights using python. After locating the element (the input box) in the html code I noticed that once you interact with the element it changes its class from class=...
Python Selenium .send_keys() doesn't work after element changes class
I am trying to input the name of the city that I want to depart from into Google Flights using python. After locating the element (the input box) in the html code I noticed that once you interact with the element it changes its class from class="II2One j0Ppje zmMKJ LbIaRd" to class="II2One j0Ppje zmMKJ LbIaRd VfPpkd-ks...
[ "Something like this? Try to send keys with ActionChains instead with send_keys function\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom seleni...
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074351338_python_selenium_selenium_webdriver.txt
Q: FastAPI JSON List in body raises 'There was an error parsing the body' exception Using the FastAPI documentation, I'm attempting to send a POST request to an endpoint that takes a JSON object with a list as input: { "urls":[ "https://www.website.com/", "https://www.anotherwebsite.com" ] } Simpli...
FastAPI JSON List in body raises 'There was an error parsing the body' exception
Using the FastAPI documentation, I'm attempting to send a POST request to an endpoint that takes a JSON object with a list as input: { "urls":[ "https://www.website.com/", "https://www.anotherwebsite.com" ] } Simplified reproducible example app code: from fastapi import FastAPI app = FastAPI() @ap...
[ "Option 1\nThe reason of the error you get is explained here and here (see this answer as well). In brief, when defining a single body parameter like urls: list[str] or urls: list[str] = Body(), FastAPI will expect a request body like this:\n[\n \"string1\", \"string2\"\n]\n\nYou can confirm the above by using the...
[ 1 ]
[]
[]
[ "fastapi", "json", "python" ]
stackoverflow_0074365853_fastapi_json_python.txt
Q: hopscotch game in python I am trying to solve this question for 2 days but unable to solve it, gets really frustrated. I hope anyone can help me to get rid out of this problem. Write a program for given an integer list where each number represents the number of hops you can make in hopscotch game, determine whethe...
hopscotch game in python
I am trying to solve this question for 2 days but unable to solve it, gets really frustrated. I hope anyone can help me to get rid out of this problem. Write a program for given an integer list where each number represents the number of hops you can make in hopscotch game, determine whether you can reach to the last in...
[ "Assuming I understood the question correctly, this should be the solution:\nsample1 = [2,3,1,1,4]\nsample2 = [3,2,1,0,4]\n\ndef hopscotch(sample):\n last_index = len(sample) - 1\n current_index = 0\n while True:\n if current_index == last_index:\n return True\n elif current_index ...
[ 2, 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074365918_list_python_python_3.x.txt
Q: How do I close a file opened using os.startfile(), Python 3.6 I want to close some files like .txt, .csv, .xlsx that I have opened using os.startfile(). I know this question asked earlier but I did not find any useful script for this. I use windows 10 Environment A: I believe the question wording is a bit mislea...
How do I close a file opened using os.startfile(), Python 3.6
I want to close some files like .txt, .csv, .xlsx that I have opened using os.startfile(). I know this question asked earlier but I did not find any useful script for this. I use windows 10 Environment
[ "I believe the question wording is a bit misleading - in reality you want to close the app you opend with the os.startfile(file_name)\nUnfortunately, os.startfile does not give you any handle to the returned process.\nhelp(os.startfile)\n\nstartfile returns as soon as the associated application is launched.\n Th...
[ 5, 3, 2, 1, 0 ]
[]
[]
[ "file", "python", "python_3.x", "python_os" ]
stackoverflow_0057909525_file_python_python_3.x_python_os.txt
Q: Pycharm AttributeError dlsym(0x2006bea00, SHA256_init): symbol not found I am currently coding a public key (asymmetric) encryption on Pycharm. My enc, dec, key generation functions are working fine. But now my RSA-sign and RSA-ver functions for Digital Signature are not working. Please see below the error message...
Pycharm AttributeError dlsym(0x2006bea00, SHA256_init): symbol not found
I am currently coding a public key (asymmetric) encryption on Pycharm. My enc, dec, key generation functions are working fine. But now my RSA-sign and RSA-ver functions for Digital Signature are not working. Please see below the error message that I get everytime I try to type the commands. What should I do? I am not g...
[ "Apparently because I'm using macOS. I had to rename some of the packages accordingly.\nMainly Crypto was renamed into the following,\nfrom Cryptodome\n\nto install it , run in terminal pip3 install pycryptodome\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "cryptography", "pycharm", "python" ]
stackoverflow_0074163330_attributeerror_cryptography_pycharm_python.txt
Q: Handling multiples tab's with Python Playwright I've read several topics in playwright documentation, but I haven't figured out how i can handle a new tab during the data scrap.I already know how to create a new tab and manipulate it, but for this I pass a url to create this tab, and the scrap I'm doing is like a ...
Handling multiples tab's with Python Playwright
I've read several topics in playwright documentation, but I haven't figured out how i can handle a new tab during the data scrap.I already know how to create a new tab and manipulate it, but for this I pass a url to create this tab, and the scrap I'm doing is like a button that whenever I click takes me to a different ...
[ "Try this:\n# Needed libs\nfrom playwright.sync_api import Playwright, sync_playwright, expect\n\nwith sync_playwright() as p:\n #We define the browser, the context and the page\n browser = p.chromium.launch(headless=False)\n context = browser.new_context()\n page = context.new_page()\n # Go to URL f...
[ 0 ]
[]
[]
[ "playwright", "python", "web_scraping" ]
stackoverflow_0074354043_playwright_python_web_scraping.txt
Q: Comparing counts in rows from a Dataframe with Pandas, Python I'm trying to obtain the most common asnwers so we have Yes/No questions and it has i eleven questions from this one I would like to know from Yes/No which was has most answers as an example: If in more than the half of the eleven i's has No>Yes the mos...
Comparing counts in rows from a Dataframe with Pandas, Python
I'm trying to obtain the most common asnwers so we have Yes/No questions and it has i eleven questions from this one I would like to know from Yes/No which was has most answers as an example: If in more than the half of the eleven i's has No>Yes the most common answers will be 'NO' but I'm not really sure what function...
[ "To obtain a list of 'yes' and 'no' you can do:\nno_count = df.iloc[0].values[1:]\nyes_count = df.iloc[1].values[1:]\nmost_common = ['no' if no_count[i]>yes_count[i] else 'yes' for i in range(len(no_count))]\n\nThen you can count the number of each\nnumber_no = most_common.count(\"no\")\nnumber_yes = most_common.co...
[ 2 ]
[]
[]
[ "dataframe", "if_statement", "pandas", "python", "row" ]
stackoverflow_0074366032_dataframe_if_statement_pandas_python_row.txt
Q: How pass an array and its dimension from Python to Fortran and use it among subroutines? So what I am trying to achieve is the following: Define an array in Python; Pass that array and its dimension into Fortran via f2py; Use that array among various subroutines within the Fortran code. (The Fortran code does not...
How pass an array and its dimension from Python to Fortran and use it among subroutines?
So what I am trying to achieve is the following: Define an array in Python; Pass that array and its dimension into Fortran via f2py; Use that array among various subroutines within the Fortran code. (The Fortran code does not change the array.) I already know that this is impossible in a common block from this answer...
[ "yes it's possible. Here is one way of doing it.\nCreate fortran code like so...\n!example.f90\nsubroutine compute(x_1d, x_2d, nx, ny)\n\n implicit none\n integer, parameter :: dp = selected_real_kind(15, 307) !double precision\n\n ! input variables\n integer, intent(in) :: nx\n integer, intent(in) ...
[ 2 ]
[]
[]
[ "arrays", "f2py", "fortran", "python" ]
stackoverflow_0074328276_arrays_f2py_fortran_python.txt
Q: Stuck in loop webscraping with selenium I'm trying to scrape leboncoin using python and selenium. I just got started when I noticed they use DataDome for bot detection, so I have to pass a captcha, but before trying to automate any of that (this question is not related to that) I just solved the Captcha by hand on...
Stuck in loop webscraping with selenium
I'm trying to scrape leboncoin using python and selenium. I just got started when I noticed they use DataDome for bot detection, so I have to pass a captcha, but before trying to automate any of that (this question is not related to that) I just solved the Captcha by hand on the chromium browser that selenium opens, an...
[ "Your code is fine.\nThe problem is that these kind of firewalls are mostly well protected against automated browsers such as Playwright, Selenium, etc. (In the end, this is what they should do, prevent bots from accessing the site)\nYou could either tweak your Selenium browsers configuration in such a way that it ...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0072762813_python_selenium_selenium_webdriver_web_scraping.txt
Q: Removing Conda environment I want to remove a certain environment created with conda. How can I achieve that? Let's say I have an active testenv environment. I tried, by following documentation, with: $ conda env remove CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove agai...
Removing Conda environment
I want to remove a certain environment created with conda. How can I achieve that? Let's say I have an active testenv environment. I tried, by following documentation, with: $ conda env remove CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove again I then deactivate it: $ sourc...
[ "You probably didn't fully deactivate the Conda environment - remember, the command you need to use with Conda is conda deactivate (for older versions, use source deactivate). So it may be wise to start a new shell and activate the environment in that before you try. Then deactivate it.\nYou can use the command\nco...
[ 846, 186, 82, 64, 48, 40, 35, 24, 19, 17, 16, 15, 10, 6, 5, 3, 3, 2 ]
[ "Because you can only deactivate the active environment, so conda deactivate does not need nor accept arguments. The error message is very explicit here.\nJust call conda deactivate\nhttps://github.com/conda/conda/issues/7296#issuecomment-389504269\n", "on terminal it's showing\n(base) [root@localhost ~]#\nsimply...
[ -2, -4 ]
[ "conda", "jupyter", "python" ]
stackoverflow_0049127834_conda_jupyter_python.txt
Q: Python: search string in a txt file always results in not finding I have been trying to debug my code for searching strings in two files, but I can't understand why the strings are not found all the time. I have been stuck here for half day, and probably you could help me to understand the error, please? The logic...
Python: search string in a txt file always results in not finding
I have been trying to debug my code for searching strings in two files, but I can't understand why the strings are not found all the time. I have been stuck here for half day, and probably you could help me to understand the error, please? The logic is: (after filtering out line in "try_ID.txt" by this piece len(re.fin...
[ "Try to read and split and search only once wherever possible. Try to keep it simple.\nwith open(\"try_ID.txt\", 'r') as fin, \\\n open(\"try_C.txt\", 'r') as co_splice, \\\n open(\"try.txt\", 'r') as ca_splice:\n co_splice = co_splice.read()\n ca_splice = ca_splice.read()\n for row in fin:\n...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074365923_python.txt
Q: How do we convert a (confusion matrix) decimal output to % with 2 decimal points when using the plot function the matrix is plotted either with a % with many decimal places or not as a % but with set decimal places how can I do both at once a % with a set decimal place disp = ConfusionMatrixDisplay(confusion_mat...
How do we convert a (confusion matrix) decimal output to % with 2 decimal points when using the plot function
the matrix is plotted either with a % with many decimal places or not as a % but with set decimal places how can I do both at once a % with a set decimal place disp = ConfusionMatrixDisplay(confusion_matrix = cm) # Use ConfusionMatrixDisplay to visualize 'cm' disp.plot(values_format='%')
[ "Try\ndisp.plot(values_format='.2%')\n\n\n" ]
[ 0 ]
[]
[]
[ "format", "matplotlib", "plot", "python" ]
stackoverflow_0074365269_format_matplotlib_plot_python.txt
Q: Running .bat file in Google Colab I am trying to run a .bat file in my Google Colab notebook, howere I cannot seem to make it happen. Whenever I navigate to the folder the code says the directory or file does not exist. from subprocess import Popen p = Popen("batch.bat", cwd=r"/content/drive/MyDrive/sd/stable-diff...
Running .bat file in Google Colab
I am trying to run a .bat file in my Google Colab notebook, howere I cannot seem to make it happen. Whenever I navigate to the folder the code says the directory or file does not exist. from subprocess import Popen p = Popen("batch.bat", cwd=r"/content/drive/MyDrive/sd/stable-diffusion/merge-models-main/") stdout, stde...
[ "Colab is an Ubuntu Linux environment so it will struggle if the file to be run contains Windows like commands. If the file contains Linux shell commands then the following code illustrates how to execute these.\nThis cell makes a batch.bat file (purists would argue that it should be batch.sh).\n# This is a Unix sh...
[ 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074365730_google_colaboratory_python.txt
Q: (Python) Socket Chat returning usernames as IP and Port I'm working on a TCP socket chat assignment for school. I'm having trouble getting the last part done, which is returning all usernames to the client when it asks for it. The client can write /users to get all connected users usernames, but instead gets the I...
(Python) Socket Chat returning usernames as IP and Port
I'm working on a TCP socket chat assignment for school. I'm having trouble getting the last part done, which is returning all usernames to the client when it asks for it. The client can write /users to get all connected users usernames, but instead gets the IP and PORT they are connected to, output example: ('127.0.0.1...
[ "In the function server, this line is sending addr as the second argument:\nthreading.Thread(target=user_conn, args=[client, addr]).start()\n\nbut the function user_conn has a second argument of nicknames:\ndef user_conn(conn: socket.socket, nicknames):\n\nso send nicknames instead in server:\nthreading.Thread(targ...
[ 0 ]
[]
[]
[ "chat", "python", "sockets", "tcp" ]
stackoverflow_0074365520_chat_python_sockets_tcp.txt
Q: Converting incoming data in the form of "multipart/form-data" into a Querydict object I want to convert a data like below to QueryDict object. Is there a ready-made class that can do this job? I could not parse the data that came in the form of the "multipart/form-data" as I wanted. So I need help data = { 'na...
Converting incoming data in the form of "multipart/form-data" into a Querydict object
I want to convert a data like below to QueryDict object. Is there a ready-made class that can do this job? I could not parse the data that came in the form of the "multipart/form-data" as I wanted. So I need help data = { 'name': 'erhan', 'last_name': 'koçlar', 'gender.code': 1, 'gender1.gender2.gender3...
[ "Something like this can do the Job. Note the modification I changed files[0].name to files[1].name as it would overwrite the field 0.\nimport re\n\ndata = {\n 'name': 'erhan',\n 'last_name': 'koçlar',\n 'gender.code': 1,\n 'gender1.gender2.gender3.gender4.code': 1,\n 'tags[5]': 'TAG_2',\n 'tags[0...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074364953_dictionary_python.txt
Q: Creating curved lines Python Plotly In this tutorial (https://plotly.com/python/lines-on-maps/ 23), the lines connecting the points are curved. However I can’t seem to recreate this behavior when using mapbox, i.e. go.Scattermapbox. With Scattermapbox the lines created are straight as shown on this page https://pl...
Creating curved lines Python Plotly
In this tutorial (https://plotly.com/python/lines-on-maps/ 23), the lines connecting the points are curved. However I can’t seem to recreate this behavior when using mapbox, i.e. go.Scattermapbox. With Scattermapbox the lines created are straight as shown on this page https://plotly.com/python/lines-on-mapbox/ 10. Are ...
[ "On mapbox the endpoints must be interpolated via slerp function (spherical \"linear\" interpolation):\nimport numpy as np\nfrom numpy import pi, sin, cos\nimport plotly.graph_objects as go\n\ndef point_sphere(lon, lat):\n #associate the cartesian coords (x, y, z) to a point on the globe of given lon and lat\n...
[ 0 ]
[]
[]
[ "data_visualization", "plotly", "python" ]
stackoverflow_0072080668_data_visualization_plotly_python.txt
Q: How to detect an XSS payload with the lxml library? I understand we can use the Cleaner object, but I don't see any direct reference in the official repository. A: We can use this to detect if the payload has XSS content: clean = lxml.html.clean.Cleaner(style=True).clean_html(document_fromstring(input)).text_con...
How to detect an XSS payload with the lxml library?
I understand we can use the Cleaner object, but I don't see any direct reference in the official repository.
[ "We can use this to detect if the payload has XSS content:\nclean = lxml.html.clean.Cleaner(style=True).clean_html(document_fromstring(input)).text_content()\n\nIf the clean variable is not equal to input so there is XSS content present.\nAlso, we need to be aware that we need to handle the ParserError exception.\n...
[ 1 ]
[]
[]
[ "lxml", "python", "xss" ]
stackoverflow_0074366514_lxml_python_xss.txt
Q: Writing parquet file in AWS Lambda I have a parquet file with 2 columns A and B. The column A has a data type string and B has a data type float64. The data type of column B need to be changed to int64. Since its not feasible to alter a parquet file, I created a new parquet file with desired data types, ie, A with...
Writing parquet file in AWS Lambda
I have a parquet file with 2 columns A and B. The column A has a data type string and B has a data type float64. The data type of column B need to be changed to int64. Since its not feasible to alter a parquet file, I created a new parquet file with desired data types, ie, A with string and B with int64. I have impleme...
[ "Thanks to Msvstl for the solution it worked.\npq.write_table(table, '/tmp/outputfile.parquet')\nwith open('/tmp/outputfile.parquet', 'rb') as f:\n s3_client.upload_fileobj(f,s3_bucket,key_output)\n\n" ]
[ 1 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "pandas", "pyarrow", "python" ]
stackoverflow_0074359934_amazon_web_services_aws_lambda_pandas_pyarrow_python.txt
Q: Printing out function containing print and return I recently came across a weird problem. I assumed that the two code snippets below should have the same output, yet they do not. Can someone explain? def my_function(): myvar = "a" print("2", myvar) return myvar print("1") print(my_function()) #will o...
Printing out function containing print and return
I recently came across a weird problem. I assumed that the two code snippets below should have the same output, yet they do not. Can someone explain? def my_function(): myvar = "a" print("2", myvar) return myvar print("1") print(my_function()) #will output: #1 #2 a #a print("1", my_function()) #wi...
[ "When you call a function with parameters, the parameters have to be fully evaluated before calling the function.\nIn the case of 2. python effectively rewrites your code like this:\n_ = my_function()\nprint(\"1\", _)\n\nSo my_function() is called first, then the parameters are passed to print()\n" ]
[ 2 ]
[]
[]
[ "printing", "python", "return" ]
stackoverflow_0074366526_printing_python_return.txt
Q: is there an 'anti-step' for a python range? range(0, 100, n) gives me every nth number, what if i want to exclude every nth number? how can I exclude numbers from a range without creating a giant list? How would I get all the numbers from 1, 100, for example, but exclude every nth number? And what about with mult...
is there an 'anti-step' for a python range? range(0, 100, n) gives me every nth number, what if i want to exclude every nth number?
how can I exclude numbers from a range without creating a giant list? How would I get all the numbers from 1, 100, for example, but exclude every nth number? And what about with multiple n's? Exclude every 3rd and every 11th number, for example. What's the best way to do this? It's easy to do with if statements and ap...
[ "Just enclose the call to range in a generator expression, and apply a filter to the not-wanted numbers, using an expression with the modulo-operator.\nfor number in (number in range(10) if number % 3):\n ...\n\nIf you need getitem and containmentship testing, make it a list comprehension instead:\nnumbers = [nu...
[ 2, 1, 1 ]
[]
[]
[ "python", "range" ]
stackoverflow_0074366426_python_range.txt
Q: Reading parquet file using pyarrow in lambda I am writing a lambda function, I have to read a parquet file, for which I am using pyarrow package. It works fine in my local machine with below line of code. pq_raw = pq.read_table(source='C:\\Users\\xxx\\Desktop\\testfolder\\yyyy.parquet') Now I want to recreate the ...
Reading parquet file using pyarrow in lambda
I am writing a lambda function, I have to read a parquet file, for which I am using pyarrow package. It works fine in my local machine with below line of code. pq_raw = pq.read_table(source='C:\\Users\\xxx\\Desktop\\testfolder\\yyyy.parquet') Now I want to recreate the same functionality in lambda function with the fil...
[ "I was able to read the file using the below method.\n obj = s3_client.get_object(Bucket=s3_bucket, Key=filekey)\n pq_raw = pq.read_table(source=BytesIO(obj['Body'].read()))\n\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "parquet", "pyarrow", "python" ]
stackoverflow_0074309651_amazon_web_services_aws_lambda_parquet_pyarrow_python.txt
Q: Writing dataframe to Excel takes extremely long I have got an excel file from work which I amended using pandas. It has 735719 rows × 31 columns, I made the changes necessary and allocated them to a new dataframe. Now I need to have this dataframe in an Excel format. I have checked to see that in jupyter notebooks...
Writing dataframe to Excel takes extremely long
I have got an excel file from work which I amended using pandas. It has 735719 rows × 31 columns, I made the changes necessary and allocated them to a new dataframe. Now I need to have this dataframe in an Excel format. I have checked to see that in jupyter notebooks the ont_dub works and it shows a dataframe. So I use...
[ "Usually, if you want to save such high amount of datas in a local folder. You don't utilize excel. If I am not mistaken excel has a know limit of displayable cells and it wasnt built to display and query such massive amounts of data (you can use pandas for that). You can either utilize feather files (a known quick...
[ 0 ]
[]
[]
[ "dataframe", "excel", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074366492_dataframe_excel_jupyter_notebook_pandas_python.txt
Q: Generating email address using first name and last name in Faker python I am trying to generate a pandas dataset comprising person data. I am employing Python's Faker library. Is there a way to generate a valid email address using the first name and last name? import pandas as pd import numpy as np import os impor...
Generating email address using first name and last name in Faker python
I am trying to generate a pandas dataset comprising person data. I am employing Python's Faker library. Is there a way to generate a valid email address using the first name and last name? import pandas as pd import numpy as np import os import random from faker import Faker def faker_categorical(num=1, seed=None): ...
[ "You can use Faker's domain_name method and string formatting alongside the already generated values:\nfirst_name = fake.first_name_male() if gender ==\"M\" else fake.first_name_female()\nlast_name = fake.last_name()\n\noutput.append(\n {\n \"First name\": first_name,\n \"Last Name\": last_name,\n \"...
[ 3, 0 ]
[]
[]
[ "email", "faker", "python" ]
stackoverflow_0068356668_email_faker_python.txt
Q: Add missing dates for every value of another column I would like to fill the missing values of the dates of a Pandas dataframe, but instead of filling the missing date based only on the date column, I would like to do it based on more than 1 column. In this case, the column source. The example is the following Ori...
Add missing dates for every value of another column
I would like to fill the missing values of the dates of a Pandas dataframe, but instead of filling the missing date based only on the date column, I would like to do it based on more than 1 column. In this case, the column source. The example is the following Original date_found source count_unique_uuids cou...
[ "here is one way to do it\n# make the date as of type datetime\ndf['date_found']=pd.to_datetime(df['date_found'])\n\n#find the min_date\nmin_date = df['date_found'].min()\n\n#find the max date\nmax_date = df['date_found'].max()\n\n\ndf2=(df.set_index(['date_found']) # set index to date, to allow for reindex\n ...
[ 1, 1, 0 ]
[]
[]
[ "datatable", "pandas", "python", "python_3.x" ]
stackoverflow_0074363227_datatable_pandas_python_python_3.x.txt
Q: Python Truncate number is rounding in some cases I have a pandas dataframe, with columns [QuantityReq] as Float and [Test] as Float. I am trying to get 3 digits after the decimal points. The [Test] column which I create is truncating for 3 digits after decimal, but in some cases it is rounding at the 3rd digit. I ...
Python Truncate number is rounding in some cases
I have a pandas dataframe, with columns [QuantityReq] as Float and [Test] as Float. I am trying to get 3 digits after the decimal points. The [Test] column which I create is truncating for 3 digits after decimal, but in some cases it is rounding at the 3rd digit. I have highlighted the error in row 2 and 3 of [Test] co...
[ "Try using decimal module it's preferred to deal with float number in python as float numbers have some problems that mention here.\nsample example\nfrom decimal import Decimal\n\nfor i in [59.307000, 0.8700000]:\n print(Decimal(i).quantize(Decimal(\"1.000\")))\n\noutput\n59.307\n0.870\n\nfor more check this.\n"...
[ 0 ]
[]
[]
[ "decimal", "pandas", "python", "truncate" ]
stackoverflow_0074366307_decimal_pandas_python_truncate.txt
Q: How to merge odt files in Python I have several odt files, and I would like to merge them into a new one. I am using relatorio library to read the odt files. from relatorio.templates.opendocument import Template from os.path import dirname, join odt_1 = Template(source='', filepath='report_test_1_fulled.odt') odt...
How to merge odt files in Python
I have several odt files, and I would like to merge them into a new one. I am using relatorio library to read the odt files. from relatorio.templates.opendocument import Template from os.path import dirname, join odt_1 = Template(source='', filepath='report_test_1_fulled.odt') odt_2 = Template(source='', filepath='rep...
[ "To combine two documents using Aspose.Words you can use Document.append_document method.\ndstDoc = aw.Document(\"documentA.odt\")\nsrcDoc = aw.Document(\"documentB.odt\")\n\n# Append the source document to the destination document.\n# Pass format mode to retain the original formatting of the source document when i...
[ 0 ]
[]
[]
[ "aspose", "aspose.words", "merge", "odt", "python" ]
stackoverflow_0074363396_aspose_aspose.words_merge_odt_python.txt
Q: Django: Are Django models dataclasses? Can we say that Django models are considered dataclasses? I don't see @dataclass annotation on them or on their base class model.Models. However, we do treat them like dataclasses because they don't have constructors and we can create new objects by naming their arguments, fo...
Django: Are Django models dataclasses?
Can we say that Django models are considered dataclasses? I don't see @dataclass annotation on them or on their base class model.Models. However, we do treat them like dataclasses because they don't have constructors and we can create new objects by naming their arguments, for example MyDjangoModel(arg1= ..., arg2=...)...
[ "A lot of the magic that happens with models, if not nearly all of it, is from its base meta class.\nThis can be found in django.db.models.ModelBase specifically in the __new__ function.\nRegardless of an __init__ method being defined or not (which actually, it is as per Abdul's comment), doesn't mean it can or sho...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074363122_django_python.txt
Q: Why does a multiline string replacement with Python work with a hard coded string, but not when the string is read from a file? I am trying to replace the contents of a string with a placeholder for later substitutions. When I execute my replacement against a string literal, the code works as expected, but if I re...
Why does a multiline string replacement with Python work with a hard coded string, but not when the string is read from a file?
I am trying to replace the contents of a string with a placeholder for later substitutions. When I execute my replacement against a string literal, the code works as expected, but if I read the same string from a file (literally the same string literal pasted into the file), it doesn't work. envelope_string = '''[ { ...
[ "It seems that the newline characters in the description were preventing apples vs apples comparison between the file data and the string literal. The solution was to place the search string to be replaced into a file as well and then to read the two files into memory. That done the search in the string.replace() w...
[ 2 ]
[]
[]
[ "multiline", "multilinestring", "python", "string" ]
stackoverflow_0074365128_multiline_multilinestring_python_string.txt
Q: Fibonacci sequence calculation in Python I tried to do a function that builds the Fibonacci series but when I try to check the calculation comes out wrong def fibo(n): i=1 j=1 for n in range(1,n): j=j+i i=j+i return i+j n=input('Enter number:') print(fibo(int(n))) A: i, j = 1, 1 f...
Fibonacci sequence calculation in Python
I tried to do a function that builds the Fibonacci series but when I try to check the calculation comes out wrong def fibo(n): i=1 j=1 for n in range(1,n): j=j+i i=j+i return i+j n=input('Enter number:') print(fibo(int(n)))
[ "i, j = 1, 1\nfor _ in range(n):\n j = j + i\n i = j + i\n\nThis is not the fibonacci sequence. Instead, try:\ni, j = 1, 1\nfor _ in range(n):\n i, j = j, i+j\n\n" ]
[ 1 ]
[]
[]
[ "fibonacci", "python" ]
stackoverflow_0074366661_fibonacci_python.txt
Q: Using Spyder / Python to Open .npy File Sorry. I'm just now learning Python and everything there is to do with data analysis. How on earth do I open a .npy file with Spyder? Or do I have to use another program? I'm using a Mac, if that is at all relevant. A: *.npy files are binary files to store numpy arrays. T...
Using Spyder / Python to Open .npy File
Sorry. I'm just now learning Python and everything there is to do with data analysis. How on earth do I open a .npy file with Spyder? Or do I have to use another program? I'm using a Mac, if that is at all relevant.
[ "*.npy files are binary files to store numpy arrays. They\nare created with\nimport numpy as np\n\ndata = np.random.normal(0, 1, 100)\nnp.save('data.npy', data)\n\nAnd read in like\nimport numpy as np\ndata = np.load('data.npy')\n\n", "Given that you asked for Spyder, you need to do two things to import those fil...
[ 51, 7, 3, 3, 3, 0 ]
[]
[]
[ "file", "numpy", "python" ]
stackoverflow_0033885051_file_numpy_python.txt
Q: Join 2 columns of a dataframe based on syntax of values in the 2 columns I have a Python dataframe and I am trying to combine the cells in the first 2 columns IF the first column value is a string with letters, and the second column value has the syntax of parentheses-single digit-parentheses. eg: this is the curr...
Join 2 columns of a dataframe based on syntax of values in the 2 columns
I have a Python dataframe and I am trying to combine the cells in the first 2 columns IF the first column value is a string with letters, and the second column value has the syntax of parentheses-single digit-parentheses. eg: this is the current layout 0 1 2 text (5) moretext this is what I want the result ...
[ "I believe join is suppose to join lists (which are inside one column) into a string and not several columns into a unique column (https://pandas.pydata.org/docs/reference/api/pandas.Series.str.join.html)\nI might not have understood your problem completely but maybe this could work :\nidx = df[(df[0].str.contains(...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074366504_dataframe_pandas_python.txt
Q: Concat dataframes with same names from multiple folders using pandas I have three folders folder1, folder2, and folder3. They have data frames as follows: folder1/ df1.csv df4.csv df5.csv folder2/ df1.csv df3.csv df4.csv folder3/ df4.csv I am confused about how to contact the data frames using pandas.concat() w...
Concat dataframes with same names from multiple folders using pandas
I have three folders folder1, folder2, and folder3. They have data frames as follows: folder1/ df1.csv df4.csv df5.csv folder2/ df1.csv df3.csv df4.csv folder3/ df4.csv I am confused about how to contact the data frames using pandas.concat() with the same names in all three folders and save them in a new folder "fin...
[ "edit to first answer:\nfrom os import listdir\nimport pandas as pd\n\nfolder_paths = ['put all the folder paths here']\ndf_dict = {'folder': [], 'file': []}\nfor folder_path in folder_paths:\n for file in listdir(folder_path):\n df_dict['folder'].append(folder_path)\n df_dict['file'].append(file)\...
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074365978_dataframe_pandas_python.txt
Q: How to return from async function? I have this function code, when I call it, output is my list printed but this list doesn't return. from pyrogram import Client from pyrogram import enums async def search_for_deals(message_to_search): async with client: async for message in client.search_global(query...
How to return from async function?
I have this function code, when I call it, output is my list printed but this list doesn't return. from pyrogram import Client from pyrogram import enums async def search_for_deals(message_to_search): async with client: async for message in client.search_global(query=message_to_search, limit=40): ...
[ "Use\nimport asyncio\nloop = asyncio.get_event_loop()\noutput = loop.run_until_complete(search_for_deals(str(input())))\n\ninstead of output = client.run(search_for_deals(str(input())))\nand do not use the list as variable name, confuses with the list class\n" ]
[ 0 ]
[]
[]
[ "pyrogram", "python", "python_asyncio", "return" ]
stackoverflow_0073986307_pyrogram_python_python_asyncio_return.txt
Q: Matplotlib - highlighting weekends on x axis? I've a time series (typically energy usage) recorded over a range of days. Since usage tends to be different over the weekend I want to highlight the weekends. I've done what seems sensible: import pandas as pd import matplotlib.pyplot as plt import datetime import ran...
Matplotlib - highlighting weekends on x axis?
I've a time series (typically energy usage) recorded over a range of days. Since usage tends to be different over the weekend I want to highlight the weekends. I've done what seems sensible: import pandas as pd import matplotlib.pyplot as plt import datetime import random #Create dummy data. start=datetime.datetime(2...
[ "OK - since matplotlib only provides the information we need to the Tick Label Formatter functions, that's what we have to use:\nminorLabels=plt.gca().xaxis.get_ticklabels(which='minor')\nmajorLabels=plt.gca().xaxis.get_ticklabels(which='major')\n\ndef MinorFormatter(dateInMinutes, index):\n # Formatter: first p...
[ 0, 0 ]
[]
[]
[ "axis_labels", "datetime", "matplotlib", "python" ]
stackoverflow_0074363137_axis_labels_datetime_matplotlib_python.txt
Q: I'm trying to allow the user to input the name of a file and then print the contents of the file, but my code doesn't print anything? The title is mostly self-explanatory. I'm trying to create a program that opens a text file based on the title a user inputs in python. However, the program doesn't print anything -...
I'm trying to allow the user to input the name of a file and then print the contents of the file, but my code doesn't print anything?
The title is mostly self-explanatory. I'm trying to create a program that opens a text file based on the title a user inputs in python. However, the program doesn't print anything - it's not taking time to compute and print out the text, but instead doesn't do anything. I've tried re-wording the program to not include ...
[ "This is the shortest possible way to do it:\nwith open(input(\"Filename: \"), \"r\") as file:\n print(file.read())\n\n", "Your program opens file 0, which could be stdin, so your program is waiting for input. I suspect you didn't mean that.\nYour code should pass parameters around:\ndef get_filename():\n r...
[ 2, 0, 0, 0 ]
[]
[]
[ "file", "python", "txt" ]
stackoverflow_0074366808_file_python_txt.txt
Q: django.core.exceptions.ImproperlyConfigured: PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are mutually exclusive I'm upgrading a django code and I faced this error when I runserver, I tryied already to ALLOWED_HOSTS = ["*"] and it doesn't work A: As the error says, you need to specify either PASSWORD_RESET...
django.core.exceptions.ImproperlyConfigured: PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are mutually exclusive
I'm upgrading a django code and I faced this error when I runserver, I tryied already to ALLOWED_HOSTS = ["*"] and it doesn't work
[ "As the error says, you need to specify either PASSWORD_RESET_TIMEOUT [Django-doc], or PASSWORD_RESET_TIMEOUT_DAYS [Django-doc], not both.\nSince the PASSWORD_RESET_TIMEOUT_DAYS setting was deprecated since django-3.1 and removed in django-4.0, it might be better to retain the PASSWORD_RESET_TIMEOUT setting, and re...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074366858_django_python.txt
Q: Pandas - How to group sequences How to group a pandas (or dask) dataframe and get the min, max and some operation, only when the diference between the grouped rows are 1 second? MY DATA: ID DT VALOR 1 12:01:00 7 1 12:01:01 1 1 12:01:02 4 1 12:01:03 3 1 12:01:08 1 1 12:01:09 5 2 12:01:09 6 1 12:01:10 6 1 ...
Pandas - How to group sequences
How to group a pandas (or dask) dataframe and get the min, max and some operation, only when the diference between the grouped rows are 1 second? MY DATA: ID DT VALOR 1 12:01:00 7 1 12:01:01 1 1 12:01:02 4 1 12:01:03 3 1 12:01:08 1 1 12:01:09 5 2 12:01:09 6 1 12:01:10 6 1 12:01:11 4 RETURN: ...
[ "Try:\ndf[\"DT\"] = pd.to_timedelta(df[\"DT\"])\n\ntmp = df.groupby(\"ID\", group_keys=False)[\"DT\"].apply(\n lambda x: (x.diff().bfill() != \"1 second\").cumsum()\n)\n\ndf = (\n df.groupby([\"ID\", tmp])\n .agg(\n ID=(\"ID\", \"first\"),\n MENOR_DT=(\"DT\", \"min\"),\n MAIOR_DT=(\"DT...
[ 2, 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074366653_group_by_pandas_python.txt
Q: XML Encoding Character Error when trying to Open in ALteryx I am using alteryx to edit an xml file and only replacing 5 numbers out of the whole 25k line file and everything is exactly the same but I get these characters in black on the left in for some reason when I export. I kept everything the same export wise ...
XML Encoding Character Error when trying to Open in ALteryx
I am using alteryx to edit an xml file and only replacing 5 numbers out of the whole 25k line file and everything is exactly the same but I get these characters in black on the left in for some reason when I export. I kept everything the same export wise but these characters seem to throw off an error The </ are black ...
[ "Just answered my question, my alteryx application is missing /> and at the end of many rows at the end but couldnt see it all the way to the right ...I might have to come up with a way to solve this\n" ]
[ 0 ]
[]
[]
[ "alteryx", "character_encoding", "encode", "python", "xml" ]
stackoverflow_0074366778_alteryx_character_encoding_encode_python_xml.txt
Q: How to make app from tkinter that can be open in other computers? I want to make an application from tkinter and I converted it from py into exe files using pyinstaller, and I want the application can be use for public. But the problem is if I use it in other computer it doesn't work, because there are files that ...
How to make app from tkinter that can be open in other computers?
I want to make an application from tkinter and I converted it from py into exe files using pyinstaller, and I want the application can be use for public. But the problem is if I use it in other computer it doesn't work, because there are files that support the application. Is it possible if I made that application and ...
[ "If your application needs attached files to work, you can store all of them in a .zip file for example, along with your .exe, on an online server.\nYou can use GitHub Pages for this, because you can access the raw files' contents unlike secured file storages that only allow you to download them using a browser.\nT...
[ 0 ]
[]
[]
[ "pyinstaller", "python", "tkinter" ]
stackoverflow_0074359083_pyinstaller_python_tkinter.txt
Q: Filter view based on the users Group I am trying to filter the query further to only show records where the Groups matches the logged in users group. I am new to Python and not sure how to add an additional filter into the below view. View @login_required(login_url='login') def home(request): q= request.GET.get...
Filter view based on the users Group
I am trying to filter the query further to only show records where the Groups matches the logged in users group. I am new to Python and not sure how to add an additional filter into the below view. View @login_required(login_url='login') def home(request): q= request.GET.get('q') if request.GET.get('q') != None else...
[ "You can filter with:\nfrom django.db.models import Q\n\n\n@login_required(login_url='login')\ndef home(request):\n q = request.GET.get('q', '')\n infs = Infringement.objects.filter(\n Q(name__icontains=q) | Q(infringer__name__icontains=q),\n groups__user=request.user,\n )\n # …\n" ]
[ 1 ]
[]
[]
[ "django", "filtering", "permissions", "python", "usergroups" ]
stackoverflow_0074366867_django_filtering_permissions_python_usergroups.txt
Q: How to select a specific input device with PyAudio When recording audio via PyAudio, how do you specify the exact input device to use? My computer has two microphones, one built-in and one via USB, and I want to record using the USB mic. The Stream class has an input_device_index for selecting the device, but it's...
How to select a specific input device with PyAudio
When recording audio via PyAudio, how do you specify the exact input device to use? My computer has two microphones, one built-in and one via USB, and I want to record using the USB mic. The Stream class has an input_device_index for selecting the device, but it's unclear how this index correlates to the devices. For e...
[ "you can use get_device_info_by_host_api_device_index.\nFor instance:\nimport pyaudio\n\np = pyaudio.PyAudio()\ninfo = p.get_host_api_info_by_index(0)\nnumdevices = info.get('deviceCount')\n\nfor i in range(0, numdevices):\n if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:\n ...
[ 38, 2, 0, 0, 0 ]
[ "I don't know about PyAudio, but with the sounddevice module it goes like that:\npython3 -m sounddevice\n\n", "Just use arecord -l to list all available input devices.\n" ]
[ -3, -3 ]
[ "audio", "linux", "pyaudio", "python" ]
stackoverflow_0036894315_audio_linux_pyaudio_python.txt
Q: grouping numbers up to 5 groups and the total size of each group should be as small as possible I have a list of numbers. I want to group this up to 5 groups and the total size of each group should be as small as possible. What would be a good approach to this? Sample data numbers = [52, 86, 102, 122, 964, 1075, 1...
grouping numbers up to 5 groups and the total size of each group should be as small as possible
I have a list of numbers. I want to group this up to 5 groups and the total size of each group should be as small as possible. What would be a good approach to this? Sample data numbers = [52, 86, 102, 122, 964, 1075, 1420] Possible result result = [[1420],[1075],[964],[122, 52],[102, 86]]
[ "I had a similar situation to you in the past. What I did was implement:\ndef lazy_split(iter_: Iterable, split_num: int) -> list[Iterable]:\n k, m = divmod(len(iter_), split_num)\n return [iter_[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(split_num)]\n\nnumbers = [52, 86, 102, 122, 964, 1075, 1420]\npr...
[ 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0074366766_algorithm_python.txt
Q: message.content is not printable/writeable in discord.py I have been trying to make a chat logger for a discord server I run that looks at a conversation takes the messages and store them in a txt file. I am unsure of any ways to log this as my current code can only log contents that mention the bot itself. I do h...
message.content is not printable/writeable in discord.py
I have been trying to make a chat logger for a discord server I run that looks at a conversation takes the messages and store them in a txt file. I am unsure of any ways to log this as my current code can only log contents that mention the bot itself. I do have the intent set to true on the discord application portal, ...
[ "Instead of using\nclient = discord.Client(intents=discord.Intents.default())\nI should have set it to\nclient = discord.Client(intents=discord.Intents.all())\nIt was a very silly mistake of mine, I apologize.\n", "Let me save you the problem with a fix that works for me, however I'm using discord.py with pycord ...
[ 1, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074257366_discord.py_python.txt
Q: Pandas: Calculate running difference based on condition from another column I want to calculate the running difference of column ['Values'] based on a binary condition in another column ['Conditions']. If condition is 0 then it calculates the difference of the current row and preceding row. If condition is 1 then ...
Pandas: Calculate running difference based on condition from another column
I want to calculate the running difference of column ['Values'] based on a binary condition in another column ['Conditions']. If condition is 0 then it calculates the difference of the current row and preceding row. If condition is 1 then it calculates the difference of the current row and the previous row where the co...
[ "First calculate the difference between two successive rows for the whole column with diff, then replace the rows with condition being 1 by the difference on the Value column once selected only the rows with 1 in condition, by index alignment it should work.\nm = df['Condition'].astype(bool)\ndf['res'] = df['Values...
[ 1, 0 ]
[]
[]
[ "conditional_statements", "difference", "pandas", "python" ]
stackoverflow_0074366671_conditional_statements_difference_pandas_python.txt
Q: Increasing size of 3d surface plot with matplotlib Picture of Plot This should really not be this difficult. I am plotting a 3d surface plot from an array. The code looks like this: z = arr y = np.arange(len(z)) x = np.arange(len(z[0])) (x ,y) = np.meshgrid(x,y) plt.figure(figsize=(100,100)) ax.plot_surface(x,y...
Increasing size of 3d surface plot with matplotlib
Picture of Plot This should really not be this difficult. I am plotting a 3d surface plot from an array. The code looks like this: z = arr y = np.arange(len(z)) x = np.arange(len(z[0])) (x ,y) = np.meshgrid(x,y) plt.figure(figsize=(100,100)) ax.plot_surface(x,y,z, cmap=cm.coolwarm) ax.set_xlabel("Bonus to AC") ax.se...
[ "you are referencing ax from a different figure than the one produced by plt.figure\nyou should instead use ax= fig.add_subplot after you assign fig= plt.figure as follows.\nz = np.ones((100,100))\ny = np.arange(len(z))\nx = np.arange(len(z[0]))\n(x ,y) = np.meshgrid(x,y)\n\nfig = plt.figure(figsize=(10,10))\nax = ...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074366206_matplotlib_pandas_python.txt
Q: Cooldown for users for many servers discord.py I am writing discord bot on python (discord.py). This bot for many servers and I want to make cooldown system. This looks like this: User uses command on the first server and if he uses it again, bot will tell user that command on cooldown, but if user will go to the ...
Cooldown for users for many servers discord.py
I am writing discord bot on python (discord.py). This bot for many servers and I want to make cooldown system. This looks like this: User uses command on the first server and if he uses it again, bot will tell user that command on cooldown, but if user will go to the second server, command will work without cooldown th...
[ "You can use\n@commands.cooldown(1, 86400, commands.BucketType.user)\nFirst number is how many times someone can run the command without triggering the cooldown.\nSecond one is how long the cooldown is in seconds.\nBucketType tells the bot its per user, there are different bucket types, for example for roles, serve...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074251511_discord_discord.py_python.txt
Q: Python how to replace a None value in list with string None I have list: test_list = ['one','two',None] Is there any simple way to replace None with 'None' ,without using index, because index for None maybe different each time. I tried : conv = lambda i : i or 'None' res = [conv(i) for i in test_list] It works ...
Python how to replace a None value in list with string None
I have list: test_list = ['one','two',None] Is there any simple way to replace None with 'None' ,without using index, because index for None maybe different each time. I tried : conv = lambda i : i or 'None' res = [conv(i) for i in test_list] It works ,is there another way to do so ?
[ "In this way all the data types would be converted to string\ntest_list = ['one','two',None] \nres = [str(i) for i in test_list]\n\nIn this the data type will also be preserved\nres = ['None' if i is None else i for i in test_list]\n\n" ]
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074366941_python_python_3.x.txt
Q: Why is this string slicing not working as desired Leetcode question: You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing or...
Why is this string slicing not working as desired
Leetcode question: You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by t...
[ "What about:\nnums1[m:] = nums2\nnums1.sort()\nprint(nums1)\n\nOutput:\n[1, 2, 2, 3, 5, 6]\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074366945_arrays_python.txt
Q: some of my outputs have both the if condtional output and else conditional output, how should i modify so the output is correct? Thank you Write a program that takes a date as input and outputs the date's season in the northern hemisphere. The input is a string to represent the month and an int to represent the da...
some of my outputs have both the if condtional output and else conditional output, how should i modify so the output is correct? Thank you
Write a program that takes a date as input and outputs the date's season in the northern hemisphere. The input is a string to represent the month and an int to represent the day. Ex: If the input is: April 11 the output is: Spring In addition, check if the string and int are valid (an actual month and day). Ex: If the ...
[ "To eliminate all your complex checks, I used the dictionary data structure and a couple of lists. I also created a namedtuple called Season which defines a tuple consisting of the season as a string followed by two ints indicating the first day of the month the season is valid as well as the last day of the month...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074365022_python.txt
Q: Merging two lists in Python into one list; side by side I have two lists: years_list = [1880, 1881, 1882, 1883] temperature_list = [23, 26, 20, 21] I would like to merge the two lists so that both lists are in one lists but side by side. Where one list contains two lists. I would like the output to look like this:...
Merging two lists in Python into one list; side by side
I have two lists: years_list = [1880, 1881, 1882, 1883] temperature_list = [23, 26, 20, 21] I would like to merge the two lists so that both lists are in one lists but side by side. Where one list contains two lists. I would like the output to look like this: 1 How can I do that? I have tried merging them with the '+' ...
[ "I got it to work by using a generator inside of a function:\ndef merge_lists(list1: list, list2: list) -> list:\n\n # Returns items at the same index from two lists\n def _(list1, list2):\n assert len(list1) == len(list2) # Lists need to be the same length\n \n # Loop over lists\n for...
[ 0 ]
[]
[]
[ "list", "merge", "python", "python_zip" ]
stackoverflow_0074367027_list_merge_python_python_zip.txt
Q: How do I get the last number in a list that is very large? def fib(n): a=0 b=1 for i in range(n+1): yield a a,b = b,a+b lastnum = [num for num in fib(150000)] lastnum[-1] This is about the largest number (150000th number in fib) I can get from this method (Memory Error if larger). Is ...
How do I get the last number in a list that is very large?
def fib(n): a=0 b=1 for i in range(n+1): yield a a,b = b,a+b lastnum = [num for num in fib(150000)] lastnum[-1] This is about the largest number (150000th number in fib) I can get from this method (Memory Error if larger). Is there ways I can improve this to get up to 2,000,000th digit? Is...
[ "If you really only want the last element, then just avoid using a list in the first place. For instance, the following took some time but didn't run into any memory issues:\ni = 2000000\nfor n in fib(i):\n result = n\nprint(result)\n\nIf, however, you want something more general (such as getting the last k elem...
[ 1 ]
[]
[]
[ "fibonacci", "python", "python_3.x" ]
stackoverflow_0074366883_fibonacci_python_python_3.x.txt
Q: Azure Linux Web App (startup.sh: not found) On Azure Linux App service, while deploying a flask app i get following error: 2019-05-12T13:07:29.931475061Z A P P S E R V I C E O N L I N U X 2019-05-12T13:07:29.931478561Z 2019-05-12T13:07:29.931481661Z Documentation: http://aka.ms/webapp-linux 2019-05-12T13:07...
Azure Linux Web App (startup.sh: not found)
On Azure Linux App service, while deploying a flask app i get following error: 2019-05-12T13:07:29.931475061Z A P P S E R V I C E O N L I N U X 2019-05-12T13:07:29.931478561Z 2019-05-12T13:07:29.931481661Z Documentation: http://aka.ms/webapp-linux 2019-05-12T13:07:29.931484961Z 2019-05-12T13:07:30.016820049Z St...
[ "We had the same problem when there was a problem with the line endings in the file, because it was edited in Notepad. Try the sed editor to fix it:\nsed -i -e 's/\\r$//' <path_to_sh_file>\n", "You should be able to customize the Python application command by following this document:\nhttps://learn.microsoft.com...
[ 2, 1, 0 ]
[]
[]
[ "azure", "linux", "python" ]
stackoverflow_0056099649_azure_linux_python.txt
Q: Kivy buttons have white line on x and y axis when I try to create buttons I get white lines on x and y axis (depending if the width or height is too low - if both then there is line on both of the axis) label_height = 30 label_width = 100 Button(text="Don't reset", size_hint=(None, None), size=(...
Kivy buttons have white line on x and y axis
when I try to create buttons I get white lines on x and y axis (depending if the width or height is too low - if both then there is line on both of the axis) label_height = 30 label_width = 100 Button(text="Don't reset", size_hint=(None, None), size=(self.label_width, self.label_height), back...
[ "Probably there is a line under the button. Because you set alpha to .4 it is visible. Try to change alpha to 1 and check if line is still visible:\nbackground_color=(1, .2, .2, 1)\n\n" ]
[ 0 ]
[]
[]
[ "button", "kivy", "python" ]
stackoverflow_0074360056_button_kivy_python.txt
Q: How to make a Discord slash command usuable in DMs I want to use a slash command in DMs. Take this simple test.py file in the folder cogs/. import discord from discord.ext import commands from discord import app_commands class Test(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot...
How to make a Discord slash command usuable in DMs
I want to use a slash command in DMs. Take this simple test.py file in the folder cogs/. import discord from discord.ext import commands from discord import app_commands class Test(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot = bot @commands.Cog.listener() async def on_read...
[ "If you are using pycord, at least for me commands were usable in dm's by default. I'll show you how to disable that if you ever need to.\n@bot.command()\n@commands.guild_only()\nasync def example(ctx):\n#do things\n\n" ]
[ 0 ]
[]
[]
[ "discord", "pycord", "python" ]
stackoverflow_0073762380_discord_pycord_python.txt
Q: '>=' not supported between instances of 'str' and 'int' students = ['Ally',100, 'Emo',88, 'Stefan',70, 'George',60, 'Alex',45, 'Vasil',32, 'Daniel',0] passed_students = list(filter(lambda x: x >= 60, students)) print(passed_students) What did I do ...
'>=' not supported between instances of 'str' and 'int'
students = ['Ally',100, 'Emo',88, 'Stefan',70, 'George',60, 'Alex',45, 'Vasil',32, 'Daniel',0] passed_students = list(filter(lambda x: x >= 60, students)) print(passed_students) What did I do wrong,I also added 'str' before student,it didn't work so i a...
[ "You data structure for students seems wrong. I suggest to convert it to dictionary, then the filtering will be easier:\n# convert students list to a dictionary:\nstudents = dict(zip(students[::2], students[1::2]))\n\n# students is now\n#{\n# \"Ally\": 100,\n# \"Emo\": 88,\n# \"Stefan\": 70,\n# \"George...
[ 1, 0 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0074367046_integer_python_string.txt
Q: Install Anaconda Navigator with Miniforge (Mac with M1 chip) I have a MacBook with an M1 chip and have installed miniforge since this will run natively on the M1 chip. Question: How do I install Anaconda Navigator so that it uses the miniforge environment when I use it to launch Spyder and Jupyterlab? Or is this c...
Install Anaconda Navigator with Miniforge (Mac with M1 chip)
I have a MacBook with an M1 chip and have installed miniforge since this will run natively on the M1 chip. Question: How do I install Anaconda Navigator so that it uses the miniforge environment when I use it to launch Spyder and Jupyterlab? Or is this currently not possible? If I run conda install anaconda-navigator, ...
[ "So as at the time(June 30, 2022) of writing this answer anaconda navigator was not yet available on M1 MacBook pro because the MacOs does not yet support Qt\nso yes, you may have to install the mini-forge which is your best alternative if you have to choose between miniconda, anaconda or mini-forge\nhttps://www.an...
[ 2, 0 ]
[]
[]
[ "anaconda", "apple_m1", "conda", "python" ]
stackoverflow_0071989801_anaconda_apple_m1_conda_python.txt
Q: How to clean duplicate data from webscraping? So I want to make a list of books from a bookstore with a web scraper. I need the title and author of books. I can get the title nicely. The problem is with author. Namely the class of title is the same with different data. If I run the script it duplictes the data and...
How to clean duplicate data from webscraping?
So I want to make a list of books from a bookstore with a web scraper. I need the title and author of books. I can get the title nicely. The problem is with author. Namely the class of title is the same with different data. If I run the script it duplictes the data and in addition the data I don't need (book code, publ...
[ "You can use CSS selectors to properly select the Title/Author:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.apollo.ee/raamatud/eestikeelsed-raamatud/ilukirjandus/ulme-ja-oudus?page=7&mode=list\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nfor book in soup.select...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074367177_beautifulsoup_python_web_scraping.txt
Q: list with a tuple of dicts instead of list of dicts I have list of dicts [{'id': 14786, 'sku': '0663370-ZWA', 'sizes': ['38', '40', '42', '44', '46'], 'color': 'zwart'}, {'id': 14787, 'sku': '0663371-ZWA', 'sizes': ['38', '40', '42', '44', '46'], 'color': 'zwart'}] want to place it in a datastructure...
list with a tuple of dicts instead of list of dicts
I have list of dicts [{'id': 14786, 'sku': '0663370-ZWA', 'sizes': ['38', '40', '42', '44', '46'], 'color': 'zwart'}, {'id': 14787, 'sku': '0663371-ZWA', 'sizes': ['38', '40', '42', '44', '46'], 'color': 'zwart'}] want to place it in a datastructure for update attributes with woocommerce api list_of_updat...
[ "You use an intermediate:\nlst_of_attributes_items=[]\n\nWhich you append a tuple of dicst to:\nattributes = {'id': 1, 'name': 'kleur', 'position': 0,'options': index['color'], 'variations': 'false','visible': 'true'},{'id': 6, 'options': index['sizes'], 'variations': 'true','visible': 'true'}\nlist_of_update_items...
[ 1 ]
[]
[]
[ "nested_lists", "python", "woocommerce_rest_api" ]
stackoverflow_0074367024_nested_lists_python_woocommerce_rest_api.txt
Q: Rounds integer even with float- python Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to ...
Rounds integer even with float- python
Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to the nearest whole number. import locale cla...
[ "The int() function always returns an integer. An integer never has any decimal points. So use only\nfloat(input(\"please input the price of the item\\n\"))\n\ninstead of\nint(float(input(\"please input the price of the item\\n\")))\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074367242_python.txt
Q: How to show the actual values and not the index in the axis when drawing a contour plot from a netcdf file using python? I am exploring options to plot a contour plot in python from a netcdf file (which can be accessed here: https://drive.google.com/file/d/1zGpDK35WmCv62gNEI8H_ONHS2V_L9JEb/view?usp=sharing). The f...
How to show the actual values and not the index in the axis when drawing a contour plot from a netcdf file using python?
I am exploring options to plot a contour plot in python from a netcdf file (which can be accessed here: https://drive.google.com/file/d/1zGpDK35WmCv62gNEI8H_ONHS2V_L9JEb/view?usp=sharing). The file contains various meteorological variables at 1 hour intervals. I am trying to produce a time-height plot of wind (which ap...
[ "You should have given time as x and height y to the contour method instead of hacking the labels on your own.\nHere is a possible solution:\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport netCDF4\nfrom netCDF4 import num2date, date2num, date2index, Dataset\n# ---------------------...
[ 0 ]
[]
[]
[ "contour", "matplotlib", "python" ]
stackoverflow_0072158348_contour_matplotlib_python.txt
Q: is there away to make loop on huge data faster? i have data (pandas data frame) with 10 millions row ,this code using for loop on data using google colab but when i perform it it is very slow . is there away to use faster loop with these multiple statements (like np.where) or other solve?? i need help for rewrite ...
is there away to make loop on huge data faster?
i have data (pandas data frame) with 10 millions row ,this code using for loop on data using google colab but when i perform it it is very slow . is there away to use faster loop with these multiple statements (like np.where) or other solve?? i need help for rewrite this code in another way (like using np.where) or oth...
[ "Generally speaking, the worst thing to do is to iterate rows.\nI can't see a totally iteration free solution (by \"iteration free\" I mean, \"without explicit iterations in python\". Of course, any solution would have iterations anyway. But some may have iterations made under the hood, by the internal code of pand...
[ 2 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074366178_loops_python.txt
Q: Python tutorial project with kivy doesn't give the same result I ran this code and it didn't show anything it only shows this: D:\python\venv\Scripts\python.exe D:/python/main.py Hi, PyCharm Process finished with exit code 0 from kivymd.app import MDApp from kivymd.uix.button import MDRoundFlatIconButton class...
Python tutorial project with kivy doesn't give the same result
I ran this code and it didn't show anything it only shows this: D:\python\venv\Scripts\python.exe D:/python/main.py Hi, PyCharm Process finished with exit code 0 from kivymd.app import MDApp from kivymd.uix.button import MDRoundFlatIconButton class Test(MDApp): def build(self): return MDRoundFlatIconB...
[ "Open your code in PyCharm, then press Control+Shift+F10 to run it.\nYou are currently running default PyCharm generated sample code.\nIf you want to run current Python script you have to use mentioned key combination or right click, then choose: Run 'your_script_name.py'.\nAfter first launch, PyCharm will create l...
[ 0 ]
[]
[]
[ "android", "kivy", "python" ]
stackoverflow_0074334911_android_kivy_python.txt
Q: How to join certain elements of a list? I have a list that looks like this: lst = [(1,'X1', 256),(1,'X2', 356),(2,'X3', 223)] The first item of each tuple is an ID and I want to marge the items of each tuple where the ID is the same. For example I want the list to look like this: lst = [(1,('X1','X2'),(256,356)),...
How to join certain elements of a list?
I have a list that looks like this: lst = [(1,'X1', 256),(1,'X2', 356),(2,'X3', 223)] The first item of each tuple is an ID and I want to marge the items of each tuple where the ID is the same. For example I want the list to look like this: lst = [(1,('X1','X2'),(256,356)),(2,'X3',223) How do I do this the easiest wa...
[ "Use a dictionary whose keys are the IDs, so you can combine all the elements with the same ID.\nfrom collections import defaultdict\n\nlst = [(1,'X1', 256),(1,'X2', 356),(2,'X3', 223)]\nresult_dict = defaultdict(lambda: [[], []])\n\nfor id, item1, item2 in lst:\n result_dict[id][0].append(item1)\n result_dic...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074367084_list_python.txt
Q: Edit data in the database that was recorded without a form In my project, there is a form and a table with checkboxes, based on the data entered in the form and the checkboxes, I fill 2 databases and redirect the user to a page where information from one table is displayed, it all worked very well until I got to e...
Edit data in the database that was recorded without a form
In my project, there is a form and a table with checkboxes, based on the data entered in the form and the checkboxes, I fill 2 databases and redirect the user to a page where information from one table is displayed, it all worked very well until I got to editing the records, I decided I do it with UpdateView, passing i...
[ "You aren't passing any additonal data to the update form. The update view is separate and doesn't inherit data from the add-campaign view, so if you need additional context, you can:\nclass CampaignEditor(UpdateView):\n model = Campaigns\n template_name = 'mailsinfo/add_campaign.html'\n form_class = Camp...
[ 2 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0074366729_database_django_python.txt
Q: How do I apply table class criteria in a web-scraper through python? Although the web-scraper below works, it also includes listed hyperlinks unrelated to the webpage tables. What I would like to have help with is limiting the class criteria to only relevant tennis match hyperlinks within the class table "table-ma...
How do I apply table class criteria in a web-scraper through python?
Although the web-scraper below works, it also includes listed hyperlinks unrelated to the webpage tables. What I would like to have help with is limiting the class criteria to only relevant tennis match hyperlinks within the class table "table-main only12 js-nrbanner-t". import requests from bs4 import BeautifulSoup im...
[ "You can just add the table to the selector in select\ntLinkSel = 'table.table-main.only12.js-nrbanner-t a[href^=\"/tennis\"]:has(strong)'\nmatchlist = set('https://www.betexplorer.com'+a.get('href') for a in soup.select(tLinkSel))\n\nalthough, I have to mention that I did not see any difference in the results when...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074366039_beautifulsoup_python_web_scraping.txt
Q: Python Block Keyboard / Mouse Input i am currently trying to write a short script that will rickroll (open a youtube link) while the user is watching and can't interfere. I have managed to open insert the link slowly letter by letter and am now trying to block user inputs. I have tried using the ctypes import to b...
Python Block Keyboard / Mouse Input
i am currently trying to write a short script that will rickroll (open a youtube link) while the user is watching and can't interfere. I have managed to open insert the link slowly letter by letter and am now trying to block user inputs. I have tried using the ctypes import to block all inputs, run the script and then ...
[ "You can use the keyboard module to block all keyboard inputs and the mouse module to constantly move the mouse, preventing the user from moving it.\nSee these links for more details:\nhttps://github.com/boppreh/keyboard\nhttps://github.com/boppreh/mouse\nThis blocks all the keys on the keyboard (the 150 is large e...
[ 3, 1, 0 ]
[]
[]
[ "block", "input", "python" ]
stackoverflow_0065801957_block_input_python.txt
Q: "buildozer -v android debug" install platform erorr I have a proplem I am using kivy to build an app on ubuntu. I am following these instructions to create a package for Android using Buildozer. cd "/mnt/c/Users/c system/Documents/rak" sudo mount -t drvfs C: /mnt/c -o metadata buildozer init buildozer -v androi...
"buildozer -v android debug" install platform erorr
I have a proplem I am using kivy to build an app on ubuntu. I am following these instructions to create a package for Android using Buildozer. cd "/mnt/c/Users/c system/Documents/rak" sudo mount -t drvfs C: /mnt/c -o metadata buildozer init buildozer -v android debug But when I run : buildozer -v android debug ...
[ "Looks like your Ubuntu is not able to clone (download) kivy repository. First run will download a lot of stuff into .buildozer directory of your project. I also takes huge amount of time (40 minutes+, depending of your internet connection and PC specs). But next build attempts will be much quicker.\nAre you using ...
[ 0 ]
[]
[]
[ "buildozer", "kivy", "python" ]
stackoverflow_0074338112_buildozer_kivy_python.txt
Q: UTF-16 representation of arbitrarily long binary string I have binary strings and want to store them as compactly (in terms of disk space) as possible. They can be between 1 and ~1000 bits of the form '011010010110100110010101'. Storing these as "TEXT" is wasteful. I'd like to retrieve and convert them back to the...
UTF-16 representation of arbitrarily long binary string
I have binary strings and want to store them as compactly (in terms of disk space) as possible. They can be between 1 and ~1000 bits of the form '011010010110100110010101'. Storing these as "TEXT" is wasteful. I'd like to retrieve and convert them back to the original binary string. SQLite's TEXT type can be UTF-8, UTF...
[ "Convert the binary string to an integer and track the number of bits. A BLOB of byte data can be generated for storage as SQLITE INTEGER size would be exceeded if you have thousands of bits.\nExample:\nimport sqlite3\nimport os\nimport math\n\n# store string of binary data packed into bytes\ndef insert(cur, binar...
[ 1 ]
[]
[]
[ "binary", "python", "sqlite", "string", "utf_16" ]
stackoverflow_0074366057_binary_python_sqlite_string_utf_16.txt
Q: Saving boards in a file I would love to have literary batch records on my computer, unfortunately this is not an option. I decided to write a program that records the layout of the letters on the board and the available letters on each line in a text file. My idea is to get it out of html with python, maybe with s...
Saving boards in a file
I would love to have literary batch records on my computer, unfortunately this is not an option. I decided to write a program that records the layout of the letters on the board and the available letters on each line in a text file. My idea is to get it out of html with python, maybe with selenium. I know Python pretty...
[]
[]
[ "If you have the algorithms and logic to convert the page into a list, I may have a solution. Try making a csv file (comma separated values), which makes a table sort-of layout that can also be converted back to an array with ease. E.g.\nwith open('board.csv', 'w') as f:\n f.write(board data here)\n f.close()\n\n...
[ -1 ]
[ "python" ]
stackoverflow_0074367448_python.txt
Q: How to concatenate rows in python pd? How can I concatenate two columns of a df into only one? I've tried lots of possible combinations (with append, with np, with concat ) ... and there's always an error or the table outputs this way ` A B 0 75 Nan 1 71 NaN 2 NaN 83 3 NaN 64 ` instead of...
How to concatenate rows in python pd?
How can I concatenate two columns of a df into only one? I've tried lots of possible combinations (with append, with np, with concat ) ... and there's always an error or the table outputs this way ` A B 0 75 Nan 1 71 NaN 2 NaN 83 3 NaN 64 ` instead of in only 1 column what do I have to do?
[ "It depends on what data your columns contain and how you want to combine it.\nThe easiest way is to do:\ndf['new_column'] = df['column1'] + df['column2']\n\nTo solve the NaN issue you'll need to remove/replace them first. For example, if you are adding columns together, you can replace the NaN's with 0 so that the...
[ 2 ]
[]
[]
[ "concatenation", "dataframe", "pandas", "python" ]
stackoverflow_0074367351_concatenation_dataframe_pandas_python.txt
Q: What is the size of turtle? I am trying to make a program as small as possible (Including the dependencies) and I cant find a way how to find the size of turtle. Edit: I tried looking for the package size on PyPi but I could not find it. A: It's around 140.3 KiB in python 3.9. You can find the file and so the si...
What is the size of turtle?
I am trying to make a program as small as possible (Including the dependencies) and I cant find a way how to find the size of turtle. Edit: I tried looking for the package size on PyPi but I could not find it.
[ "It's around 140.3 KiB in python 3.9.\nYou can find the file and so the size of it in your files in:\n/lib/python3.9#Replace the *3.9* with your python version.\n\nBut for it to work you also need a lot of other python modules e.g. tkinter and that's another 709 KiB already.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074310574_python_python_3.x_python_turtle_turtle_graphics.txt
Q: Can't zoom in with gluLookAt(), only zoom out? I'm trying to implement an orbital camera in PyOpenGL Legacy and am trying to make it zoom in and out (so, go forward and back). This is the relevant bit of code: def update(self): self.pos = self.orbitalPos() print(f"self.pos length {self.magnitude(self.pos)}...
Can't zoom in with gluLookAt(), only zoom out?
I'm trying to implement an orbital camera in PyOpenGL Legacy and am trying to make it zoom in and out (so, go forward and back). This is the relevant bit of code: def update(self): self.pos = self.orbitalPos() print(f"self.pos length {self.magnitude(self.pos)}") self.look = self.pos * (-1.0) gluLookAt(*...
[ "gluLookAt not only sets a matrix, but defines a matrix and multiplies the current matrix (which can be the matrix of the last frame) with the new look at matrix. Therefore you have to load the identity matrix with glLoadIdentity before calling gluLookAt:\ndef update(self):\n self.pos = self.orbitalPos()\n p...
[ 1 ]
[]
[]
[ "linear_algebra", "opengl", "pygame", "pyopengl", "python" ]
stackoverflow_0074365424_linear_algebra_opengl_pygame_pyopengl_python.txt
Q: Multi-processed file reading in python I want a file to be read in a multi-processed way. Each process will be a class instance doing some specific task, but the class where the file is being opened will be a singleton class. We don't want to batch the entire file into a number of processes instead we want each pr...
Multi-processed file reading in python
I want a file to be read in a multi-processed way. Each process will be a class instance doing some specific task, but the class where the file is being opened will be a singleton class. We don't want to batch the entire file into a number of processes instead we want each process to asynchronously read a batch of line...
[ "What you want is not necessarily a singleton but rather a class instance that can be sharable among multiple processes. The most straightforward way I know of doing this (other people might have other ideas) is to create a managed class from ListTextFile. I would first modify its definition so that method get_list...
[ 0 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "python_3.x", "software_design" ]
stackoverflow_0074358359_multiprocessing_multithreading_python_python_3.x_software_design.txt
Q: Bin values into groups The relevant data in my dataframe looks as follows: Datapoint Values 1 0.2 2 0.8 3 0.4 4 0.1 5 1.0 6 0.6 7 0.7 8 0.2 9 0.5 10 0.1 I am hoping to group the numbers in the Values column into three categories: less than 0.25 as 'low', between 0.25 and 0.75 as middle and greater than...
Bin values into groups
The relevant data in my dataframe looks as follows: Datapoint Values 1 0.2 2 0.8 3 0.4 4 0.1 5 1.0 6 0.6 7 0.7 8 0.2 9 0.5 10 0.1 I am hoping to group the numbers in the Values column into three categories: less than 0.25 as 'low', between 0.25 and 0.75 as middle and greater than 0.75 as h...
[ "If you're using a dataframe, Pandas has a built-in function called pd.cut()\nimport pandas as pd\nimport numpy as np\nfrom io import StringIO\n\ndf = pd.read_csv(StringIO('''Datapoint Values\n1 0.2\n2 0.8\n3 0.4\n4 0.1\n5 1.0\n6 0.6\n7 0.7\n8 0.2\n9 0.5\n10 0.1'''), sep='\\t')\n\ndf['category']...
[ 1, 0, 0 ]
[]
[]
[ "binning", "data_processing", "python" ]
stackoverflow_0074367526_binning_data_processing_python.txt
Q: Elasticsearch in Python: "unknown parameter [analyser] on mapper [institution] of type [text]" when trying to create index I'm trying to create my first index in Elasticsearch with Python. I keep getting errors of the type : "unknown parameter [analyser] on mapper [institution] of type [text]" or "index has not be...
Elasticsearch in Python: "unknown parameter [analyser] on mapper [institution] of type [text]" when trying to create index
I'm trying to create my first index in Elasticsearch with Python. I keep getting errors of the type : "unknown parameter [analyser] on mapper [institution] of type [text]" or "index has not been configured in mapper" when trying to create the index. I've tried several ways of creating the index with "put_settings" and ...
[ "You misspelled \"analyzer\" - you wrote it with \"s\" - \"analyser\". The rest of the request looks ok. Consider adding Kibana to your implementation, and test your requests with dev tools. That's a really simple way of correcting those mistakes. That's how I found this misspelling.\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "indexing", "python" ]
stackoverflow_0074367500_elasticsearch_indexing_python.txt
Q: What is the most efficient way to run this kind of python code? I was coding a discord bot and realized I had difficulty parsing messages. I ended up using a double for loop (yuck). What can I do to optimize this code? (this is a far more straightforward version of the code) string = "His name is food" list = ["fo...
What is the most efficient way to run this kind of python code?
I was coding a discord bot and realized I had difficulty parsing messages. I ended up using a double for loop (yuck). What can I do to optimize this code? (this is a far more straightforward version of the code) string = "His name is food" list = ["food", "numbers"] parsed_string = string.split(" ") print(parced_string...
[ "string = \"His name is food\"\nmylist = [\"food\", \"numbers\"]\n\nif set(string.split()).intersection(mylist):\n print(\"stop\")\n\nor\nif not set(string.split()).isdisjoint(mylist):\n print(\"stop\")\n\n", "For a long list of keywords, prefer a set.\ntext = \"His name is food\"\nwords = {\"food\", \"numb...
[ 1, 1, 0 ]
[]
[]
[ "for_loop", "optimization", "python" ]
stackoverflow_0074367541_for_loop_optimization_python.txt
Q: How to drop duplicates based on value in dataframe column? I have a very simple Pandas dataframe: Revenue City 27 "New York" 59 "New York" 52 "New York" 34 "London" 14 "London" 24 "London" 45 "Tokyo" 54 "Los Angeles" 24 "Los Angel...
How to drop duplicates based on value in dataframe column?
I have a very simple Pandas dataframe: Revenue City 27 "New York" 59 "New York" 52 "New York" 34 "London" 14 "London" 24 "London" 45 "Tokyo" 54 "Los Angeles" 24 "Los Angeles" I would like to remove all duplicates in 'City' column, exc...
[ "try this:\ndf = df.loc[(df.duplicated(subset=['City'], keep='first') == False) | (~df['City'].isin(mask)]\n\n" ]
[ 0 ]
[]
[]
[ "data_science", "dataframe", "pandas", "python" ]
stackoverflow_0074367461_data_science_dataframe_pandas_python.txt
Q: How can I use UUIDs in SQLAlchemy? Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)? A: The sqlalchemy postgres dialect supports UUID columns. This is easy (and the question is specifically postgres) -- I don't understand why the other answers are all so com...
How can I use UUIDs in SQLAlchemy?
Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?
[ "The sqlalchemy postgres dialect supports UUID columns. This is easy (and the question is specifically postgres) -- I don't understand why the other answers are all so complicated.\nHere is an example:\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom flask_sqlalchemy import SQLAlchemy\nimport uuid\n\ndb = SQ...
[ 276, 68, 40, 24, 14, 7, 3, 1, 0 ]
[ "You could try writing a custom type, for instance:\nimport sqlalchemy.types as types\n\nclass UUID(types.TypeEngine):\n def get_col_spec(self):\n return \"uuid\"\n\n def bind_processor(self, dialect):\n def process(value):\n return value\n return process\n\n def result_proc...
[ -21 ]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0000183042_postgresql_python_sqlalchemy.txt
Q: Simple way to read a mixed binary / ascii file in python? I'm trying to open and interpret a P6 ppm image file by hand in python. A ppm p6 file has a few lines of plain ascii at the start, followed by the actual image data in binary (this in contrast to a ppm p3 file, which is all plain text). I've found a few mod...
Simple way to read a mixed binary / ascii file in python?
I'm trying to open and interpret a P6 ppm image file by hand in python. A ppm p6 file has a few lines of plain ascii at the start, followed by the actual image data in binary (this in contrast to a ppm p3 file, which is all plain text). I've found a few modules that can read ppm files (opencv, numpy), but I'd really li...
[ "you can do something like this, open the file in rb mode and check if the current byte is printable, if it is print as a character if not print as hex value.\nimport string\n\n\nwith open(\"file name\", \"rb\") as file:\n data = file.read()\n# to print, go through the file data\nfor byte in data:\n # check i...
[ 0 ]
[]
[]
[ "binary", "ppm", "python" ]
stackoverflow_0074367573_binary_ppm_python.txt
Q: Python: Multiprocessing.Process does not invoke target function sometimes I have a script that runs daily and while invoking processes, out of 100+ processes sometimes randomly 2 or 3 process do not get started and my target function is not called. This started occurring recently and before some days it was runnin...
Python: Multiprocessing.Process does not invoke target function sometimes
I have a script that runs daily and while invoking processes, out of 100+ processes sometimes randomly 2 or 3 process do not get started and my target function is not called. This started occurring recently and before some days it was running fine. There is no pattern in its skipping processes also, it happens on rando...
[ "Firstly you are not actually checking what's going on. After joining all processes you should check their exitcode to make sure they all executed correctly. It's always a good practice to check the exit status of your processes to make sure everything ran smoothly.\nSecondly, you claim you are starting more than a...
[ 2 ]
[]
[]
[ "multiprocess", "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0074361292_multiprocess_multiprocessing_python_python_multiprocessing.txt
Q: how to combine everything in a pandas dataframe into another dataframe I have a dataframe with information, where the rows are not related to eachother: Fruits Vegetables Protein 1 Apple Spinach Beef 2 Banana Cucumber Chicken 3 Pear Carrot Pork I essentially just want to create a pandas ...
how to combine everything in a pandas dataframe into another dataframe
I have a dataframe with information, where the rows are not related to eachother: Fruits Vegetables Protein 1 Apple Spinach Beef 2 Banana Cucumber Chicken 3 Pear Carrot Pork I essentially just want to create a pandas series with all of that information, I want it to look like this: All Foo...
[ "Dump into numpy and create a new dataframe:\nout = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n\n", "Just pd.concat them together (and reset the index).\nall_fo...
[ 1, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074367634_pandas_python.txt
Q: Python read Cassandra data into pandas What is the proper and fastest way to read Cassandra data into pandas? Now I use the following code but it's very slow... import pandas as pd from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory auth...
Python read Cassandra data into pandas
What is the proper and fastest way to read Cassandra data into pandas? Now I use the following code but it's very slow... import pandas as pd from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory auth_provider = PlainTextAuthProvider(username=C...
[ "I got the answer at the official mailing list (it works perfectly):\n\nHi,\ntry to define your own pandas row factory:\ndef pandas_factory(colnames, rows):\n return pd.DataFrame(rows, columns=colnames)\n\nsession.row_factory = pandas_factory\nsession.default_fetch_size = None\n\nquery = \"SELECT ...\"\nrslt = s...
[ 50, 14, 0, 0, 0, 0 ]
[]
[]
[ "cassandra", "pandas", "python" ]
stackoverflow_0041247345_cassandra_pandas_python.txt
Q: Hashing in SHA512 using a salt? - Python I have been looking through ths hashlib documentation but haven't found anything talking about using salt when hashing data. Help would be great. A: Samir's answer is correct but somewhat cryptic. Basically, the salt is just a randomly derived bit of data that you prefix ...
Hashing in SHA512 using a salt? - Python
I have been looking through ths hashlib documentation but haven't found anything talking about using salt when hashing data. Help would be great.
[ "Samir's answer is correct but somewhat cryptic. Basically, the salt is just a randomly derived bit of data that you prefix or postfix your data with to dramatically increase the complexity of a dictionary attack on your hashed value. So given a salt s and data d you'd just do the following to generate a salted has...
[ 83, 19, 12, 7, 3, 2, 0 ]
[]
[]
[ "hashlib", "python", "salt", "saltedhash", "sha" ]
stackoverflow_0002898685_hashlib_python_salt_saltedhash_sha.txt