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: ERROR: Could not install packages due to an OSError: [Errno 28] No space left on device I am facing an error to install the packages on aws ec2 instance with Ubuntu 18 using the following command - pip install -e . The error is - ERROR: Could not install packages due to an OSError: [Errno 28] No space left on devi...
ERROR: Could not install packages due to an OSError: [Errno 28] No space left on device
I am facing an error to install the packages on aws ec2 instance with Ubuntu 18 using the following command - pip install -e . The error is - ERROR: Could not install packages due to an OSError: [Errno 28] No space left on device What did I check? RAM using free -h command. Disk utilization using sudo ncdu -x command....
[ "The answer provided at https://github.com/pypa/pip/issues/5816#issuecomment-425410189, states that\n\npip downloads files to temporary directory, environment variable TMPDIR specifies that directory, also pip puts files into cache thus --cache-dir specification, --no-cache-dir should work too. --build specifies di...
[ 4 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0074515846_pip_python_python_3.x.txt
Q: How to access class object when I use torch.nn.DataParallel()? I want to train my model using PyTorch with multiple GPUs. I included the following line: model = torch.nn.DataParallel(model, device_ids=opt.gpu_ids) Then, I tried to access the optimizer that was defined in my model definition: G_opt = model.module....
How to access class object when I use torch.nn.DataParallel()?
I want to train my model using PyTorch with multiple GPUs. I included the following line: model = torch.nn.DataParallel(model, device_ids=opt.gpu_ids) Then, I tried to access the optimizer that was defined in my model definition: G_opt = model.module.optimizer_G However, I got an error: AttributeError: 'DataParallel...
[ "Use model.module , but sometime before running the model it doesn't work for some reason, use model.module.module at that time.\nBest of luck\n" ]
[ 0 ]
[]
[]
[ "multi_gpu", "python", "pytorch", "torch" ]
stackoverflow_0066607905_multi_gpu_python_pytorch_torch.txt
Q: Python Decimal - multiplication by zero Why does the following code: from decimal import Decimal result = Decimal('0') * Decimal('0.8881783462119193534061639577') print(result) return 0E-28 ? I've traced it to the following code in the module: if not self or not other: ans = _dec_from_triple(resultsign, '0', ...
Python Decimal - multiplication by zero
Why does the following code: from decimal import Decimal result = Decimal('0') * Decimal('0.8881783462119193534061639577') print(result) return 0E-28 ? I've traced it to the following code in the module: if not self or not other: ans = _dec_from_triple(resultsign, '0', resultexp) # Fixing in case the exponent ...
[ "Raymond Hettinger has given a comprehensive explanation at cpython github:\nIn Arithmetic Operations, the section on Arithmetic operations rules tells us:\n\nTrailing zeros are not removed after operations.\n\nThere are test cases covering multiplication by zero. Here are some from multiply.decTest:\n-- zeros, etc...
[ 1 ]
[]
[]
[ "arithmetic_expressions", "decimal", "python" ]
stackoverflow_0074500614_arithmetic_expressions_decimal_python.txt
Q: Tkinter window Completly freeze when you move it The window of Tkinter just completly freeze with all the widgets when I move the Tkinter window and that's my problem I tested it with another code and it always does the same thing Is the problem exclusively with tkinter? just move your tkinter window from left to ...
Tkinter window Completly freeze when you move it
The window of Tkinter just completly freeze with all the widgets when I move the Tkinter window and that's my problem I tested it with another code and it always does the same thing Is the problem exclusively with tkinter? just move your tkinter window from left to right you will see that absolutely all the program fre...
[ "I played a bit with your code and it seems that problem is with your while loops.\nEven though you used threads correctly, using while loops this way makes your program uses all the resources to loop into it. What I means is as you started program, even before you press label to show entry widgets, your loops just...
[ 1 ]
[]
[]
[ "freeze", "python", "tkinter" ]
stackoverflow_0074512081_freeze_python_tkinter.txt
Q: I want to replace special symbol to another text in python with pandas I want to change the characters at once, but it doesn't change when I use the special symbol like [ or ( or : or - . What should I do? my sample datatable is below df col1 0 ( red ) apple 1 [ 20220901 ] autumn 2 - gotohome 3 sample : sa...
I want to replace special symbol to another text in python with pandas
I want to change the characters at once, but it doesn't change when I use the special symbol like [ or ( or : or - . What should I do? my sample datatable is below df col1 0 ( red ) apple 1 [ 20220901 ] autumn 2 - gotohome 3 sample : salt bread and I want to get this below df col1 0 red apple 1 20220...
[ "You can maybe use something like:\nimport re\n\nbadchars = '()[]\\t-:'\ndf2 = (df['col1']\n .str.strip(badchars+' ') # strip unwanted chars at extremities\n .str.split(f'\\s*[{re.escape(badchars)}]+\\s*') # split on badchars + spaces\n .explode().to_frame() # explode as new rows\n )\n\n...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074515003_pandas_python.txt
Q: How to compare datetime.time objects I have a column in my Dataframe that contains datetime.time() values. example : --> df.loc[0,'tat'] output: datetime.time(0, 21, 4) I want to write multiple if conditions with this column. example: --> if df.loc[0,'tat'] < 2: df.loc[0,'SLA'] = 'less than 2 hour SLA' e...
How to compare datetime.time objects
I have a column in my Dataframe that contains datetime.time() values. example : --> df.loc[0,'tat'] output: datetime.time(0, 21, 4) I want to write multiple if conditions with this column. example: --> if df.loc[0,'tat'] < 2: df.loc[0,'SLA'] = 'less than 2 hour SLA' else: df.loc[0,'SLA'] = 'greater than ...
[ "You need compare hours with scalars, solution for new helper column hour with cut:\nhours = pd.to_datetime(df['tat'].astype(str)).dt.hour\n\nhours = df['tat'].apply(lambda x: x.hour)\n\ndf['SLA'] = pd.cut(hours, bins=[0,2,3,24], \n labels=['less than 2 hour SLA','2-4 hour SLA','greater than 4 hour...
[ 3, 0, 0 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074515699_datetime_pandas_python.txt
Q: Difference between del, remove, and pop on lists Is there any difference between these three methods to remove an element from a list? >>> a = [1, 2, 3] >>> a.remove(2) >>> a [1, 3] >>> a = [1, 2, 3] >>> del a[1] >>> a [1, 3] >>> a = [1, 2, 3] >>> a.pop(1) 2 >>> a [1, 3] A: The effects of the three different m...
Difference between del, remove, and pop on lists
Is there any difference between these three methods to remove an element from a list? >>> a = [1, 2, 3] >>> a.remove(2) >>> a [1, 3] >>> a = [1, 2, 3] >>> del a[1] >>> a [1, 3] >>> a = [1, 2, 3] >>> a.pop(1) 2 >>> a [1, 3]
[ "The effects of the three different methods to remove an element from a list:\nremove removes the first matching value, not a specific index:\n>>> a = [0, 2, 3, 2]\n>>> a.remove(2)\n>>> a\n[0, 3, 2]\n\ndel removes the item at a specific index:\n>>> a = [9, 8, 7, 6]\n>>> del a[1]\n>>> a\n[9, 7, 6]\n\nand pop removes...
[ 1640, 261, 122, 68, 29, 23, 3, 3, 2, 1, 0, 0, 0 ]
[ "You can also use remove to remove a value by index as well. \nn = [1, 3, 5]\n\nn.remove(n[1])\n\nn would then refer to [1, 5]\n" ]
[ -5 ]
[ "list", "python" ]
stackoverflow_0011520492_list_python.txt
Q: Prophet Forecasting My dataframe is in weekly level as below: sample was trying to implement prophet model using the below code. df.columns = ['ds', 'y'] # define the model model = Prophet(seasonality_mode='multiplicative') # fit the model model1=model.fit(df) model1.predict(10) I need to predict the output in a...
Prophet Forecasting
My dataframe is in weekly level as below: sample was trying to implement prophet model using the below code. df.columns = ['ds', 'y'] # define the model model = Prophet(seasonality_mode='multiplicative') # fit the model model1=model.fit(df) model1.predict(10) I need to predict the output in a weekly level for the nex...
[ "You need to use model.make_future_dataframe to create new dates:\nmodel = Prophet()\nmodel.fit(df)\n\nfuture = model.make_future_dataframe(periods=10, freq='W')\n\npredictions = model.predict(future)\n\npredictions will give predicted values for the whole dataframe, you can reach to the forecasted values for the n...
[ 1 ]
[]
[]
[ "pandas", "prophet", "python" ]
stackoverflow_0074515286_pandas_prophet_python.txt
Q: Send and receive objects through sockets in Python I have searched a lot on the Internet, but I haven't been able to find the solution to send an object over the socket and receive it as is. I know it needs pickling which I have already done. And that converts it to bytes and is received on the other hand. But how...
Send and receive objects through sockets in Python
I have searched a lot on the Internet, but I haven't been able to find the solution to send an object over the socket and receive it as is. I know it needs pickling which I have already done. And that converts it to bytes and is received on the other hand. But how can I convert those bytes to that type of object? proce...
[ "You're looking for pickle and the loads and dumps operations. Sockets are basically byte streams. Let us consider the case you have.\nclass ProcessData:\n process_id = 0\n project_id = 0\n task_id = 0\n start_time = 0\n end_time = 0\n user_id = 0\n weekend_id = 0\n\nAn instance of this class n...
[ 27, 0 ]
[ "An option is to use JSON serialization.\nHowever, Python objects are not serializable, so you have to map your class object into Dict first, using either function vars (preferred) or the built-in __dict__.\nAdapting the answer from Sudheesh Singanamalla and based on this answer:\nClient\nimport socket, json\n\ncla...
[ -1 ]
[ "marshalling", "python", "serialization", "sockets" ]
stackoverflow_0047391774_marshalling_python_serialization_sockets.txt
Q: Unable to save data from Django form I am trying to save data from a form into a database table named 'ModuleNames', but it is updating 'ModuleType' column of foreign(instance) table. I created an instance of said foreign table because it was giving a different error about assigning value to the foreign key colum...
Unable to save data from Django form
I am trying to save data from a form into a database table named 'ModuleNames', but it is updating 'ModuleType' column of foreign(instance) table. I created an instance of said foreign table because it was giving a different error about assigning value to the foreign key column and from various blogs I learned that th...
[ "I think the problem is here:\nform = ModuleForm(request.POST, instance=ModuleTypes.objects.get(ModuleType=moduletype)) # <-- here\n\nYou are passing ModuleTypes as instance where your should be passing ModuleNames model instance. So you should update the form like this:\nform = ModuleForm(request.POST, instance=M...
[ 0, 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0054166392_django_forms_python.txt
Q: merge two dataframes on common cell values of different columns I have two dataframes df1 = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) df2 = pd.DataFrame({'col3': [1,5,3]}) and would like to left merge df1 to df2. I don't have a fixed merge column in df1 though. I would like to merge on col1 if the cell val...
merge two dataframes on common cell values of different columns
I have two dataframes df1 = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) df2 = pd.DataFrame({'col3': [1,5,3]}) and would like to left merge df1 to df2. I don't have a fixed merge column in df1 though. I would like to merge on col1 if the cell value of col1 exists in df2.col3 and on col2 if the cell value of col2 e...
[ "Perform the merges in the preferred order, and use combine_first to combine the merges:\n(df1.merge(df2, left_on='col1', right_on='col3', how='left')\n .combine_first(df1.merge(df2, left_on='col2', right_on='col3', how='left')\n )\n)\n\nFor a generic method with many columns:\ncols = ['col1', '...
[ 0, 0 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074515932_dataframe_merge_pandas_python.txt
Q: (python) MNIST with local picture face img AttributeError: 'PngImageFile' object has no attribute 'reshape' environment: google colab, python goal: python mnist predict my own picture issue: AttributeError: 'PngImageFile' object has no attribute 'reshape' Update tried code, and output import keras from keras.datas...
(python) MNIST with local picture face img AttributeError: 'PngImageFile' object has no attribute 'reshape'
environment: google colab, python goal: python mnist predict my own picture issue: AttributeError: 'PngImageFile' object has no attribute 'reshape' Update tried code, and output import keras from keras.datasets import mnist import matplotlib.pyplot as plt import PIL from PIL import Image (train_images,train_labels),(te...
[ "The problem is not due to path. When you are reading an image (like Png) with PIL, the type in PngImageFile which does not have reshape method. The reshape is for the tensor class. convert the Image that you read into proper data format you expect then rehsape and give to your model\ntensor = tf.keras.utils.img_to...
[ 0 ]
[]
[]
[ "keras", "matplotlib", "mnist", "python", "typeerror" ]
stackoverflow_0074514954_keras_matplotlib_mnist_python_typeerror.txt
Q: iloc[] by value columns I want to use iloc with value in column. df1 = pd.DataFrame({'col1': ['1' ,'1','1','2','2','2','2','2','3' ,'3','3'], 'col2': ['A' ,'B','C','D','E','F','G','H','I' ,'J','K']}) I want to select index 2 in each column value as data frame and the result will be like col1 col2 ...
iloc[] by value columns
I want to use iloc with value in column. df1 = pd.DataFrame({'col1': ['1' ,'1','1','2','2','2','2','2','3' ,'3','3'], 'col2': ['A' ,'B','C','D','E','F','G','H','I' ,'J','K']}) I want to select index 2 in each column value as data frame and the result will be like col1 col2 1 C 2 F 3 K...
[ "Use GroupBy.nth:\ndf2 = df1.groupby('col1', as_index=False).nth(2)\n\nAlternative with GroupBy.cumcount:\ndf2 = df1[df1.groupby('col1').cumcount().eq(2)]\n\n\nprint (df2)\n col1 col2\n2 1 C\n5 2 F\n10 3 K\n\n", "Use GroupBy.nth with as_index=False:\ndf1.groupby('col1', as_index=False).nth(2...
[ 4, 3, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071392956_pandas_python.txt
Q: How to make a clear messages command in cog import discord from discord.ext import commands class Purge(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def clear(ctx, amount = 5): if amount == 0: await ctx.send("AMOUNT CANNOT BE 0!...
How to make a clear messages command in cog
import discord from discord.ext import commands class Purge(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def clear(ctx, amount = 5): if amount == 0: await ctx.send("AMOUNT CANNOT BE 0!") else: await ctx.channel.pu...
[ "async def setup(client):\n\n await client.add_cog(Purge(client))\n\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0068144114_discord.py_python.txt
Q: Calling Python 2 script from Python 3 I have two scripts, the main is in Python 3, and the second one is written in Python 2 (it also uses a Python 2 library). There is one method in the Python 2 script I want to call from the Python 3 script, but I don't know how to cross this bridge. A: Calling different pyt...
Calling Python 2 script from Python 3
I have two scripts, the main is in Python 3, and the second one is written in Python 2 (it also uses a Python 2 library). There is one method in the Python 2 script I want to call from the Python 3 script, but I don't know how to cross this bridge.
[ "Calling different python versions from each other can be done very elegantly using execnet. The following function does the charm:\nimport execnet\n\ndef call_python_version(Version, Module, Function, ArgumentList):\n gw = execnet.makegateway(\"popen//python=python%s\" % Version)\n channel = gw.remote_e...
[ 28, 18, 12, 3, 2, 1, 0, 0 ]
[ "I recommend to convert the Python2 files to Python3:\nhttps://pythonconverter.com/\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0027863832_python.txt
Q: Python - multiple *args inside a tuple (is it possible at all?) I am not sure if that is possible at all. I want when I create a tuple and iterate over it multiple *args to be created. For example: alabama_state="Alabama","Montgomery","Mobile","Tuscaloosa","Dothan","Huntsville","Birmingham","Madison","Auburn","Ph...
Python - multiple *args inside a tuple (is it possible at all?)
I am not sure if that is possible at all. I want when I create a tuple and iterate over it multiple *args to be created. For example: alabama_state="Alabama","Montgomery","Mobile","Tuscaloosa","Dothan","Huntsville","Birmingham","Madison","Auburn","Phenix City" state_name,capital,*metropolitan,*city=alabama_state print...
[ "itertools.islice may be an option, but it is not readable enough:\n>>> from itertools import islice\n>>> alabama_state = (\"Alabama\", \"Montgomery\", \"Mobile\", \"Tuscaloosa\", \"Dothan\",\n... \"Huntsville\", \"Birmingham\", \"Madison\", \"Auburn\", \"Phenix City\")\n>>> it = iter(alabama_state...
[ 1, 0 ]
[]
[]
[ "arguments", "iteration", "python", "tuples" ]
stackoverflow_0074515962_arguments_iteration_python_tuples.txt
Q: Select all c files except file name or path contains particular string I have a folder with many subfolders including zip files. I want to select .c files if the file path does not contain particular strings. For example, exclude file paths containing "abc", "myfiles", "new" exclude C:\Users\Downloads\All_h_files...
Select all c files except file name or path contains particular string
I have a folder with many subfolders including zip files. I want to select .c files if the file path does not contain particular strings. For example, exclude file paths containing "abc", "myfiles", "new" exclude C:\Users\Downloads\All_h_files\abcmln.c C:\Users\Downloads\All_h_files\myfilesos\mlo.c C:\Users\Downloads\...
[ "change this sentence:\nif \"new\" or \"myfiles\" or \"abc\" not in source:\n\nto\nif not all([item not in source for item in [\"new\", \"myfiles\", \"abc\"]]):\n\nfurthermore you could use the glob package to list the files. like glob.glob(os.path.join(what_ever_pth, '*.c')) to list file with *.c extension.\nand ...
[ 0 ]
[]
[]
[ "glob", "python", "shutil" ]
stackoverflow_0074515562_glob_python_shutil.txt
Q: User input shape size, then calculate using class in python Hi I'm a beginner and this is the details to code. Create a parent class called shape. This should have following methods inputSides() – Ask user to enter the sides of the shape. Now create subclasses for a circle, rectangle and triangle. These should inc...
User input shape size, then calculate using class in python
Hi I'm a beginner and this is the details to code. Create a parent class called shape. This should have following methods inputSides() – Ask user to enter the sides of the shape. Now create subclasses for a circle, rectangle and triangle. These should include an appropriate area() method that will use the side values f...
[ "You should work more on inheritance.You shouldn't create instances from parent into child classes.\nAs all of your shapes have an area attribute, let's put area calculator inside parent class.\nclass shape():\n def calculateArea(self,*args):\n a = 1\n [a:= a*i for i in args]\n return a\n\nt...
[ 0 ]
[]
[]
[ "class", "input", "math", "python", "superclass" ]
stackoverflow_0074516047_class_input_math_python_superclass.txt
Q: Add two legends in the same plot I've a x and y. Both are flattened 2D arrays. I've two similar arrays, one for determining the colour of datapoint, another for determining detection method ("transit" or "radial"), which is used for determining the marker shape. a=np.random.uniform(0,100,(10,10)).ravel() #My x b=...
Add two legends in the same plot
I've a x and y. Both are flattened 2D arrays. I've two similar arrays, one for determining the colour of datapoint, another for determining detection method ("transit" or "radial"), which is used for determining the marker shape. a=np.random.uniform(0,100,(10,10)).ravel() #My x b=np.random.uniform(0,100,(10,10)).ravel...
[ "You could just manually add the first legend to the Axes:\nleg1 = ax.legend(*scatter1.legend_elements(), bbox_to_anchor=(1.04, 1), loc=\"upper left\", title=\"Legend\")\nax.add_artist(leg1)\n\n\nHowever, this is not every clear as the color legend uses the marker for Radial and the Detection legend uses just two a...
[ 2 ]
[]
[]
[ "colors", "legend", "matplotlib", "python", "scatter_plot" ]
stackoverflow_0074510820_colors_legend_matplotlib_python_scatter_plot.txt
Q: I'm trying to get specific results from my Lucky Sevens program, but I'm not sure where to go from here I'm trying to calculate the number of rolls it takes to go broke, and the amount of rolls that would have left you with the most money. The program is split into several functions outside of main (not my choice)...
I'm trying to get specific results from my Lucky Sevens program, but I'm not sure where to go from here
I'm trying to calculate the number of rolls it takes to go broke, and the amount of rolls that would have left you with the most money. The program is split into several functions outside of main (not my choice) so that makes it more difficult for me. I'm very new to python, and this is an exercise for school. I'm just...
[ "import random\n\nmaxmoney = []\nminmoney = []\n\ndef displayHeader():\n print (\"--------------------------\")\n print (\"--------------------------\")\n print (\"- Lucky Sevens -\")\n print (\"--------------------------\")\n print (\"--------------------------\")\n funds = int(input(\"...
[ 0, 0 ]
[]
[]
[ "loops", "parameters", "python" ]
stackoverflow_0074514985_loops_parameters_python.txt
Q: Label a whole numpy array with one label on matplotlib I would like to label a whole numpy array with only one label. The following code for example creates 6 (=2+4) labels instead of only 2 labels: import numpy as np import matplotlib.pyplot as plt a = np.random.rand(10,2) b = np.random.rand(10,4) plt.figure() ...
Label a whole numpy array with one label on matplotlib
I would like to label a whole numpy array with only one label. The following code for example creates 6 (=2+4) labels instead of only 2 labels: import numpy as np import matplotlib.pyplot as plt a = np.random.rand(10,2) b = np.random.rand(10,4) plt.figure() plt.plot(a, 'blue', label = 'a') plt.plot(b, 'red', label =...
[ "a_lines = plt.plot(a, c='blue')\nb_lines = plt.plot(b, c='red')\nplt.legend(handles=[a_lines[0], b_lines[0]], labels=['a', 'b'])\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "numpy_ndarray", "python" ]
stackoverflow_0074509789_matplotlib_numpy_ndarray_python.txt
Q: How to change file names in bulk, beginner here enter image description here I have files names like that in a directory, what I want to do is, ISOLUX_LL2023_864-EN-P4-500-730.JPG rename this file for example to; LL2023_864-EN-P4-500-700.jpg first to delete "ISOLUX_" from all, then turn the file extension to.jpg,...
How to change file names in bulk, beginner here
enter image description here I have files names like that in a directory, what I want to do is, ISOLUX_LL2023_864-EN-P4-500-730.JPG rename this file for example to; LL2023_864-EN-P4-500-700.jpg first to delete "ISOLUX_" from all, then turn the file extension to.jpg, I am a beginner by the way, don't know much about us...
[ "This should work, As you have not mentioned a way the \"bulk\" files should be named I just made a list to name them.\nThe file names would change for the old file name, check the number of files in the folder for the range(3).\nYou can also use a loop to create a list of the new names.\nimport os\nfrom os import ...
[ 0 ]
[]
[]
[ "python", "python_3.x", "rename", "windows" ]
stackoverflow_0074515551_python_python_3.x_rename_windows.txt
Q: brownie:ValueError: execution reverted: VM Exception while processing transaction: revert Macbook Pro : Monterey Intel Core i7 Brownie v1.17.2 I am learning solidity according to reference(https://www.youtube.com/watch?v=M576WGiDBdQ&t=25510s). What I tried to do here, is use brownie to deploy a contract(FundMe) in...
brownie:ValueError: execution reverted: VM Exception while processing transaction: revert
Macbook Pro : Monterey Intel Core i7 Brownie v1.17.2 I am learning solidity according to reference(https://www.youtube.com/watch?v=M576WGiDBdQ&t=25510s). What I tried to do here, is use brownie to deploy a contract(FundMe) in a script (deploy.py),then write a test script(scripts/fund_and_withdraw.py.py) I met the same ...
[ "function getEntranceFee() public view returns (uint256) {\n // mimimumUSD\n uint256 mimimumUSD = 50 * 10**18;\n uint256 price = getPrice();\n uint256 precision = 1 * 10**18;\n return (mimimumUSD * precision) / price;\n }\n\nYou do not need to multiply with precison. currently,...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "brownie", "chainlink", "ethereum", "python", "solidity" ]
stackoverflow_0070751581_brownie_chainlink_ethereum_python_solidity.txt
Q: Unable to print TCPcump information using python subprocess I wanted to process tcpdump output in a python script and so far I was able to get to this implementation from subprocess import Popen, PIPE, CalledProcessError import os import signal import time if __name__=="__main__": cmd = ["sudo","tcpdump"...
Unable to print TCPcump information using python subprocess
I wanted to process tcpdump output in a python script and so far I was able to get to this implementation from subprocess import Popen, PIPE, CalledProcessError import os import signal import time if __name__=="__main__": cmd = ["sudo","tcpdump", "-c","1000","-i","any","port","22","-n"] with Popen(cmd, st...
[ "tcpdump uses a larger buffer if you connect its standard output to a pipe. You can easily see this by running the following two commands. (I changed the count from 1000 to 40 and removed port 22 in order to quickly get output on my system.)\n$ sudo tcpdump -c 40 -i any -n\n$ sudo tcpdump -c 40 -i any -n | cat\n\nT...
[ 1 ]
[]
[]
[ "networking", "python", "scripting", "subprocess", "ubuntu" ]
stackoverflow_0074499381_networking_python_scripting_subprocess_ubuntu.txt
Q: how to define selection condition in regex in python I am having a string in which some binary numbers are mentioned. I want to count number of occurrence of given pattern, but I want set my pattern above 7 digits of character, so the result should show only more than 7 characters. it means how I can set my patte...
how to define selection condition in regex in python
I am having a string in which some binary numbers are mentioned. I want to count number of occurrence of given pattern, but I want set my pattern above 7 digits of character, so the result should show only more than 7 characters. it means how I can set my pattern selection, so it should count only 7 digits and above ...
[ "The simplest solution is to filter the list of regex matches.\nimport re\nfrom collections import Counter\n\npattern = r\"0+1+0+1+0+1+\"\n\ntest_str = '01010100110011001100011100011110000101101110100001101011000111011001010011001001001101000011' \\\n '00110011001100110011010101001100110001111110010100100...
[ 2 ]
[]
[]
[ "python", "regex", "select", "string" ]
stackoverflow_0074515999_python_regex_select_string.txt
Q: Jupyter’s kernel crash when i use groupby I’m analizing a dataset with 200 columns and 6000 rows. I computed all the possibile differences between columns using iterools and implemented them into the dataset. So now the number of columns has increased. Until now everything work fine and kernel doesn’t have problem...
Jupyter’s kernel crash when i use groupby
I’m analizing a dataset with 200 columns and 6000 rows. I computed all the possibile differences between columns using iterools and implemented them into the dataset. So now the number of columns has increased. Until now everything work fine and kernel doesn’t have problems. Kernel dies when i try to group columns with...
[ "Kernel crashes often suggest a large spike in resource usage, which your machine and/or juypter configuration could not handle.\nThe question is then, \"What am I doing that is using so many resources?\".\nThat's for you to figure out, but my guess is that it has to do with your list comprehension over permutation...
[ 0 ]
[]
[]
[ "crash", "pandas", "python" ]
stackoverflow_0074512801_crash_pandas_python.txt
Q: find resources that are never tagged in aws using boto3 Using this we can't find resources that are never tagged: client = boto3.client('resourcegroupstaggingapi') How to find resources that are never tagged in AWS using boto3? A: We are using a tagging concept that requires 5 tags as mandatory, and we created ...
find resources that are never tagged in aws using boto3
Using this we can't find resources that are never tagged: client = boto3.client('resourcegroupstaggingapi') How to find resources that are never tagged in AWS using boto3?
[ "We are using a tagging concept that requires 5 tags as mandatory, and we created a config rule that checks for these.\nhttps://docs.aws.amazon.com/config/latest/developerguide/required-tags.html\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "boto3", "python" ]
stackoverflow_0074514475_amazon_web_services_aws_lambda_boto3_python.txt
Q: Equivalent for R / dplyr's glimpse() function in Python for Panda dataframes? I find the glimpse function very useful in R/dplyr. But as someone who is used to R and is working with Python now, I haven't found something as useful for Panda dataframes. In Python, I've tried things like .describe() and .info() and ....
Equivalent for R / dplyr's glimpse() function in Python for Panda dataframes?
I find the glimpse function very useful in R/dplyr. But as someone who is used to R and is working with Python now, I haven't found something as useful for Panda dataframes. In Python, I've tried things like .describe() and .info() and .head() but none of these give me the useful snapshot which R's glimpse() gives us. ...
[ "Here is one way to do it:\ndef glimpse(df):\n print(f\"Rows: {df.shape[0]}\")\n print(f\"Columns: {df.shape[1]}\")\n for col in df.columns:\n print(f\"$ {col} <{df[col].dtype}> {df[col].head().values}\")\n\nThen:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\"column_one\": [\"A\", \"B\", \"C\",...
[ 1 ]
[]
[]
[ "dplyr", "pandas", "python", "r" ]
stackoverflow_0074414355_dplyr_pandas_python_r.txt
Q: How can i allow both IP Address and URL in django field? I want to allow both flutterdemo.hp.com and 12.135.720.12 in django field. This is what i tried. from rest_framework import serializers, viewsets from django.core.validators import URLValidator class FlutterSerializer(serializers.HyperlinkedModelSerializer)...
How can i allow both IP Address and URL in django field?
I want to allow both flutterdemo.hp.com and 12.135.720.12 in django field. This is what i tried. from rest_framework import serializers, viewsets from django.core.validators import URLValidator class FlutterSerializer(serializers.HyperlinkedModelSerializer): fqdn_ip = serializers.CharField(max_length = 100, valida...
[ "You can use this third-party library for Validating URL and IP.\nValidate Ipv4 Ip here\nValidate Ipv6 Ip here\nValidate Url here\nAfter validate you can save with CharField\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "orm", "python" ]
stackoverflow_0074515515_django_django_models_django_rest_framework_orm_python.txt
Q: pyspark dataframe combine identical rows based on start and end column I have a dataframe contains billion records and which I want to combine identical rows into one rows based on their effective_start and effective_end date key1 key2 start end k11 k2 2000-01-01 2000-02-01 k11 k2 2000-02-01 2000-03-01 k11 k2 ...
pyspark dataframe combine identical rows based on start and end column
I have a dataframe contains billion records and which I want to combine identical rows into one rows based on their effective_start and effective_end date key1 key2 start end k11 k2 2000-01-01 2000-02-01 k11 k2 2000-02-01 2000-03-01 k11 k2 2000-03-01 2000-04-01 k11 k2 2000-04-01 2000-05-01 k11 k2 2000-0...
[ "The logic is:\n\nAppend \"end\" column shifted by one record. Since, spark has distributed architecture, there is no notion of \"position or index\" of a record. This is done with help of Window function and columns with which to order by.\nCompute the diff between \"start\" and previous record's \"end\" column.\n...
[ 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python", "sql" ]
stackoverflow_0074515764_apache_spark_apache_spark_sql_pyspark_python_sql.txt
Q: How to mock httpx.AsyncClient() in Pytest I need to write test case for a function which use to fetch data from API. In there i used httpx.AsyncClient() as context manager. But i don't understand how to write test case for that function. async def make_dropbox_request(url, payload, dropbox_token): async with httpx...
How to mock httpx.AsyncClient() in Pytest
I need to write test case for a function which use to fetch data from API. In there i used httpx.AsyncClient() as context manager. But i don't understand how to write test case for that function. async def make_dropbox_request(url, payload, dropbox_token): async with httpx.AsyncClient(timeout=None, follow_redirects=Tru...
[ "TL;DR: use return_value.__aenter__.return_value to mock the async context.\nAssuming you are using Pytest and pytest-mock, your can use the mocker fixture to mock httpx.AsyncClient.\nSince the post function is async, you will need to use an AsyncMock.\nFinally, since you use an async context, you will also need to...
[ 2, 1, 0 ]
[]
[]
[ "asynchronous", "httpx", "mocking", "pytest", "python" ]
stackoverflow_0070633584_asynchronous_httpx_mocking_pytest_python.txt
Q: Index i out of range for an array while using nested loops Starting to learn to code and I was doing the fantasy items exercise from automate boring stuff with python. I tried comparing each item of the addedItems array to the dictionary keys to see if they exist, if not I would create a new key with the default v...
Index i out of range for an array while using nested loops
Starting to learn to code and I was doing the fantasy items exercise from automate boring stuff with python. I tried comparing each item of the addedItems array to the dictionary keys to see if they exist, if not I would create a new key with the default value 1. However it says that I have index out of range error, al...
[ "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, ...
[ 2, 0 ]
[]
[]
[ "dictionary", "indexing", "list", "nested", "python" ]
stackoverflow_0074516186_dictionary_indexing_list_nested_python.txt
Q: Azure App Service with AAD identity provider - Python & Streamlit framework for app - get logged in user Have a web app developed in Python with the Streamlit framework. Deploying as an Azure app service. Authentication to the app is via AAD. I'm unable to get details such as name/email address of the logged in us...
Azure App Service with AAD identity provider - Python & Streamlit framework for app - get logged in user
Have a web app developed in Python with the Streamlit framework. Deploying as an Azure app service. Authentication to the app is via AAD. I'm unable to get details such as name/email address of the logged in user. Most welcome any suggestions (I've tried /.auth/me endpoint, looking at cookie sessions). Thanks!
[ "The /.auth/me endpoint gives you the information you need, i.e., it is a part of the access token (RS256 encoded) and maybe even decoded as well. You need to include the AppServiceAuthSession cookie in your get request to the endpoint.\nThis code snippet should work in streamlit:\nimport requests\nfrom streamlit.s...
[ 0, 0 ]
[]
[]
[ "azure", "azure_web_app_service", "python" ]
stackoverflow_0070162168_azure_azure_web_app_service_python.txt
Q: create a xml with just root tag using python I'm trying to create a xml file with just one root tag without any subElements to it. I tried with following code import xml.etree.cElementTree as ET root = ET.Element("root") tree = ET.ElementTree(root) tree.write("filename.xml") I am getting filename.xml as below: ...
create a xml with just root tag using python
I'm trying to create a xml file with just one root tag without any subElements to it. I tried with following code import xml.etree.cElementTree as ET root = ET.Element("root") tree = ET.ElementTree(root) tree.write("filename.xml") I am getting filename.xml as below: <root /> But I am expecting as below: <root> </roo...
[ "The element can be self-closing if it is empty, meaning your output is valid XML.\nSee: https://www.w3schools.com/xml/xml_elements.asp\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "xml" ]
stackoverflow_0074516498_python_python_3.x_xml.txt
Q: How to save output after two layers of neural network in Pytorch I wrote a convolutional autoencoder that was supposed to work on the ORL dataset (400 images in dataset, size 32*32) in csv. format. What I want is to observe how the data changes through the autoencoder. That's why I wrote a test1 function in the cl...
How to save output after two layers of neural network in Pytorch
I wrote a convolutional autoencoder that was supposed to work on the ORL dataset (400 images in dataset, size 32*32) in csv. format. What I want is to observe how the data changes through the autoencoder. That's why I wrote a test1 function in the class that goes through only the first two layers. class ConvAutoencoder...
[ "You specify a batch size of 200 but then take only the first element (inputs = data[0])\nIf you want to run it on all images change the batch size to 400 and don't take only the first element\n" ]
[ 1 ]
[]
[]
[ "autoencoder", "batchsize", "python", "pytorch" ]
stackoverflow_0074516025_autoencoder_batchsize_python_pytorch.txt
Q: Python inheritance - add argument to parent method I have a base class with function run. For example: class A: @abstractmethod def run(self, steps): ... It is possible to define class B with more arguments to the run method. class B(A): def run(self, steps, save): ... Working with ty...
Python inheritance - add argument to parent method
I have a base class with function run. For example: class A: @abstractmethod def run(self, steps): ... It is possible to define class B with more arguments to the run method. class B(A): def run(self, steps, save): ... Working with typing, I can specify if a function gets either A or B as ...
[ "In Python you can do something like the following.\nclass A:\n\n def run(self, steps):\n print(\"Using class A's run.\")\n print(f\"steps are {steps}\")\n\n\nclass B(A):\n\n def run(self, steps, other_arg=None):\n if other_arg:\n print(\"Using class B's override.\")\n print(f\"steps are {steps...
[ 1 ]
[]
[]
[ "inheritance", "overriding", "python" ]
stackoverflow_0074516402_inheritance_overriding_python.txt
Q: How to reate a dataframe based on excel sheet name and cell position? I have an excel table (sample.xlsx) which contains 3 sheets ('Sheet1','Sheet2','Sheet3'). Now I have read all the sheets and combine them into one dataframe. import pandas as pd data_df = pd.concat(pd.read_excel("sample.xlsx", header=None, index...
How to reate a dataframe based on excel sheet name and cell position?
I have an excel table (sample.xlsx) which contains 3 sheets ('Sheet1','Sheet2','Sheet3'). Now I have read all the sheets and combine them into one dataframe. import pandas as pd data_df = pd.concat(pd.read_excel("sample.xlsx", header=None, index_col=None, sheet_name=None)) data_df looks like this: 0 ...
[ "Since the values in your data_df don't matter, you could build the cartesian product of index and columns and build a new dataframe of it.\nmapping = dict(enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))\n\nmapping is needed to convert the column numbers 0,1,2,... to A,B,C,...\nUPDATE\nIn case you have excel sheets with m...
[ 1, 0 ]
[]
[]
[ "data_analysis", "dataframe", "excel", "pandas", "python" ]
stackoverflow_0074514966_data_analysis_dataframe_excel_pandas_python.txt
Q: Use python and pandas to set key for imported data from text file to dataframe This feels like an incredibly straight forward problem, but I am new and stuck, apologies. It doesn't necessarily need a key, but that was how I thought to solve it. I have a text file whose abbreviated contents resemble this: name_of_s...
Use python and pandas to set key for imported data from text file to dataframe
This feels like an incredibly straight forward problem, but I am new and stuck, apologies. It doesn't necessarily need a key, but that was how I thought to solve it. I have a text file whose abbreviated contents resemble this: name_of_source 128 1024.000000 225.569918 name_of_source_2 140 1120.000000 229.085200 etc etc...
[ "You can use pandas.DataFrame.join:\ndf= pd.read_csv(\"test.txt\", header=None)\n\nout= (\n df.rename(columns= {0: \"Name\"})\n .join(df.shift(-1).rename(columns={0: \"Vals\"}))\n .iloc[::2]\n )\n\n# Output :\nprint(out)\n Name Vals\n0 name_of_so...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074515584_pandas_python.txt
Q: "No module named 'sympy'" Error. Problem occurs after installation I am new to Python. I am trying to use the Sympy package. I am running Python 3.11 in Pycharm I am using Windows 10. It displays: ModuleNotFoundError: No module named 'sympy' I ran pip install sympy, it installed it. And when I try reinstalling ...
"No module named 'sympy'" Error. Problem occurs after installation
I am new to Python. I am trying to use the Sympy package. I am running Python 3.11 in Pycharm I am using Windows 10. It displays: ModuleNotFoundError: No module named 'sympy' I ran pip install sympy, it installed it. And when I try reinstalling it, it displays: Requirement already satisfied: sympy in c:\users\jrk\a...
[ "My instructions might be a bit rusty as I don't regularly use Windows for Python but here goes:\nYou'll notice that the path to your Pycharm Python interpreter (c:\\Users\\jrk\\PycharmProjects..) is different than the path reported by pip in your error messages (c:\\Users\\jrk\\appdata..).\nIt's perfectly normal t...
[ 0, 0 ]
[ "Try Uninstalling it and reinstalling\npip uninstall sympy\n\npip install sympy\n" ]
[ -2 ]
[ "module", "pip", "pycharm", "python", "sympy" ]
stackoverflow_0074357986_module_pip_pycharm_python_sympy.txt
Q: Is an abstract method a normal instance method in a non-abstract class in Python? I defined the abstract method sound() with @abstractmethod under the non-abstract class Animal which doesn't extend ABC and Cat class extends Animal class, then I could instantiate both Animal and Cat classes without any errors as sh...
Is an abstract method a normal instance method in a non-abstract class in Python?
I defined the abstract method sound() with @abstractmethod under the non-abstract class Animal which doesn't extend ABC and Cat class extends Animal class, then I could instantiate both Animal and Cat classes without any errors as shown below: from abc import ABC, abstractmethod class Animal: # Doesn't extend "ABC" ...
[ "The abstractmethod decorator just adds some annotation to the method, which is evaluated by ABC when you try to instantiate the class. The method itself doesn't change in any way, it's still a regular instance method. It's the cooperation of ABC together with those abstractmethod decorator annotations that result ...
[ 3 ]
[]
[]
[ "abstract_class", "abstract_methods", "instance_methods", "python", "python_3.x" ]
stackoverflow_0074516565_abstract_class_abstract_methods_instance_methods_python_python_3.x.txt
Q: Shortest way to get first item of `OrderedDict` in Python 3 What's the shortest way to get first item of OrderedDict in Python 3? My best: list(ordered_dict.items())[0] Quite long and ugly. I can think of: next(iter(ordered_dict.items())) # Fixed, thanks Ashwini But it's not very self-describing. Any bet...
Shortest way to get first item of `OrderedDict` in Python 3
What's the shortest way to get first item of OrderedDict in Python 3? My best: list(ordered_dict.items())[0] Quite long and ugly. I can think of: next(iter(ordered_dict.items())) # Fixed, thanks Ashwini But it's not very self-describing. Any better suggestions?
[ " Programming Practices for Readabililty \nIn general, if you feel like code is not self-describing, the usual solution is to factor it out into a well-named function:\ndef first(s):\n '''Return the first element from an ordered collection\n or an arbitrary element from an unordered collection.\n Rai...
[ 73, 31, 5, 5, 0 ]
[ "First record:\n[key for key, value in ordered_dict][0]\n\nLast record:\n[key for key, value in ordered_dict][-1]\n\n" ]
[ -2 ]
[ "indexing", "iterable", "python", "python_3.x" ]
stackoverflow_0021062781_indexing_iterable_python_python_3.x.txt
Q: Why can't dataclasses have mutable defaults in their class attributes declaration? This seems like something that is likely to have been asked before, but an hour or so of searching has yielded no results. Passing default list argument to dataclasses looked promising, but it's not quite what I'm looking for. Here'...
Why can't dataclasses have mutable defaults in their class attributes declaration?
This seems like something that is likely to have been asked before, but an hour or so of searching has yielded no results. Passing default list argument to dataclasses looked promising, but it's not quite what I'm looking for. Here's the problem: when one tries to assign a mutable value to a class attribute, there's an...
[ "It looks like my question was quite clearly answered in the docs (which derived from PEP 557, as shmee mentioned):\n\nPython stores default member variable values in class attributes. Consider this example, not using dataclasses:\nclass C:\n x = []\n def add(self, element):\n self.x.append(element)\n\...
[ 106, 3 ]
[ "import field like dataclass.\nfrom dataclasses import dataclass, field\n\nand use this for lists:\n@dataclass\nclass Foo:\n bar: list = field(default_factory=list)\n\n" ]
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0053632152_python_python_3.x.txt
Q: Python 3.10 .join function questions So let's say, i want to do something thing like this a = ['AB', 'CD'] s = '1. \n' print(s.join(a)) Expected Output: 1. AB 2. CD Actual Output: AB1. CD1. So my question is, How can i add something at the beginning of the string s? And also increase the number. example: 1. ......
Python 3.10 .join function questions
So let's say, i want to do something thing like this a = ['AB', 'CD'] s = '1. \n' print(s.join(a)) Expected Output: 1. AB 2. CD Actual Output: AB1. CD1. So my question is, How can i add something at the beginning of the string s? And also increase the number. example: 1. ... 2. ...
[ "a = ['AB', 'CD']\nrs = \"\"\nfor i, v in enumerate(a):\n rs += f\"{i + 1}. {v}\\n\"\nprint(rs)\n\n", "You can use enumerate and a list comprehension to create that string:\na = ['AB', 'CD']\n\ns = '\\n'.join(\n f\"{idx}. {val}\"\n for idx, val in enumerate(a, 1))\n\n" ]
[ 0, 0 ]
[]
[]
[ "list", "printing", "python", "string" ]
stackoverflow_0074516502_list_printing_python_string.txt
Q: Increase performance of df.rolling(...).apply(...) for large dataframes Execution time of this code is too long. df.rolling(window=255).apply(myFunc) My dataframes shape is (500, 10000). 0 1 ... 9999 2021-11-01 0.011111 0.054242 2021-11-04 0.025244 0.003653 2021-11-05 0.524521 0...
Increase performance of df.rolling(...).apply(...) for large dataframes
Execution time of this code is too long. df.rolling(window=255).apply(myFunc) My dataframes shape is (500, 10000). 0 1 ... 9999 2021-11-01 0.011111 0.054242 2021-11-04 0.025244 0.003653 2021-11-05 0.524521 0.099521 2021-11-06 0.054241 0.138321 ... I make the calculation for each...
[ "This can be done using numpy+numba pretty efficiently.\nQuick MRE:\nimport numpy as np, pandas as pd, numba\n\ndf = pd.DataFrame(\n np.random.random(size=(500, 10000)),\n index=pd.date_range(\"2021-11-01\", freq=\"D\", periods=500)\n)\n\ncoefs = np.random.random(size=255)\n\nWrite the function using pure num...
[ 2, 2 ]
[]
[]
[ "dask", "pandas", "python", "swifter" ]
stackoverflow_0074487361_dask_pandas_python_swifter.txt
Q: How to get the indexes of the same values in a list? Say I have a list like this: l = [1, 2, 3, 4, 5, 3] how do I get the indexes of those 3s that have been repeated? A: First you need to figure out which elements are repeated and where. I do it by indexing it in a dictionary. Then you need to extract all repeat...
How to get the indexes of the same values in a list?
Say I have a list like this: l = [1, 2, 3, 4, 5, 3] how do I get the indexes of those 3s that have been repeated?
[ "First you need to figure out which elements are repeated and where. I do it by indexing it in a dictionary.\nThen you need to extract all repeated values.\nfrom collections import defaultdict\n\nl = [1, 2, 3, 4, 5, 3]\n_indices = defaultdict(list)\n\nfor index, item in enumerate(l):\n _indices[item].append(inde...
[ 1, 1, 1, 1 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0070488053_arrays_list_python.txt
Q: How to add empty/dummy row with continuous datetime index in pandas? This is my dataframe consumption hour start_time 2022-09-30 14:00:00+02:00 199.0 14.0 2022-09-30 15:00:00+02:00 173.0 15.0 2022-09-30 16:00:00+02:00 173.0 16.0 2022-09-30 17:00...
How to add empty/dummy row with continuous datetime index in pandas?
This is my dataframe consumption hour start_time 2022-09-30 14:00:00+02:00 199.0 14.0 2022-09-30 15:00:00+02:00 173.0 15.0 2022-09-30 16:00:00+02:00 173.0 16.0 2022-09-30 17:00:00+02:00 156.0 17.0 2022-09-30 18:00:00+02:00 142....
[ "Create helper DataFrame and add to original by concat:\nN = 2\ndf1 = (pd.DataFrame({'consumption':0}, \n index=pd.date_range(df.index.max() + pd.Timedelta('1h'),\n df.index.max() + pd.Timedelta(f'{N}h'),\n freq='H'))\n .assign(hour=la...
[ 1 ]
[]
[]
[ "datetime", "dummy_variable", "pandas", "python", "time_series" ]
stackoverflow_0074516628_datetime_dummy_variable_pandas_python_time_series.txt
Q: Selenium element not interactable error on headless mode but works without headless I'm trying to scrape the webpage ted.europa.eu using Python with Selenium to retrieve information from the tenders. The script is supposed to be executed once a day with the new publications. The problem I have is that navigating t...
Selenium element not interactable error on headless mode but works without headless
I'm trying to scrape the webpage ted.europa.eu using Python with Selenium to retrieve information from the tenders. The script is supposed to be executed once a day with the new publications. The problem I have is that navigating to the new tenders I need Selenium to apply a filter to get only the ones from the same da...
[ "This is probably because of the window size.\nTry adding this:\n chrome_options = Options()\n chrome_options.add_argument(\"--window-size=1920,1080\")\n chrome_options.add_argument(\"--start-maximized\")\n chrome_options.add_argument(\"--headless\")\n\n", "So, after a long time of try and error, I fou...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074473765_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: Azure Databricks workspace CLI - cannot create new folder in /Repos folder as service principle I am developing an Azure pipeline and want to create (https://docs.databricks.com/dev-tools/api/latest/repos.html#operation/create-repo) a repo in Databricks and save it to /Repos/sub_folder/repo_name To test the comman...
Azure Databricks workspace CLI - cannot create new folder in /Repos folder as service principle
I am developing an Azure pipeline and want to create (https://docs.databricks.com/dev-tools/api/latest/repos.html#operation/create-repo) a repo in Databricks and save it to /Repos/sub_folder/repo_name To test the commands in the pipeline, I am using the Databricks cli and repos API (as described in the link above) loca...
[ "The issue was two-fold. Firstly the service principle was not configured with admin rights so could not create the sub-folder in /Repos. Once this was fixed, I got a different error when issuing the post command trying to create the repo (in the newly created sub-folder). The error I got was:\n{\"error_code\":\"PE...
[ 0 ]
[]
[]
[ "azure", "azure_databricks", "pipeline", "python" ]
stackoverflow_0074482670_azure_azure_databricks_pipeline_python.txt
Q: How do I count the number of messages per day in pycord? So I basicly count all the messages in a channel. I also want to count the number of messages per day. I know message.created_at returns a datetime, but how do I count how many times a date is present in this list? this is my current code: count = 0 async fo...
How do I count the number of messages per day in pycord?
So I basicly count all the messages in a channel. I also want to count the number of messages per day. I know message.created_at returns a datetime, but how do I count how many times a date is present in this list? this is my current code: count = 0 async for message in channel.history(limit=None): count += 1 p...
[ "Your code isn't counting the number of messages on a certain date, it's counting the message on a certain datetime.datetime object, which represents a specific point in time (could be down to a microsecond depending on the API precision).\nThis is because message.created_at returns the time and date of the message...
[ 0 ]
[]
[]
[ "datetime", "discord", "pycord", "python" ]
stackoverflow_0074516627_datetime_discord_pycord_python.txt
Q: how to check right number of products and breaking my while loop? I got a mission to wright a code to grocery shopping list, every number that I put in should activete other function. I got 3 problems in this code. the greater problem is that the loop should break when I put in the number 9 and that isn't break. ...
how to check right number of products and breaking my while loop?
I got a mission to wright a code to grocery shopping list, every number that I put in should activete other function. I got 3 problems in this code. the greater problem is that the loop should break when I put in the number 9 and that isn't break. in the function how_moch_product_name_in_list I need a for loop that ad...
[ "The while loop in your main function calls the process_grocery_store function twice - once in the condition evaluation, and once if the condition is True, and you ignore the return value there. so if you enter \"break\" when the function is run the inside the loop, than the \"break\" has no effect.\nTry something ...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074516051_python_python_3.x.txt
Q: Can't change a value of a function's variable inside a "with" block python I want my function to return True or False but it always return False. I've tried to remove the first assignment of user(user = False) but an error occured : "user is not defined" Here is the function def findUser(name): user = False ...
Can't change a value of a function's variable inside a "with" block python
I want my function to return True or False but it always return False. I've tried to remove the first assignment of user(user = False) but an error occured : "user is not defined" Here is the function def findUser(name): user = False with open('users', 'rb') as usersFile: myUnpickle = pickle.Unpickler(u...
[ "I was just opening the wrong file when looking for the user, I didn't add what to do if the file wasn't find that's why when there was not an initialization of the return variable I got an error. I had just to change the file name. The variable's value inside the \"with\" wasn't take into account because the \"wit...
[ 0 ]
[]
[]
[ "environment_variables", "python", "return_value", "variables", "with_statement" ]
stackoverflow_0074502881_environment_variables_python_return_value_variables_with_statement.txt
Q: How do i create a number of inputs from an input I'm brand new to this, 10 days in. Ive been thinking how I could solve this for 30 min. Please help. Find Average You need to calculate the average of a collection of values. Every value will be valid number. The average must be printed with two digits after the de...
How do i create a number of inputs from an input
I'm brand new to this, 10 days in. Ive been thinking how I could solve this for 30 min. Please help. Find Average You need to calculate the average of a collection of values. Every value will be valid number. The average must be printed with two digits after the decimal point. Input- On the first line, you will receiv...
[ "a=int(input('Total number of input: '))\n\ntotal = 0.0\n\nfor i in range(a):\n total += float(input(f'Input #{i+1}: '))\n \nprint('average: ', round(total/a,2))\n\nModified a bit on your version to make it work\n", "There were few things that you were doing wrong. when the numbers are decimals use float no...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074516401_python_python_3.x.txt
Q: ValueError: could not convert string to float: '$2,464.34' I am trying to convert the data to float in order make it as numerical format in excel to sort the data i am getting error.wherever the float in mentioned i did it now but previously there was no float . def get_output_value(self, key, value, neutral=None...
ValueError: could not convert string to float: '$2,464.34'
I am trying to convert the data to float in order make it as numerical format in excel to sort the data i am getting error.wherever the float in mentioned i did it now but previously there was no float . def get_output_value(self, key, value, neutral=None): display = value if value is None and not neutral.pers...
[ "The answer is in the error message in this case. '$2,464.34' is a string with $ and , characters in it, but float() expects a number-like input.\nTLDR, you want float('2464.34') but you're giving float('$2,464.34')\n" ]
[ 4 ]
[]
[]
[ "django", "excel", "python", "python_3.x" ]
stackoverflow_0074516822_django_excel_python_python_3.x.txt
Q: Can mark_geoshape () be used for Canadian Provinces/cities? I'm looking to somehow figure out a way to insert a geographic graph of British Columbia which is a part of Canada in my data analysis. I have made this image here explaining what tree is being planted the most in Vancouver Now I want to make a geograph ...
Can mark_geoshape () be used for Canadian Provinces/cities?
I'm looking to somehow figure out a way to insert a geographic graph of British Columbia which is a part of Canada in my data analysis. I have made this image here explaining what tree is being planted the most in Vancouver Now I want to make a geograph kind of like this https://altair-viz.github.io/gallery/airports_c...
[ "Canadian provinces are not part of world_110m map in the example gallery. You would need to provide your own geojson and topojson file that contains that information in order to work with Altair and then follow the guidelines here How can I make a map using GeoJSON data in Altair?.\nYou can also work with geopanda...
[ 1, 0, 0 ]
[]
[]
[ "altair", "geojson", "python", "topojson", "vega_lite" ]
stackoverflow_0074168389_altair_geojson_python_topojson_vega_lite.txt
Q: '<' not supported between instances of 'str' and 'int' in Python When I try to create a new variable in dataframe Call08q1_09q1 by adding two float variable Call08q1_09q1['MBS']=Call08q1_09q1['RCFD8639']+Call08q1_09q1['RCFD2170'] the error below shows up: '<' not supported between instances of 'str' and 'int' in ...
'<' not supported between instances of 'str' and 'int' in Python
When I try to create a new variable in dataframe Call08q1_09q1 by adding two float variable Call08q1_09q1['MBS']=Call08q1_09q1['RCFD8639']+Call08q1_09q1['RCFD2170'] the error below shows up: '<' not supported between instances of 'str' and 'int' in Python However, I don't have string in my dataframe. Call08q1_09q1.inf...
[ "You have loads of nulls in your columns as the printout tells you. How are those represented? Can you add these nulls with ints? I suggest you debug by inspecting these null values and taking appropriate action to fill them, drop them, or otherwise transform them into something useful.\n", "The error has not occ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074516633_pandas_python.txt
Q: Appium-python-client, find element function im new to the appium library and I'm facing issues with the methods to locate elements in an android app, the two methods in question are: 1- driver.find_element_by_id 2- driver.find_element #desired_cap defined above driver = web.driver.remote("http://localhost:4723/wd/...
Appium-python-client, find element function
im new to the appium library and I'm facing issues with the methods to locate elements in an android app, the two methods in question are: 1- driver.find_element_by_id 2- driver.find_element #desired_cap defined above driver = web.driver.remote("http://localhost:4723/wd/hub", desired_cap) driver.find_element_by_id(#ele...
[ "First of all, I believe you have a typo and it should read webdriver iso web.driver:\ndriver = webdriver.remote(\"http://localhost:4723/wd/hub\", desired_cap)\n\nTo answer your question: Appium works with accessibility ID, like so:\ndriver.find_element(\"AppiumBy.ACCESSIBILITY_ID\",\"SomeAccessibilityID\")\n\nAppi...
[ 0 ]
[]
[]
[ "python", "python_appium" ]
stackoverflow_0074506206_python_python_appium.txt
Q: Data transfer for Jinja2 from Updateviev I have such a template on every html page into which I want to transfer data from my url processors: {% block title %} {{ title }} {% endblock %} {% block username %} <b>{{username}}</b> {% endblock %} When using regular def functions, I pass them like this: data_ = { ...
Data transfer for Jinja2 from Updateviev
I have such a template on every html page into which I want to transfer data from my url processors: {% block title %} {{ title }} {% endblock %} {% block username %} <b>{{username}}</b> {% endblock %} When using regular def functions, I pass them like this: data_ = { 'form': form, 'data': data, 'username'...
[ "You override get_context_data:\nclass CampaignEditor(UpdateView):\n model = Campaigns\n template_name = 'dashboard/add_campaign.html'\n form_class = CampaignsForm\n\n def get_context_data(self, *args, **kwargs):\n return super().get_context_data(\n *args,\n **kwargs,\n ...
[ 2 ]
[]
[]
[ "django", "jinja2", "python", "updateview" ]
stackoverflow_0074516873_django_jinja2_python_updateview.txt
Q: is there a function in python to round off three digits after decimal but show all three digits even if zero i want to round off number 7.00087 and output should be 7.000 I tried round() function but it eliminates zero. A: This function gives the right output: def my_round(x, decimals): str_decimals = str(x ...
is there a function in python to round off three digits after decimal but show all three digits even if zero
i want to round off number 7.00087 and output should be 7.000 I tried round() function but it eliminates zero.
[ "This function gives the right output:\ndef my_round(x, decimals):\n str_decimals = str(x % int(x))\n return str(int(x)) + str_decimals[1 : 2 + decimals]\n\nWhat does my_round() do:\n1- It retrieves decimals in a string format as a variable named str_decimals\n2- Concatenates rounded int(x) with desired decim...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074516459_python.txt
Q: How to perform replacements on a string only if it is not preceded and followed by a substring? import re, datetime input_text = "Alrededor de las 00:16 am o las 23:30 pm 2022_-_02_-_18 , quizas cerca del 2022_-_02_-_18 llega el avion, pero no (2022_-_02_-_18 20:16 pm) a las (2022_-_02_-_18 00:16 am), de esos hay...
How to perform replacements on a string only if it is not preceded and followed by a substring?
import re, datetime input_text = "Alrededor de las 00:16 am o las 23:30 pm 2022_-_02_-_18 , quizas cerca del 2022_-_02_-_18 llega el avion, pero no (2022_-_02_-_18 20:16 pm) a las (2022_-_02_-_18 00:16 am), de esos hay dos (22)" print(repr(input_text)) # --> output input_date_structure = r"(?P<year>\d*)_-_(?P<month...
[ "You can merge the two regexps to form an expression like (Group1)?(...)(Group5)? (5 is due to the fact you have three capturing groups in the middle part, and even though they are named capturing groups, they are still assigned a numeric ID), and then check if Group 1 or 5 is matched inside the lambda:\nimport re,...
[ 2 ]
[]
[]
[ "python", "python_3.x", "regex", "regex_group", "replace" ]
stackoverflow_0074514707_python_python_3.x_regex_regex_group_replace.txt
Q: Problem at calling module paddleocr in Python with Anaconda Good morning, I have been trying to install paddleOCR(https://github.com/PaddlePaddle/PaddleOCR) with anaconda and I tried to start it with the command line at cmd and it works fine: (paddle_env) C:\OCR>paddleocr --image_dir source/test.png --use_angle_cl...
Problem at calling module paddleocr in Python with Anaconda
Good morning, I have been trying to install paddleOCR(https://github.com/PaddlePaddle/PaddleOCR) with anaconda and I tried to start it with the command line at cmd and it works fine: (paddle_env) C:\OCR>paddleocr --image_dir source/test.png --use_angle_cls true --lang en But when I try to do it by code: from paddleocr...
[ "Try this prompt command:\npip install \"paddleocr>=2.0.1\"\nLink to documentation: https://pypi.org/project/paddleocr/\n", "Try this prompt command:\npip install \"paddlepadlle\"\n" ]
[ 1, 0 ]
[]
[]
[ "conda", "paddle_paddle", "pip", "python" ]
stackoverflow_0069324201_conda_paddle_paddle_pip_python.txt
Q: How do I get specific keys and their values from nested dict in python? I need help, please be kind I'm a beginner. I have a nested dict like this: dict_ = { "timestamp": "2022-11-18T10: 10: 49.301Z", "name" : "example", "person":{ "birthyear": "2002" "birthname": "Examply" }, "order":{ "orderId":...
How do I get specific keys and their values from nested dict in python?
I need help, please be kind I'm a beginner. I have a nested dict like this: dict_ = { "timestamp": "2022-11-18T10: 10: 49.301Z", "name" : "example", "person":{ "birthyear": "2002" "birthname": "Examply" }, "order":{ "orderId": "1234" "ordername": "onetwothreefour" } } How do I get a new dict like...
[ "A general approach:\ndict_ = {\n \"timestamp\": \"2022-11-18T10: 10: 49.301Z\",\n \"name\": \"example\",\n \"person\": {\n \"birthyear\": \"2002\",\n \"birthname\": \"Examply\"\n },\n \"order\": {\n \"orderId\": \"1234\",\n \"ordername\": \"onetwothreefour\"\n }\n}\n\n...
[ 1, 1 ]
[]
[]
[ "dictionary", "key", "nested", "python" ]
stackoverflow_0074516642_dictionary_key_nested_python.txt
Q: TypeError: Missing 1 required positional argument: 'self' I can't get past the error: Traceback (most recent call last): File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module> p = Pump.getPumps() TypeError: getPumps() missing 1 required positional argument: 'self' I examined several tutorials but the...
TypeError: Missing 1 required positional argument: 'self'
I can't get past the error: Traceback (most recent call last): File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module> p = Pump.getPumps() TypeError: getPumps() missing 1 required positional argument: 'self' I examined several tutorials but there doesn't seem to be anything different from my code. The only...
[ "You need to instantiate a class instance here.\nUse\np = Pump()\np.getPumps()\n\nSmall example - \n>>> class TestClass:\n def __init__(self):\n print(\"in init\")\n def testFunc(self):\n print(\"in Test Func\")\n\n\n>>> testInstance = TestClass()\nin init\n>>> testInstance.testF...
[ 526, 96, 20, 10, 6, 4, 1, 0 ]
[]
[]
[ "constructor", "instance_methods", "python", "python_3.x", "self" ]
stackoverflow_0017534345_constructor_instance_methods_python_python_3.x_self.txt
Q: How to append data to an existing csv file in AWS S3 using python boto3 I have a csv file in s3 but I have to append the data to that file whenever I call the function but i am not able to do that, df = pd.DataFrame(data_list) bytes_to_write = df.to_csv(None, header=None, index=False).encode() file_name = "Words/w...
How to append data to an existing csv file in AWS S3 using python boto3
I have a csv file in s3 but I have to append the data to that file whenever I call the function but i am not able to do that, df = pd.DataFrame(data_list) bytes_to_write = df.to_csv(None, header=None, index=False).encode() file_name = "Words/word_dictionary.csv" # Not working the below line s3_client.put_object(Body=by...
[ "s3 has no append functionality. You need to read the file from s3, append the data in your code, then upload the complete file to the same key in s3.\nCheck this thread on the AWS forum for details\nThe code will probably look like:\ndf = pd.DataFrame(data_list)\nbytes_to_write = df.to_csv(None, header=None, index...
[ 5, 2, 1 ]
[]
[]
[ "amazon_s3", "boto3", "python" ]
stackoverflow_0061453620_amazon_s3_boto3_python.txt
Q: Python getpixel then click on described color in RGB I've found this code at stackoverflow color = (0, 137, 241) s = pyautogui.screenshot() for x in range(s.width): for y in range(s.height): if s.getpixel((x, y)) == color: pyautogui.click(x, y) # do something here break I'm cr...
Python getpixel then click on described color in RGB
I've found this code at stackoverflow color = (0, 137, 241) s = pyautogui.screenshot() for x in range(s.width): for y in range(s.height): if s.getpixel((x, y)) == color: pyautogui.click(x, y) # do something here break I'm creating some bot for a game that waits for its turn, picks ...
[ "The key here is to break both for loops once it met your condition. The problem with your code is it only stops on the current column of pixels that met your condition then continue to search on other columns of pixels because that initial loop hasn't been broken.\ncolor = (0, 137, 241)\ns = pyautogui.screenshot()...
[ 0 ]
[]
[]
[ "getpixel", "python", "screenshot" ]
stackoverflow_0062321751_getpixel_python_screenshot.txt
Q: Azureml - Why my environment image build status is always "already exists" I'm using custom Dockerfile to create environment for Azure machine learning. However everytime I run my code, I always get back "already exists" on the UI for my environment. I didn't find much documentation on this status which is why I'm...
Azureml - Why my environment image build status is always "already exists"
I'm using custom Dockerfile to create environment for Azure machine learning. However everytime I run my code, I always get back "already exists" on the UI for my environment. I didn't find much documentation on this status which is why I'm asking here. I assume that this means that an image with the same dockerfile ex...
[ "By default, all the environments will be working on Linux machine as it is from the docker image. With respect to the issue, we need to clear the cache of the images and then restart the run. Check out the below\nsyntaxes which need to be used.\ndocker-compose build --no-cache -> to clear the cache\nand don't forg...
[ 0 ]
[]
[]
[ "azure", "azure_machine_learning_service", "azureml_python_sdk", "azuremlsdk", "python" ]
stackoverflow_0074491717_azure_azure_machine_learning_service_azureml_python_sdk_azuremlsdk_python.txt
Q: How to plot average value lines and not every single value in Plotly First of all; sorry if what I am writing here is not up to stackoverflow standards, I am trying my best. I have a dataframe with around 18k rows and 89 columns with information about football players. For example I need to plot a line graph to vi...
How to plot average value lines and not every single value in Plotly
First of all; sorry if what I am writing here is not up to stackoverflow standards, I am trying my best. I have a dataframe with around 18k rows and 89 columns with information about football players. For example I need to plot a line graph to visualize the connection between age and overall rating of a player. But whe...
[ "It sounds like what you might want to do here is groupby() on \"age\" and then average on \"overall\" to create a final dataframe before plugging into that plotting function.\nRoughly,\nimport pandas as pd\n\ndata = {\n \"age\": [1, 1, 2, 2, 3, 3],\n \"overall\": [50, 100, 1, 1, 600, 700],\n # clarifies h...
[ 1 ]
[]
[]
[ "average", "line", "pandas", "plotly", "python" ]
stackoverflow_0074516853_average_line_pandas_plotly_python.txt
Q: How to remove a node from a dict using jsonpath-ng? In Python I have a list of dictionaries and I want to remove a given node from each dictionary in the list. I don't know anything about those dictionaries except they all have the same (unknown) schema. The node to be removed may be anywhere in the dictionaries a...
How to remove a node from a dict using jsonpath-ng?
In Python I have a list of dictionaries and I want to remove a given node from each dictionary in the list. I don't know anything about those dictionaries except they all have the same (unknown) schema. The node to be removed may be anywhere in the dictionaries and it is specified by a JSONPath expression. Example: Inp...
[ "Here's a naive solution which I've used in the past:\nimport copy\nimport jsonpath_ng.ext as jp\n\ndef remove_matched_element(path, spec):\n _new_spec = copy.deepcopy(spec)\n jep = jp.parse(path)\n for match in jep.find(spec):\n _t_path = \"$\"\n spec_path = _new_spec\n spec_path_pare...
[ 0 ]
[ "If you know the schema is fixed, you can simply remove the key like this\nl = [\n { \"top\": { \"lower\": 1, \"other\": 1 } },\n { \"top\": { \"lower\": 2, \"other\": 4 } },\n { \"top\": { \"lower\": 3, \"other\": 9 } }\n]\n\nfor d in l:\n del d[\"top\"][\"lower\"]\n\n" ]
[ -2 ]
[ "jsonpath", "jsonpath_ng", "python" ]
stackoverflow_0071500862_jsonpath_jsonpath_ng_python.txt
Q: Extract any possible combination of two strings Giving these two strings x = 'abc' y = 'dc'; How can I get this output -> set()={'ac', 'ab', 'cd', 'ad', 'cb', 'bd'} Getting ab from x then ac from x then ad from x and y ... If it is possible using only set functions without additional libraries. I tried this : ...
Extract any possible combination of two strings
Giving these two strings x = 'abc' y = 'dc'; How can I get this output -> set()={'ac', 'ab', 'cd', 'ad', 'cb', 'bd'} Getting ab from x then ac from x then ad from x and y ... If it is possible using only set functions without additional libraries. I tried this : X = set() for i in x: for j in y: X.add(...
[ "You can try the following code :\ndef get_combinations(x, y):\n r = set()\n\n def add(s):\n if s[::-1] not in r and s[0] != s[1]:\n r.add(s)\n\n c = set(x + y)\n for i in c:\n for j in c:\n if i <= j:\n add(i + j)\n\n return r\n\nThe inner add funct...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074516597_python.txt
Q: Bigquery converts my string field into integer while loading json file with Python {"number":"1234123"} I am assigning this data to my Bigquery table using bigquery.LoadJobConfig in python. The type of my number column in my bigquery table is string. When I do the load operation, it converts the data type in my bi...
Bigquery converts my string field into integer while loading json file with Python
{"number":"1234123"} I am assigning this data to my Bigquery table using bigquery.LoadJobConfig in python. The type of my number column in my bigquery table is string. When I do the load operation, it converts the data type in my bigquery table to integer. How can I solve this? The file type I loaded: json. job_config ...
[ "I recommend you to pass a BigQuery schema to prevent this situation, instead to use autodetect=True, example :\nfrom google.cloud import bigquery\n\n# Construct a BigQuery client object.\nclient = bigquery.Client()\n\n# TODO(developer): Set table_id to the ID of the table to create.\n# table_id = \"your-project.yo...
[ 0 ]
[]
[]
[ "google_bigquery", "json", "python" ]
stackoverflow_0074516188_google_bigquery_json_python.txt
Q: Fast Bitwise Get Column in Python Is there an efficient way to get an array of boolean values that are in the n-th position in bitwise array in Python? Create numpy array with values 0 or 1: import numpy as np array = np.array( [ [1, 0, 1], [1, 1, 1], [0, 0, 1], ] ) Compress size...
Fast Bitwise Get Column in Python
Is there an efficient way to get an array of boolean values that are in the n-th position in bitwise array in Python? Create numpy array with values 0 or 1: import numpy as np array = np.array( [ [1, 0, 1], [1, 1, 1], [0, 0, 1], ] ) Compress size by np.packbits: pack_array = np.pack...
[ "Besides some micro-optimisations, I dont believe that there is much that can be optimised here. There are also a few small mistakes in your code:\n\n@njit(nopython=True) is saying the same thing twice (the n in njit already stands for nopython mode.) simply @njit or @jit(nopython=True) should be used\nfastMath is ...
[ 2 ]
[]
[]
[ "bit", "bit_manipulation", "numba", "numpy", "python" ]
stackoverflow_0074512005_bit_bit_manipulation_numba_numpy_python.txt
Q: Python Function to test ping I'm trying to create a function that I can call on a timed basis to check for good ping and return the result so I can update the on-screen display. I am new to python so I don't fully understand how to return a value or set a variable in a function. Here is my code that works: import ...
Python Function to test ping
I'm trying to create a function that I can call on a timed basis to check for good ping and return the result so I can update the on-screen display. I am new to python so I don't fully understand how to return a value or set a variable in a function. Here is my code that works: import os hostname = "google.com" respons...
[ "It looks like you want the return keyword\ndef check_ping():\n hostname = \"taylor\"\n response = os.system(\"ping -c 1 \" + hostname)\n # and then check the response...\n if response == 0:\n pingstatus = \"Network Active\"\n else:\n pingstatus = \"Network Error\"\n \n return pin...
[ 42, 20, 14, 5, 2, 1, 0 ]
[ "This is my version of check ping function. May be if well be usefull for someone:\ndef check_ping(host):\nif platform.system().lower() == \"windows\":\nresponse = os.system(\"ping -n 1 -w 500 \" + host + \" > nul\")\nif response == 0:\nreturn \"alive\"\nelse:\nreturn \"not alive\"\nelse:\nresponse = os.system(\"pi...
[ -2 ]
[ "function", "python", "return", "variables" ]
stackoverflow_0026468640_function_python_return_variables.txt
Q: background function in Python I've got a Python script that sometimes displays images to the user. The images can, at times, be quite large, and they are reused often. Displaying them is not critical, but displaying the message associated with them is. I've got a function that downloads the image needed and saves ...
background function in Python
I've got a Python script that sometimes displays images to the user. The images can, at times, be quite large, and they are reused often. Displaying them is not critical, but displaying the message associated with them is. I've got a function that downloads the image needed and saves it locally. Right now it's run inli...
[ "Do something like this:\ndef function_that_downloads(my_args):\n # do some long download here\n\nthen inline, do something like this:\nimport threading\ndef my_inline_function(some_args):\n # do some stuff\n download_thread = threading.Thread(target=function_that_downloads, name=\"Downloader\", args=some_...
[ 165, 7, 6, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007168508_multithreading_python.txt
Q: nbdev_export fails - TypeError: _default_exp_() takes 3 positional arguments but 4 were given I'm very new with nbdev. I have created nbdev environment, worked on one notebook inside "nbs" folder. However, I had to organize the notebooks on "nbs" and I created new folder to contain some of these notebooks. (for ex...
nbdev_export fails - TypeError: _default_exp_() takes 3 positional arguments but 4 were given
I'm very new with nbdev. I have created nbdev environment, worked on one notebook inside "nbs" folder. However, I had to organize the notebooks on "nbs" and I created new folder to contain some of these notebooks. (for example, I have folder name "nbs" and then inside it I have several notebooks and folders such as "we...
[ "In the end the problem was inside one of the notebooks.\nThe first block had problem with the deafult_exp:\n##this is error:\n#|default_exp my notebook\n\n##this is correct (with _ and without space)\n#|default_exp my_notebook\n\nThe way to debug it was to take out of nbs folder all the notebooks and then try one ...
[ 0 ]
[]
[]
[ "bash", "jupyter_notebook", "nbdev", "python" ]
stackoverflow_0074516831_bash_jupyter_notebook_nbdev_python.txt
Q: how to i get os.listdir with follow the file? enter image description here enter image description here Hello, I have encountered a problem. When I use os.listdir, I hope that the effect of picture 1 will appear, but the effect of python is reversed. I would like to ask how can I get the data and want the effect o...
how to i get os.listdir with follow the file?
enter image description here enter image description here Hello, I have encountered a problem. When I use os.listdir, I hope that the effect of picture 1 will appear, but the effect of python is reversed. I would like to ask how can I get the data and want the effect of picture 1
[ "import os\nfiles = os.listdir()[::-1]\nprint(files)\n\nsomelist[::-1] reverses the list\nstarts from the end towards the first taking each element as step=-1\nSee this answer\n", "Do not post images of text (your second image). Use reverse()\nfiles = os.listdir()\nfiles.reverse()\n\nIt is unclear how the files a...
[ 0, 0 ]
[]
[]
[ "list", "python", "python_os" ]
stackoverflow_0074517276_list_python_python_os.txt
Q: iterate through slices of a numpy array I have a pandas dataframe e.g. df = pd.DataFrame({'dim1': ['a', 'a', 'b', 'b'], 'dim2': ['x', 'y', 'x', 'y'], 'val': [2, 4, 6, 8]}) This can represent an array of N dimensions, I have chosen two here for simplicity. I will convert this to a numpy array and then want to iter...
iterate through slices of a numpy array
I have a pandas dataframe e.g. df = pd.DataFrame({'dim1': ['a', 'a', 'b', 'b'], 'dim2': ['x', 'y', 'x', 'y'], 'val': [2, 4, 6, 8]}) This can represent an array of N dimensions, I have chosen two here for simplicity. I will convert this to a numpy array and then want to iterate and sum over this numpy array for each 's...
[ "looking to your data frame it feels like your headers are misleading. the dimesion is x and y. In this case you have unorganized data set. So if you want to have 4 dimensional you can still keep structure of your data frame just have extra 2 rows for each a and b. like now you have a: x, y. Then you can have a: x,...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074517286_arrays_numpy_python.txt
Q: How to run batch command in my python script? I have to run a one-line batch command in my Python script. Currently, I am saving my command in a .bat file and executing the .bat file using the subprocess. But I want to omit the .bat file and directly include the command in my python script. Because I might need to...
How to run batch command in my python script?
I have to run a one-line batch command in my Python script. Currently, I am saving my command in a .bat file and executing the .bat file using the subprocess. But I want to omit the .bat file and directly include the command in my python script. Because I might need to use different bat files for different use cases. I...
[ "your question is ambiguous. if i interpreted it correctly, you can use os.system\nos.system is a function which executes commands from console.\nimport os\n\nos.system('\"C:\\Program Files (x86)\\temp\\FL.B5.exe\" /s /a \"C:\\Users\\kuk\\Downloads\\B5+Typ B.2.asc\" /o \"C:\\Users\\kuk\\Download\\B5+Typ B.2.docx\"'...
[ 0, 0 ]
[]
[]
[ "batch_file", "python" ]
stackoverflow_0074516912_batch_file_python.txt
Q: AssertionError: Signal dimention should be of the format of (N,) but it is (743424, 2) instead For my ML project, I'm using a Model to which I give a video and audio as input file to detect the synthetic voice in the video. But it returns an error on the audio_processing() function: Code for audio_processing() def...
AssertionError: Signal dimention should be of the format of (N,) but it is (743424, 2) instead
For my ML project, I'm using a Model to which I give a video and audio as input file to detect the synthetic voice in the video. But it returns an error on the audio_processing() function: Code for audio_processing() def audio_processing(wav_file, verbose=True): rate, sig = wav.read(wav_file) if verbose: ...
[ "From the looks of it, your audio file contains two channels, which you can check by looking at the shape of the array that the wav.read function returns: sig.shape.\nThe speechpy.feature.mfcc function expects a single-channel audio.\nI believe what you can do is to convert your audio to a single channel, for examp...
[ 1 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "scipy", "tensorflow" ]
stackoverflow_0074516426_deep_learning_machine_learning_python_scipy_tensorflow.txt
Q: Video streaming with OpenCV and flask I have a flask web application that reads my camera and is supposed to display it in my web browser. But instead of displaying it, I am getting a blank image as shown here: py file import cv2 import numpy from flask import Flask, render_template, Response, stream_with_context...
Video streaming with OpenCV and flask
I have a flask web application that reads my camera and is supposed to display it in my web browser. But instead of displaying it, I am getting a blank image as shown here: py file import cv2 import numpy from flask import Flask, render_template, Response, stream_with_context, Request video = cv2.VideoCapture(0) app ...
[ "\nRemove whitespaces from boundary = frame\nRestart server\n\ncode:\ndef video_feed():\n return Response(video_stream(), mimetype= 'multipart/x-mixed-replace; boundary=frame')\n\n" ]
[ 0 ]
[]
[]
[ "flask", "opencv", "python", "video_capture" ]
stackoverflow_0074515443_flask_opencv_python_video_capture.txt
Q: Why an uninstalled module is still importable in Python I want to get rid of a module in Python and I use the "pip uninstall " command. However, for some reason the module is still importable! I am using VS code on a Mac OS. Here is the screenshot of the code: As you can see, the yellow warning says the polars pa...
Why an uninstalled module is still importable in Python
I want to get rid of a module in Python and I use the "pip uninstall " command. However, for some reason the module is still importable! I am using VS code on a Mac OS. Here is the screenshot of the code: As you can see, the yellow warning says the polars package is not installed (because I already excuted the uninsta...
[ "1 -Try to use %pip, maybe you are using virtual machines and %pip is 'magic' command that actually runs commands to uninstall the same package across all machines in the cluster\n2- Script wrappers installed by python setup.py develop.\nYou need to remove all files manually, and also undo any other stuff that ins...
[ 0 ]
[ "All you have to do is restart your kernel.\nUse this button to restart the kernel\nhttps://i.stack.imgur.com/S9Q6L.png\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0074517161_python.txt
Q: How to upload folder on Google Cloud Storage using Python API I have successfully uploaded single text file on Google Cloud Storage. But when i try to upload whole folder, It gives permission denied error. filename = "d:/foldername" #here test1 is the folder. Error: Traceback (most recent call last): File "te...
How to upload folder on Google Cloud Storage using Python API
I have successfully uploaded single text file on Google Cloud Storage. But when i try to upload whole folder, It gives permission denied error. filename = "d:/foldername" #here test1 is the folder. Error: Traceback (most recent call last): File "test1.py", line 142, in <module> upload() File "test1.py", lin...
[ "This works for me. Copy all content from a local directory to a specific bucket-name/full-path (recursive) in google cloud storage:\nimport glob\nfrom google.cloud import storage\n\ndef upload_local_directory_to_gcs(local_path, bucket, gcs_path):\n assert os.path.isdir(local_path)\n for local_file in glob.gl...
[ 16, 8, 4, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0025599503_django_google_app_engine_python.txt
Q: Python insert element based on condition I'm trying to make a list where based on a condition, an element may or may not exist. For example, if it's true, the list is [1, 2, 3], and otherwise, it's [1, 3]. Currently, what I could do is either initialize the list and call .insert or .append the elements individuall...
Python insert element based on condition
I'm trying to make a list where based on a condition, an element may or may not exist. For example, if it's true, the list is [1, 2, 3], and otherwise, it's [1, 3]. Currently, what I could do is either initialize the list and call .insert or .append the elements individually, or alternatively, I could do something like...
[ "I'm also used to doing this in Perl with a pattern like:\nmy @arr = (1, (condition? (2) : ()), 3);\n\nIn Python you can get somewhat close to this with a solution that's pretty close to what you have with the list +, but uses * unpacking to avoid a lot of the other arrays:\narr = [1, *((2,) if condition else ()), ...
[ 7, 4, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0056150856_list_python.txt
Q: How do I increase the fontsize of the scale tick in matplotlib? I am trying to increase the fontsize of the scale tick in a matplotlib plot when using scientific notation for the tick labels. import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 100, 100) y = np.power(x, 3) plt.ticklabel_forma...
How do I increase the fontsize of the scale tick in matplotlib?
I am trying to increase the fontsize of the scale tick in a matplotlib plot when using scientific notation for the tick labels. import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 100, 100) y = np.power(x, 3) plt.ticklabel_format( axis="y", style="sci", ...
[ "You could try using plt.rc('font', size=30) to set the font size of everything on the plot?\nimport matplotlib.pyplot as plt \nimport numpy as np \n\nx = np.linspace(0, 100, 100)\ny = np.power(x, 3) \n\nplt.ticklabel_format(\n axis=\"y\",\n style=\"sci\",\n ...
[ 1, 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0070880042_matplotlib_plot_python.txt
Q: Different results in ndiffs pmdarima (Time Series) I am analyzing a time series. It clearly has a trend and a seasonal component. When I do the adf root test I get a p-value of 0.98, meaning it's non stationary. But when I do the ndiffs in pmdarima, Philippe Perron and Dickey Fuller returns a 0, when clearly has a...
Different results in ndiffs pmdarima (Time Series)
I am analyzing a time series. It clearly has a trend and a seasonal component. When I do the adf root test I get a p-value of 0.98, meaning it's non stationary. But when I do the ndiffs in pmdarima, Philippe Perron and Dickey Fuller returns a 0, when clearly has a trend. KPSS return 1, which seems more accurate. Happen...
[ "Not sure if helps but I found this example where the approach is to take the max result of these tests and continue with it: https://notebook.community/tgsmith61591/pyramid/examples/stock_market_example\nfrom pmdarima.arima import ndiffs\n\nkpss_diffs = ndiffs(y_train, alpha=0.05, test='kpss', max_d=6)\nadf_diffs...
[ 0 ]
[]
[]
[ "pmdarima", "python", "time_series" ]
stackoverflow_0063859508_pmdarima_python_time_series.txt
Q: Python Sending email using SMTP - target machine actively refused connection I am trying to send email internally within work using the smtplib package in Python. I am running this script behind a VPN using the same proxy settings for R and Spyder. I use the following code which was adapted from mkyoung.com import...
Python Sending email using SMTP - target machine actively refused connection
I am trying to send email internally within work using the smtplib package in Python. I am running this script behind a VPN using the same proxy settings for R and Spyder. I use the following code which was adapted from mkyoung.com import smtplib to = 'foo@foo-corporate.com' corp_user = 'foo@foo-corporate.com' corp_pw...
[ "Seems like the context is not needed at all.\nThis is an example using TLS. Give it a try, at least in my environment, this worked.\nimport smtplib\n\nsmtp_server = 'mail.example.com'\nport = 587 # For starttls\nsender_email = \"from@mail.com\"\nreceiver_email = 'to@mail.com'\npassword = r'password'\nmessage = f'...
[ 1, 0 ]
[]
[]
[ "email", "python", "r" ]
stackoverflow_0074478118_email_python_r.txt
Q: Why cumulative sum has a drop I have a certain feature in my data which looks like this: I'm trying to introduce cumulative sum this column in the DataFrame as following (the feature is int64 type): df['Cumulative'] = df['feature'].cumsum() But for unknown reason I have a drop in this function which is weird sinc...
Why cumulative sum has a drop
I have a certain feature in my data which looks like this: I'm trying to introduce cumulative sum this column in the DataFrame as following (the feature is int64 type): df['Cumulative'] = df['feature'].cumsum() But for unknown reason I have a drop in this function which is weird since the min number in the original co...
[ "Like in the comments suggested, sorting first and after that build the cumulative sum.\nDid you try it like this:\ndf = df.sort_values(by='Date') #where \"Date\" is the column name of the values on the x-axis\ndf['cumulative'] = df['feature'].cumsum()\n\n" ]
[ 1 ]
[]
[]
[ "cumulative_sum", "dataframe", "pandas", "python" ]
stackoverflow_0074516792_cumulative_sum_dataframe_pandas_python.txt
Q: how to handle POST request with flask At first I should say that I searched a lot and think that there's no problem with the code but it doesn't work. I send a dict by post method in the local host through this code: `<body> <div class="middle"> <form action="insert.py" method="post" > <input type="n...
how to handle POST request with flask
At first I should say that I searched a lot and think that there's no problem with the code but it doesn't work. I send a dict by post method in the local host through this code: `<body> <div class="middle"> <form action="insert.py" method="post" > <input type="number" class="num" name="temp" placeh...
[ "You are supposed to post the form to some endpoint with action. Please pay attention to where you are posting to. insert.py is not a valid endpoint in your application, on the other hand /POST probably is.\n<form action=\"/POST\" method=\"post\">\n...\n\n" ]
[ 0 ]
[]
[]
[ "flask", "http", "http_post", "python" ]
stackoverflow_0074510740_flask_http_http_post_python.txt
Q: KafkaSource connection to Confluent Kafka (with SSL & SchemaRegistry) I tried to connect to Confluent Kafka with KafkaSource (from MLRun) and I used historically this easy code: # code with usage 'kafka-python>=2.0.2' from kafka import KafkaProducer, KafkaConsumer consumer = KafkaConsumer( 'ak47-data.v1', ...
KafkaSource connection to Confluent Kafka (with SSL & SchemaRegistry)
I tried to connect to Confluent Kafka with KafkaSource (from MLRun) and I used historically this easy code: # code with usage 'kafka-python>=2.0.2' from kafka import KafkaProducer, KafkaConsumer consumer = KafkaConsumer( 'ak47-data.v1', bootstrap_servers =[ 'cpkafka01.eu.prod:9092', 'cpkafka02...
[ "Let me share function code for KafkaSource (for MLRun>=1.1.0). You can specific certificate (see rootca.crt) and list of kafka topics also.\nfrom mlrun.datastore.sources import KafkaSource\n\n# certificate\nwith open('/v3io/bigdata/rootca.crt') as x: \n caCert = x.read()\n\n# definition of KafkaSource\nkafka_so...
[ 1 ]
[]
[]
[ "confluent_kafka_python", "mlrun", "python" ]
stackoverflow_0074511987_confluent_kafka_python_mlrun_python.txt
Q: Repost deleted images to discord using a bot I have written a discord.py bot on repl.it that makes one able to quote on text. i will spare you on the code for this one, since it does not help in answerign the question, but basically, it splits a send message with a parameter and puts these splits into an embed. To...
Repost deleted images to discord using a bot
I have written a discord.py bot on repl.it that makes one able to quote on text. i will spare you on the code for this one, since it does not help in answerign the question, but basically, it splits a send message with a parameter and puts these splits into an embed. To make the channel look clean, the bot then deletes...
[ "This happens because you are deleting the message the image is sent in. Discord sees the relevant message is gone and removes the file from its servers to save space.\nYou need to save the image either locally or in memory then upload it to either discord's CDN or a third party CDN and refer to it in your embed.\n...
[ 0 ]
[]
[]
[ "discord", "discord.py", "image", "python", "repl.it" ]
stackoverflow_0074508070_discord_discord.py_image_python_repl.it.txt
Q: NameError: name 'sosete' is not defined I try to get the len of all products displayed on this site https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html Using this code import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrom...
NameError: name 'sosete' is not defined
I try to get the len of all products displayed on this site https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html Using this code import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdri...
[ "Page is being loaded dynamically, as you scroll. here is way to (correctly) define the product range, scroll the page, wait for them to load, and print them out:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selen...
[ 1 ]
[]
[]
[ "python", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074517086_python_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: ModuleNotFoundError: No module named '_ctypes' Mac M1 While installing some libraries you may find the issue ModuleNotFoundError: No module named '_ctypes' A: Short version: Try installing python 3.7.13 with pyenv: pyenv install 3.7.13, and if that does not work, try python 3.7.12 (pyenv install 3.7.12). The pye...
ModuleNotFoundError: No module named '_ctypes' Mac M1
While installing some libraries you may find the issue ModuleNotFoundError: No module named '_ctypes'
[ "Short version:\nTry installing python 3.7.13 with pyenv:\npyenv install 3.7.13, and if that does not work, try python 3.7.12 (pyenv install 3.7.12).\nThe pyenv release 2.2.3 addresses the compilation problems for 3.6.15/3.7.12 on M1 macs, specifically for ctypes.\nLong version:\nThe underlying cause for the _ctype...
[ 17, 11, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0069496504_macos_python.txt
Q: Django `bulk_create` with related objects I have a Django system that runs billing for thousands of customers on a regular basis. Here are my models: class Invoice(models.Model): balance = models.DecimalField( max_digits=6, decimal_places=2, ) class Transaction(models.Model): amount = ...
Django `bulk_create` with related objects
I have a Django system that runs billing for thousands of customers on a regular basis. Here are my models: class Invoice(models.Model): balance = models.DecimalField( max_digits=6, decimal_places=2, ) class Transaction(models.Model): amount = models.DecimalField( max_digits=6, ...
[ "You could bulk_create all the Invoice objects, refresh them from the db, so that they all have ids, create the Transaction objects for all the invoices and then also save them with bulk_create. All of this can be done inside a single transaction.atomic context. \nAlso, specifically for django 1.10 and postrgres, l...
[ 12, 2, 0 ]
[]
[]
[ "bulkinsert", "django", "django_models", "python" ]
stackoverflow_0040789962_bulkinsert_django_django_models_python.txt
Q: Python - ModuleNotFoundError- No module named 'XXX' I have folder hierarchy as: ->Project Folder -Main.py ->modules Folder ->PowerSupply Folder - PowerSupply.py - SerialPort.py In Main.py I am importing PowerSupply.py with following command from modules.PowerSupply.PowerSupply import * Then i...
Python - ModuleNotFoundError- No module named 'XXX'
I have folder hierarchy as: ->Project Folder -Main.py ->modules Folder ->PowerSupply Folder - PowerSupply.py - SerialPort.py In Main.py I am importing PowerSupply.py with following command from modules.PowerSupply.PowerSupply import * Then inside of PowerSupply.py, I am importing SerilPort.py with...
[ "Well described here: https://docs.python.org/3/reference/import.html\nWhen importing modules, you need to stick to hierarchy.\nIf modules folder is part of hierarchy, you cannot skip it.\nYou could solve it with adding PowerSupply folder to Python search path.\n", "Inside Powersupply.py try explicit relative imp...
[ 1, 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074517208_python_visual_studio_code.txt
Q: Python: transforming complex data for a Sankey plot I am trying to produce a Sankey plot of the events that take one week before and one week after an index event of a patient. Imagine I have the following data frame: df = patient_id start_date end_date Value Index_event_date Value_Index_event 1 2...
Python: transforming complex data for a Sankey plot
I am trying to produce a Sankey plot of the events that take one week before and one week after an index event of a patient. Imagine I have the following data frame: df = patient_id start_date end_date Value Index_event_date Value_Index_event 1 28-12-1999 02-01-2000 A 01-01-2000 X 2 ...
[ "With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"patient_id\": [1, 2, 3],\n \"start_date\": [\"28-12-1999\", \"28-12-2000\", \"28-12-2001\"],\n \"end_date\": [\"02-01-2000\", \"02-12-2001\", \"02-01-2002\"],\n \"Value\": [\"A\", \"B\", \"A\"],\n ...
[ 1 ]
[]
[]
[ "pandas", "python", "sankey_diagram" ]
stackoverflow_0074419763_pandas_python_sankey_diagram.txt
Q: Null Space of Large Sparse Matrix I am working on a project that requires me to compute the null space of fairly large sparse matrices (2400 x 2400) multiple times. So far I have been using the scipy library to do so (does not take in account that matrix is sparse), although I am sure there must be a faster way. L...
Null Space of Large Sparse Matrix
I am working on a project that requires me to compute the null space of fairly large sparse matrices (2400 x 2400) multiple times. So far I have been using the scipy library to do so (does not take in account that matrix is sparse), although I am sure there must be a faster way. Looking around I found lots of publicati...
[ "Look in scipy.sparse.linalg there seems to be everything you need to find the null space.\nFor instance:\nhttps://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.spsolve.html#scipy.sparse.linalg.spsolve\n" ]
[ 0 ]
[]
[]
[ "matrix", "performance", "python" ]
stackoverflow_0074517598_matrix_performance_python.txt
Q: Detecting unexpected type conversion in python I have a piece of complex Python code involving the using of 32-bit numerical values (for saving memory and bandwidth). But later I discovered many of these 32-bit numbers were implicitly converted to 64-bit in some high-level functions. For example, the sum function,...
Detecting unexpected type conversion in python
I have a piece of complex Python code involving the using of 32-bit numerical values (for saving memory and bandwidth). But later I discovered many of these 32-bit numbers were implicitly converted to 64-bit in some high-level functions. For example, the sum function, by default, can transforms a 32bit array to a 64bit...
[ "I think you are nearly there to be honest.\noriginal_dtype = x32.dtype\n\nnew_dtype = sum(x32, start=np.float32(0))).dtype\n\nassert new_dtype == original_dtype, f\"dtypes differ, {new_dtype=} != {original_dtype=}\"\n\nTo use this method globally, you can write something like:\ndef type_checker_func(func,input_arr...
[ 1 ]
[]
[]
[ "python", "type_conversion" ]
stackoverflow_0074516195_python_type_conversion.txt
Q: Python Pandas Read from column A & B instead of column name I'm relativley new to python I have a excel file where i can read,Column A "url" and Column B "name". In the future the columns will have no "column name" so i need it to read from Column A directly and column B and start iterating from cell 1. I tried u...
Python Pandas Read from column A & B instead of column name
I'm relativley new to python I have a excel file where i can read,Column A "url" and Column B "name". In the future the columns will have no "column name" so i need it to read from Column A directly and column B and start iterating from cell 1. I tried using index_col(0) but can't really seem to get the hang of it. Th...
[ "You can set header=None as an argument of pandas.read_excel and give names to your columns.\nTry this :\nimport requests\nimport pandas as pd\n \ndf = pd.read_excel(r'C:\\Users\\exdata1.xlsx', header=None, names=['url', 'name'])\n\nfor index, row in df.iterrows():\n url = row['url']\n file_name = url.split(...
[ 2, 0 ]
[]
[]
[ "dataframe", "excel", "loops", "pandas", "python" ]
stackoverflow_0074517443_dataframe_excel_loops_pandas_python.txt
Q: list of entries (files and folders) in a directory tree by os.scandir() in Python I have used "os.walk()" to list all subfolders and files in a directory tree , but heard that "os.scandir()" does the job up to 2X - 20X faster. So I tried this code: def tree2list (directory:str) -> list: import os tree = []...
list of entries (files and folders) in a directory tree by os.scandir() in Python
I have used "os.walk()" to list all subfolders and files in a directory tree , but heard that "os.scandir()" does the job up to 2X - 20X faster. So I tried this code: def tree2list (directory:str) -> list: import os tree = [] counter = 0 for i in os.scandir(directory): if i.is_dir(): ...
[ "Using generators (yield, yield from) allows to manage the recursion with concise code:\nfrom pprint import pprint\nfrom typing import Iterator, Tuple\n\n\ndef tree2list(directory: str) -> Iterator[Tuple[str, str, str]]:\n import os\n\n for i in os.scandir(directory):\n if i.is_dir():\n yiel...
[ 2, 2, 0 ]
[]
[]
[ "python", "python_3.x", "scandir" ]
stackoverflow_0072938098_python_python_3.x_scandir.txt
Q: AWS CDK can't find ARN of dead letter queue when creating SQS I'm trying to create an SQS with a dead letter queue but when I deploy AWS says it can't find the ARN for the dead letter queue. My code is below for my SQS stack. class SqsCdkStack(Stack): def __init__(self, scope: Construct, construct_id: str, app...
AWS CDK can't find ARN of dead letter queue when creating SQS
I'm trying to create an SQS with a dead letter queue but when I deploy AWS says it can't find the ARN for the dead letter queue. My code is below for my SQS stack. class SqsCdkStack(Stack): def __init__(self, scope: Construct, construct_id: str, app_name: str, **kwargs) -> None: super().__init__(scope, con...
[ "CloudFormation should know to create the DLQ before the Queue, but try making the dependency explicit with:\nself.sqs_queue.node.add_dependency(dead_letter_queue)\n\n" ]
[ 0 ]
[]
[]
[ "amazon_sqs", "amazon_web_services", "aws_cdk", "python" ]
stackoverflow_0074489043_amazon_sqs_amazon_web_services_aws_cdk_python.txt
Q: In pyspark how to check the format a pyspark was read in? Delta vs parquet I have function that reads in file which could either be in delta or parquet format. def getData(filename,fileFormat) if data_format == "parquet": return spark.read.parquet(filename) elif data_format == "delta": ...
In pyspark how to check the format a pyspark was read in? Delta vs parquet
I have function that reads in file which could either be in delta or parquet format. def getData(filename,fileFormat) if data_format == "parquet": return spark.read.parquet(filename) elif data_format == "delta": return spark.read.format("delta").load(filename) I then use the returned pyspar...
[ "You can't do that with Spark, but you can use dbutils.fs to check if delta metadata file exists\n", "You can do it with the isDeltaTable method from the Delta Lake API.\n\nhttps://docs.delta.io/latest/api/python/index.html\nhttps://docs.delta.io/latest/api/python/index.html#delta.tables.DeltaTable.isDeltaTable\n...
[ 0, 0 ]
[]
[]
[ "apache_spark_sql", "azure_databricks", "pyspark", "python" ]
stackoverflow_0071288669_apache_spark_sql_azure_databricks_pyspark_python.txt
Q: libGL.so.1: cannot open shared object file: No such file or directory - even when using open cv headless I have a Docker image I am building to run on AWS Lambda. One of the dependencies is opencv, but I am using the headless version. My requirements file is: absl-py==1.0.0 attrs==21.4.0 cycler==0.11.0 flatbuffers...
libGL.so.1: cannot open shared object file: No such file or directory - even when using open cv headless
I have a Docker image I am building to run on AWS Lambda. One of the dependencies is opencv, but I am using the headless version. My requirements file is: absl-py==1.0.0 attrs==21.4.0 cycler==0.11.0 flatbuffers==2.0 fonttools==4.33.3 imageio==2.19.2 jmespath==1.0.0 kiwisolver==1.4.2 matplotlib==3.5.2 mediapipe==0.8.10 ...
[ "I needed to update my container repositories and install a dependency, libgl1-mesa-glx:\nRUN apt update\n# Dependency for opencv-python (cv2). `import cv2` raises ImportError: libGL.so.1: cannot open shared object file: No such file or directory\n# Solution from https://askubuntu.com/a/1015744\nRUN apt install -y ...
[ 0 ]
[]
[]
[ "aws_lambda", "docker", "opencv", "python" ]
stackoverflow_0072365190_aws_lambda_docker_opencv_python.txt