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: Message: unknown error: cannot parse internal JSON template: Line: 1, column: 1, Unexpected token options = webdriver.ChromeOptions() options.add_argument("user-data-dir=C:\\Users\\jack_l\\AppData\\Local\\Google\\Chrome\\User Data") options.add_argument(r'--profile-directory=Profile 8') driver = webdriver.Chrome(...
Message: unknown error: cannot parse internal JSON template: Line: 1, column: 1, Unexpected token
options = webdriver.ChromeOptions() options.add_argument("user-data-dir=C:\\Users\\jack_l\\AppData\\Local\\Google\\Chrome\\User Data") options.add_argument(r'--profile-directory=Profile 8') driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) I'm getting the Message: unknown error: cannot parse...
[ "I managed to get it up and running again! The solution that worked for me was deleting C:\\Users\\USER\\AppData\\Local\\Google\\Chrome folder and reinstalling Chrome. If you run into this problem, give it a try.\n", "I solved by deleting the folder .config. In my particular case I use this custom path:\nself.opt...
[ 1, 0 ]
[]
[]
[ "chromium", "google_chrome", "python", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0072223705_chromium_google_chrome_python_selenium_chromedriver_selenium_webdriver.txt
Q: How do I write dictionary inside a DataFrame as an element? Is it possible to write a dictionary into Data Frame? I have created the following DataFrame with my structure: df =pd.DataFrame({'name': ['L1', 'L2'], 'DEF': [None, None]}) df Out[70]: name DEF 0 L1 None 1 L2 None I also have a dictionary di...
How do I write dictionary inside a DataFrame as an element?
Is it possible to write a dictionary into Data Frame? I have created the following DataFrame with my structure: df =pd.DataFrame({'name': ['L1', 'L2'], 'DEF': [None, None]}) df Out[70]: name DEF 0 L1 None 1 L2 None I also have a dictionary dict1={'DEF120':50} If try to write dictionary into df as df.loc[d...
[ "Dictionaries/lists have a special meaning when assigned using loc. Pandas will try to expand them to Series.\nYou need to cheat a bit and use at:\ns = df.name=='L2'\nidx = s[s].index[0]\ndf.at[idx, 'DEF'] = dict1\n\nupdated dataframe:\n name DEF\n0 L1 None\n1 L2 {'DEF120': 50}\n\n", ...
[ 1, 1, 0, 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074126395_dataframe_dictionary_pandas_python.txt
Q: Counting using for loops within a list For this function, I have to count repeated items within a list. For instance, given the following list = [1,1,1,3,3,3,4,4,4] the output should be returned the number of different repeated values within that list, so the output would be 3 while data < 15 count = 1 ...
Counting using for loops within a list
For this function, I have to count repeated items within a list. For instance, given the following list = [1,1,1,3,3,3,4,4,4] the output should be returned the number of different repeated values within that list, so the output would be 3 while data < 15 count = 1 num = 1 for i in range(len(data) - 1)...
[ "You can do with collections.Counter,\nfrom collections import Counter\nprint(Counter(lst).most_common()[0][1])\n\nCounter will return a dictionary with values and counts\nExecution:\nIn [1]: lst = [1,1,1,3,3,3,4,4,4]\n\nIn [2]: print(Counter(lst).most_common()[0][1])\n3\n\nIn [3]: lst = [4,4,2,2,2,2,2,2,2,2,2,2,2,...
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074126444_loops_python.txt
Q: AttributeError: Can't get attribute 'new_block' on I was using pyspark on AWS EMR (4 r5.xlarge as 4 workers, each has one executor and 4 cores), and I got AttributeError: Can't get attribute 'new_block' on <module 'pandas.core.internals.blocks'. Below is a snippet of the code that threw this error: search = Sear...
AttributeError: Can't get attribute 'new_block' on
I was using pyspark on AWS EMR (4 r5.xlarge as 4 workers, each has one executor and 4 cores), and I got AttributeError: Can't get attribute 'new_block' on <module 'pandas.core.internals.blocks'. Below is a snippet of the code that threw this error: search = SearchEngine(db_file_dir = "/tmp/db") conn = sqlite3.connect(...
[ "Solutions\n\nKeeping the pickle file unchanged ,upgrade your pandas version to 1.3.x and then load the pickle file.\n\nOr\n\nKeeping your current pandas version unchanged, downgrade the pandas version to 1.2.x on the dumping side, and then dump a new pickle file with v1.2.x. Load it on your side with your pandas o...
[ 65, 10, 6, 4, 1, 0, 0 ]
[]
[]
[ "apache_spark", "attributeerror", "pandas", "pyspark", "python" ]
stackoverflow_0068625748_apache_spark_attributeerror_pandas_pyspark_python.txt
Q: Unable to open file libtensorflow_io.so caused by undefined symbol I have a tensorflow 2.2 conda environment setup with python 3.8.2 on Ubuntu. I ran pip install tensorflow-io==0.14.0. When I try to import tensorflow-io as tfio I get the erorr: File "/home/somedir/miniconda3/envs/env_name/lib/python3.8/site-packa...
Unable to open file libtensorflow_io.so caused by undefined symbol
I have a tensorflow 2.2 conda environment setup with python 3.8.2 on Ubuntu. I ran pip install tensorflow-io==0.14.0. When I try to import tensorflow-io as tfio I get the erorr: File "/home/somedir/miniconda3/envs/env_name/lib/python3.8/site-packages/tensorflow_io/core/python/ops/__init__.py", line 65, in _load_librar...
[ "As @Smedegaard mentioned, tensorflow_io is not on conda forge. The answer of vlasenkoalexey on Github issues to tackle this:\n\nObvious workaround is to uninstall tensorflow and tensorflow-io and install them from pip: \npip uninstall tensorflow \npip uninstall tensorflow-io \npip install tensorflow-gpu \npip inst...
[ 6, 0, 0, 0 ]
[]
[]
[ "conda", "pip", "python", "tensorflow", "undefined_symbol" ]
stackoverflow_0065623468_conda_pip_python_tensorflow_undefined_symbol.txt
Q: How to convert image files to tensor I am trying to convert the NIH Chest X-Ray (dataset available in kaggle) images into a tensor format that is suitable for feeding into a Keras model. datagen=ImageDataGenerator( ) datagen.fit('E:/Trial chest x-ray dataset/train resized (224,224)') I tried the code mentioned ...
How to convert image files to tensor
I am trying to convert the NIH Chest X-Ray (dataset available in kaggle) images into a tensor format that is suitable for feeding into a Keras model. datagen=ImageDataGenerator( ) datagen.fit('E:/Trial chest x-ray dataset/train resized (224,224)') I tried the code mentioned above but it is saying- could not convert ...
[ "Are these folders already created?\n\ntrain_images\nvalidation_images...\n\nIf you haven't already, please check this:\nhttps://www.tensorflow.org/hub/tutorials/tf2_image_retraining\n" ]
[ 1 ]
[ "image = tf.io.read_file(image_path)\nimage = tf.image.decode_jpeg(image, channels=3)\nimage = tf.image.convert_image_dtype(image,tf.float32)\nimage = tf.image.resize(image,size = [img_size,img_size])\n\n" ]
[ -1 ]
[ "python", "tensor", "tensorflow" ]
stackoverflow_0066326466_python_tensor_tensorflow.txt
Q: Press Fn key Python 3 I bought a new keyboard and everytime I turn on my computer I have to press Fn + 5 (3 times) to set the color I want for the backlighting, so I decided to try to script it. First I tried with the pyautogui library: import pyautogui as pg import time for x in range(0,2): pg.hotkey('fn','...
Press Fn key Python 3
I bought a new keyboard and everytime I turn on my computer I have to press Fn + 5 (3 times) to set the color I want for the backlighting, so I decided to try to script it. First I tried with the pyautogui library: import pyautogui as pg import time for x in range(0,2): pg.hotkey('fn','5') time.sleep(0.2) Bu...
[ "There are keys for pressing fn+special keys:\nfor example for volume control:\n'volumedown', 'volumemute', 'volumeup'\nimport pyautogui\npyautogui.press('volumeup')\n\nAll the keys are in a list that you can access by typing\nprint(pyautogui.KEYBOARD_KEYS)\n\noutput:\n['\\t', '\\n', '\\r', ' ', '!', '\"', '#', '$'...
[ 5, 0 ]
[]
[]
[ "pyautogui", "python", "python_3.x", "windows" ]
stackoverflow_0053971335_pyautogui_python_python_3.x_windows.txt
Q: How to find number of Fridays/Thursdays in date range Is there any python function to deduce the number of Fridays or Thursdays from a date range? I searched google and I found many methods which usually use days divided by 7 concept but it does not give you the accurate days. For example from 1/Nov/2016 to 12/Nov...
How to find number of Fridays/Thursdays in date range
Is there any python function to deduce the number of Fridays or Thursdays from a date range? I searched google and I found many methods which usually use days divided by 7 concept but it does not give you the accurate days. For example from 1/Nov/2016 to 12/Nov/2016 there are two Fridays and two Thursdays so the result...
[ "You can do it with numpy:\nimport numpy as np\nfrom datetime import datetime\n\nstart_date = datetime(2022, 10, 19).strftime('%Y-%m-%d')\nend_date = datetime(2022, 12, 21).strftime('%Y-%m-%d')\n\nweekend_days = np.busday_count(start_date, end_date, weekmask='0000110').item()\n\nnumpy busday_count doc\nKeep in mind...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0040382423_python_python_2.7.txt
Q: How to print random rows from xslx file with python openpyxl is there any way to print random rows from xlsx file with openpyxl? I am still a python beginner, so I have no idea how. I've tried to look it up on google but the only way to do that is with xlrd. Unfortunately, xlrd doesn't support xslx anymore. How to...
How to print random rows from xslx file with python openpyxl
is there any way to print random rows from xlsx file with openpyxl? I am still a python beginner, so I have no idea how. I've tried to look it up on google but the only way to do that is with xlrd. Unfortunately, xlrd doesn't support xslx anymore. How to read and print random rows from Excel file in Python? This is the...
[ "You can use below code to print random rows from an excel sheet using openpyxl\nimport openpyxl\nimport random\nwb=openpyxl.load_workbook('Sample.xlsx') ## Read excel\nws=wb['Sheet1'] ## Sheet to read\nlen = ws.max_row ## read the number of rows in that sheet\nbreakout = False ## Use to break out of both loop - t...
[ 0 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0074124350_openpyxl_python.txt
Q: How to perform a vectorized function on a 2D numpy array? vecs = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) def find_len(vector): return (vector[0] ** 2 + vector[1] ** 2 + vector[2] ** 2) ** 0.5 vec_len = np.vectorize(find_len) I want to apply find_len to every vector in t...
How to perform a vectorized function on a 2D numpy array?
vecs = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) def find_len(vector): return (vector[0] ** 2 + vector[1] ** 2 + vector[2] ** 2) ** 0.5 vec_len = np.vectorize(find_len) I want to apply find_len to every vector in the 2d array and create a new numpy array with the values return...
[ "Are you just looking for this result:\narray([ 3.74165739, 8.77496439, 13.92838828])\n\nbecause you can achieve that without vectorize, just use:\n(vecs**2).sum(axis=1)**0.5\n\nThis also has the advantage of not being specific to vectors of length 3.\n\nOperations are already applied element-wise, so you can hand...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074126609_python.txt
Q: Multiprocessing Pool Loses Variable Values on Some Runs I have code similar to this: import multiprocessing const = "ABC" val_list = [1, 2, 3] args = [{"val": val, "const": const} for val in val_list] with multiprocessing.Pool() as p: p.map(functionWrapper, args) When I run with a long val_list, e.g., ...
Multiprocessing Pool Loses Variable Values on Some Runs
I have code similar to this: import multiprocessing const = "ABC" val_list = [1, 2, 3] args = [{"val": val, "const": const} for val in val_list] with multiprocessing.Pool() as p: p.map(functionWrapper, args) When I run with a long val_list, e.g., 2,000 entries, then for some of the multiprocessing runs, the...
[ "You explain that given args like\n[{'val': 1, 'const': 'ABC'},\n {'val': 2, 'const': 'ABC'},\n {'val': 3, 'const': 'ABC'}]\n\noccasionally functionWrapper will unexpectedly receive\nthe literal string 'const', or 'val', as input argument.\nWell, that's Bad.\nWe want to know where those literals came from.\nDoing t...
[ 1 ]
[]
[]
[ "docker", "multiprocessing", "python", "vscode_debugger" ]
stackoverflow_0074120026_docker_multiprocessing_python_vscode_debugger.txt
Q: Unix timestamp conversion to time with microsecond accuracy of seconds I have 1000 of UYC timestamps in csv file, I want to convert it into date and time but I am only interested in second like Timestamps= 1666181576.26295, 1666181609.54292 19/10/2022 15:45:25.34568 from that I only have interest in 25.34568 sec...
Unix timestamp conversion to time with microsecond accuracy of seconds
I have 1000 of UYC timestamps in csv file, I want to convert it into date and time but I am only interested in second like Timestamps= 1666181576.26295, 1666181609.54292 19/10/2022 15:45:25.34568 from that I only have interest in 25.34568 seconds, also the numbers after points. How can I get this type of conversion i...
[ "You can use datetime,\nfrom datetime import datetime\nts = 1666181576.26295\nmseconds = datetime.utcfromtimestamp(ts).microsecond\n\n", "from datetime import datetime\nfrom decimal import Decimal\nts = 1666181576.26295\ntimestamp = datetime.fromtimestamp(ts)\nresult = timestamp.second + Decimal(timestamp.microse...
[ 0, 0, 0 ]
[]
[]
[ "python", "timestamp", "utc" ]
stackoverflow_0074126574_python_timestamp_utc.txt
Q: Comparison of two data frames and getting the differences by two columns - Pandas I would like to compare two data frames, for example import pandas as pd az_df = pd.DataFrame({'name': ['CR1', 'CR2'], 'age': [1, 5], 'dr':[1, 2]})[['name', 'age']] za_df = pd.DataFrame({'name': ['CR2', 'CR1'], 'age': [2, 1], 'dr':[...
Comparison of two data frames and getting the differences by two columns - Pandas
I would like to compare two data frames, for example import pandas as pd az_df = pd.DataFrame({'name': ['CR1', 'CR2'], 'age': [1, 5], 'dr':[1, 2]})[['name', 'age']] za_df = pd.DataFrame({'name': ['CR2', 'CR1'], 'age': [2, 1], 'dr':[2, 4]})[['name', 'age']] AZ_DF table: name age dr CR1 1 1 CR2 5 2 ZA_DF ...
[ "Try this:\nimport pandas as pd\n\naz_df = pd.DataFrame({'name': ['CR1', 'CR2'], 'age': [1, 5], 'dr':[1, 2]})[['name', 'age']]\nza_df = pd.DataFrame({'name': ['CR2', 'CR1'], 'age': [2, 1], 'dr':[2, 4]})[['name', 'age']]\n\nmerge = pd.merge(az_df, za_df, on='name', how='outer')\nmerge.rename(columns={'age_x': 'only ...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074125766_dataframe_pandas_python.txt
Q: Web Scraping School Project I need help with a school project. The code that I have "#" I can't seem to get to work with the table I scraped. I need to change it into a data frame. Can anyone see what I'm missing and if I am missing a step. Tertiary=pd.read_html("https://en.wikipedia.org/wiki/List_of_countries_by_...
Web Scraping School Project
I need help with a school project. The code that I have "#" I can't seem to get to work with the table I scraped. I need to change it into a data frame. Can anyone see what I'm missing and if I am missing a step. Tertiary=pd.read_html("https://en.wikipedia.org/wiki/List_of_countries_by_tertiary_education_attainment") T...
[ "Everything works fine for me.\nimport pandas as pd\n\ndf = pd.read_html(\"https://en.wikipedia.org/wiki/List_of_countries_by_tertiary_education_attainment\")\ntable = pd.DataFrame(df[1])\nprint(table)\nprint(table.columns)\n\nOutput:\n Country Age 25–64 (%) Age Year N...
[ 0 ]
[]
[]
[ "dataframe", "google_colaboratory", "python" ]
stackoverflow_0074124724_dataframe_google_colaboratory_python.txt
Q: Extract specific variable names from functions Below you can see the function for extracting separate words from the text. Below you can see the text and code. import re text = ''' def function_cal(revenues_shops, surplus_margin, meadian_profit): median_profit= revenues_shops* surplus_margin return med...
Extract specific variable names from functions
Below you can see the function for extracting separate words from the text. Below you can see the text and code. import re text = ''' def function_cal(revenues_shops, surplus_margin, meadian_profit): median_profit= revenues_shops* surplus_margin return median_profit def function_cal_new (revenues_stories_...
[ "If you want to place the words into a data structure you can use the following code (replacing the last line of code in you shared):\nsplited_table1, splited_table2 = zip(*extraction_variables(text))\ntable = []\nfor elem in splited_table1:\n table.append(elem)\nfor sub_array in splited_table2:\n for elem in...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074126700_python.txt
Q: How to get generator function to print Edit: I saw a post about including brackets to make a list. In this case, where would I insert said brackets? Sorry, newbie. I have a function to generate combinations of any given number range but I need to print out or list all the possible combinations. Instead I'm getting...
How to get generator function to print
Edit: I saw a post about including brackets to make a list. In this case, where would I insert said brackets? Sorry, newbie. I have a function to generate combinations of any given number range but I need to print out or list all the possible combinations. Instead I'm getting this: <generator object combinations at 0x0...
[ "Generators and iterators are lazily evaluated functions, hence the use of the yield keyword. Therefore, to get the next value from a generator or iterator, say gen, we call next(gen). Some other comments on your post are saying that you should just cast your generator to a list, which is fine but may defeat the pu...
[ 0 ]
[]
[]
[ "combinations", "iterator", "permutation", "python" ]
stackoverflow_0074125661_combinations_iterator_permutation_python.txt
Q: Pandas, Multi Column Table Am trying to create a multi-column table, meaning a column has three sub-columns. I tried a solution from this: How to Insert a List of Data into Pandas Multi-Index Dataframe But the thing is that it passes a list, each item in the list corresponds to a column; i want to pass a data fram...
Pandas, Multi Column Table
Am trying to create a multi-column table, meaning a column has three sub-columns. I tried a solution from this: How to Insert a List of Data into Pandas Multi-Index Dataframe But the thing is that it passes a list, each item in the list corresponds to a column; i want to pass a data frame and align the values to each s...
[ "Do you want to generate a MultiIndex?\nYou can use concat:\ndf = pd.concat({'Masculine': med}, axis=1)\n\n# OR\ndf = pd.concat([med], keys=colnames, axis=1)\n\noutput:\n Masculine \n Gold Silver Bronze\n0 54 42 41\n1 37 40 49\n2 37 26 29\n3 14...
[ 0 ]
[]
[]
[ "dataframe", "multi_index", "multiple_columns", "pandas", "python" ]
stackoverflow_0074126754_dataframe_multi_index_multiple_columns_pandas_python.txt
Q: how to succesfully compile python 3.x Upon attempting to compile python 3.7 I hit Could not import runpy module: jeremyr@b88:$ wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz .... jeremyr@b88:~/Python-3.7.3$ ./configure --enable-optimizations jeremyr@b88:~/Python-3.7.3$ make clean jeremyr@b88...
how to succesfully compile python 3.x
Upon attempting to compile python 3.7 I hit Could not import runpy module: jeremyr@b88:$ wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz .... jeremyr@b88:~/Python-3.7.3$ ./configure --enable-optimizations jeremyr@b88:~/Python-3.7.3$ make clean jeremyr@b88:~/Python-3.7.3$ make -j32 .... gcc -pth...
[ "It seems the enable-optimizations was the problem, \njeremyr@b88:~/Python-3.7.3$ ./configure \njeremyr@b88:~/Python-3.7.3$ make clean \n\ntakes care of it in my case.\n", "In case others come across this question: I encountered the same problem on Centos 7. I also had --enable-optimizations but didn't want to ...
[ 34, 5, 0 ]
[]
[]
[ "compiler_errors", "gcc", "python", "python_3.7", "runpy" ]
stackoverflow_0058048079_compiler_errors_gcc_python_python_3.7_runpy.txt
Q: Overlay of two imshow plots on top of each other, with a slider to change the opacity of the layer The code below works to overlay two imshow plots, and to create a slider which changes the value of the global variable OPACITY. Unfortunately, img1.set_data(y); fig.canvas.draw_idle() doesn't redraw the new opacity....
Overlay of two imshow plots on top of each other, with a slider to change the opacity of the layer
The code below works to overlay two imshow plots, and to create a slider which changes the value of the global variable OPACITY. Unfortunately, img1.set_data(y); fig.canvas.draw_idle() doesn't redraw the new opacity. How to make an overlay of two imshow plots with a slider to change the opacity of the 2nd layer? impor...
[ "You can re-set the opacity of the overlaying img1 within the update function by img1.set_alpha():\n\n\nCode:\nimport numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets\n\nOPACITY = 0.5\n\nx = np.random.random((100, 50))\ny = np.linspace(0, 0.1, 100*50).reshape((100, 50))\n\n# PLOT\nfig, (ax0, a...
[ 2, 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0073951076_matplotlib_numpy_python.txt
Q: Is Pylance working properly for Annotated Pydantic Fields? Why does Pylance warn for Alice? I expect that field seed should be identical for both classes User1 and User2. import random from typing import Annotated from pydantic import BaseModel, Field RandomInt = Annotated[int, Field(default_factory=lambda:rando...
Is Pylance working properly for Annotated Pydantic Fields?
Why does Pylance warn for Alice? I expect that field seed should be identical for both classes User1 and User2. import random from typing import Annotated from pydantic import BaseModel, Field RandomInt = Annotated[int, Field(default_factory=lambda:random.randint(0, 1000))] class User1(BaseModel): name : str ...
[ "The usage in User1.seed and User2.seed is not equivalent. Pydantic's Field is not a type annotation, it must be used as a value (as is for User2.seed). Such, pydantic just interprets User1.seed as an int field, with no default value, and so requires you to provide a value on creation.\nAnnotated is used for provid...
[ 1 ]
[]
[]
[ "pydantic", "pylance", "python", "python_typing" ]
stackoverflow_0074126661_pydantic_pylance_python_python_typing.txt
Q: ImportError: cannot import name 'views' from 'birds_eye' I've recently started to learn how to build django projects with multiple apps. I have learnt that by using from . import views I can import the different views from the current directory that I am in. However, when using this method, the prompt would give m...
ImportError: cannot import name 'views' from 'birds_eye'
I've recently started to learn how to build django projects with multiple apps. I have learnt that by using from . import views I can import the different views from the current directory that I am in. However, when using this method, the prompt would give me an error saying: ImportError: cannot import name 'views' fro...
[ "You don't have a views.py file in the same directory as your urls.py file. I assume your views are in your other apps (clubs, posts, etc)?\nYou would be better to import each view directly from those apps, e.g. in your urls.py\nfrom ..clubs.views import ...\n\nAlternatively, if you do want to carry on down the rou...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074126159_django_python.txt
Q: Grouped pandas dataframe from nested list I have a nested list in this format mydata=[[01/01/20,['point1','point2','point3,...]],[02/01/20,['point1','point2','point3']],...] I want to create a pandas dataframe grouped by date with every point as a different row. I have tried manually adding each row through a for ...
Grouped pandas dataframe from nested list
I have a nested list in this format mydata=[[01/01/20,['point1','point2','point3,...]],[02/01/20,['point1','point2','point3']],...] I want to create a pandas dataframe grouped by date with every point as a different row. I have tried manually adding each row through a for loop, but other than taking more than an hour, ...
[ "The expected output is not fully clear, but if I guess correctly:\nmydata = [['01/01/20',['point1','point2','point3']],\n ['02/01/20',['point1','point2','point3']]]\n\ndf = pd.DataFrame(dict(mydata))\n\nOr:\ncols, data = zip(*mydata)\n\ndf = pd.DataFrame(zip(*data), columns=cols)\n\noutput:\n 01/01/20 02...
[ 1 ]
[]
[]
[ "dataframe", "nested_lists", "pandas", "python" ]
stackoverflow_0074126924_dataframe_nested_lists_pandas_python.txt
Q: Finding duplicates in two separate txt files line by line and print only duplicates Tldr: Open two txt files, use one to search the other and then print any duplicates. Hi everyone, first time posting on here and very new to coding and python, I'm searching for an answer and unable to find anything that uses .txt ...
Finding duplicates in two separate txt files line by line and print only duplicates
Tldr: Open two txt files, use one to search the other and then print any duplicates. Hi everyone, first time posting on here and very new to coding and python, I'm searching for an answer and unable to find anything that uses .txt files like I'm trying to do. I am trying to search for a group of strings or single strin...
[ "To remove duplicates you can use set\nf1 = open(r\"test.txt\", \"r\")\nf2 = open(r\"test2.txt\", \"r\")\nfile1 = f1.read().splitlines()\nfile2 = f2.read().splitlines()\nd = list(set(file1+file2)) # Combine and remove duplcates\nprint(d)\nf1.close()\nf2.close()\n\nNB: (x for x in z if z.count (x) > 1) you are creat...
[ 0, 0 ]
[]
[]
[ "duplicates", "list", "python", "text" ]
stackoverflow_0074126791_duplicates_list_python_text.txt
Q: AttributeError: module 'semver' has no attribute 'compare' [Python-Gitlab] I'm getting this error in vscode. AttributeError: module 'semver' has no attribute 'compare' Python version: Python 3.10.6 Pip version: pip 22.3 semver version: 2.8.1 import semver def is_equals(): result = semver.co...
AttributeError: module 'semver' has no attribute 'compare' [Python-Gitlab]
I'm getting this error in vscode. AttributeError: module 'semver' has no attribute 'compare' Python version: Python 3.10.6 Pip version: pip 22.3 semver version: 2.8.1 import semver def is_equals(): result = semver.compare('0.0.1', '1.0.0')
[ "You should check your filename. Gives error if \"semver\" is same as filename\nRename your python filename\nAnd\npip install semver\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x", "semantic_versioning" ]
stackoverflow_0074122259_python_python_3.x_semantic_versioning.txt
Q: Copying from a range of cells with openpyxl, Error: Colors must be aRGB hex values I am copying a range of cells with openpyxl from one workbook to another with the following code: import openpyxl import os #Current path path = os.path.dirname(os.path.abspath(__file__)) #Beregningsmodul navn Beregningsmodul_mode...
Copying from a range of cells with openpyxl, Error: Colors must be aRGB hex values
I am copying a range of cells with openpyxl from one workbook to another with the following code: import openpyxl import os #Current path path = os.path.dirname(os.path.abspath(__file__)) #Beregningsmodul navn Beregningsmodul_moder_navn = "Beregning COREP LCR - MODER - 202202.xlsx" #workbook_beregn path beregn_path ...
[ "I've just ran across the same issue. Not sure if you still need the answer, anyway I want to leave more elegant solution to the problem for guys from the future. Insert this monkey-patching code before in front of your code:\nfrom openpyxl.styles.colors import WHITE, RGB\n\n__old_rgb_set__ = RGB.__set__\n\n\ndef _...
[ 2, 1, 0 ]
[]
[]
[ "excel", "openpyxl", "python", "python_3.x" ]
stackoverflow_0071733414_excel_openpyxl_python_python_3.x.txt
Q: How to extract the characters that simultaneously exist in multiple columns and print the matched row in the new pd? I have a file with multiple columns. I want to extract the characters that simultaneously exist in from1 and to1 columns, and print the corresponding matched rows in a new pd. Here is my data. class...
How to extract the characters that simultaneously exist in multiple columns and print the matched row in the new pd?
I have a file with multiple columns. I want to extract the characters that simultaneously exist in from1 and to1 columns, and print the corresponding matched rows in a new pd. Here is my data. classes = [('2.7.2.3', 'a primary alcohol','pyruvate'), ('2.7.1.3', 'a secondary alcohol','acetoacetyl-CoA'), ...
[ "It is a stupid code but useful, hoping anyone could give more simple method.\nfrom1 = alls['from1'].tolist()\nto1 = alls['to1'].tolist()\ncon_exist1 = [x for x in from1 if x in to1]\ncon_exist2 = [y for y in to1 if y in from1]\ncon_exist = con_exist1 + con_exist2\ntargets = '|'.join(con_exist)\n#targets\n\nll1 = a...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074122779_pandas_python.txt
Q: Random Number in Python from a Specific Set I want to generate random ints from 4 specific numbers (1,2,5,10). I only want the output to be one of these. How? A: You can use the choice method: random.choice([1, 2, 5 ,10]) Hope this helps A: You can use random.choice like so: import random nums = [1, 2, 5, 10...
Random Number in Python from a Specific Set
I want to generate random ints from 4 specific numbers (1,2,5,10). I only want the output to be one of these. How?
[ "You can use the choice method:\nrandom.choice([1, 2, 5 ,10])\n\nHope this helps\n", "You can use random.choice like so:\nimport random\n\nnums = [1, 2, 5, 10]\nprint(random.choice(nums)) # prints either 1, 2, 5, or 10\n\nYou can view more at the documentation: https://docs.python.org/3/library/random.html#random...
[ 1, 1 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0074127059_list_python_random.txt
Q: Converting YBR_RCT Photometric Interpretation to RGB I have a J2k Lossless dicom image and upon reading it with pydicom I see that it's in the YBR_RCT Color Space. I want to convert the Color Space to RGB. I tried using the convert_color_space method from pydicom however, apparently this conversion is not implemen...
Converting YBR_RCT Photometric Interpretation to RGB
I have a J2k Lossless dicom image and upon reading it with pydicom I see that it's in the YBR_RCT Color Space. I want to convert the Color Space to RGB. I tried using the convert_color_space method from pydicom however, apparently this conversion is not implemented. In their documentation they mention this link as refe...
[ "It's difficult to tell without a dataset to play with, but given RCT is intended to be losslessly reversible, the following should be sufficient (no clipping needed):\nfrom pydicom import dcmread\nimport numpy as np\n\nds = dcmread(\"path/to/file\")\narr = ds.pixel_array\n\nrgb = np.empty(arr.shape, dtype=arr.dtyp...
[ 2, 1, 0, 0 ]
[]
[]
[ "medical_imaging", "pydicom", "python", "simpleitk" ]
stackoverflow_0066504131_medical_imaging_pydicom_python_simpleitk.txt
Q: Read HDF5 File Created With h5py Using Pandas I have a bunch of hdf5 files, and I want to turn some of the data in them into parquet files. I'm struggling to read them into pandas/pyarrow though. Which I think is related to the way that the files were originally created. If I open the file using h5py the data look...
Read HDF5 File Created With h5py Using Pandas
I have a bunch of hdf5 files, and I want to turn some of the data in them into parquet files. I'm struggling to read them into pandas/pyarrow though. Which I think is related to the way that the files were originally created. If I open the file using h5py the data looks exactly how I would expect. import h5py file_pat...
[ "I had a similar problem with not being able to read hdf5 into pandas df. With this post I made a script that turns the hdf5 into a dictionary and then the dictionary into a pandas df, like this:\nimport h5py\nimport pandas as pd\n\n\ndictionary = {}\nwith h5py.File(filename, \"r\") as f:\n for key in f.keys():\...
[ 0 ]
[]
[]
[ "h5py", "hdfstore", "pandas", "python" ]
stackoverflow_0071388502_h5py_hdfstore_pandas_python.txt
Q: Moving states inside a tensor (QuTip) I have a qutip tensor as follows: psi = constants*tensor(fock(N,0),fock(N,1),fock(N,2)) I need a way to swap the positions of the third state with the second state such that the structure becomes: psi = (some operation on psi) psi = constants*tensor(fock(N,0),fock(N,2),fock(N...
Moving states inside a tensor (QuTip)
I have a qutip tensor as follows: psi = constants*tensor(fock(N,0),fock(N,1),fock(N,2)) I need a way to swap the positions of the third state with the second state such that the structure becomes: psi = (some operation on psi) psi = constants*tensor(fock(N,0),fock(N,2),fock(N,1)) I need it to maintain the ket nature ...
[ "You can use the permute() method\nN = 10\npsi = tensor(fock(N, 0), fock(N, 1), fock(N, 2))\ngoal_psi = tensor(fock(N, 0), fock(N, 2), fock(N, 1))\nnew_psi = psi.permute([0, 2, 1])\nisequal(new_psi, goal_psi)\n\n" ]
[ 0 ]
[]
[]
[ "python", "qutip" ]
stackoverflow_0072750858_python_qutip.txt
Q: How do I make my selenium code download the file in a particular location? I am working with the following selenium code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from sel...
How do I make my selenium code download the file in a particular location?
I am working with the following selenium code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options=Options() opti...
[ "df1.to_excel('output1.xlsx', engine='xlsxwriter') \n\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_chromedriver" ]
stackoverflow_0071966352_python_python_3.x_selenium_selenium_chromedriver.txt
Q: Define a function to a dataframe Consider this code in Python filter_2020 = hdb_million[hdb_million["year"]==2020] town_2020 = filter_2020["town"].unique() results_2020 = len(town_2020) print(town_2020) print("in 2020 the number of towns are:", results_2020) print("\n") filter_2021 = hdb_million[hdb_million["year...
Define a function to a dataframe
Consider this code in Python filter_2020 = hdb_million[hdb_million["year"]==2020] town_2020 = filter_2020["town"].unique() results_2020 = len(town_2020) print(town_2020) print("in 2020 the number of towns are:", results_2020) print("\n") filter_2021 = hdb_million[hdb_million["year"]==2021] town_2021 = filter_2021["tow...
[ "You can iterate through a loop,\nfor year in [2020, 2021, 2022]:\n filter_year = hdb_million[hdb_million[\"year\"]== year]\n town = filter_year[\"town\"].unique()\n results = len(town)\n print(town)\n print(f\"in {year} the number of towns are:\", results)\n print(\"\\n\")\n\n", "If you just wa...
[ 3, 0 ]
[]
[]
[ "dataframe", "function", "python" ]
stackoverflow_0074127048_dataframe_function_python.txt
Q: How to use mathematics formula to generate DataFrame? I am calculating a housing loan table. Basically I had variables like: total_loan_amount = 1000000 downpayment = 100000 period_payment = 420 interest_rate = 0.05 I want to generate a dataframe like this and export it to excel: Years Principal Interest Balance...
How to use mathematics formula to generate DataFrame?
I am calculating a housing loan table. Basically I had variables like: total_loan_amount = 1000000 downpayment = 100000 period_payment = 420 interest_rate = 0.05 I want to generate a dataframe like this and export it to excel: Years Principal Interest Balance 1 5711.68 19014.59 444288.32 2 11670.90 37781.66 ...
[ "you can use \"apply\" to apply functions and make new columns:\ndef add_values(a,b):\n return a+b\n\ndf[\"new_colum\"]=df[lambda x: add_function(x.a,x.b), axis=1]\n\nso you basically put all your math into functions and call them to create new columns.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074127125_dataframe_matplotlib_pandas_python_seaborn.txt
Q: Linking / callbacks not working in Holoviz / Panel dashboards Linking doesn't appear to be working. I create a dashboard or linked widget (code samples below) and I change a value in a drop down and nothing appears to happen. I'm expecting the "linked code" to be called but instead, nothing appears to happen at al...
Linking / callbacks not working in Holoviz / Panel dashboards
Linking doesn't appear to be working. I create a dashboard or linked widget (code samples below) and I change a value in a drop down and nothing appears to happen. I'm expecting the "linked code" to be called but instead, nothing appears to happen at all. Print statements do not show and output in the UI does not chang...
[ "I figured it out. I wasn't calling:\n\npn.extension()\n\n\n" ]
[ 0 ]
[]
[]
[ "holoviz", "holoviz_panel", "python" ]
stackoverflow_0074115792_holoviz_holoviz_panel_python.txt
Q: Most efficient way to iterate over list of objects This is a list of object: obj_list = [obj1, obj2, obj3, obj4, ... ,objn] Object look like this: def __init__(self, number): self.number = number What is the most efficient way to compare obj.number to all the objects in a list? What I`ve tried: for i in range(...
Most efficient way to iterate over list of objects
This is a list of object: obj_list = [obj1, obj2, obj3, obj4, ... ,objn] Object look like this: def __init__(self, number): self.number = number What is the most efficient way to compare obj.number to all the objects in a list? What I`ve tried: for i in range(0, len(obj_list)): temp = obj_list[i] count = i + 1 ...
[ "If youre comparing class items, I'd recommend writing your own dunder methods for the less-than (<, lt) and greater-than, etc. methods. Here is an example of how you can use the python builtin sorted() method on a list of custom Number classes:\nclass Number():\n def __init__(self, number) -> None:\n sel...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074054147_python.txt
Q: How do I return all strings containing a "£" in them? I'm trying to web scrape a site that is badly designed and I am trying to gather the prices of items. The only thing in common with each page is that the prices all start with a "£" so I thought that if I searched through all the HTML content and returned all s...
How do I return all strings containing a "£" in them?
I'm trying to web scrape a site that is badly designed and I am trying to gather the prices of items. The only thing in common with each page is that the prices all start with a "£" so I thought that if I searched through all the HTML content and returned all strings with "£" attached it would work. I am not quite sure...
[ "If you just want to pull out the prices with '£' prefix then can try something like this.\nimport re\n\nhtml = \"\"\"\ncost of living is £2,232\nbottle of milk costs £1 and it goes up to £1.05 a year later...\n\"\"\"\n\nprint(re.findall(r\"£\\S+\", html))\n\nOutput:\n['£2,232', '£1', '£1.05']\n\nIf you want to ext...
[ 1 ]
[]
[]
[ "full_text_search", "python", "web_scraping" ]
stackoverflow_0074127164_full_text_search_python_web_scraping.txt
Q: Django Transactions ATOMIC_REQUESTS I'm really unclear how atomic requests are set in Django. When ATOMIC_REQUESTS is set to True in the DB settings does that mean that all views now run in a transaction? What if I want only certain views to be run in a transaction? Do I then need to explicitly define all the othe...
Django Transactions ATOMIC_REQUESTS
I'm really unclear how atomic requests are set in Django. When ATOMIC_REQUESTS is set to True in the DB settings does that mean that all views now run in a transaction? What if I want only certain views to be run in a transaction? Do I then need to explicitly define all the others that are not run in a transaction with...
[ "When ATOMIC_REQUESTS is set to True in the DB settings does that mean that all views now run in a transaction?\nYes. From the docs:\n\nBefore calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django...
[ 10, 0 ]
[]
[]
[ "django", "django_views", "python", "python_3.x", "transactions" ]
stackoverflow_0031734306_django_django_views_python_python_3.x_transactions.txt
Q: How to randomly generate and test if an integer is unique on a list and repeat if it is not I am trying to make a program to learn binary. It would work as follows: the program asks me to convert from decimal to binary between 0 and 15, once this conversion is done the decimal digit is removed and must not reappea...
How to randomly generate and test if an integer is unique on a list and repeat if it is not
I am trying to make a program to learn binary. It would work as follows: the program asks me to convert from decimal to binary between 0 and 15, once this conversion is done the decimal digit is removed and must not reappear in one of the next questions. Thus, the 16 digits will be asked one and only one time in the di...
[ "The problem stems from the fact that you are appending strings to binaire_deja_fait and asking if it contains integer.\nYou can fix it by changing existe to:\ndef existe(liste, n):\n if str(n) in liste:\n return 1\n else:\n return 0\n\nI absolutely hate the existance of the existe function, tho...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074126976_list_python.txt
Q: How to Conditionally Format Excel Rows With Text Phrases Using xlswriter Module The script below works as intended by highlighting the Excel Rows that contain keyword1 as red. import xlsxwriter workbook = xlsxwriter.Workbook('conditional_format.xlsx') worksheet1 = workbook.add_worksheet() # Keyword keyword1 = 'r...
How to Conditionally Format Excel Rows With Text Phrases Using xlswriter Module
The script below works as intended by highlighting the Excel Rows that contain keyword1 as red. import xlsxwriter workbook = xlsxwriter.Workbook('conditional_format.xlsx') worksheet1 = workbook.add_worksheet() # Keyword keyword1 = 'red' keyword2 = 'yellow' # Add a format. Light red fill with dark red text. red_colou...
[ "I'm not sure you can do this with a text condition, but you should be able to do this with a formula condition, like this:\nformula = '=AND(ISNUMBER(SEARCH(\"red\",B1)),ISNUMBER(SEARCH(\"yellow\",B1)))'\nworksheet1.conditional_format('$B$1:$B$4', {'type': 'formula',\n 'cr...
[ 0 ]
[]
[]
[ "excel", "python", "python_3.x", "xlsxwriter" ]
stackoverflow_0074125778_excel_python_python_3.x_xlsxwriter.txt
Q: How do I parse json to run git commands from python? My git repo is not getting checked out, I am new to python and I don't know why My input arguments are in json and I need to read them and to checkout my git repo Can someone help get what I am doing wrong? class GitCheckout: def parse_json(self, text): ...
How do I parse json to run git commands from python?
My git repo is not getting checked out, I am new to python and I don't know why My input arguments are in json and I need to read them and to checkout my git repo Can someone help get what I am doing wrong? class GitCheckout: def parse_json(self, text): self.json_dict = json.loads(text) self.extract...
[ "Your indentation is incorrect, your main() function isn't defined properly, and you aren't actually calling your main() function. Indentation should be like so (note the last two blocks are outdented):\nclass GitCheckout:\n def parse_json(self, text):\n self.json_dict = json.loads(text)\n self.ext...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074127256_python.txt
Q: Different Python version in jupyter When I run !python -V, in jupyterlab I have Python 3.8.13 When I run !py -V, also in jupyter I have this time Python 3.10.7 When I run python -V and py -V in Powershell I have Python 3.10.7 When I run import sys print(sys.executable) print(sys.version) print(sys.version_info) I...
Different Python version in jupyter
When I run !python -V, in jupyterlab I have Python 3.8.13 When I run !py -V, also in jupyter I have this time Python 3.10.7 When I run python -V and py -V in Powershell I have Python 3.10.7 When I run import sys print(sys.executable) print(sys.version) print(sys.version_info) I have 3.10.7 (tags/v3.10.7:6cc6b13, Sep ...
[ "JupyterLab is launched from your Conda environment that has Python 3.8.13 installed in it. This is the actual Python version you are running in jupyterlab, and the same version is shown when you type !python -V.\nYou also have a separate non-Conda Python 3.10.7 installation on your system. The py command is instal...
[ 2, 1 ]
[]
[]
[ "jupyter", "jupyter_lab", "jupyter_notebook", "python", "python_3.x" ]
stackoverflow_0074124899_jupyter_jupyter_lab_jupyter_notebook_python_python_3.x.txt
Q: How to merge two csv files based on a column value? have two csv files. One with 200 bridges with names of people assigned to them and other data. the second has 800 bridges with the lat/long and other data. I am trying to merge the two csv files in order to get lat/long for the 200 bridges. I am using pandas merg...
How to merge two csv files based on a column value?
have two csv files. One with 200 bridges with names of people assigned to them and other data. the second has 800 bridges with the lat/long and other data. I am trying to merge the two csv files in order to get lat/long for the 200 bridges. I am using pandas merge but doesn't matter what "how=" I use it just merges the...
[ "Columns names seems to be mismatching. check\ndisplay(wb1.columns, wb2.columns) \n\nand compare the names\nnames are in quotes, so whitespaces will show up\n" ]
[ 0 ]
[]
[]
[ "csv", "merge", "pandas", "python" ]
stackoverflow_0074127255_csv_merge_pandas_python.txt
Q: Adding row values to a group by result I have a dataframe that looks something like this: df = pd.DataFrame([1,'A','X','1/2/22 12:00:00AM','1/1/22 12:00:00 AM'], [1,'A','X','1/1/22 1:00:00AM','1/1/22 12:00:00 AM'], [1,'A','Y','1/3/22 12:00:00AM','1/2/22 12:00:00 AM'], [1,'B','X','1/1/22 1:00:00AM','1/1/22 12:00:00...
Adding row values to a group by result
I have a dataframe that looks something like this: df = pd.DataFrame([1,'A','X','1/2/22 12:00:00AM','1/1/22 12:00:00 AM'], [1,'A','X','1/1/22 1:00:00AM','1/1/22 12:00:00 AM'], [1,'A','Y','1/3/22 12:00:00AM','1/2/22 12:00:00 AM'], [1,'B','X','1/1/22 1:00:00AM','1/1/22 12:00:00 AM'], [2,'A','X','1/2/22 12:00:00AM','1/1/2...
[ "Process used:\n\nFirst convert the dates into appropriate format to allow subtraction\nRemove the duplicates, and keep only the first date.\nWith duplicates removed, now calculate the differences\nNeeded to re-order, rename and format the columns to match the expected output\n\nimport pandas as pd\n\ncols = ['ID',...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074126488_dataframe_group_by_pandas_python.txt
Q: How do I replace the matching end of a string in Python? I am learning how to apply string operations in Python, How would I go about replacing the last occurrence of a substring? Question/Code given to debug: The replace_ending function replaces the old string in a sentence with the new string, but only if the se...
How do I replace the matching end of a string in Python?
I am learning how to apply string operations in Python, How would I go about replacing the last occurrence of a substring? Question/Code given to debug: The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occ...
[ "Using .index(old) is wrong since it will match the first occurrence of the word. Checking with .endswith(old) is more than enough. After that, since you already know that the strings ends with old, you can just discard len(old) characters from the end of the string.\ndef replace_ending(sentence, old, new):\n if...
[ 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0061550001_python_python_3.x.txt
Q: Rearranging list based on order of another list I am sure this question has possibly been asked before but I can't seem to find the correct answer. If I have two lists _list1 = ["keyName", "test1", "test2"] _list2 = ["keyName", "test2", "test1"] I am trying to use _list1 to rearrange elements in _list2 so that th...
Rearranging list based on order of another list
I am sure this question has possibly been asked before but I can't seem to find the correct answer. If I have two lists _list1 = ["keyName", "test1", "test2"] _list2 = ["keyName", "test2", "test1"] I am trying to use _list1 to rearrange elements in _list2 so that they match the order exactly. What's the cleanest way t...
[ "try to use key with sorted:\nsorted(_list2,key=_list1.index)\n\nfor nested list you can use list comphresnion:\n[sorted(x,key=_lis1.index) for x in _list2]\n\n", "In [84]: _list1 = [\"keyName\", \"test1\", \"test2\"]\n\nIn [85]: d = {k:v for v,k in enumerate(_list1)}\n\nIn [86]: _list2 = [\"keyName\", \"test2\",...
[ 13, 7, 1 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0027725703_list_python_sorting.txt
Q: How to change the background color using tkinter.Label I'm trying to build GUI program and want to know who to change the label background color? import tkinter as tk window = Tk() timer_label = Label(text="Timer", fg=GREEN, font=(FONT_NAME, 50, "normal")) timer_label.pack() root.mainloop() A: To change the b...
How to change the background color using tkinter.Label
I'm trying to build GUI program and want to know who to change the label background color? import tkinter as tk window = Tk() timer_label = Label(text="Timer", fg=GREEN, font=(FONT_NAME, 50, "normal")) timer_label.pack() root.mainloop()
[ "To change the background you can use the \"bg\" for expmle:\ntimer_label = Label(text=\"Timer\", fg=GREEN, bg=\"red\" font=(FONT_NAME, 50, \"normal\"))\n\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074127378_python_tkinter.txt
Q: py.test skips test class if constructor is defined I have following unittest code running via py.test. Mere presence of the constructor make the entire class skip when running py.test -v -s collected 0 items / 1 skipped Can anyone please explain to me this behaviour of py.test? I am interested in understanding py....
py.test skips test class if constructor is defined
I have following unittest code running via py.test. Mere presence of the constructor make the entire class skip when running py.test -v -s collected 0 items / 1 skipped Can anyone please explain to me this behaviour of py.test? I am interested in understanding py.test behaviour, I know the constructor is not needed. Th...
[ "The documentation for py.test says that py.test implements the following standard test discovery:\n\ncollection starts from the initial command line arguments which may be directories, filenames or test ids. \nrecurse into directories, unless they match norecursedirs\ntest_*.py or *_test.py files, imported by thei...
[ 71, 56, 0, 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0021430900_pytest_python.txt
Q: how do we typecast a large C structure from a DLL to a Python ctypes.Structure I've got a pointer to an XML document structure generated through libxml2. How do I cast it to my Python class xmlDoc(ctypes.Structure):? Here's my Python code: # libxml2 is a software library for parsing XML documents. ''' This lib is...
how do we typecast a large C structure from a DLL to a Python ctypes.Structure
I've got a pointer to an XML document structure generated through libxml2. How do I cast it to my Python class xmlDoc(ctypes.Structure):? Here's my Python code: # libxml2 is a software library for parsing XML documents. ''' This lib is used instead of the standard Python XML lib because it's using the regular libxml2 ...
[ "As your comment says, the first parameter to the prototype is the return value. Instead of the incorrect c_uint32 which will truncate the returned pointer if on a 64-bit OS use POINTER(xmlDoc) and you won’t have to cast.\nI would also use .argtypes and .restype instead of the more complicated prototype and params ...
[ 1 ]
[]
[]
[ "ctypes", "libxml2", "python" ]
stackoverflow_0074117123_ctypes_libxml2_python.txt
Q: How to reverse a filter class in Python/Django? I needed to filter models instances with custom function, and using Post.objects.filter(func) didnt help, I got a type error cause "object is not iterable, so I went with def filter_posts(x): if x.author in followed_author_list: return True ...
How to reverse a filter class in Python/Django?
I needed to filter models instances with custom function, and using Post.objects.filter(func) didnt help, I got a type error cause "object is not iterable, so I went with def filter_posts(x): if x.author in followed_author_list: return True else: return False posts = filte...
[ "def users_by_active(active: bool):\n users = User.objects.all()\n ids = [user.id for user in users if user.is_active == active]\n return users.filter(id__in=ids)\n\nyou can make something similar to this function\nbest of luck\n", "So, I listened to your comments and started looking how to make query to...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074124775_django_python.txt
Q: Python Check if at least 1 item in a 2d list is None Consider some 2d lists: a = [[1,2,3,4], [5,6,7,None]] b = [[1,2,3,4], [5,6,7,8]] How to check if there is at least one None in a 2d list? Outputs: deal with a should output a bool value False, and b should output True. I have no ideas when the list b...
Python Check if at least 1 item in a 2d list is None
Consider some 2d lists: a = [[1,2,3,4], [5,6,7,None]] b = [[1,2,3,4], [5,6,7,8]] How to check if there is at least one None in a 2d list? Outputs: deal with a should output a bool value False, and b should output True. I have no ideas when the list be a 2d list.
[ "You can use two loops, one inside the other.\ndef at_least_one_none(array):\n for row in array:\n for item in row:\n if item == None:\n return True\n return False\n\nThis can be simplified by using None in row rather than the inner loop.\ndef at_least_one_none(array):\n fo...
[ 2, 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074127474_python_python_3.x.txt
Q: How do I improve this for loop in python, maybe numpy arrays? This code works but is too slow, any ideas for improvement would be appreciated. Numpy arrays?, other? Estatus=Vigentes[['UUID','Estatus']] MOV_10 = MOV_09.copy() MOV_10['Estatus'] = "" for i in range(0, len(MOV_10[['UUID']])): u = MOV_10.loc[i][0] ...
How do I improve this for loop in python, maybe numpy arrays?
This code works but is too slow, any ideas for improvement would be appreciated. Numpy arrays?, other? Estatus=Vigentes[['UUID','Estatus']] MOV_10 = MOV_09.copy() MOV_10['Estatus'] = "" for i in range(0, len(MOV_10[['UUID']])): u = MOV_10.loc[i][0] w = MOV_10.loc[i][1] tempu = Estatus.loc[Estatus['UUID'] ==...
[ "You should be able to do much better than your existing method. I assume your existing data structure is a pandas dataframe. If so, it's very straightforward swap to use vector operations for a lot of the calculations. This approach should also scale much better than your approach.\nuuid_index = Estatus.set_index(...
[ 1 ]
[]
[]
[ "for_loop", "loops", "performance", "python" ]
stackoverflow_0074089347_for_loop_loops_performance_python.txt
Q: Web driver "get" method error, when receives the url from the property of class instance or dictionary I want to organize my urls for the testing project, so I tried to create a separate class or dictionary to store urls, but whenever I tried to call a "driver.get(pages.url)" method I get an error. Although if you...
Web driver "get" method error, when receives the url from the property of class instance or dictionary
I want to organize my urls for the testing project, so I tried to create a separate class or dictionary to store urls, but whenever I tried to call a "driver.get(pages.url)" method I get an error. Although if you pass the url from a variable or a string directly, everything works. I can't understand where is the proble...
[ "Print your url before passing it to driver.get to make sure its valid.\nAs some of the comments suggest try adding http/https.\n", "\nI think you are missing https:// in the URL\n\nThis is the correct answer. Thanks Sighil, and others.\n" ]
[ 0, 0 ]
[]
[]
[ "get", "python", "selenium", "url" ]
stackoverflow_0074121450_get_python_selenium_url.txt
Q: How to calculate 10^pandas series? I am trying to get a new series by calculating 10 to the power of an existing series. I have tried pandas.Series.rpow and numpy.power, but they all show strange results. Here is my code: data = pd.read_csv('Book1.csv', sep=',', header=None, encoding='utf-8') iexp = data.iloc[:, 9...
How to calculate 10^pandas series?
I am trying to get a new series by calculating 10 to the power of an existing series. I have tried pandas.Series.rpow and numpy.power, but they all show strange results. Here is my code: data = pd.read_csv('Book1.csv', sep=',', header=None, encoding='utf-8') iexp = data.iloc[:, 9] s = pd.Series(10, index=iexp.index) pr...
[ "As @BigBen suggested, int64 is the problem here. You need to change it to a proper dtype:\ndf = df.astype(\"float\")\n\nConsider the following example:\ndf = pd.DataFrame({'A': [10,20,30,34],\n 'B': [10,10,10,10]})\ndf\n\noutput:\n\nThe columns have int64 dtypes:\ndf.dtypes\n\noutput:\n\nSomethin...
[ 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074127325_pandas_python.txt
Q: ModuleNotFoundError: No module named 'huggingface_hub.utils' using Anaconda I'm trying to execute the example code of the huggingface website: from transformers import GPTJTokenizer, TFGPTJModel import tensorflow as tf tokenizer = GPTJTokenizer.from_pretrained("EleutherAI/gpt-j-6B") model = TFGPTJModel.from_pretr...
ModuleNotFoundError: No module named 'huggingface_hub.utils' using Anaconda
I'm trying to execute the example code of the huggingface website: from transformers import GPTJTokenizer, TFGPTJModel import tensorflow as tf tokenizer = GPTJTokenizer.from_pretrained("EleutherAI/gpt-j-6B") model = TFGPTJModel.from_pretrained("EleutherAI/gpt-j-6B") inputs = tokenizer("Hello, my dog is cute", return_...
[ "I had the same problem. In my case, it was related to the fact that work with libssl library was messed up in a newer version of a hugging face. Downgrading a little bit resolved the issue for me.\nThis would downgrade tokenizers to 0.10.3 and transformers to a last version that suitable for the tokenizers.\nconda...
[ 3, 2 ]
[]
[]
[ "anaconda", "huggingface", "modulenotfounderror", "python" ]
stackoverflow_0073960201_anaconda_huggingface_modulenotfounderror_python.txt
Q: connecting to sharepoint with python - Invalid URI: The Authority/Host could not be parsed.', "500 Server Error: Internal Server Error for url errors I'm trying to connect to company sharepoint and use one of the example codes i found in this topic: Accessing Microsoft Sharepoint files and data using Python the ...
connecting to sharepoint with python - Invalid URI: The Authority/Host could not be parsed.', "500 Server Error: Internal Server Error for url errors
I'm trying to connect to company sharepoint and use one of the example codes i found in this topic: Accessing Microsoft Sharepoint files and data using Python the first lines of the code worked, I got "Authenticated into sharepoint as:********" after I used this and it worked also ####Function for extracting the file...
[ "You can try a virtual printer driver that has a bidirectional integration to SharePoint. Here is a link to the download https://www.microsoft.com/store/apps/9NZL8MWS3MLG and here is a quick video https://vimeo.com/manage/videos/515880976\n" ]
[ 0 ]
[]
[]
[ "python", "sharepoint" ]
stackoverflow_0073909154_python_sharepoint.txt
Q: How to get only the index in numpy.where instead of a tuple I have an array of strings arr in which I want to search for elements and get the index of element. Numpy has a method where to search element and return index in a tuple form. arr = numpy.array(["string1","string2","string3"]) print(numpy.where(arr == "s...
How to get only the index in numpy.where instead of a tuple
I have an array of strings arr in which I want to search for elements and get the index of element. Numpy has a method where to search element and return index in a tuple form. arr = numpy.array(["string1","string2","string3"]) print(numpy.where(arr == "string1") It prints: (array([0], dtype=int64),) But I only want ...
[ "TL;DR\nUse:\ntry:\n i = numpy.where(arr == \"string1\")[0][0]\nexcept IndexError:\n # handle the case where \"string1\" was not found in arr\n\nor\nindices = list(numpy.where(arr == \"string1\")[0])\n\nDetails\nFinding elements in NumPy arrays is not intuitive the first time you try to do it.\nLet's decompos...
[ 3 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074126454_arrays_numpy_python.txt
Q: Getting a Total for a value in a csv file row that is a text I am trying to get the total number of Mondays in my cvs file. My current code will return all the Mondays, but I need it to return 1972. I am at a loss. I was trying it is searchcursor, but that was a nightmare. I am new to programming python so I am l...
Getting a Total for a value in a csv file row that is a text
I am trying to get the total number of Mondays in my cvs file. My current code will return all the Mondays, but I need it to return 1972. I am at a loss. I was trying it is searchcursor, but that was a nightmare. I am new to programming python so I am look for your individual wisdoms. Thank you for your time code is b...
[ "An example, not tested as I was not going to hand transcribe the data from the image.\nimport csv\n\nwith open(r\"C:\\users\\david\\OneDrive\\Documents\\ArcGIS\\Projects\\MyProject1\\Burglaries_TableToExcel.csv\", 'r') as monday:\n mon_ct = 0\n cvs_dict = csv.DictReader(monday)\n for row in csv_dict:\n ...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074100004_csv_python.txt
Q: How to solve TypeError: sequence item 1: expected str instance, float found I am new to Python and trying to solve the following. I have an excel sheet with phone-numbers in different formats. I would like to change them to only one format. +31612345678 These are the formats I see in the sheet: Below is the code....
How to solve TypeError: sequence item 1: expected str instance, float found
I am new to Python and trying to solve the following. I have an excel sheet with phone-numbers in different formats. I would like to change them to only one format. +31612345678 These are the formats I see in the sheet: Below is the code. import pandas as pd import re telephonesheet = 'telefoon-nummers.xlsx' df_tele...
[ "It's because your '+' pattern in the regular expression is not optional and you didn't specified patterns for '(', ')', and '-'(after 31).\nDo like this.\n...\n .str.extract('^(?:\\(?(?P<plus>\\+)?(?P<prefix>31)\\)?-?)?0?(?P<number>\\d)?-?(?P<numbers>\\d+)')\n .fillna({'plus': '+', 'prefix': '31'})\n...
[ 0 ]
[]
[]
[ "pandas", "python", "regex" ]
stackoverflow_0074124239_pandas_python_regex.txt
Q: binding Label in tkinter while function runs I have a code where by clicking button, function runs. But inside function there are two labels that I want them to appear with text inside labels while python runs from top to bottom inside function. As it displays in cmd if they were print() statements, whenever curso...
binding Label in tkinter while function runs
I have a code where by clicking button, function runs. But inside function there are two labels that I want them to appear with text inside labels while python runs from top to bottom inside function. As it displays in cmd if they were print() statements, whenever cursor reads, and display the message. But in tkinter i...
[ "Normally every GUI updates window after running user's function - to make less redrawings and not \"blink\" on every redraw.\nIf you have long-running code then you may need to use root.update() after every widget to force tkinter to redraw it at once (before end of function.)\n\nMinimal working code.\nI uses time...
[ 1 ]
[]
[]
[ "python", "tkinter", "tkinter_button", "tkinter_text" ]
stackoverflow_0074126339_python_tkinter_tkinter_button_tkinter_text.txt
Q: How to do multiprocessing for my specific for loop? I have two lists list1 = [3,4,5,6,7,8] and list2 = [8,9,10,12,14,16,18,20]. I have written this for loop: list3 = [] for i in list1: for j in list2: if (i+j)%2 == 0: list3.append([i,j]) break How could i rewrite it with multipr...
How to do multiprocessing for my specific for loop?
I have two lists list1 = [3,4,5,6,7,8] and list2 = [8,9,10,12,14,16,18,20]. I have written this for loop: list3 = [] for i in list1: for j in list2: if (i+j)%2 == 0: list3.append([i,j]) break How could i rewrite it with multiprocessing? I see that there is multiprocessing.Pool functi...
[ "I can't think of a way to do this using pandas but here's a more efficient way using itertools.product in a comprehension:\nfrom itertools import product\n\nlist1 = [3,4,5,6,7,8]\nlist2 = [8,9,10,12,14,16,18,20]\nprev = None\n\nlist3 = [[prev := i, j] for i, j in product(list1, list2) if not (i + j) % 2 and i != p...
[ 0 ]
[]
[]
[ "dataframe", "loops", "multiprocessing", "python", "python_3.x" ]
stackoverflow_0074127246_dataframe_loops_multiprocessing_python_python_3.x.txt
Q: Rearranging a pandas dataframe accordino to a citation network EDITED: Let's make the story as simple as possible. I am working in pandas. My data are nodes (docdb_id) that cite other nodes (cited_patents). In this case, the distance of a node in ddocdb_id is min(Dist_cited_patents)+1. Nodes at distance 0 are cons...
Rearranging a pandas dataframe accordino to a citation network
EDITED: Let's make the story as simple as possible. I am working in pandas. My data are nodes (docdb_id) that cite other nodes (cited_patents). In this case, the distance of a node in ddocdb_id is min(Dist_cited_patents)+1. Nodes at distance 0 are considered those having Fields!="". I would like to construct a variable...
[ "This can be seen as a graph problem, you can solve it with networkx:\n# identify terminal nodes (leafs)\nm = df['Fields'].eq('')\nleafs = set(df.loc[~m, 'docdb'])\n# {2, 4}\n\n# generate exploded version of DataFrame to be able to construct the graph\ndf2 = df.explode(['cited_patents', 'dist_cited_patents'])\n\n# ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074127008_dataframe_pandas_python.txt
Q: "View Page Source" via command line I would like to download the content that I get from the "view page source" e.g. in Chromium or Firefox in some automated way (python or bash..). wget, curl or alike... I do not get the right data from the website downloaded if i e.g. use: curl https://www.google.com/search?foo...
"View Page Source" via command line
I would like to download the content that I get from the "view page source" e.g. in Chromium or Firefox in some automated way (python or bash..). wget, curl or alike... I do not get the right data from the website downloaded if i e.g. use: curl https://www.google.com/search?foo&baa Chromium too seems to have a proble...
[ "you can for example make file:\ntouch gnu_source\nand then curl link and append it to gnu_souce:\ncurl https://www.gnu.org/ >> gnu_source\n", "The solution is crazy simple... use quotation marks!\ncurl \"https://www.google.com/search?foo&baa\"\n\ninstead of\ncurl https://www.google.com/search?foo&baa\n\nMany web...
[ 0, 0 ]
[]
[]
[ "command_line", "linux", "python" ]
stackoverflow_0074094834_command_line_linux_python.txt
Q: Remove substring in array of strings column in dataframe I have dataframe column which is array of strings ```` | fruits | |--------------------------------| |['fruit=apple', 'fruit=banana'] | |['fruit=orange', 'fruit=banana']| |['fruit=apple', 'fruit=orange'] | |['fruit=orange', 'fruit=ora...
Remove substring in array of strings column in dataframe
I have dataframe column which is array of strings ```` | fruits | |--------------------------------| |['fruit=apple', 'fruit=banana'] | |['fruit=orange', 'fruit=banana']| |['fruit=apple', 'fruit=orange'] | |['fruit=orange', 'fruit=orange']| ```` I want to get result like `` | fruits ...
[ "You can apply a function to the column. In this case split each string by = and take the last element of the result.\ndf['fruits'].apply(lambda x: [f.split('=')[-1] for f in x])\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "dataframe", "python", "string", "substring" ]
stackoverflow_0074127799_arrays_dataframe_python_string_substring.txt
Q: Why list([]) weighs less than [] I have such code: from sys import getsizeof as sizer test_list = [i for i in range(10)] test_list2 = list([i for i in range(10)]) test_list3 = [] for i in range(10): test_list3.append(i) print(f"""{sizer(test_list)} bytes: {test_list} {sizer(test_list2)} bytes: {test_list2} {...
Why list([]) weighs less than []
I have such code: from sys import getsizeof as sizer test_list = [i for i in range(10)] test_list2 = list([i for i in range(10)]) test_list3 = [] for i in range(10): test_list3.append(i) print(f"""{sizer(test_list)} bytes: {test_list} {sizer(test_list2)} bytes: {test_list2} {sizer(test_list3)} bytes: {test_list3}...
[ "lists in Python do not have fixed size. They expand and contract as items are added and removed. In order for that to happen, the list sometimes needs to be moved to a different place in memory. As copying on each added/removed element would slow down the operations by a lot, Python can allocate some spare space f...
[ 3, 1 ]
[]
[]
[ "generator", "list", "memory", "python" ]
stackoverflow_0074127373_generator_list_memory_python.txt
Q: Peak finding algorithm using Scipy/python i have the random data in which i plotted graph for finding the peaks which is originated from zero i used this code op_col = [] for i in df['Speed ']: op_col.append(i) print(op_col) converting 'Speed' values to 1d array using for loop [0, 7, 18, 24, 26, 27, 26, 25, 26, 1...
Peak finding algorithm using Scipy/python
i have the random data in which i plotted graph for finding the peaks which is originated from zero i used this code op_col = [] for i in df['Speed ']: op_col.append(i) print(op_col) converting 'Speed' values to 1d array using for loop [0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27, 22, 26, 27, 26, 25, ...
[ "Given the constraints you supplied (i.e. the first peak after every zero), this should find the peaks of interest. Please note that if there are negative numbers, this will no longer behave as desired. Adjust as needed for special cases like that.\n*Edit: I have added the updated request of only finding peaks abov...
[ 1 ]
[ "Maybe u can modify like this:\nx = [0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27, 22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11, 12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22, 27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20...
[ -1 ]
[ "numpy", "python", "scipy" ]
stackoverflow_0074125508_numpy_python_scipy.txt
Q: Apache Beam Pipeline runs with DirectRunner, but fails with DataflowRunner (SDK harness sdk-0-0 disconnected) during initial read step TL;DR We have a default VPC. Tried to run dataflow job. Initial step (Read file) manages to process 1/2 steps. Get JOB_MESSAGE_ERROR: SDK harness sdk-0-0 disconnected error message...
Apache Beam Pipeline runs with DirectRunner, but fails with DataflowRunner (SDK harness sdk-0-0 disconnected) during initial read step
TL;DR We have a default VPC. Tried to run dataflow job. Initial step (Read file) manages to process 1/2 steps. Get JOB_MESSAGE_ERROR: SDK harness sdk-0-0 disconnected error message, but nothing else in the logs. Have tried setup roles and vpc firewall rules. Problem I want to run a Dataflow job using the Geobeam image ...
[ "After some trial and error, I found that the python version of the geobeam base image has to match the local python version on your machine, or else it won't work. At time of answering, this is python 3.8.\n", "\nThere is the runner that instantiates the job : your local virtual env\nIn the execution phase, the ...
[ 3, 0 ]
[]
[]
[ "apache_beam", "geojson", "google_cloud_dataflow", "google_vpc", "python" ]
stackoverflow_0074111801_apache_beam_geojson_google_cloud_dataflow_google_vpc_python.txt
Q: fixing an error on a web images downloader python script I've tried to build a function to download multiple images from this web page https://www.stocksy.com/service/contributors/ with name replacement of each name but I've got errors I tried to change 'href' to 'data-profile' here is the full code : import req...
fixing an error on a web images downloader python script
I've tried to build a function to download multiple images from this web page https://www.stocksy.com/service/contributors/ with name replacement of each name but I've got errors I tried to change 'href' to 'data-profile' here is the full code : import requests from bs4 import BeautifulSoup import os #url = 'https:/...
[ "First, make sure you didn't get captcha page (try to set User-Agent HTTP header). Then, use correct CSS selector:\nimport requests\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:105.0) Gecko/20100101 Firefox/105.0\"\n}\n\n\ndef imagedown(url, folder)...
[ 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074127481_beautifulsoup_python.txt
Q: Can you create a python generator to provide values over a range in a random order without repetition? I am unsure if this is one of those problems that is impossible or not, in my mind it seems like it should be possible. Edit - We more or less agree it is impossible Given a range specified by two integers (i.e. ...
Can you create a python generator to provide values over a range in a random order without repetition?
I am unsure if this is one of those problems that is impossible or not, in my mind it seems like it should be possible. Edit - We more or less agree it is impossible Given a range specified by two integers (i.e. n1 ... n2), is it possible to create a python generator that yields a random integer from the range WITHOUT ...
[ "How can we shuffle something?\nThe Idea:\n\ngenerate pairs (random integer, the stuff you want shuffled)\nsort those pairs by the random integer part\noutput the list of second parts\n\nunsorted = [(random(), x) for x in range(n1,n2) ]\nsorted = sort(unsorted, key = lambda x : x[0])\nresult = [p[1] for p in sorte...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0074127611_python.txt
Q: Take a string and return a new string with each characters and their occurence How would you create a Python function that takes a string and returns a new string that contains the characters of the given string once each (without repetitions), in the same order, and with their number of repetitions. For example, ...
Take a string and return a new string with each characters and their occurence
How would you create a Python function that takes a string and returns a new string that contains the characters of the given string once each (without repetitions), in the same order, and with their number of repetitions. For example, if the given string is "aaaabbbbccddde", the result would be "a4b4c2d3e1".
[ "Try itertools.groupby:\nfrom itertools import groupby\n\ns = \"aaaabbbbccddde\"\n\nout = \"\".join(f\"{v}{sum(1 for _ in g)}\" for v, g in groupby(s))\nprint(out)\n\nPrints:\na4b4c2d3e1\n\n", "You can iterate through the set and append the count along with it. So, there might be a chance of changing the order of...
[ 1, 0 ]
[ "One class in the Python standard library is the Counter class (from collections import Counter). This counts the occurrences of any character into a dict-like. For your use case, it can be used like this:\nfrom collections import Counter\n\nstring = \"aaaabbbbccddde\"\ncounter = Counter(string)\n\nnew_string = “”\...
[ -1 ]
[ "python", "string" ]
stackoverflow_0074127365_python_string.txt
Q: How to add line break in pdf generated using pdfkit.from_string()? I try to generate a pdf file from a string using pdfkit. However, in the result all new line characters \n are ignored. Thus, I get a pdf with a string printed as a single sentence. For example: import pdfkit s = "Some text\n" s += "Ok, let's add s...
How to add line break in pdf generated using pdfkit.from_string()?
I try to generate a pdf file from a string using pdfkit. However, in the result all new line characters \n are ignored. Thus, I get a pdf with a string printed as a single sentence. For example: import pdfkit s = "Some text\n" s += "Ok, let's add something more\n" s += "And more..." pdfkit.from_string(s,"file.pdf",{'en...
[]
[]
[ "you can replace the '\\n' with a moveDown() operation in javascript so far.\nlet doc = new PDFDocument({ size: \"A4\", margin: 50 });\ndoc.text(\"Some text\")\n .moveDown()\n .text(\"Ok, let's add something more\")\n .moveDown()\n .text(\"And more...\");\n\ndoc.end();\nconst path = \"/Users/user1234/Docume...
[ -1 ]
[ "pdf", "pdfkit", "python" ]
stackoverflow_0062173624_pdf_pdfkit_python.txt
Q: Python search for string in whole pandas dataframe and make that first column So I have a irregular dataframe with unnamed columns which looks something like this: Unnamed:0 Unnamed:1 Unnamed:2 Unnamed:3 Unnamed:4 nan nan nan 2022-01-01 nan nan nan nan nan nan nan ...
Python search for string in whole pandas dataframe and make that first column
So I have a irregular dataframe with unnamed columns which looks something like this: Unnamed:0 Unnamed:1 Unnamed:2 Unnamed:3 Unnamed:4 nan nan nan 2022-01-01 nan nan nan nan nan nan nan nan String Name Currency nan nan nan nan ...
[ "In your example you can drop the columns that are entirely null, then drop rows with any null values. The result is the slice you are looking for. You can then promote the first row to headers.\ndf = df.dropna(axis=1,how='all').dropna().reset_index(drop=True)\ndf = df.rename(columns=df.iloc[0]).drop(df.index[0])...
[ 1, 0 ]
[]
[]
[ "apply", "dataframe", "pandas", "python" ]
stackoverflow_0074127794_apply_dataframe_pandas_python.txt
Q: Django Dataframe not able to convert timestamp to date Django Data frame not able to convert timestamp to date in template view Query result of Select * from paper_trade where date = now()::date order by open_time is Date day open_time 2022-10-19 Wednesday 10:54 My code is as below sql_query_n = pd.re...
Django Dataframe not able to convert timestamp to date
Django Data frame not able to convert timestamp to date in template view Query result of Select * from paper_trade where date = now()::date order by open_time is Date day open_time 2022-10-19 Wednesday 10:54 My code is as below sql_query_n = pd.read_sql_query("""Select * from paper_trade where date = now()...
[ "You need to convert the column manually;\nExample (from my own codebase):\ndf = pd.DataFrame.from_records(data=analytics)\nif df.empty:\n return Response([])\n\ndf = df[df.columns.drop(list(df.filter(regex='Unnamed')))]\ndate_range = pd.date_range(\n **get_min_max_date_range_from_dataframe(\n ...
[ 0 ]
[]
[]
[ "dataframe", "django", "pandas", "python" ]
stackoverflow_0074126197_dataframe_django_pandas_python.txt
Q: Run parts of a ipython notebook in a loop / with different input parameter I have written a ipython notebook, which analyses a dataset. Now I want to use this code to loop over different datasets. The code is split into about 50 cells (including comments, markdown explanations,...). Is there a way to run parts of...
Run parts of a ipython notebook in a loop / with different input parameter
I have written a ipython notebook, which analyses a dataset. Now I want to use this code to loop over different datasets. The code is split into about 50 cells (including comments, markdown explanations,...). Is there a way to run parts of a notebook in a loop or running a whole notebook with different input parameter...
[ "What I usually do in these scenarios is wrap the important cells as functions (you don't have to merge any of them) and have a certain master cell that iterates over a list of parameters and calls these functions. E.g. this is what a \"master cell\" looks like in one of my notebooks:\nimport itertools\n# parameter...
[ 36, 6, 6, 2, 1 ]
[]
[]
[ "ipython", "jupyter", "jupyter_lab", "jupyter_notebook", "python" ]
stackoverflow_0015635341_ipython_jupyter_jupyter_lab_jupyter_notebook_python.txt
Q: How do I retrieve the datemodtime of each file based on filename in python? My current process involves looping through my source directory and adding the name of each file to my dataframe in python. I want to get the datemodified for each of these files as well import datetime import os import pandas as pd #set s...
How do I retrieve the datemodtime of each file based on filename in python?
My current process involves looping through my source directory and adding the name of each file to my dataframe in python. I want to get the datemodified for each of these files as well import datetime import os import pandas as pd #set src directory os.chdir('C:/Users/jj/Desktop/do/Claims/globmove') def read_files(f...
[ "Here's how I do it.\nimport os\nfrom pathlib import Path\n\nimport pandas as pd\nimport pendulum\n\n\nclass FileDates:\n def __init__(self, **kwargs):\n self.file_type = kwargs.get(\"file_type\")\n self.file_path = kwargs.get(\"file_path\")\n self.path = kwargs.get(\"path\")\n self.t...
[ 1, 0 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074114175_datetime_pandas_python.txt
Q: Python equivalent of object?.method() basicInfo = { "details": basicSoup.select_one('.basics-description .basics-text').getText(), "dose": basicSoup.select_one('.basics-description .basics-dose').getText(), "price": basicSoup.select_one('.basics-description .basics-price').getText(), "chemistr...
Python equivalent of object?.method()
basicInfo = { "details": basicSoup.select_one('.basics-description .basics-text').getText(), "dose": basicSoup.select_one('.basics-description .basics-dose').getText(), "price": basicSoup.select_one('.basics-description .basics-price').getText(), "chemistry": basicSoup.select_one('.basics-descripti...
[ "This is verbose compared to object? but you can use getattr() where the third parameter indicates the default value to be returned if the attribute doesn't exist. Since you're about to call it, this should be a function that does nothing. Here you have it written as a lambda:\ngetattr(obj, \"method\", lambda: None...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074127828_python.txt
Q: set axes containing % automatically with plotly I wrote a code that returns a scatter chart, but when I use plot I can't set axis properly, instead of have a lower and upper well-defined, they don't have a pattern when inputted in the chart. How could i set this to occur automatically, because my data come from a ...
set axes containing % automatically with plotly
I wrote a code that returns a scatter chart, but when I use plot I can't set axis properly, instead of have a lower and upper well-defined, they don't have a pattern when inputted in the chart. How could i set this to occur automatically, because my data come from a callback in dash plotly. my_dict = {'A': {67: '4.50%...
[ "I suggest the following:\n\nRemove the % from all cells in the dataframe to be ready for the next step.\nConvert all columns to float instead of string.\nCustomize automatically the ranges based on the min and max values of each column.\nAdd the % to the axes to be consistent with the format of the data in the dat...
[ 0 ]
[]
[]
[ "graph", "plotly", "plotly_dash", "python" ]
stackoverflow_0074117109_graph_plotly_plotly_dash_python.txt
Q: Python 3.10 multiprocessing hangs (only sometimes) after poisoning I've got the following toy script: #!/usr/bin/env python3 import multiprocessing as mp def main(): queue = mp.Queue() stop = mp.Event() workers = [] n = mp.cpu_count() print(f"starting {n} processes") for i in range(n): ...
Python 3.10 multiprocessing hangs (only sometimes) after poisoning
I've got the following toy script: #!/usr/bin/env python3 import multiprocessing as mp def main(): queue = mp.Queue() stop = mp.Event() workers = [] n = mp.cpu_count() print(f"starting {n} processes") for i in range(n): p = mp.Process(target=work, args=(i, queue, stop)) workers...
[ "It looks like there are two possible deadlocks. First, the docs mention this issue:\n\nWarning As mentioned above, if a child process has put items on a queue (and it has not used JoinableQueue.cancel_join_thread), then that process will not terminate until all buffered items have been flushed to the pipe.\nThis ...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "poison_queue", "python", "queue" ]
stackoverflow_0074105679_multiprocessing_poison_queue_python_queue.txt
Q: for message in messages: TypeError: 'Messages' object is not iterable Am having issues with looping through an object here is my code from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messag...
for message in messages: TypeError: 'Messages' object is not iterable
Am having issues with looping through an object here is my code from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messages User = get_user_model() class ChatConsumer(WebsocketConsumer): de...
[ "I believe the problem is here.\n def new_messages(self, data):\n sender = data['from']\n author_user = User.objects.filter(username=sender)[0] \n message = Messages.objects.create(sender=author_user, msg=data['message'])\n content = {\n 'command': 'new_messages',\n ...
[ 3 ]
[]
[]
[ "django", "django_channels", "object", "python" ]
stackoverflow_0074127977_django_django_channels_object_python.txt
Q: CMD opens Windows Store when I type 'python' Today when I tried to run simple code on Sublime Text 3, the following message appeared: Python was not found but can be installed from the Microsoft Store: https://go.microsoft.com/fwlink?linkID=2082640 And when I type Python in CMD, it opens the Windows Store for me...
CMD opens Windows Store when I type 'python'
Today when I tried to run simple code on Sublime Text 3, the following message appeared: Python was not found but can be installed from the Microsoft Store: https://go.microsoft.com/fwlink?linkID=2082640 And when I type Python in CMD, it opens the Windows Store for me to download Python 3.7. This problem started toda...
[ "Use the Windows search bar to find \"Manage app execution aliases\". There should be two aliases for Python. Unselect them, and this will allow the usual Python aliases \"python\" and \"python3\". See the image below.\n\nI think we have this problem when installing Python because in a new Windows installation the ...
[ 513, 25, 23, 20, 7, 3, 3, 2, 1, 1, 1 ]
[ "Adding a bit to the question. Even when I typed pip freeze, it wasn't showing anything.\nHere's what I did:\nThere were multiple instances for the Python application in /AppData/Local/Microsoft/WindowApps.\nI deleted those and then it worked.\n" ]
[ -4 ]
[ "python", "sublimetext3", "windows_10" ]
stackoverflow_0058754860_python_sublimetext3_windows_10.txt
Q: Reading vcf file data using python and re library Here is content inside .vcf file data. BEGIN:VCARD VERSION:4.0 N:Muller;CCCIsabella;;; FN:Muller ORG:Bubba Gump Shrimp Co. TITLE:Shrimp Man PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif TEL;TYPE=work,voice;VALUE=uri:tel:+16829185770 REV:2...
Reading vcf file data using python and re library
Here is content inside .vcf file data. BEGIN:VCARD VERSION:4.0 N:Muller;CCCIsabella;;; FN:Muller ORG:Bubba Gump Shrimp Co. TITLE:Shrimp Man PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif TEL;TYPE=work,voice;VALUE=uri:tel:+16829185770 REV:20080424T195243Z END:VCARD BEGIN:VCARD VERSION:4.0 N:Mr...
[ "You can try the below code. \nimport re\nfile = open('vcards-2.vcf', 'r')\ncontacts = []\nphone = []\nfor line in file:\n name = re.findall('FN:(.*)', line)\n nm = ''.join(name)\n if len(nm) == 0:\n continue\n\n data = {'name' : nm.strip()}\n for lin in file:\n tel = re.findall('pref:...
[ 1, 1, 0 ]
[]
[]
[ "python", "vcf_vcard" ]
stackoverflow_0054551712_python_vcf_vcard.txt
Q: PySide6 - how do I call objects with dynamically generated string names? I would like to to generate the "X" in self.X method with concatenating strings. Obviously, self.text method called below doesn't work. self.myLineEdit_1= QLineEdit(self) var = 1 text = "myLineEdit_" + str(var) self.text.setText(...
PySide6 - how do I call objects with dynamically generated string names?
I would like to to generate the "X" in self.X method with concatenating strings. Obviously, self.text method called below doesn't work. self.myLineEdit_1= QLineEdit(self) var = 1 text = "myLineEdit_" + str(var) self.text.setText("text here") I tried to use the self.findChild method as a work around, but t...
[ "Assuming that you have many QLineEdit() objects:\nself.myLineEdit_1 = QLineEdit(self)\nself.myLineEdit_2 = QLineEdit(self)\nself.myLineEdit_3 = QLineEdit(self)\n...\n\nthen you want them in a collection:\nself.lines = [None, self.myLineEdit_1, self.myLineEdit_2, self.myLineEdit_3, ...]\n\nNow you can index them:\n...
[ 1 ]
[]
[]
[ "pyside6", "python", "qt" ]
stackoverflow_0074127903_pyside6_python_qt.txt
Q: Does it exist a word2vec model in french? Is there a pre-trained word2vec model in french language ? The must would be to get it with an api that let me finetune it easily. I was thinking of gensim but can't find such a model in french language. A: You could try one of Facebook's published pre-trained FastText m...
Does it exist a word2vec model in french?
Is there a pre-trained word2vec model in french language ? The must would be to get it with an api that let me finetune it easily. I was thinking of gensim but can't find such a model in french language.
[ "You could try one of Facebook's published pre-trained FastText models: https://fasttext.cc/docs/en/crawl-vectors.html\nTheir text versions, with just whole-word vectors, can be loaded as read-only KeyedVectors instances in Gensim. Their full binary models can be loaded as a FastText model that (technically) suppor...
[ 0, 0 ]
[]
[]
[ "python", "word2vec" ]
stackoverflow_0072620805_python_word2vec.txt
Q: How to make different session/proxy with each request? I want to make something like round-robin(each request different proxy/session) implementation. So, I have code example in Golang: // Round Robin algorithm implementation func RoundRobin(proxies ...string) func(*http.Request) (*url.URL, error) { var urls [...
How to make different session/proxy with each request?
I want to make something like round-robin(each request different proxy/session) implementation. So, I have code example in Golang: // Round Robin algorithm implementation func RoundRobin(proxies ...string) func(*http.Request) (*url.URL, error) { var urls []*url.URL for _, proxy := range proxies { u, err...
[ "Maybe it will be useful for someone\nimport concurrent.futures\nimport random\nimport requests\n\nfrom itertools import cycle\nfrom time import sleep\n\n\ndef do_requests(proxi, url):\n print(url, proxi)\n r = requests.get(\n url,\n proxies=dict(http=proxi),\n )\n print(r.text)\n\n\ndef r...
[ 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0074110824_algorithm_python.txt
Q: Infinite loop while adding two integers using bitwise operations? I am trying to solve a problem, using python code, which requires me to add two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers: def getSum(self, a, b): while (a & b): ...
Infinite loop while adding two integers using bitwise operations?
I am trying to solve a problem, using python code, which requires me to add two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers: def getSum(self, a, b): while (a & b): x = a & b y = a ^ b a = x << 1 b = y ...
[ "Python 3 has arbitrary-precision integers (\"bignums\"). This means that anytime x is negative, x << 1 will make x a negative number with twice the magnitude. Zeros shifting in from the right will just push the number larger and larger. \nIn two's complement, positive numbers have a 0 in the highest bit and neg...
[ 9, 0 ]
[ "I'm guessing that this is a homework question, so I don't want to just give you a function that works --- you'll learn more by struggling with it.\nThe issue stems from the way that negative integers are stored. For illustration purposes, let's pretend that you're dealing with 4-bit signed integers (instead of 32-...
[ -2 ]
[ "bit_manipulation", "bitwise_operators", "python", "python_3.x" ]
stackoverflow_0039113479_bit_manipulation_bitwise_operators_python_python_3.x.txt
Q: Create dataframe with specific slices out of existing dataframe, based on date variabels I have the following dataframe (df) with a column 'date' and 'values'. I am looking for a solution how to create a new dataframe from the variables start_MM_DD and end_MM_DD (month and day). For each year a column with the cor...
Create dataframe with specific slices out of existing dataframe, based on date variabels
I have the following dataframe (df) with a column 'date' and 'values'. I am looking for a solution how to create a new dataframe from the variables start_MM_DD and end_MM_DD (month and day). For each year a column with the corresponding values should be created. the data frame "df" can start earlier or data can be miss...
[ "This is just a pivot table that has been filtered by dates:\nimport pandas as pd\nimport numpy as np\n\n\ndf = pd.DataFrame({'date':pd.date_range(start='2020-01-03', end='2022-01-10')})\ndf['randNumCol'] = np.random.randint(1, 6, df.shape[0])\n\ndf = (\n df.loc[(df['date'].dt.month.eq(1)) & (df['date'].dt.day.b...
[ 0, 0 ]
[]
[]
[ "columnsorting", "dataframe", "date", "pandas", "python" ]
stackoverflow_0074128033_columnsorting_dataframe_date_pandas_python.txt
Q: How to read string as dataframe separating by comma but with irregular quotation marks? This is a small example of a big csv file. Imagine this csv file contais a text like this one below: import io import pandas as pd text="""A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P "2019,01/2019,Brazil,0,""166,229"",0,""22578,86292"",""...
How to read string as dataframe separating by comma but with irregular quotation marks?
This is a small example of a big csv file. Imagine this csv file contais a text like this one below: import io import pandas as pd text="""A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P "2019,01/2019,Brazil,0,""166,229"",0,""22578,86292"",""47,417"",,,,,,,," "2019,01/2019,Brazil,95,0,""50,34563"",0,""5,137"",,,,,,,," 2019,01/2019,Br...
[ "First I would check how the CSV file is generated and fix the root cause (why are there the quotation marks?) If this isn't possible, try to remove all quotation marks:\ntext = \"\"\"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P\n\"2019,01/2019,Brazil,0,\"\"166,229\"\",0,\"\"22578,86292\"\",\"\"47,417\"\",,,,,,,,\"\n\"2019,01/2...
[ 1 ]
[]
[]
[ "csv", "pandas", "python", "string" ]
stackoverflow_0074127998_csv_pandas_python_string.txt
Q: Web Scraping from dynamic real time website I´ve been hardly trying to scrape the following data from this page: https://lambda-app-eia.herokuapp.com/ I need to scrape the numbers selected: in the following image. Im trying to create a list so that i can treat them as data types , and make some calculations. i´ve ...
Web Scraping from dynamic real time website
I´ve been hardly trying to scrape the following data from this page: https://lambda-app-eia.herokuapp.com/ I need to scrape the numbers selected: in the following image. Im trying to create a list so that i can treat them as data types , and make some calculations. i´ve been told bs4 does not read dynamic websites, so ...
[ "You have to get the text of the element not the href, like below, also add some wait time:\ntime.sleep(2)\nelements = driver.find_elements(By.CSS_SELECTOR, \".MuiTypography-root.MuiTypography-h4.css-2voflx\")\n\njob_list = []\nfor job in elements:\n job_list.append(job.text)\nprint(job_list)\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074127412_beautifulsoup_python_selenium_selenium_webdriver_web_scraping.txt
Q: Can I make a Python if condition using Regex on Pandas column to see if it contains something and then create a new column to hold it Say I have data like this Account 1 Kevin (1234567) 2 Buzz (7896345) 3 Snakes (5438761) 4 Marv 5 Harry (9083213) I want to use an if condition to search to see if the account...
Can I make a Python if condition using Regex on Pandas column to see if it contains something and then create a new column to hold it
Say I have data like this Account 1 Kevin (1234567) 2 Buzz (7896345) 3 Snakes (5438761) 4 Marv 5 Harry (9083213) I want to use an if condition to search to see if the account number exists at the end of the name in the account column, if it does split the account number off and put it in a new colu...
[ "here is one way to do it\n# split the account on ( and create two columns\ndf[['Account','Account Number']]= df['Account'].str.split('(', expand=True)\n\n#replace the trailing ) with empty string\ndf['Account Number']=df['Account Number'].str.replace(r'\\)','', regex=True ).str.strip()\ndf\ndfdf\n\n Account...
[ 1, 1 ]
[]
[]
[ "pandas", "python", "regex" ]
stackoverflow_0074128196_pandas_python_regex.txt
Q: make public the object created by tcp socket i am making a GUI application, the problem that i had is that i dont know how to access the object created by .accept(), i had seen a lot of tutorials but all of them do like console application, so i need to create in some how the socket object, i open the connection w...
make public the object created by tcp socket
i am making a GUI application, the problem that i had is that i dont know how to access the object created by .accept(), i had seen a lot of tutorials but all of them do like console application, so i need to create in some how the socket object, i open the connection with a push button and other process send the data ...
[ "i solved this by my self, it was more simple than i thougt i just needed to delcare two globals objects and done\nclass MainWindow:\n conn=socket.AF_INET\n addr=socket.SOCK_STREAM\n\n" ]
[ 0 ]
[]
[]
[ "python", "tcp" ]
stackoverflow_0074047451_python_tcp.txt
Q: Python simple lazy loading I'm trying to clean up some logic and remove duplicate values in some code and am looking for a way to introduce some very simple lazy-loading to handle settings variables. Something that would work like this: FOO = {'foo': 1} BAR = {'test': FOO['foo'] } # ...complex logic here which ul...
Python simple lazy loading
I'm trying to clean up some logic and remove duplicate values in some code and am looking for a way to introduce some very simple lazy-loading to handle settings variables. Something that would work like this: FOO = {'foo': 1} BAR = {'test': FOO['foo'] } # ...complex logic here which ultimately updates the value of Fo...
[ "As I stated in the comment above, what you are seeking is some of the facilities of reactive programming paradigm. (not to be confounded with the JavaScript library which borrows its name from there).\nIt is possible to instrument objects in Python to do so - I think the minimum setup here would be a specialized t...
[ 2, 1, 1 ]
[]
[]
[ "lazy_loading", "python", "python_3.x" ]
stackoverflow_0074127537_lazy_loading_python_python_3.x.txt
Q: MySQL load data infile using Python not working I am trying to upload a file using MySQL LOAD DATA LOCAL INFILE function in Python. In my load.py file, I have done: import MySQLdb conn = MySQLdb.connect(host, db_username, db_password, "Core_ver") c = conn.cursor() sql = """LOAD DATA LOCAL INFILE 'contact.out' INTO...
MySQL load data infile using Python not working
I am trying to upload a file using MySQL LOAD DATA LOCAL INFILE function in Python. In my load.py file, I have done: import MySQLdb conn = MySQLdb.connect(host, db_username, db_password, "Core_ver") c = conn.cursor() sql = """LOAD DATA LOCAL INFILE 'contact.out' INTO TABLE userinfo FIELDS TERMINATED BY '\t' OPTIONALLY ...
[ "I had a foreign key constraint on the table Core_ver. But during performing LOAD DATA LOCAL INFILE function in python, I was not getting any errors, that's led to panic.\nAnyways, the script is working fine. Thank Guys for the help.\n", "I faced the same issue while working with mysql-connector-python. Adding th...
[ 0, 0 ]
[]
[]
[ "load_data_infile", "mysql", "python" ]
stackoverflow_0018024765_load_data_infile_mysql_python.txt
Q: open cv2 image isn't updating on cv2.putText I have a typical computer vision project in Python...counting people in a room, but one thing I notice is that when trying to plot in the frame people top left in the screenshot below the number is getting garbled some how. Its very "jumpy" as I am still finding a good ...
open cv2 image isn't updating on cv2.putText
I have a typical computer vision project in Python...counting people in a room, but one thing I notice is that when trying to plot in the frame people top left in the screenshot below the number is getting garbled some how. Its very "jumpy" as I am still finding a good model so I its like the number keeps updating but ...
[ "Per @stateMachine comment: https://towardsdatascience.com/shallow-deep-copies-stop-making-these-slicing-mistakes-12d02ffa2f7f\nI moved the cv2 code that isnt plotting properly to a new function, this part of the original function shown in the question:\nimage = insert_people_count(image,people)\nreturn image, peop...
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074128045_opencv_python.txt
Q: Python Request HTML for BeautifulSoup Parsing I have no idea it's working only when I right-click, copy the entire body as HTML into a file and parse it, but when I access it directly from the link via request, I get 0 results. Ex. Sample HTML bsoup.py When I use these codes from bs4 import BeautifulSoup with op...
Python Request HTML for BeautifulSoup Parsing
I have no idea it's working only when I right-click, copy the entire body as HTML into a file and parse it, but when I access it directly from the link via request, I get 0 results. Ex. Sample HTML bsoup.py When I use these codes from bs4 import BeautifulSoup with open("index.html") as fp: soup = BeautifulSoup(f...
[ "Try to html.unescape the response from the www.bulongheng.com:\nimport html\nimport requests\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Max-...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "python_requests", "python_requests_html" ]
stackoverflow_0074127640_beautifulsoup_python_python_3.x_python_requests_python_requests_html.txt
Q: Why does poetry install windows only dependency on macOS and linux? I have tried listing the following dependency in pyproject.toml to have this particular torch only be installed when on Windows platforms. torch = { url = "https://download.pytorch.org/whl/cpu/torch-1.7.0%2Bcpu-cp36-cp36m-win_amd64.whl", platform ...
Why does poetry install windows only dependency on macOS and linux?
I have tried listing the following dependency in pyproject.toml to have this particular torch only be installed when on Windows platforms. torch = { url = "https://download.pytorch.org/whl/cpu/torch-1.7.0%2Bcpu-cp36-cp36m-win_amd64.whl", platform = "windows"} torch = { url = "https://download.pytorch.org/whl/cpu/torch...
[ "This problem should be solved from version 1.2.0b3 as described in this ticket: https://github.com/python-poetry/poetry/issues/1616\n" ]
[ 0 ]
[]
[]
[ "python", "python_poetry", "pytorch", "torch" ]
stackoverflow_0069470989_python_python_poetry_pytorch_torch.txt
Q: Python Requests : How to send many post requests in the same time wait response the first and second _1 = requests.post(logUrl,data=userDayta, headers=logHead) i want send many post request like this in the same time A: Here are two methods that work: The reason that i posted both methods in full is that the exa...
Python Requests : How to send many post requests in the same time wait response the first and second
_1 = requests.post(logUrl,data=userDayta, headers=logHead) i want send many post request like this in the same time
[ "Here are two methods that work:\nThe reason that i posted both methods in full is that the examples given on the main website throw (RuntimeError: Event loop is closed) messages whereas both of these work.\nMethod 1: few lines of code, but longer run time (6.5 seconds):\nimport aiohttp\nimport asyncio\nimport tim...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074127490_python.txt
Q: Renaming a file in pyton using a variable hey all hope someone can help! Im using the below to find the most recent file downloaded in the specified directory. I need to be able to rename the file from how it comes to a specic name - any help would be appreciated. import glob import os download_path = f'C:\\Users\...
Renaming a file in pyton using a variable
hey all hope someone can help! Im using the below to find the most recent file downloaded in the specified directory. I need to be able to rename the file from how it comes to a specic name - any help would be appreciated. import glob import os download_path = f'C:\\Users\\{os.getlogin()}\\Downloads' list_of_files = gl...
[ "ext = latest_file.split('.')[-1]\nos.rename(latest_file, f\"{download_path}/new_file.{ext}\")\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074128346_python.txt
Q: How to update class attributes with load function I have a class in which the method save stores the created object to disk using the pickle package: def save( self, filepath, ): #CHECK ATTRIBUTE VALUES pickle_out = open(filepath+'.pickle', 'wb') pickle.dump(self, pickle_out) ...
How to update class attributes with load function
I have a class in which the method save stores the created object to disk using the pickle package: def save( self, filepath, ): #CHECK ATTRIBUTE VALUES pickle_out = open(filepath+'.pickle', 'wb') pickle.dump(self, pickle_out) pickle_out.close() Similarly, I want to add a load m...
[ "When not using a C extension or slots, class instance data is stored in a dictionary. You could unpickle the class and replace that dictionary.\nimport pickle\n\nclass Foo:\n\n def __init__(self, val):\n self.val = val\n\n def save(self, filepath):\n with open(filepath,'wb') as outfile:\n ...
[ 2 ]
[]
[]
[ "class", "object", "pickle", "python" ]
stackoverflow_0074128238_class_object_pickle_python.txt
Q: using datetime module to create pause-able timer getting weird results I'm trying to create a pause-able timer in Python. During my search I came across this answer. https://stackoverflow.com/a/60027719/11892518 I modified the code a little and added the timer in a while loop I also used the keyboard module for hu...
using datetime module to create pause-able timer getting weird results
I'm trying to create a pause-able timer in Python. During my search I came across this answer. https://stackoverflow.com/a/60027719/11892518 I modified the code a little and added the timer in a while loop I also used the keyboard module for human interaction while the loop is running: from datetime import datetime, ti...
[ "The way your keyboard loop works is that it calls the method multiple times while the key is pressed (evident from the multiple prints when you press g).\nWhen the timer is resumed, the pause time is subtracted. In your version, the block is disabled for only continuing if the timer is actually paused, so the paus...
[ 1 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0074124888_cpython_python.txt
Q: Display data based on user input in pandas Im quite new to python and my goal is to create a function that will ask the user to choose a department number and a year. All of the data is based on a csv file that I imported. Based on his answer I have to display him the results based on his two criteria. import pand...
Display data based on user input in pandas
Im quite new to python and my goal is to create a function that will ask the user to choose a department number and a year. All of the data is based on a csv file that I imported. Based on his answer I have to display him the results based on his two criteria. import pandas as pd df=pd.read_csv('liste_incendies_-du_12...
[ "Why not use if dep.lower() == \"all\": instead of if dep== \"All\" or dep== \"all\" or dep== \"ALL\":. Also for elif use elif dep.lower() != \"all\":\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074127884_pandas_python_python_3.x.txt
Q: How can I get the generic type of a parameterized generic used to annotate a dataclass property? I have a dataclass: import dataclasses @dataclasses.dataclass class Foo: first: dict[str, int] How can I determine that the generic type dict is the type expected with a str to int mapping? I want to be able to d...
How can I get the generic type of a parameterized generic used to annotate a dataclass property?
I have a dataclass: import dataclasses @dataclasses.dataclass class Foo: first: dict[str, int] How can I determine that the generic type dict is the type expected with a str to int mapping? I want to be able to do something like: for field in dataclasses.fields(Foo): if generic_type_of_field == dict: ...
[ "If you want to be able to tell the original generic type of a specified generic type, you can use typing.get_origin.\nThe problem is that it will return None, if you pass it a non-specified generic type. If you want to account for that, the simplest solution I can think of something along these lines:\nimport data...
[ 1 ]
[]
[]
[ "python", "python_typing" ]
stackoverflow_0074128466_python_python_typing.txt