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: recursion exceeding the limit while iam trying to split my list into length of one iam trying to write merge sort but its not working why here when i run this code it's not splitting all the list and it is just repeating this form ID_list=[5,8,9] def merge_sort(Id_list): #define middle middle_index=len(ID_list)...
recursion exceeding the limit while iam trying to split my list into length of one
iam trying to write merge sort but its not working why here when i run this code it's not splitting all the list and it is just repeating this form ID_list=[5,8,9] def merge_sort(Id_list): #define middle middle_index=len(ID_list)//2 #split array into two parts (copies: left and right) left=ID_list[:middle_index] ...
[ "ID_list=[5,8,9]\n\nSo you want to split it in 1-value lists?\nresult = [[element] for element in ID_list]\n\nNothing hard.\n", "You mix up the variable identifiers. You have global list called ID_list and the parameter of the parameter function Id_list. The problem is that you never call the parameter of the fun...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074244120_python.txt
Q: Trying to compare each element location, and if the location are the same return false, otherwise return true I have tried to write here a code that takes a random permutation from random_list and compares each element's location. I do get a False and True result but not sure that my code goes through the list and...
Trying to compare each element location, and if the location are the same return false, otherwise return true
I have tried to write here a code that takes a random permutation from random_list and compares each element's location. I do get a False and True result but not sure that my code goes through the list and compares every single element. Any suggestion will be helpful. def not_correct_order(n): randomList = random...
[ "Thanks to Tim Roberts, he helped me to figure out my answer. by using a.any() I could compare my list to its position and if any element was not in the correct position it gives back a false.\ndef not_correct_order(n):\n randomList = random_List(n)\n\n return any(i==j for i,j in enumerate(randomList))\n\n" ]
[ 1 ]
[]
[]
[ "physics", "probability", "python" ]
stackoverflow_0074199617_physics_probability_python.txt
Q: Selenium: Process unexpectedly closed with status 11 Running this python script with selenium result in an error. Python script: "First selenium script" from selenium import webdriver from selenium.webdriver.firefox.service import Service as FirefoxService from webdriver_manager.firefox import GeckoDriverManager ...
Selenium: Process unexpectedly closed with status 11
Running this python script with selenium result in an error. Python script: "First selenium script" from selenium import webdriver from selenium.webdriver.firefox.service import Service as FirefoxService from webdriver_manager.firefox import GeckoDriverManager driver = webdriver.Firefox( service=FirefoxService(ex...
[ "I'm currently using chrome instead of firefox, everything is working fine.\n" ]
[ 0 ]
[]
[]
[ "firefox", "geckodriver", "linux", "python", "selenium" ]
stackoverflow_0074238792_firefox_geckodriver_linux_python_selenium.txt
Q: Changing the same element in all lists in a 2D-array When doing something like for example: arr = [[0]*3]*3 arr[1][0] = 4 It will alter the first element in all three lists. Is this because we are only making a copy of the first list and the elements share the same pointer in memory? That is, the first list is fo...
Changing the same element in all lists in a 2D-array
When doing something like for example: arr = [[0]*3]*3 arr[1][0] = 4 It will alter the first element in all three lists. Is this because we are only making a copy of the first list and the elements share the same pointer in memory? That is, the first list is for example: [A,A+C,A+2C] where C is the Offset and A is the...
[ "Exactly. The repeat command *3 Makes a shallow copy, in all instances. Something to watch out for. I personally have been bitten by this in initialization, e.g.\na, b = []*2\n\nMakes a and b refer to the same object.\n" ]
[ 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074244207_arrays_python.txt
Q: Open AI gym render function not working(MACbook pro M1 max chip) Try to run the cartpole environment on my macbook pro and the render function cannot work as there shows no animation about the cart. However, the code seems to work and my DQN can train under the environment. Still no animation after trying some tip...
Open AI gym render function not working(MACbook pro M1 max chip)
Try to run the cartpole environment on my macbook pro and the render function cannot work as there shows no animation about the cart. However, the code seems to work and my DQN can train under the environment. Still no animation after trying some tips provided by stack overflow. Codes as below import gym env = gym.make...
[ "I don't know the particular reason why this happens, but for latest chipsets (m1,m2,m1 pro,m1 max) are not rendering the environment of the gym while the algorithm works just as fine as normal. Fortunately I have found one fix for this problem. For that, we need to use miniconda.\n\ninstall miniconda in your MacBo...
[ 0 ]
[]
[]
[ "animation", "dqn", "macos", "openai_gym", "python" ]
stackoverflow_0073760009_animation_dqn_macos_openai_gym_python.txt
Q: How to find symmetric mean absolute error in python? How can I calculate symmetric mean absolute error in python using numpy or pandas? Is there are metric present in scikit sklearn ? Example data: Actual value: 2,3,4,5,6,7,8,9 Forecast value: 1,3,5,4,6,7,10,7 Formula for SMAPE see screenshot below: How can I ...
How to find symmetric mean absolute error in python?
How can I calculate symmetric mean absolute error in python using numpy or pandas? Is there are metric present in scikit sklearn ? Example data: Actual value: 2,3,4,5,6,7,8,9 Forecast value: 1,3,5,4,6,7,10,7 Formula for SMAPE see screenshot below: How can I do it in python using pandas or numpy and calculate SMAPE....
[ "It's pretty straightforward to convert the equation to numpy\nimport numpy as np\n\ndef smape(A, F):\n return 100/len(A) * np.sum(2 * np.abs(F - A) / (np.abs(A) + np.abs(F)))\n\nA = np.array([2,3,4,5,6,7,8,9])\nF = np.array([1,3,5,4,6,7,10,7])\nprint(smape(A, F))\n\n", "Try the following.\ndef mape(row):\n ...
[ 36, 1, 1, 0 ]
[]
[]
[ "numpy", "python", "statistics" ]
stackoverflow_0051439892_numpy_python_statistics.txt
Q: OpenCV python process dead . I am using anaconda 4.8.3, spyder 4.1.3 and opencv-python 4.2.0.34. When I am trying to read simple image, then the python process is suspend. when I am trying to read the video there is the same problem. After each run of program I must restart the kernel. my code for image: import ...
OpenCV python process dead
. I am using anaconda 4.8.3, spyder 4.1.3 and opencv-python 4.2.0.34. When I am trying to read simple image, then the python process is suspend. when I am trying to read the video there is the same problem. After each run of program I must restart the kernel. my code for image: import cv2 img = cv2.imread("lena.png"...
[ "Code for Image\nimport cv2\n\nimg = cv2.imread(\"lena.png\")\ncv2.imshow(\"Output\",img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nCode for video\nimport cv2\nframeWidth = 640\nframeHeight = 480\ncap = cv2.VideoCapture(\"test.mp4\")\nwhile True:\n success, img = cap.read()\n img = cv2.resize(img, (frameWid...
[ 0 ]
[]
[]
[ "opencv", "python", "spyder" ]
stackoverflow_0062342589_opencv_python_spyder.txt
Q: How to determine whether java is installed on a system through python? Using Python, I want to know whether Java is installed. A: There is no 100% reliable / portable way to do this, but the following procedure should give you some confidence that Java has been installed and configured properly (on a Linux): Ch...
How to determine whether java is installed on a system through python?
Using Python, I want to know whether Java is installed.
[ "There is no 100% reliable / portable way to do this, but the following procedure should give you some confidence that Java has been installed and configured properly (on a Linux):\n\nCheck that the \"JAVA_HOME\" environment variable has been set and that it points to a directory containing a \"bin\" directory and ...
[ 7, 5, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0001332598_java_python.txt
Q: PYTHON split ThreadPoolExecutor to multiple CPU Cores Hey I am pretty new to this community and I was wondering if this is possible? For example I have a ThreadPoolExecutor with: from concurrent.futures import ThreadPoolExecutor, as_completed from threading import Semaphore lock = Semaphore(1) # Just a pseudocod...
PYTHON split ThreadPoolExecutor to multiple CPU Cores
Hey I am pretty new to this community and I was wondering if this is possible? For example I have a ThreadPoolExecutor with: from concurrent.futures import ThreadPoolExecutor, as_completed from threading import Semaphore lock = Semaphore(1) # Just a pseudocode example profileTasks = ["TEST1", "TEST2", "TEST3", "TEST4...
[ "The mostly used Python implementation (from python.org, commonly referred to as cpython because it is written in C) enforces that only one thread at a time can be executing python bytecodes.\nSo using threads to speed up computationally intensive applications does not work with this implementation.\nIf you want to...
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0074244230_multiprocessing_multithreading_python.txt
Q: Can't drop a certain row in Pandas note that title is index. title rating rat_count 'Til There Was You 2.333333 9 1-900 2.600000 5 101 Dalmatians 2.908257 109 12 Angry Men 4.344000 125 ... ... ... Young Guns 3.207921 101 I tried i = movies[movies['rating']==3.4444].index movies.drop(i) # This one has no ef...
Can't drop a certain row in Pandas
note that title is index. title rating rat_count 'Til There Was You 2.333333 9 1-900 2.600000 5 101 Dalmatians 2.908257 109 12 Angry Men 4.344000 125 ... ... ... Young Guns 3.207921 101 I tried i = movies[movies['rating']==3.4444].index movies.drop(i) # This one has no effect and didn't removed 2...
[ "movies.drop(movies.index[0])\n\nsolved the problem.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "drop", "pandas", "python" ]
stackoverflow_0074244290_dataframe_drop_pandas_python.txt
Q: ModuleNotFoundError: No module named '_dbus_bindings' debian 11 bullseye python 3.9.2 I'm upgrading my arm based system from debian 10 to debian 11, but python is giving me a headache. I'm running a bluetooth server on it, with the bluedot api, but this requires the dbus-python api. This was a hassle to install on...
ModuleNotFoundError: No module named '_dbus_bindings' debian 11 bullseye python 3.9.2
I'm upgrading my arm based system from debian 10 to debian 11, but python is giving me a headache. I'm running a bluetooth server on it, with the bluedot api, but this requires the dbus-python api. This was a hassle to install on its own but now the module not found error has shifted from dbus to _dbus_bindings. And no...
[ "it seems that installing an older version worked:\npip3 install dbus-python==1.2.16\ninstead of 1.2.18, tried this because this is also the version that is installed on my ubuntu desktop.\nwaiting to try it out on the actual hardware instead of in chroot.\nresult is a success. I've seen more people struggling with...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0073149688_python_python_3.x.txt
Q: Python decorators passing attributes I'm using decorators to enhance some methods, but I'm suffering from the lack of interoperability between them. As an example, let's say I want to use the functools.cache decorator to memoize the results and a hand-made decorator to count the number of calls to that method: fro...
Python decorators passing attributes
I'm using decorators to enhance some methods, but I'm suffering from the lack of interoperability between them. As an example, let's say I want to use the functools.cache decorator to memoize the results and a hand-made decorator to count the number of calls to that method: from functools import cache, wraps from typin...
[ "Decoration is just syntactic sugar for passing some callable (function or class) to another callable (the decorator) and that syntax is restricted to class/function definition statements.\nGiven some decorator dec, writing\n@dec\ndef f(): ...\n\nis equivalent to this:\ndef f(): ...\n\nf = dec(f)\n\nIt is also impo...
[ 1 ]
[]
[]
[ "decorator", "python", "python_3.x", "python_decorators" ]
stackoverflow_0074157283_decorator_python_python_3.x_python_decorators.txt
Q: How to remove "g" with regex from this list in python with regex? I have this list: list = ['12kg','900g', '2,7kg', '801g', '15', '3,63kg', '1kg'] and I want to remove only letter g (or replace with "") when I have pattern <number>g, which means: new_list = ['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg] I...
How to remove "g" with regex from this list in python with regex?
I have this list: list = ['12kg','900g', '2,7kg', '801g', '15', '3,63kg', '1kg'] and I want to remove only letter g (or replace with "") when I have pattern <number>g, which means: new_list = ['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg] I've tried to write the following but failed they all failed: [^kK]g: f...
[ "Is this what you're looking for?\nimport re\n\n\nlst = ['12kg', '900g', '2,7kg', '801g', '15', '3,63kg', '1kg']\nnewLst = [re.sub('([0-9]+)g$', lambda x: x.groups()[0], el) for el in lst]\nprint(newLst) # => ['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg']\n\nThe regex I used here was ([0-9]+)g$. This will ...
[ 1, 1, 1 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0074242340_python_regex_replace.txt
Q: Query DNS server for usable/plain IP address I am trying to write a program to query multiple DNS servers for the IP address of a hostname. My only problem is that I can't get the actual IP address, only the server's response. This is my code: import dns.resolver my_resolver = dns.resolver.Resolver() reply_list ...
Query DNS server for usable/plain IP address
I am trying to write a program to query multiple DNS servers for the IP address of a hostname. My only problem is that I can't get the actual IP address, only the server's response. This is my code: import dns.resolver my_resolver = dns.resolver.Resolver() reply_list = [] dns_list = ['8.8.8.8', '8.8.4.4', '1.2.3.4'] ...
[ "answer.response contains the actual DNS protocol response from the server. Instead, you can use str(answer) to get the resolved IP address instead. Like this:\nimport dns.resolver\n\nserver_list = ['8.8.8.8', '8.8.4.4']\nrecords = []\n\ndns.resolver.default_resolver = dns.resolver.Resolver(configure=False)\n\nfor ...
[ 0, 0 ]
[]
[]
[ "dns", "python" ]
stackoverflow_0074242296_dns_python.txt
Q: Implementing custom Manim Animation Manim's Animation class calls the interpolate_submobject method which is implemented in a subclass. So I implemented this interface/contract: class ScaleAction(Animation): def __init__( self, mobject: Mobject, **kwargs, ): super().__init__...
Implementing custom Manim Animation
Manim's Animation class calls the interpolate_submobject method which is implemented in a subclass. So I implemented this interface/contract: class ScaleAction(Animation): def __init__( self, mobject: Mobject, **kwargs, ): super().__init__(mobject, **kwargs) def inte...
[ "The submobject being passed to interpolate_submobject is the one you need to modify directly; reassigning the variable will not change the mobject. By changing your reassignment to\nsubmobject.become(starting_submobject.copy().apply_function(action))\n\nyour animation will work correctly; I've tested it with the s...
[ 1 ]
[]
[]
[ "manim", "python" ]
stackoverflow_0074242875_manim_python.txt
Q: Foreign Key TestCase I am trying to run tests on models and am having trouble with ones that have a foreign key. When I try to get the card made in setUp I am not able to. I am not understanding why. The value expected for the attribute category is an int. Either category, category.id, nor 'Test Category' work. Co...
Foreign Key TestCase
I am trying to run tests on models and am having trouble with ones that have a foreign key. When I try to get the card made in setUp I am not able to. I am not understanding why. The value expected for the attribute category is an int. Either category, category.id, nor 'Test Category' work. Code: models.py class Catego...
[ "Instead of providing the category.id just give the category object itself.\ncard = Card.objects.filter(category=category,\n question='Hello?',\n answer='Hello!',\n slug='slug'\n )\n\nI am usi...
[ 2 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0074244118_django_python_unit_testing.txt
Q: Querying TEXT column containing valid JSON using SqlAlchemy I wish to query a valid json placed in a column of type TEXT(not JSON). E.g. I wish to something like that: records = db_session.query(Resource).filter( Resources.data["lastname"] == "Doe" ).all() What should I do if the data colu...
Querying TEXT column containing valid JSON using SqlAlchemy
I wish to query a valid json placed in a column of type TEXT(not JSON). E.g. I wish to something like that: records = db_session.query(Resource).filter( Resources.data["lastname"] == "Doe" ).all() What should I do if the data column is of type TEXT?
[ "You can cast the column to JSON (or JSONB if you are using PostgreSQL) to enable JSON operations:\nrecords = db_session.query(Resource).filter(\n db.cast(Resources.data, db.JSON)[\"lastname\"] == \"Doe\"\n ).all()\n\nalternatively, use the column's cast method:\nrecords = db_session.query(Res...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074138817_python_sqlalchemy.txt
Q: Search large file to see if a sentence with missing words can be found This is my current code, I have the message_list (the input) and the book (3686 lines) and need to check if the book contains the message. But the message has gaps, "_", and a gap equals a word. But I don't know how to parse this into my re arg...
Search large file to see if a sentence with missing words can be found
This is my current code, I have the message_list (the input) and the book (3686 lines) and need to check if the book contains the message. But the message has gaps, "_", and a gap equals a word. But I don't know how to parse this into my re arguments. I have never worked with re before and that was my try on this. mess...
[ "If the underscores can represent one word, then you can change them from underscores into a \"single word match\", which you can then make optional or multiple as required, in constructing a regular expression to match against the text. You just have to be careful about spaces, since there's normally a single spac...
[ 0 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0074244229_python_python_re.txt
Q: Replicating rows based on another column I have the below data frame Now I want to transfer the data frame like below I have used the python commands to do that but none of them worked . Could anyone please help me with how to do that df.loc[df.index.repeat(df.mas_id)].reset_index(drop=True) n_df = pd.concat([df...
Replicating rows based on another column
I have the below data frame Now I want to transfer the data frame like below I have used the python commands to do that but none of them worked . Could anyone please help me with how to do that df.loc[df.index.repeat(df.mas_id)].reset_index(drop=True) n_df = pd.concat([df] * final_n) newdf = pd.DataFrame(np.repeat(df...
[ "Use itertools library's function product\nfrom itertools import product\n\ncombi_rows = product(df.store.dropna(), df.mas_id.dropna())\nnew_df = pd.DataFrame(combi_rows, columns=df.columns)\n\nOutput\n store mas_id\n0 100.0 1\n1 100.0 2\n2 100.0 3\n3 100.0 4\n4 101.0 1\n...
[ 2, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074243243_dataframe_pandas_python.txt
Q: How to find the subarray with given sum Code is below find the subarray which matches given sum arr is given array, s is the sum def getsub(arr,s): result = [] for x in range(len(arr)): result.append(arr[x]) while sum(result) > s: result.pop(0) if sum(result) == s: ...
How to find the subarray with given sum
Code is below find the subarray which matches given sum arr is given array, s is the sum def getsub(arr,s): result = [] for x in range(len(arr)): result.append(arr[x]) while sum(result) > s: result.pop(0) if sum(result) == s: return result arr = [4, 1, 6, 5, 2, 3]...
[ "There could be 2 possible approach for this.\n\nSlidding Window\nHashing\n\nSlidding Window:\n# Function to find sublist having a given sum using hashing sliding window\ndef find_sub_list_using_sliding_window(arr, expected_sum):\n \n # maintains the sum of the current window\n windowSum = 0\n \n # maintai...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069263743_python.txt
Q: How can Python Poetry be forced to use a certain setuptools version? I would like to use the Python library pyhash in my project. The dependencies are managed by Poetry. If I add pyhash as a dependency, I get a build error: error in pyhash setup command: use_2to3 is invalid. This is a well-known bug due to setupto...
How can Python Poetry be forced to use a certain setuptools version?
I would like to use the Python library pyhash in my project. The dependencies are managed by Poetry. If I add pyhash as a dependency, I get a build error: error in pyhash setup command: use_2to3 is invalid. This is a well-known bug due to setuptools > 58.0.0 not supporting use_2to3 anymore. In a non-Poetry setup, the f...
[ "I found a workaround for my problem. In the case of pyhash, the dependency on use_2to3 has already been removed in the master branch. This fix has unfortunately not been released yet. However, it is possible for pip and also for poetry to install directly from a github repository. Any ref can be specified, so bran...
[ 0 ]
[]
[]
[ "python", "python_packaging", "python_poetry", "setuptools" ]
stackoverflow_0074233434_python_python_packaging_python_poetry_setuptools.txt
Q: Comparing Python Data-frames I have two data frames, e.g., df_1: index A B C D 1 2 5 9 12 2 9 8 13 22 3 0 44 3 1 and df_2: index A C 1 12 40 2 9 13 3 16 1 4 0 21 I am looking for a way to compare these two dfs and the final product should be rows in df_1 suc...
Comparing Python Data-frames
I have two data frames, e.g., df_1: index A B C D 1 2 5 9 12 2 9 8 13 22 3 0 44 3 1 and df_2: index A C 1 12 40 2 9 13 3 16 1 4 0 21 I am looking for a way to compare these two dfs and the final product should be rows in df_1 such that the values in column A and ...
[ "I think you just want to have an inner merge.\ndf_1.merge(df_2, on=['A', 'C'], how='inner')\n\n A B C D\n0 9 8 13 22\n\n" ]
[ 0 ]
[]
[]
[ "compare", "database", "dataframe", "pandas", "python" ]
stackoverflow_0074244467_compare_database_dataframe_pandas_python.txt
Q: KeyError when I read environment variables while doing makemigrations in django Context of the problem - I want to migrate from the SQLite database to Postgres. When I makemigrations with Postgres settings which are passed to the settings file with environment variables, I get KeyError; however, another variable f...
KeyError when I read environment variables while doing makemigrations in django
Context of the problem - I want to migrate from the SQLite database to Postgres. When I makemigrations with Postgres settings which are passed to the settings file with environment variables, I get KeyError; however, another variable from the same file does not cause any problems. My secrets file: SECRET_KEY='secret ke...
[]
[]
[ "I solved it by replacing os.environ['DB_NAME'] to os.environ.get('DB_NAME').\nBut I don't understand the reason. If the key is not there, os.environ.get will return None, right?\nIf it doesn't return None, why os.environ['DB_NAME'] throws an exception?\n", "When you are using the os.environ.get('DB_NAME') method...
[ -1, -1 ]
[ "django", "postgresql", "python" ]
stackoverflow_0074243304_django_postgresql_python.txt
Q: How to efficiently convert a large parallel corpus to a Huggingface dataset to train an EncoderDecoderModel? Typical EncoderDecoderModel that works on a Pre-coded Dataset The code snippet snippet as below is frequently used to train an EncoderDecoderModel from Huggingface's transformer library from transformers im...
How to efficiently convert a large parallel corpus to a Huggingface dataset to train an EncoderDecoderModel?
Typical EncoderDecoderModel that works on a Pre-coded Dataset The code snippet snippet as below is frequently used to train an EncoderDecoderModel from Huggingface's transformer library from transformers import EncoderDecoderModel from transformers import PreTrainedTokenizerFast multibert = EncoderDecoderModel.from_en...
[ "TL;DR\n(Answer's credits goes to @lhoestq)\nIf you have a TSV file that looks like this:\nhello world\\tHallo Welt\nhow are you?\\twie gehts?\n...\\t...\n\nload the dataset as such:\n# tatoeba-sentpairs.tsv is a pretty large file.\nds = load_dataset(\"csv\", data_files=\"../input/tatoeba/tatoeba-sentpairs.tsv\", \...
[ 2, 2 ]
[]
[]
[ "dataset", "huggingface", "parallel_processing", "python", "pytorch" ]
stackoverflow_0074146965_dataset_huggingface_parallel_processing_python_pytorch.txt
Q: Choosing a specific contour in oscillatory data to plot with matplotlib I have oscillatory data to which I would like to add a specific contour line. For example, the data pass through a value several times, and I would like to pick a specific instance of that value to highlight with a contour. As an example, co...
Choosing a specific contour in oscillatory data to plot with matplotlib
I have oscillatory data to which I would like to add a specific contour line. For example, the data pass through a value several times, and I would like to pick a specific instance of that value to highlight with a contour. As an example, consider a Bessel function. Below, I plot the contours with a single level, 0....
[ "Let's see how you like this ;) ... I plot all contour lines invisibly, but extract the contour object and replot the first one (that I just figured out by trial and error, and might be different in your case).\nfrom scipy.special import jv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-20...
[ 1 ]
[]
[]
[ "contour", "matplotlib", "python" ]
stackoverflow_0074241636_contour_matplotlib_python.txt
Q: skip ending rows containing string while reading a txt file with numpy to generate a numerical array I'm trying to generate an array reading a text file from internet. My target is to use Python instead of MATLAB, to replace this step in MATLAB: url=['http://www.cdc.noaa.gov/Correlation/amon.us.long.data']; urlwri...
skip ending rows containing string while reading a txt file with numpy to generate a numerical array
I'm trying to generate an array reading a text file from internet. My target is to use Python instead of MATLAB, to replace this step in MATLAB: url=['http://www.cdc.noaa.gov/Correlation/amon.us.long.data']; urlwrite(url,'file.txt'); I'm using this code: urllib.urlretrieve('http://www.cdc.noaa.gov/Correlation/amon.us....
[ "For more complex text loading, have a look at numpy.genfromtxt.\nIt's slower than numpy.loadtxt but more flexible.\nIn your case (I'm avoiding saving a temporary file here...):\nimport numpy as np\nimport urllib2\n\nurl = 'http://www.cdc.noaa.gov/Correlation/amon.us.long.data'\ndata = np.genfromtxt(urllib2.urlopen...
[ 11, 2, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0007894504_numpy_python_scipy.txt
Q: How to log uncaught exceptions in Flask routes with logging? What is the standard way to log uncaught expressions in Flask routes with logging? This nearly works: import logging, sys, flask logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s %(levelname)s %(message)s') sys.excepthook = lambd...
How to log uncaught exceptions in Flask routes with logging?
What is the standard way to log uncaught expressions in Flask routes with logging? This nearly works: import logging, sys, flask logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s %(levelname)s %(message)s') sys.excepthook = lambda exctype, value, tb: logging.error("", exc_info=(exctype, value, ...
[ "How to log uncaught exceptions in Flask routes with logging?\nFlask is a popular web framework for Python that allows you to create web applications easily and quickly. However, sometimes your Flask routes may encounter uncaught exceptions that cause your application to crash or return an error response. To debug ...
[ 3, 2, 1, 1 ]
[]
[]
[ "flask", "logging", "python", "python_logging" ]
stackoverflow_0074155189_flask_logging_python_python_logging.txt
Q: How to read the data from txt to python pandas if the data looks compacted by date? I received a text file, which looks like Time Purchasing_item 20120701 00:00 Apple pie 00:01 Coca-cola 20120702 00:00 Pepsi 00:01 Fish-ball However, I want when I load the data into pandas, I want the data to look like Added one c...
How to read the data from txt to python pandas if the data looks compacted by date?
I received a text file, which looks like Time Purchasing_item 20120701 00:00 Apple pie 00:01 Coca-cola 20120702 00:00 Pepsi 00:01 Fish-ball However, I want when I load the data into pandas, I want the data to look like Added one column myself, but don't want to duplicate the date so many times beforehand. Date Tim...
[ "Here is one way to do it:\ndf = pd.read_table('Data/file.txt', names=['DateTime'], skiprows=1)\n\ndf[['DateTime', 'Purchasing_item']] = df['DateTime'].str.split(n=1, expand=True)\n\nfor i in df.index:\n if df['Purchasing_item'].isna()[i] == True:\n df.iloc[i+1, 0] = df.iloc[i, 0] + ' ' + df.iloc[i+1, 0]\...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074244105_pandas_python.txt
Q: Why doesn't tempfile.SpooledTemporaryFile implement readable, writable, seekable? In Python 3.6.1, I've tried wrapping a tempfile.SpooledTemporaryFile in an io.TextIOWrapper: with tempfile.SpooledTemporaryFile() as tfh: do_some_download(tfh) tfh.seek(0) wrapper = io.TextIOWrapper(tfh, encoding='utf-8')...
Why doesn't tempfile.SpooledTemporaryFile implement readable, writable, seekable?
In Python 3.6.1, I've tried wrapping a tempfile.SpooledTemporaryFile in an io.TextIOWrapper: with tempfile.SpooledTemporaryFile() as tfh: do_some_download(tfh) tfh.seek(0) wrapper = io.TextIOWrapper(tfh, encoding='utf-8') yield from do_some_text_formatting(wrapper) The line wrapper = io.TextIOWrapper(t...
[ "SpooledTemporaryFile actually uses 2 different _file implementations under the hood - initially an io Buffer (StringIO or BytesIO), until it rolls over and creates a \"file-like object\" via tempfile.TemporaryFile() (for example, when max_size is exceeded).\nio.TextIOWrapper requires a BufferedIOBase base class/in...
[ 10, 1 ]
[]
[]
[ "io", "python", "temporary_files" ]
stackoverflow_0047160211_io_python_temporary_files.txt
Q: What's the best way to setup playwright in Apache Airflow in Docker? I've been asked to learn Docker so that we can eventually setup our web scraping scripts in Apache Airflow Docker + Kubernetes clusters. If I am using these terms the wrong way, it's because I am a beginner at Docker. I do not know a whole bunch,...
What's the best way to setup playwright in Apache Airflow in Docker?
I've been asked to learn Docker so that we can eventually setup our web scraping scripts in Apache Airflow Docker + Kubernetes clusters. If I am using these terms the wrong way, it's because I am a beginner at Docker. I do not know a whole bunch, but I will try to explain the details. Apache Airflow do have their own i...
[ "The best way to do it is using playwright docker image as base image, then you won't need to install its dependencies. Take a look to the documentation here: https://playwright.dev/docs/docker\n", "As it turns out Playwright is not supported for ARM64, which includes the Apple M1 chip.\nhttps://github.com/micros...
[ 2, 2, 1 ]
[]
[]
[ "airflow", "docker", "docker_compose", "dockerfile", "python" ]
stackoverflow_0072431221_airflow_docker_docker_compose_dockerfile_python.txt
Q: i keep getting this massege "ModuleNotFoundError: No module named 'pygame'" whenever i try to import it eventhough i have installed it, why is that? python, ModuleNotFoundError: No module named 'pygame', pip in the command prompt, it says "Requirement already satisfied" but when trying to import, I keep getting er...
i keep getting this massege "ModuleNotFoundError: No module named 'pygame'" whenever i try to import it eventhough i have installed it, why is that?
python, ModuleNotFoundError: No module named 'pygame', pip in the command prompt, it says "Requirement already satisfied" but when trying to import, I keep getting errors.
[ "You have probably multiple python versions installed. But 'pip' only installed the package for one of those versions.\nYou can specify the python version like this\npython[your version] -m pip install [package]\nThis will install 'pygame' for python 3.10:\npython3.10 -m pip install pygame\n", "U may have to inst...
[ 0, 0 ]
[]
[]
[ "import", "module", "pip", "pygame", "python" ]
stackoverflow_0074244483_import_module_pip_pygame_python.txt
Q: Python decorator that uses an instance of the class Logger for all the methods it decorates Can you show an example of how to create a function decorator that wrap it with logging, but uses the same logger instance? For example, take a look on logging_instance. It will be wrong to create it every time the decorato...
Python decorator that uses an instance of the class Logger for all the methods it decorates
Can you show an example of how to create a function decorator that wrap it with logging, but uses the same logger instance? For example, take a look on logging_instance. It will be wrong to create it every time the decorator is called. logging_instance = logging.getLogger('logger_name') ... def logging(log_string=''):...
[ "It is not created everytime, a logger is preserved and returned whenever getLogger is called with the same name. As logging documentation states:\n\nLoggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLo...
[ 3 ]
[]
[]
[ "design_patterns", "python", "python_decorators" ]
stackoverflow_0074244551_design_patterns_python_python_decorators.txt
Q: Cloning a Linked List not printing correctly I am trying to define a function called clone which clones the linked list Here is the LinkedList class with the clone function defined class Node: def __init__(self, d, n): self.data = d self.next = n class LinkedList: def __init__(self): self.head = None ...
Cloning a Linked List not printing correctly
I am trying to define a function called clone which clones the linked list Here is the LinkedList class with the clone function defined class Node: def __init__(self, d, n): self.data = d self.next = n class LinkedList: def __init__(self): self.head = None self.length = 0 def __str__(self): if ...
[ "in your clone method change it to:\nwhile ptr!=None:\n ls.insert(i,ptr.data)\n ptr=ptr.next\n i+=1\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074244471_python.txt
Q: Using Python, I want to print only positive integers on the list through recursion I'm studying recursion now, and my head is about to explode trying to use it. If lst = [-1, -4, 0, 3, 6], my expecting output is result = [3, 6]. I tried this, def positive(lst): result = [] if not lst: return result...
Using Python, I want to print only positive integers on the list through recursion
I'm studying recursion now, and my head is about to explode trying to use it. If lst = [-1, -4, 0, 3, 6], my expecting output is result = [3, 6]. I tried this, def positive(lst): result = [] if not lst: return result else: if lst[0] > 0: result.append(lst[0]) return posit...
[ "You are not passing your cache down through recursion\ndef positive(lst, result):\n if not lst:\n return result\n else:\n if lst[0] > 0:\n result.append(lst[0])\n return positive(lst[1:], result)\n\n\nlst_in = [-1, -4, 0, 3, 6]\nresult = []\nres = positive(lst_in, result)\npri...
[ 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074244463_python_recursion.txt
Q: why does the return function in python is returning a value of 1 in factorial prog #factorial prog def fac(y): fact=1 i=1 for i in range(1,y+1): fact=i*fact return fact x=int(input("enter no")) y=fac(x) print(y) why does the return function return 1 when I remove the defined functio...
why does the return function in python is returning a value of 1 in factorial prog
#factorial prog def fac(y): fact=1 i=1 for i in range(1,y+1): fact=i*fact return fact x=int(input("enter no")) y=fac(x) print(y) why does the return function return 1 when I remove the defined function and find the factorial by same method in the main function its giving the correct ans...
[ "Indentation level of your return statement is wrong. You should do as following:\n#factorial prog\ndef fac(y):\n fact=1\n i=1\n for i in range(1,y+1):\n fact=i*fact\n return fact\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074244611_python.txt
Q: While extracting data from excel sheet using python (xlrd package). getting some junk data too I'm extracting data from excel sheet using python (xlrd package). With the original data im getting some junk data, please help me to remove those Getting junk values like [text:u as below: [text:u'NAME', text:u'JACK'] <...
While extracting data from excel sheet using python (xlrd package). getting some junk data too
I'm extracting data from excel sheet using python (xlrd package). With the original data im getting some junk data, please help me to remove those Getting junk values like [text:u as below: [text:u'NAME', text:u'JACK'] <CODE> from xlrd import open_workbook book = open_workbook('C:/Users/arun/Desktop/EX.xls') sheet0 =...
[ "Your \"junk\" looks like a list of xlrd Cells that are of type \"text\". That is, I don't think it is junk; it is a normal return value created by xlrd. If you want the values from a column (say, column 0), try\nprint sheet0.col_values(0)\n\nSee https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#sh...
[ 4, 1, 0 ]
[]
[]
[ "excel", "python", "xlrd" ]
stackoverflow_0015544484_excel_python_xlrd.txt
Q: Create mask OpenCV python I'm trying to create a mask. I have database of images similar like this image. INPUT IMAGE CODE import cv2 import numpy as np img = cv2.imread('sample1.png', cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) #img_ = cv2.threshold(gray,100,225,cv2.THRESH_BINARY) edges = c...
Create mask OpenCV python
I'm trying to create a mask. I have database of images similar like this image. INPUT IMAGE CODE import cv2 import numpy as np img = cv2.imread('sample1.png', cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) #img_ = cv2.threshold(gray,100,225,cv2.THRESH_BINARY) edges = cv2.Canny(gray, 250, 250) cv2.im...
[ "Well, there are many ways to do that. All of them need some tuning, depending on your image.\nThere is, for example, a floodfill function in opencv.\nBut the easiest is probably to use some mathematical morphology and then connected component. Because from the connected component, it is easier to adjust result if ...
[ 1 ]
[]
[]
[ "canny_operator", "image_processing", "numpy", "opencv", "python" ]
stackoverflow_0074244274_canny_operator_image_processing_numpy_opencv_python.txt
Q: How to detect self-intersections in a spatial path in Python? Let's say I have a path in a multidimensional space, given by an array of points along the path. E.g. p[0] = [ 0, 0, 0, 0,...] p[1] = [ 0, 0, 0,0.01,...] etc. What's an efficient algorithm for detecting if the path has any self-intersections? ...
How to detect self-intersections in a spatial path in Python?
Let's say I have a path in a multidimensional space, given by an array of points along the path. E.g. p[0] = [ 0, 0, 0, 0,...] p[1] = [ 0, 0, 0,0.01,...] etc. What's an efficient algorithm for detecting if the path has any self-intersections? It's entirely possible that the path intersects at a point in betwe...
[ "Self-intersection search can be implemented via BVH traverse with complexity of O(log(n)) + O(n*log(n)) to build the tree (usually BVH is built once and used many times for different purposes).\nFor this case traverse is quite simple, let me show example for binary BVH:\n\nFirst we define task - two nodes of BVH t...
[ 2 ]
[]
[]
[ "algorithm", "curve", "graph_theory", "python" ]
stackoverflow_0050167737_algorithm_curve_graph_theory_python.txt
Q: Python OpenCV set timeout on VideoCapture Trying to set a max timeout for VideoCapture to catch the exception and print a message if the stream is down. For example, I need it to try for 10 seconds and then assume the stream is offline. I have the following code so far. import cv2 try: cap = cv2.VideoCapture(...
Python OpenCV set timeout on VideoCapture
Trying to set a max timeout for VideoCapture to catch the exception and print a message if the stream is down. For example, I need it to try for 10 seconds and then assume the stream is offline. I have the following code so far. import cv2 try: cap = cv2.VideoCapture("rtsp://Username:Password@IP_ADDRESS:PORT") ...
[ "When opening the stream you only get a video object. Then you have to start reading the frames from the video object. This will tell you if there is a video stream.\nTIMEOUT: The code stops if during 10 seconds no frames have been received.\nRESET TIMEOUT: If within the 10 seconds new frames are being received the...
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074244577_opencv_python.txt
Q: Why is facecolor argument in plot_surface of matplotlib not working in python? I want my python code to generate a plot with alternating colors. For the sake of the problem, the alternating colors are irrelevant so let's say they're red and blue. I'm creating a numpy array of the alternating colors with the same s...
Why is facecolor argument in plot_surface of matplotlib not working in python?
I want my python code to generate a plot with alternating colors. For the sake of the problem, the alternating colors are irrelevant so let's say they're red and blue. I'm creating a numpy array of the alternating colors with the same shape as the inputs x, y and z (251, 251) colortuple = ('red', 'blue') colors = np.ar...
[ "\nfacecolors must be RGB or RGBA, it's simpler to use a 2-entries colormap.\nfrom numpy import arange, cos, linspace, meshgrid, sin\nfrom matplotlib import colors, pyplot\nN = 32\nx = linspace(0, 6.28, N)\nX, Y = meshgrid(x, x)\nZ = 2*sin(X)+cos(Y/2)\ncheckers = (arange((N-1)**2)%2).reshape((N-1,N-1))\n# if (N-1) ...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074243811_matplotlib_python.txt
Q: Resizing a folder of images and saving it with the same name in a different folder with opencv Been trying to resize a folder of images (folder name here = Images) to a new folder named "Images_r" and saving the images with same name as the previous folder , but can't seem to be able to save them with the previos ...
Resizing a folder of images and saving it with the same name in a different folder with opencv
Been trying to resize a folder of images (folder name here = Images) to a new folder named "Images_r" and saving the images with same name as the previous folder , but can't seem to be able to save them with the previos names . inputFolder = 'Images' for img in glob.glob(inputFolder + "/*.jpg"): image = cv2.imread...
[ "You need to extract file name from img and grab the last element, which is filename\nimport cv2\nimport os\nimport glob\ninputFolder = 'Images'\n\n\nfor img in glob.glob(inputFolder + \"/*.jpg\"):\n image = cv2.imread(img)\n h = image\n imgResized = cv2.resize(image, (300, 400))\n cv2.imwrite(os.path.j...
[ 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0074244841_path_python.txt
Q: How to combine string | REGEX import re def tst(): text = ''' <script> ''' if proxi := re.findall(r"(?:<td\s[^>]*?><font\sclass\=spy14>(.*?)<script.*?\"\+(.*?)\)<\/script)", text): for proxy, port in proxi: yield f"{proxy}:{''.join(port)}" if dtt := re.findall(r"<td colspan=1><font clas...
How to combine string | REGEX
import re def tst(): text = ''' <script> ''' if proxi := re.findall(r"(?:<td\s[^>]*?><font\sclass\=spy14>(.*?)<script.*?\"\+(.*?)\)<\/script)", text): for proxy, port in proxi: yield f"{proxy}:{''.join(port)}" if dtt := re.findall(r"<td colspan=1><font class\=spy1><font class\=spy14>(.*?)</f...
[ "This approach reads all lines into a list, then iterates the IP lines and date lines in tandem to generate the output.\ntext = '''157.245.247.84:7497\n184.190.137.213:8111\n202.149.89.67:7999\n27-oct-2022 11:05 (49 mins ago)\n27-oct-2022 11:04 (50 mins ago)\n27-oct-2022 11:03 (51 mins ago)'''\nlines = text.split('...
[ 1, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074243647_python_regex.txt
Q: How to implement clear in cmd.Cmd? I am working on a custom command line interpreter, and I want to implement the 'clear' command, just like the the one in bash shell. Is there any way to do that? I have attempted it but I don't think it is correct at all: #!/usr/bin/python3 import cmd import sys import os class ...
How to implement clear in cmd.Cmd?
I am working on a custom command line interpreter, and I want to implement the 'clear' command, just like the the one in bash shell. Is there any way to do that? I have attempted it but I don't think it is correct at all: #!/usr/bin/python3 import cmd import sys import os class HBNBCommand(cmd.Cmd): """Command li...
[ "When inheriting from cmd to build your custom shell, methods expect at least one argument. To quote from this resource, \"The interpreter uses a loop to read all lines from its input, parse them, and then dispatch the command to an appropriate command handler. Input lines are parsed into two parts. The command, an...
[ 2 ]
[]
[]
[ "python", "python_cmd" ]
stackoverflow_0074244681_python_python_cmd.txt
Q: How to accept the integer and float values in same input variable in python? How to Accept the integer and float values in the same input variable in python def interest_rate(): while True: interest_rate = input("Enter the annual interest rates: ") if interest_rate.isdigit() == True: ...
How to accept the integer and float values in same input variable in python?
How to Accept the integer and float values in the same input variable in python def interest_rate(): while True: interest_rate = input("Enter the annual interest rates: ") if interest_rate.isdigit() == True: interest_rate = int(interest_rate) if interest_rate >= 0: ...
[ "The value returned from input() is a string <class 'str'>. If you want to convert that to some numeric value you call int() or float() according to your needs. Do this in a try/except ValueError code block. Note that, for example, the string '1.5' could be converted to float but '1.5'.isdigit() == False\nAssuming ...
[ 0 ]
[]
[]
[ "floating_point", "input", "integer", "python" ]
stackoverflow_0074244701_floating_point_input_integer_python.txt
Q: Detecting colour difference between images in python I have a collection of images taken with different lens (same distorsion) and I want to see if theres a difference in the colour. I think the best way to compare is simple average, for which I have: import cv2 import numpy myimg = cv2.imread('image.jpg') avg_col...
Detecting colour difference between images in python
I have a collection of images taken with different lens (same distorsion) and I want to see if theres a difference in the colour. I think the best way to compare is simple average, for which I have: import cv2 import numpy myimg = cv2.imread('image.jpg') avg_color_per_row = numpy.average(myimg, axis=0) avg_color = nump...
[ "That is a very broad question. And it depends on what you call \"difference of color\".\n\nAre your images supposed to be strictly (to the pixel) aligned? Your comparison by rows seems to indicate so. But the rest of the text makes it very unrealistic (in fact, even in industrial computer vision, for example to co...
[ 0 ]
[]
[]
[ "average", "colors", "image", "python" ]
stackoverflow_0074244700_average_colors_image_python.txt
Q: How can I make my GUI program(tkinter) work on computers with no python installed such that no console window appears? Here's what I have done so far: -I made a desktop search program/GUI using python and tkinter. -Then I used py2exe to convert it to an exe. -Now the software perfectly works on a machine(windows)...
How can I make my GUI program(tkinter) work on computers with no python installed such that no console window appears?
Here's what I have done so far: -I made a desktop search program/GUI using python and tkinter. -Then I used py2exe to convert it to an exe. -Now the software perfectly works on a machine(windows) without python installed, but the problem is that a creepy black window just appears along with the GUI when the .exe is op...
[ "Change the file extension from .py to .pyw\n(You must have Python installed for this to work.)\nDuplicate:\nHide console window with Tkinter and cx_Freeze\n", "Before converting your file to an exe, change the file extension (by renaming the file) from .py to .pyw.\n'.py' files open with the console, whereas '.p...
[ 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0038541974_python_tkinter_user_interface.txt
Q: How to run marqo on macbook i have been using marqo library for a week now and it has been working well on my windows machine, but today i am trying to run the same program on my m1 mac but i keep getting error. i tried reading through the documentation and i saw this: Marqo does not yet support the docker-in-doc...
How to run marqo on macbook
i have been using marqo library for a week now and it has been working well on my windows machine, but today i am trying to run the same program on my m1 mac but i keep getting error. i tried reading through the documentation and i saw this: Marqo does not yet support the docker-in-docker backend configuration for the...
[ "i was also having the same issue.Try uninstalling docker, restarting your machine and reinstall docker, then run the two commands again hopefully it should work.\n" ]
[ 1 ]
[]
[]
[ "backend", "pip", "python", "python_3.x" ]
stackoverflow_0074244709_backend_pip_python_python_3.x.txt
Q: Selenium Python not detecting log In button I am trying to click the log in button from https://search.connectourkids.org driver = webdriver.Chrome("/Users/nicknavarro/Documents/DVS/chromedriver") url = 'https://search.connectourkids.org' driver.get(url) print ("Opened Website") sleep(30) login = driver.find_elem...
Selenium Python not detecting log In button
I am trying to click the log in button from https://search.connectourkids.org driver = webdriver.Chrome("/Users/nicknavarro/Documents/DVS/chromedriver") url = 'https://search.connectourkids.org' driver.get(url) print ("Opened Website") sleep(30) login = driver.find_element_by_css_selector("body > app-root > div > rout...
[ "I could able to access the website through VPN only, so I didn't run this script, but it should work, try with these locators, all are XPaths:\nFor 'Log In' link the main page:\n//a[contains(text(),'Log In')]\n\nFor email or username field:\n//input[@type='email']\n\nFor password field:\n//input[@type='password']\...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074240351_python_selenium_selenium_webdriver.txt
Q: Logical operators for Boolean indexing in Pandas I'm working with a Boolean index in Pandas. The question is why the statement: a[(a['some_column']==some_number) & (a['some_other_column']==some_other_number)] works fine whereas a[(a['some_column']==some_number) and (a['some_other_column']==some_other_number)] ex...
Logical operators for Boolean indexing in Pandas
I'm working with a Boolean index in Pandas. The question is why the statement: a[(a['some_column']==some_number) & (a['some_other_column']==some_other_number)] works fine whereas a[(a['some_column']==some_number) and (a['some_other_column']==some_other_number)] exits with error? Example: a = pd.DataFrame({'x':[1,1],'...
[ "When you say\n(a['x']==1) and (a['y']==10)\n\nYou are implicitly asking Python to convert (a['x']==1) and (a['y']==10) to Boolean values.\nNumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a Boolean value -- in other words, they raise\n\nValueError: The truth value of an array i...
[ 323, 197, 8, 0 ]
[]
[]
[ "boolean", "dataframe", "filtering", "pandas", "python" ]
stackoverflow_0021415661_boolean_dataframe_filtering_pandas_python.txt
Q: How to run two python scripts, simultaneously? I have two python scripts, both of whom i need to start at exactly the same time This is because i am trying to measure performance metrics of both the scripts and it is a compulsory requirement of the task at hand that both of them should have started their execution...
How to run two python scripts, simultaneously?
I have two python scripts, both of whom i need to start at exactly the same time This is because i am trying to measure performance metrics of both the scripts and it is a compulsory requirement of the task at hand that both of them should have started their execution at the same time Is there a trivial way to do this?...
[ "It depends on what precision you mean with \"exactly the same time\".\nIf that means \"within a microsecond\", then it is probably not possible.\nBut it I write a script like this (assuming a POSIX operating system):\npython a.py >/dev/null &\npython b.py >/dev/null &\n\nAnd run that with /usr/bin/time sh together...
[ 0 ]
[ "I think you mean you want to open two python files at the same time? Just CTRL click them so that they are both selected and then press ENTER or right click --> open\nhope that helps\n" ]
[ -1 ]
[ "performance", "python" ]
stackoverflow_0074244401_performance_python.txt
Q: How do you calculate spherical camera position from point correspondence? I have 4 points marked in an equirectangular image. [Red dots] I also have the 4 corresponding points marked in an overhead image [ Red dots ] How do I calculate where on the overhead image the camera was positioned? So far I see there are...
How do you calculate spherical camera position from point correspondence?
I have 4 points marked in an equirectangular image. [Red dots] I also have the 4 corresponding points marked in an overhead image [ Red dots ] How do I calculate where on the overhead image the camera was positioned? So far I see there are 4 rays (R1, R2, R3, R4) extending from the unknown camera center C = (Cx, Cy, ...
[ "EDIT: using the MAP picture width/length for spherical conversion gives way better results for camera center. Points positions are still a bit messy.\nMap with a better solution for camera center: , points are somewhat flattened\nI took the liberty of rewriting a bit of the code, adding points identification using...
[ 0, 0 ]
[]
[]
[ "camera_calibration", "computer_vision", "opencv", "python" ]
stackoverflow_0074173467_camera_calibration_computer_vision_opencv_python.txt
Q: Renaming column names in Pandas I want to change the column labels of a Pandas DataFrame from ['$a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e'] A: Rename Specific Columns Use the df.rename() function and refer the columns to be renamed. Not all the columns have to be renamed: df = df.rename(columns={'...
Renaming column names in Pandas
I want to change the column labels of a Pandas DataFrame from ['$a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e']
[ "Rename Specific Columns\nUse the df.rename() function and refer the columns to be renamed. Not all the columns have to be renamed:\ndf = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})\n# Or rename the existing DataFrame (rather than creating a copy) \ndf.rename(columns={'oldName1': 'newName1',...
[ 4161, 2471, 493, 253, 192, 153, 139, 90, 79, 43, 41, 31, 30, 28, 25, 21, 21, 20, 20, 18, 18, 15, 12, 12, 11, 10, 9, 9, 8, 6, 6, 6, 2, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "rename", "replace" ]
stackoverflow_0011346283_dataframe_pandas_python_rename_replace.txt
Q: How to normalize negative number in numpy array I have video features as numpy files (.npy) with the shape of (15, 2048) with positive and negative value. I want to normalize it so that all the values are positive only. The numpy array is something like this: array([[-1.4004713 , 0.6517762 , -0.11610898, ..., 0....
How to normalize negative number in numpy array
I have video features as numpy files (.npy) with the shape of (15, 2048) with positive and negative value. I want to normalize it so that all the values are positive only. The numpy array is something like this: array([[-1.4004713 , 0.6517762 , -0.11610898, ..., 0.3231497 , 0.10557604, -1.0216804 ], [...
[ "Assuming you want to normalize to the global min and max, and there are no NaNs, the normalized array is given by:\n(arr - arr.min()) / (arr.max() - arr.min())\n\nIf you have NaNs, rephrase this with np.nanmin() and np.nanmax().\n" ]
[ 1 ]
[]
[]
[ "normalize", "numpy", "python" ]
stackoverflow_0074244970_normalize_numpy_python.txt
Q: Conditionally count items in list I have prepared the following code: data = [] for i in range(4, 8): for value in round(df["month"] / 12, 1) #converting months to years if value > i: data.append(value) What I am wanting to do is count the number of values stored in this list data which are gr...
Conditionally count items in list
I have prepared the following code: data = [] for i in range(4, 8): for value in round(df["month"] / 12, 1) #converting months to years if value > i: data.append(value) What I am wanting to do is count the number of values stored in this list data which are greater than i and then store this inform...
[ "Or just\nover4=(round(df.month/12)>=4).sum()\n\nNote: one good rule of thumb to keep in mind \"If I am iterating over pandas rows, I am very probably doing something wrong\"\nTo create your dataframe\novers=pd.DataFrame([[f\"≥{i}\",(round(df.month/12)>=i).sum()] for i in range(4,8)], columns=[\"Description\", \"co...
[ 1, 0 ]
[]
[]
[ "conditional_statements", "list", "python" ]
stackoverflow_0074244601_conditional_statements_list_python.txt
Q: Drawing bbox for realtime object detection without ML I am attempting to do real-time object detection without any ML. The approach is to identify the object per its color profile. I am trying to identify a rectangular object with a single colour and draw a bounding box. This is the code: import cv2 import numpy a...
Drawing bbox for realtime object detection without ML
I am attempting to do real-time object detection without any ML. The approach is to identify the object per its color profile. I am trying to identify a rectangular object with a single colour and draw a bounding box. This is the code: import cv2 import numpy as np class ColourBounds: def __init__(self, rgb): ...
[ "You are trying to do \"color detection\" and then draw a bounding box around it.\nThe easiest way:\nStep 1: Implement color detection.\nI implemented the following code to find the right values for the mask for your image. Play with the trackbars and when you are satisfied with the results, press q and the values ...
[ 3, 0 ]
[]
[]
[ "computer_vision", "object_detection", "opencv", "python" ]
stackoverflow_0069295962_computer_vision_object_detection_opencv_python.txt
Q: ModuleNotFoundError: No module named 'category_encoders' I tried few way to install category encoders and it never works. Here are the ways I did, each installation shows success. anyone has any suggestion? Thanks pip install --upgrade category_encoders conda install -c conda-forge category_encoders from categor...
ModuleNotFoundError: No module named 'category_encoders'
I tried few way to install category encoders and it never works. Here are the ways I did, each installation shows success. anyone has any suggestion? Thanks pip install --upgrade category_encoders conda install -c conda-forge category_encoders from category_encoders.target_encoder import TargetEncoder -------------...
[ "\nmake sure you are using the same python version, when you install the library and you run it.\nmy suggestion is create new virtual environment and activate then install all library that needed, then run your app from there.\n\n", "try this\nfrom sklearn.preprocessing import OneHotEncoder\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0073942841_python.txt
Q: How can I offset / thicken / solidify a 3D mesh in Python? I'm looking for a way to offset a TIN (triangulated irregular network) mesh (e.g. of a landscape) by a consistent distance via a Python script. In the past I've called Blender's Solidify modifier via the API, which works well, but I'd like to find an alter...
How can I offset / thicken / solidify a 3D mesh in Python?
I'm looking for a way to offset a TIN (triangulated irregular network) mesh (e.g. of a landscape) by a consistent distance via a Python script. In the past I've called Blender's Solidify modifier via the API, which works well, but I'd like to find an alternative that doesn't require Blender as a dependency. Currently, ...
[ "I think the easy fix for your offsetting is to move the vertices along the mean normal, instead of moving it by the mean of along each normal.\n(ok the difference can be tricky to see in that sentence ;) )\nto do it by hand\nWhat I mean is that when you get sharp geometries the mean of neighbooring normal is no mo...
[ 0, 0 ]
[]
[]
[ "3d", "mesh", "python" ]
stackoverflow_0061511541_3d_mesh_python.txt
Q: Python version error when running the Splunk TA-geoip2 app I am using Splunk 8+ and Python 3.6. I am trying to run this https://github.com/0x616c6578/TA-geoip2 plugin. I get this error message when I look into search.log and try to run the Python command in the log by itself: C:\Users\strozllc>"C:\Program Files...
Python version error when running the Splunk TA-geoip2 app
I am using Splunk 8+ and Python 3.6. I am trying to run this https://github.com/0x616c6578/TA-geoip2 plugin. I get this error message when I look into search.log and try to run the Python command in the log by itself: C:\Users\strozllc>"C:\Program Files\Splunk\bin\Python3.exe" "C:\Program Files\Splunk\etc\apps\TA-ge...
[ "This is a case of Python 3 trying to run Python 2 code. The latest versions of Splunk (you didn't say which one you're using) only support Python 3 so an error will be thrown when an outdated library file is encountered.\nI'd suggest filing an issue on GitHub, but the app appears to be abandonware since it hasn't...
[ 1 ]
[]
[]
[ "geoip", "maxmind", "python", "splunk" ]
stackoverflow_0074242030_geoip_maxmind_python_splunk.txt
Q: Creating a plot of a SymPy expression with a a equation with multiple variables I have figured out how to make a equation with SymPy, however, I am not sure how to plot the relationship between two values. I keep getting an TypeError: Cannot convert expression to float whenever I write plt.plot(Rho , T). I have a ...
Creating a plot of a SymPy expression with a a equation with multiple variables
I have figured out how to make a equation with SymPy, however, I am not sure how to plot the relationship between two values. I keep getting an TypeError: Cannot convert expression to float whenever I write plt.plot(Rho , T). I have a code like this so far: import matplotlib as plt from sympy import init_session init_...
[ "You need to provide values for the independent variable(s). For example, to plot an expression like y = x**2 - 1, I would do this:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(0, 20) # Provide the range of the independent variable.\ny = x**2 - 1 # Compute the dependent variable.\...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python", "sympy" ]
stackoverflow_0074241891_matplotlib_plot_python_sympy.txt
Q: I keep getting an error when running my program in VS Code I have recently started coding and I am using Pycharm and VS Code. I encountered a problem and I cant seem to find any soloution to it, and I am to fresh to figure it out myself. I run this simple program: count = 0 for number in range(1, 10): if numbe...
I keep getting an error when running my program in VS Code
I have recently started coding and I am using Pycharm and VS Code. I encountered a problem and I cant seem to find any soloution to it, and I am to fresh to figure it out myself. I run this simple program: count = 0 for number in range(1, 10): if number % 2 == 0: count += 1 print(number) print(f"We ...
[ "I went in there and I had these three lines printed in the top of my file:\nfrom distutils.cmd import Command\nfrom termios import CBAUDEX\nfrom tkinter import FIRST.\nI removed them and now I dont get the error anymore!\n" ]
[ 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074087872_python_visual_studio_code.txt
Q: de-dup list of tuples while preserving order of initial appearance I have a list of tuples which might have duplicates. I need to remove the duplicates (in the strict sense, e.g., after the initial appearance of a given tuple.) However, the gimmicks I found online using set-based list comprehensions don't work for...
de-dup list of tuples while preserving order of initial appearance
I have a list of tuples which might have duplicates. I need to remove the duplicates (in the strict sense, e.g., after the initial appearance of a given tuple.) However, the gimmicks I found online using set-based list comprehensions don't work for me because I need to preserve the order: >>> x = [(4,0),(4,0),(1,3) ......
[ "Aside from the dict.fromkeys-method suggested by @andrej-kesely, I can think of three different solutions to this problem.\nI know you did not ask for this, but I wrote a little test script for fun to see, how the various correct approaches hold up in terms of execution time. This should work under Python 3.7+:\ni...
[ 1 ]
[]
[]
[ "python", "set", "tuples" ]
stackoverflow_0074244127_python_set_tuples.txt
Q: Return a List Based on Multiple Filters from Multiple Dataframes How do I return a list based on multiple filters from multiple dataframes? I have three dataframes: df1 Ticker Company Name COMBOACCRUAL 0 ABC ABC Co. 0.9 1 DEF DEF Co. 0.99 2 GHI GHI Co. 0.5 df2 Ticker Company Name PMAN 0 AB...
Return a List Based on Multiple Filters from Multiple Dataframes
How do I return a list based on multiple filters from multiple dataframes? I have three dataframes: df1 Ticker Company Name COMBOACCRUAL 0 ABC ABC Co. 0.9 1 DEF DEF Co. 0.99 2 GHI GHI Co. 0.5 df2 Ticker Company Name PMAN 0 ABC ABC Co. 0.7 1 DEF DEF Co. 0.3 2 GHI GHI Co. 0.55 df3 Ticke...
[ "Merge the three df together first and apply your filter?\ncolumns = ['Ticker', 'Company', 'Name']\n\ndf4 = df1.merge(df2, on=columns).merge(df3, on=columns)\n\ndf4 = df4[(df4['COMBOACCRUAL'] < 0.95) & (df4['PMAN'] < 0.95) & (df4['PFD'] < 0.95)]\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "filter", "list", "python" ]
stackoverflow_0074245079_dataframe_filter_list_python.txt
Q: Python. variable +=1 is not working as it should be in turtle I'm trying to make something like a "clicker" on buttons for 2 person's, but my variable +=1 is not working in this program. My code: from tkinter import * import turtle wn = turtle.Screen() wn.title("Pong by Daniel") wn.bgcolor("black") wn.setup(width=...
Python. variable +=1 is not working as it should be in turtle
I'm trying to make something like a "clicker" on buttons for 2 person's, but my variable +=1 is not working in this program. My code: from tkinter import * import turtle wn = turtle.Screen() wn.title("Pong by Daniel") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) score_a = 0 score_b = 0 pen = turtle...
[ "there is nothing wrong with variable += 1. Its not working because of scope issue and not defind commend to buttons. Try this:\nfrom tkinter import *\nimport turtle\n\nwn = turtle.Screen()\nwn.title(\"Pong by Daniel\")\nwn.bgcolor(\"black\")\nwn.setup(width=800, height=600)\nwn.tracer(0)\nscore_a = 0\nscore_b = 0...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074245130_python.txt
Q: comas with quote mark right behind I need to format a string dictionary before convert it into dict I tried it with regex: decmark_reg = re.compile('(?<=\d),(?=\d)') dict_decmark = decmark_reg.sub('.',dict_quotes) convertedDict = json.loads(dict_decmark) but then I realized it mess with "f...
comas with quote mark right behind
I need to format a string dictionary before convert it into dict I tried it with regex: decmark_reg = re.compile('(?<=\d),(?=\d)') dict_decmark = decmark_reg.sub('.',dict_quotes) convertedDict = json.loads(dict_decmark) but then I realized it mess with "fingerOne_OffTimes" values dict_str =...
[ "Try (regex101):\nimport re\n\ndict_str = \"\"\"\\\n{\"level\":0,6, \n \"params\": {\n \"startLvlTime\":1114.3851318359375,\n \"fingerOne_OffTimes\":[459,4716491699219,78532]}}\"\"\"\n\npat = re.compile(r\"(\\[.*?\\])|(\\d,\\d)\")\n\ndict_str = pat.sub(\n lambda g: g.group(1) or g.group(2).replace(\",\", \"....
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074245115_python_regex.txt
Q: Pandas pipe throws error that df to be passed as an argument Pandas pipe throws error that df to be passed as argument Ideally pipe should take the dataframe as argument by default which is not happening in my case. class Summary: def get_src_base_df(self): <do stuff> return df @staticmethod def sum_a...
Pandas pipe throws error that df to be passed as an argument
Pandas pipe throws error that df to be passed as argument Ideally pipe should take the dataframe as argument by default which is not happening in my case. class Summary: def get_src_base_df(self): <do stuff> return df @staticmethod def sum_agg(df): cols = 'FREQUENCY_ID|^FLAG_' df = (df.filter(regex...
[ "By doing self.sum_agg(), you're calling the sum_agg function (@staticmethods in Python are pretty much indistinguishable from functions), and since it doesn't have an argument right there in that call, it rightfully fails. You need to pass the function object, not the value returned by the function.\nDo this, inst...
[ 2 ]
[]
[]
[ "pandas", "pipe", "python" ]
stackoverflow_0074245075_pandas_pipe_python.txt
Q: Replacin values of a pandas column I have the following dataframe: col1 01 1 02 2 03 3 00 0 How can I replace values in col1 to be like the expected output below: Expected Output: col1 1 1 2 2 3 3 0 0 A: Can you try this? df['col1']=[int(x) for x in df['col1']] A: You can do it like this: df['col1'] = df['col...
Replacin values of a pandas column
I have the following dataframe: col1 01 1 02 2 03 3 00 0 How can I replace values in col1 to be like the expected output below: Expected Output: col1 1 1 2 2 3 3 0 0
[ "Can you try this?\ndf['col1']=[int(x) for x in df['col1']]\n\n", "You can do it like this:\ndf['col1'] = df['col1'].astype('int')\n\n", "df['col1'] = df['col1'].map(int)\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074242479_pandas_python.txt
Q: Python > Getting stuck on Proceed to Checkout New to Python. Creating smoke test for Checkout process. Am unable to click the Proceed to Checkout button. On the Add-Ons page of the Checkout process, I am unable to click the Proceed to Checkout button which allows the user to go to the Attendee Info page of Checkou...
Python > Getting stuck on Proceed to Checkout
New to Python. Creating smoke test for Checkout process. Am unable to click the Proceed to Checkout button. On the Add-Ons page of the Checkout process, I am unable to click the Proceed to Checkout button which allows the user to go to the Attendee Info page of Checkout. I've tried a few different things. Below is the...
[ "I don't know why but CSS_SELECTOR has problem even with button[title] but XPATH works for me\nfind_element(By.XPATH, \"//button[@title='proceed to checkout']\")\n\n\nBTW:\nfirst I tested it with find_elements (with s at the end) and it finds two buttons with 'proceed to checkout' - maybe this makes some problem wi...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074244446_python.txt
Q: Install Scip optimization I'm trying install Scip optimization for python and I'm following a video but in the video it is installing Scip Optimization 7, and I'm installing Scip Optimization 8. Then I need to install on prompt too. pip install pyscipopt but it gave me an error: Microsoft Windows [versão 10.0.19...
Install Scip optimization
I'm trying install Scip optimization for python and I'm following a video but in the video it is installing Scip Optimization 7, and I'm installing Scip Optimization 8. Then I need to install on prompt too. pip install pyscipopt but it gave me an error: Microsoft Windows [versão 10.0.19043.1645] (c) Microsoft Corpor...
[ "I was stuck with the same problem.\nIt was resolved by installing the \"Microsoft C++ Build Tools\" for desktop C++ development which I had not chosen in my earlier attempts.\n" ]
[ 0 ]
[]
[]
[ "installation", "python", "scip" ]
stackoverflow_0072131821_installation_python_scip.txt
Q: 'Pixmap' object has no attribute 'getImageData' I am trying to create pdf reader in python and I have used tkPDFViewer library but when i run this according to tkPDFViewer library and i used tkPDFViewer Library example at first it shows 'Page' object has no attribute 'getPixmap' but when i searched this problem i ...
'Pixmap' object has no attribute 'getImageData'
I am trying to create pdf reader in python and I have used tkPDFViewer library but when i run this according to tkPDFViewer library and i used tkPDFViewer Library example at first it shows 'Page' object has no attribute 'getPixmap' but when i searched this problem i got an answer in stackoverflow and it said pix = page...
[ "please use\nimg = pix1.tobytes(\"ppm\")\n\ninstead of\nimg = pix1.getImageData(\"ppm\")\n\nin line no 48 in tkPDFViewer library\nafter editing the tkPDFViewer library it will be looked like this\n try:\n from tkinter import*\n import fitz\n from tkinter.ttk import Progressbar\n from threading import Th...
[ 1 ]
[]
[]
[ "pdf_viewer", "python", "tkpdfviewer" ]
stackoverflow_0074235747_pdf_viewer_python_tkpdfviewer.txt
Q: os.system argument from config file I made this activity and it works. I need to have config file with USB/VID/PID. def resetactivity(): os.system(r'"devcon.exe restart "*USB\VID_04E8&PID_3321*"') I try to do this with config parser. I made config.txt: [My Section] usbdev = r'"devcon.exe restart "*USB\VID...
os.system argument from config file
I made this activity and it works. I need to have config file with USB/VID/PID. def resetactivity(): os.system(r'"devcon.exe restart "*USB\VID_04E8&PID_3321*"') I try to do this with config parser. I made config.txt: [My Section] usbdev = r'"devcon.exe restart "*USB\VID_04E8&PID_3321*"' I read my config file ...
[ "Try this code\nimport configparser\nimport os\n\ndef resetactivity():\n config = configparser.ConfigParser()\n config.read('config.txt')\n usbdev = config.get('My Section', 'usbdev')\n print(usbdev)\n os.system(usbdev)\n\nif __name__ == \"__main__\":\n resetactivity()\n\nWith config.txt formatted...
[ 0 ]
[]
[]
[ "configparser", "os.system", "python" ]
stackoverflow_0074245258_configparser_os.system_python.txt
Q: How to process large amounts of un/semi-structured data in a distributed manner? I have a mongodb collection with tens of millions of documents. Every document can be considered self-contained (i.e, when I process 1 document, it contains all the data you need to analyse/process that document. you don't have to loo...
How to process large amounts of un/semi-structured data in a distributed manner?
I have a mongodb collection with tens of millions of documents. Every document can be considered self-contained (i.e, when I process 1 document, it contains all the data you need to analyse/process that document. you don't have to lookup another collection, etc). Currently I process the data (in python) like so: creat...
[ "You could utilize apache airflow. It allows you to create data pipelines using python code\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "mongodb", "parallel_processing", "python" ]
stackoverflow_0074245188_apache_spark_mongodb_parallel_processing_python.txt
Q: How can I reshape a 2D array into 1D in python? Let me edit my question again. I know how flatten works but I am looking if it possible to remove the inside braces and just simple two outside braces just like in MATLAB and maintain the same shape of (3,4). here it is arrays inside array, and I want to have just on...
How can I reshape a 2D array into 1D in python?
Let me edit my question again. I know how flatten works but I am looking if it possible to remove the inside braces and just simple two outside braces just like in MATLAB and maintain the same shape of (3,4). here it is arrays inside array, and I want to have just one array so I can plot it easily also get the same res...
[ "Simply, using reshape function with -1 as shape should do:\nprint(s)\nprint(s.reshape(-1))\n\n[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n[ 0 1 2 3 4 5 6 7 8 9 10 11]\n\n", "Try .ravel():\ns = np.arange(12).reshape(3, 4)\nprint(s.ravel())\n\nPrints:\n[ 0 1 2 3 4 5 6 7 8 9 10 11]\n\n", "F...
[ 1, 1, 1, 0 ]
[]
[]
[ "arrays", "flatten", "matrix", "python" ]
stackoverflow_0074244578_arrays_flatten_matrix_python.txt
Q: Difference between 'cls' and 'self' in Python classes? Why is cls sometimes used instead of self as an argument in Python classes? For example: class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname @classmethod def from_fullname(cls,...
Difference between 'cls' and 'self' in Python classes?
Why is cls sometimes used instead of self as an argument in Python classes? For example: class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname @classmethod def from_fullname(cls, fullname): cls.firstname, cls.lastname = fullname.s...
[ "The distinction between \"self\" and \"cls\" is defined in PEP 8 . As Adrien said, this is not mandatory. It's a coding style. PEP 8 says:\n\nFunction and method arguments:\nAlways use self for the first argument to instance methods.\nAlways use cls for the first argument to class methods.\n\n", "cls implies tha...
[ 399, 115, 61, 33, 9, 9, 0 ]
[]
[]
[ "class", "object", "python", "self", "terminology" ]
stackoverflow_0004613000_class_object_python_self_terminology.txt
Q: Is there a faster way to iterate through rows in a specific column of a pandas.DataFrame without using a loop? I have a pandas.DataFrame with data from various news articles in the Urdu language, and I'm using the Natural Language Toolkit (NLTK) to scrape through it for use in my n-gram language model. For this, I...
Is there a faster way to iterate through rows in a specific column of a pandas.DataFrame without using a loop?
I have a pandas.DataFrame with data from various news articles in the Urdu language, and I'm using the Natural Language Toolkit (NLTK) to scrape through it for use in my n-gram language model. For this, I have to initially tokenise the data, which is stored in a 'News Text' column inside my pandas.DataFrame, and then s...
[ "I believe df.column.map() is supposed to be faster.\ndf['token'] = df['News Text'].map(nltk.tokenize.word_tokenize)\n\nIf a str() conversion is needed I suggest putting it in the word_tokenize function.\n", "Besides the .map method mentioned in the answer by the other person, I'd try one more thing:\ntokens = ''...
[ 0, 0 ]
[]
[]
[ "dataframe", "nltk", "numpy", "pandas", "python" ]
stackoverflow_0074245105_dataframe_nltk_numpy_pandas_python.txt
Q: Failed to convert a NumPy array to a Tensor (Unsupported object type list) I am getting this error all the time. Any idea? I have added all the necessary libraries required. Anything wrong with tensorflow? I am not able to understand it.Trying to create a chat bot. The json file is ok. I have checked some videos, ...
Failed to convert a NumPy array to a Tensor (Unsupported object type list)
I am getting this error all the time. Any idea? I have added all the necessary libraries required. Anything wrong with tensorflow? I am not able to understand it.Trying to create a chat bot. The json file is ok. I have checked some videos, I guess I have to change the train_x and train_y data. import random import nump...
[ "Only 1's are appended to the area due to a faulty if condition in your code, resulting in a variable number of elements in each row of train_x. Since an array must have the same amount of elements in all of its rows, the list is not converted to np.array. Kindly change the code as follows.\nfor word in words:\n ...
[ 0 ]
[]
[]
[ "keras", "numpy", "python", "tensorflow" ]
stackoverflow_0067827177_keras_numpy_python_tensorflow.txt
Q: Scaling gives me worse result (lower R-squared) in Linear Regression (I leave my dataset at the bottom line). I'm trying to use Linear Regression on a dataset where predictors are the product ID, weight, type, Outlet_Establishment_Year, etc and target variable is the Item_Outlet_Sales. I use R-squared as the metri...
Scaling gives me worse result (lower R-squared) in Linear Regression
(I leave my dataset at the bottom line). I'm trying to use Linear Regression on a dataset where predictors are the product ID, weight, type, Outlet_Establishment_Year, etc and target variable is the Item_Outlet_Sales. I use R-squared as the metric. I think the predictors have different units so I'll need to scale them....
[ "It seems like the scaling is also applied to the one-hot-encoded dummy variable which IMO should not happen. If you only scale continuous variables, does that change the behavior?\nGenerally, scaling only affects the interpretation of the coefficients and not the quality of the model. After standard scaling, a coe...
[ 0 ]
[]
[]
[ "linear_regression", "python", "scaling" ]
stackoverflow_0074245326_linear_regression_python_scaling.txt
Q: How can we create this type of filter checkbox in Streamlit Python? I have tried doing this: import pandas as pd import streamlit as st import plotly.express as px from PIL import Image st.set_page_config(page_title=' Sales Report ') st.header('Sales Report') st.subheader('Results') df=pd.read_csv('data') st.da...
How can we create this type of filter checkbox in Streamlit Python?
I have tried doing this: import pandas as pd import streamlit as st import plotly.express as px from PIL import Image st.set_page_config(page_title=' Sales Report ') st.header('Sales Report') st.subheader('Results') df=pd.read_csv('data') st.dataframe(df) I got the table showing up on Website, but how can I add th...
[ "Explanation in the code\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\nnp.random.seed(0)\n\n# toy data\ndef get_data():\n df = pd.DataFrame(np.random.randn(10, 3), columns=[\"Category\", \"A\",\"B\"])\n df[\"Category\"] = np.random.choice(['Apple', 'Banana', 'Grapes'], 10)\n return df\n...
[ 1 ]
[]
[]
[ "filter", "pandas", "plotly", "python", "streamlit" ]
stackoverflow_0074243710_filter_pandas_plotly_python_streamlit.txt
Q: Script for exporting/importing a Python Virtual Environment (venv) - I'm looking for a way to easily move it to another computer Normally when I want to move a Python-project to another computer it's always a bit of a hassle. I thought maybe there was a way to export/import a project with a bat-script (Windows 10)...
Script for exporting/importing a Python Virtual Environment (venv) - I'm looking for a way to easily move it to another computer
Normally when I want to move a Python-project to another computer it's always a bit of a hassle. I thought maybe there was a way to export/import a project with a bat-script (Windows 10), but I suspect it's a bit more tricky. What I normally do when I want to move a project to another computer is that I first create th...
[ "I figured out a way to do it, just thought I'd share if anyone else is interested. There might be better ways to do this though, so feel free to improve upon my solution :)\nMy main project:\nIn my main project (which I want to move to another computer) I have created a folder with the Python-installer I've used f...
[ 0 ]
[]
[]
[ "batch_file", "copy", "duplicates", "environment", "python" ]
stackoverflow_0074236872_batch_file_copy_duplicates_environment_python.txt
Q: keras - Graph disconnected: cannot obtain value for tensor KerasTensor I've been trying to create a 7 columns (features) model with Keras functional API and map it to the a 6 classes output. import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Input, Dense, Concatenate in...
keras - Graph disconnected: cannot obtain value for tensor KerasTensor
I've been trying to create a 7 columns (features) model with Keras functional API and map it to the a 6 classes output. import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Input, Dense, Concatenate input_message = Input(shape=(128,)) x = Dense(64, activation="relu")(input_mes...
[ "You may want to look at the variable names that you have. Usually the GraphDisconnected error is caused by having overriding names in the program.\n", "Why are you creating so many models when you actually want one?\nimport tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import...
[ 2, 1, 0 ]
[]
[]
[ "keras", "python", "tensorflow", "text_classification" ]
stackoverflow_0068432386_keras_python_tensorflow_text_classification.txt
Q: Why is this python loop not working as I expect? Why does it not generate two random numbers untill theyre are 5 and 3? import random rolla = int(0) rollb = int(0) while rolla != 5 and rollb != 3: rolla = random.randint(1, 10) rollb = random.randint(1, 11) print(rolla, ' - ', rollb) A: import random rol...
Why is this python loop not working as I expect?
Why does it not generate two random numbers untill theyre are 5 and 3? import random rolla = int(0) rollb = int(0) while rolla != 5 and rollb != 3: rolla = random.randint(1, 10) rollb = random.randint(1, 11) print(rolla, ' - ', rollb)
[ "import random\n\nrolla = 0\nrollb = 0\n\nwhile not(rolla == 5 and rollb == 3):\n rolla = random.randint(1, 10)\n rollb = random.randint(1, 11)\n print(rolla, ' - ', rollb)\n\n\n\n\nyou would have to use a not statement to encompass the entire phrase, otherwise it will stop if one of the conditions is false.\n",...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074244439_python.txt
Q: Floor `pandas.DatetimeIndex` using `grouper` Consider the following index i which spans 1.5 days: import pandas as pd i = pd.date_range('2022-01-01', freq='H', periods=36) The timestamps can be floored to the nearest day start, which gives 24 times '2022-01-01' and 12 times '2022-01-02': i.floor("D") # DatetimeIn...
Floor `pandas.DatetimeIndex` using `grouper`
Consider the following index i which spans 1.5 days: import pandas as pd i = pd.date_range('2022-01-01', freq='H', periods=36) The timestamps can be floored to the nearest day start, which gives 24 times '2022-01-01' and 12 times '2022-01-02': i.floor("D") # DatetimeIndex(['2022-01-01', '2022-01-01', '2022-01-01', '20...
[ "There is not much advantage in \"reusing\" gr, it's not like reusing a GroupbBy object: g = df.groupby(...) that can be expensive to compute.\nNevertheless, looks like you want:\ngr = pd.Grouper(freq='D', offset=pd.Timedelta(hours=6))\n\ng = pd.Series(index=i, dtype='float').groupby(gr)\n\nidx = g.size()\n\nout = ...
[ 1 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074245377_datetime_pandas_python.txt
Q: Efficient Bulk Insert/Update Operations on Existing Table Using SQLAlchemy I am looking to insert/update a large volume of data stored in either a list of tuples or list of dictionaries into an existing table using SQLAlchemy. What is the most efficient way to do this? What I have right now is this, session_maker ...
Efficient Bulk Insert/Update Operations on Existing Table Using SQLAlchemy
I am looking to insert/update a large volume of data stored in either a list of tuples or list of dictionaries into an existing table using SQLAlchemy. What is the most efficient way to do this? What I have right now is this, session_maker = sqlalchemy.orm.sessionmaker() session_maker .configure(bind=engine) inspector ...
[ "You should try using bulk_update_mappings/bulk_insert_mappings. Also, you have an option of using a parameter called fast_executemany on the engine creation. Please, refer to my answer at:\nUsing bulk_update_mappings in SQLAlchemy to update multiple rows with different values.\n" ]
[ 1 ]
[]
[]
[ "bulkinsert", "bulkupdate", "python", "sqlalchemy" ]
stackoverflow_0069939236_bulkinsert_bulkupdate_python_sqlalchemy.txt
Q: LeetCode challenge|| Python || 645. Set Mismatch | I encountered a confusing error So, I was trying to solve this problem in leetcode :(this is a direct link to the problem : Set Mismatch - LeetCode ). You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some e...
LeetCode challenge|| Python || 645. Set Mismatch | I encountered a confusing error
So, I was trying to solve this problem in leetcode :(this is a direct link to the problem : Set Mismatch - LeetCode ). You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results...
[]
[]
[ "In Python it is always worth looking for ways which do not involve huge loops and indices. For example using Counter, dictionary and sets.\nfrom collections import Counter\n\nmylist = sorted([1, 2, 2, 4])\nmyset = {x for x in range(1, mylist[-1] + 1)}\n\ncounts = Counter(mylist) # a dictionary of counts in mylist...
[ -1 ]
[ "mismatch", "python", "set" ]
stackoverflow_0074245222_mismatch_python_set.txt
Q: Why are edges added as nodes in networkx? Why is 0,1,2 added to nodes upon adding edges (last print statement in code below)? import networkx as nx G = nx.Graph() G.add_nodes_from([(0,0,0), (1,0,0), (1,1,0)]) print(G.nodes) # >> [(0, 0, 0), (1, 0, 0), (1, 1, 0)] edges = [(0, 1),(1,2)] G.add_edges_from(edges) print...
Why are edges added as nodes in networkx?
Why is 0,1,2 added to nodes upon adding edges (last print statement in code below)? import networkx as nx G = nx.Graph() G.add_nodes_from([(0,0,0), (1,0,0), (1,1,0)]) print(G.nodes) # >> [(0, 0, 0), (1, 0, 0), (1, 1, 0)] edges = [(0, 1),(1,2)] G.add_edges_from(edges) print(G.nodes) # >> [(0, 0, 0), (1, 0, 0), (1, 1, 0)...
[ "In NetworkX, nodes are identified by any hashable object. So the add_nodes_from call adds three nodes, each a tuple:\n\n(0, 0, 0)\n(1, 0, 0)\n(1, 1, 0)\n\nMaybe you understood this already.\nadd_edges_from takes an iterable of 2-tuples (or 3-tuples), where each tuple identifies two nodes. So (0, 1) adds an edge be...
[ 3 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0074245476_networkx_python.txt
Q: convert 1d array to length of 2d array column in pandas dataframe The dataframe contains two array columns which are 1d and 2d arrays. | 1d_col | 2d_col | | --------------------------| ---------------------------| | ["negative", "positive"] | [["zero", ""], ["one", ""]]| | [...
convert 1d array to length of 2d array column in pandas dataframe
The dataframe contains two array columns which are 1d and 2d arrays. | 1d_col | 2d_col | | --------------------------| ---------------------------| | ["negative", "positive"] | [["zero", ""], ["one", ""]]| | ["positive", "negative"] | [["two", ""], ["zero", ""]]| | ["negative"] ...
[ "With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"1d_col\": [\n [\"negative\", \"positive\"],\n [\"positive\", \"negative\"],\n [\"negative\"],\n [\"positive\"],\n ],\n \"2d_col\": [\n [[\"zero\", \"\"]...
[ 1 ]
[]
[]
[ "dataframe", "multidimensional_array", "pandas", "python" ]
stackoverflow_0074225028_dataframe_multidimensional_array_pandas_python.txt
Q: TypeError: 'Adam' object is not callable I'm trying to use this method of updating a pretrained model based on learning rate for each group of layers. I apply the same method but I get this error TypeError: 'Adam' object is not callable This is the code for the training loop: from typing import Dict, List, Tuple ...
TypeError: 'Adam' object is not callable
I'm trying to use this method of updating a pretrained model based on learning rate for each group of layers. I apply the same method but I get this error TypeError: 'Adam' object is not callable This is the code for the training loop: from typing import Dict, List, Tuple def train_step(model: torch.nn.Module, ...
[ "I assume that parameters_1 is some dict of parameters.\ntry unpacking it: optimizer = torch.optim.Adam(**parameters_1)\n" ]
[ 0 ]
[]
[]
[ "deep_learning", "python", "pytorch" ]
stackoverflow_0074238235_deep_learning_python_pytorch.txt
Q: Moving Python & Javascript code to Raspberry Pi created INTERNAL SERVER ERROR with Twilio Video Streaming Demo I setup a Twilio video streaming tutorial using a walkthrough part 1 and part 2 which works great on my Macbook. I then moved the code to a Raspberry PI and I'm not able to get it to work. After trouble...
Moving Python & Javascript code to Raspberry Pi created INTERNAL SERVER ERROR with Twilio Video Streaming Demo
I setup a Twilio video streaming tutorial using a walkthrough part 1 and part 2 which works great on my Macbook. I then moved the code to a Raspberry PI and I'm not able to get it to work. After troubleshooting various library issues, the server now runs. The problem is the video doesn't load. Specifically in the br...
[ "I was able to fix this by re-creating the project from scratch directly on the Raspberry Pi.\nAlthough I would love to know why it didn't 'just' transfer, I'm happy to have it working.\n" ]
[ 0 ]
[]
[]
[ "javascript", "python", "twilio", "video_streaming" ]
stackoverflow_0074226499_javascript_python_twilio_video_streaming.txt
Q: How to convert random number generation from Matlab to Python Here is the code I am trying to convert from Matlab: function x=finiterv(s,p,m) % returns m samples % of finite (s,p) rv %s=s(:);p=p(:); r=rand(m,1); cdf=cumsum(p); x=s(1+count(cdf,r));` And here is my Python code: def infinterv(s,p,m): #return m sampl...
How to convert random number generation from Matlab to Python
Here is the code I am trying to convert from Matlab: function x=finiterv(s,p,m) % returns m samples % of finite (s,p) rv %s=s(:);p=p(:); r=rand(m,1); cdf=cumsum(p); x=s(1+count(cdf,r));` And here is my Python code: def infinterv(s,p,m): #return m samples #of finite (s,p) rv r=random.uniform((m,1)) cdf=p.cumsum(axis=0)...
[ "Change r=random.uniform((m,1)) to r=random.uniform(m,1).\nThe way you wrote it, you are passing one argument (which is a tuple) to the uniform function, but it expects two individual numbers.\n" ]
[ 0 ]
[]
[]
[ "matlab", "python", "random" ]
stackoverflow_0074245540_matlab_python_random.txt
Q: Save a list from cvs.DictReader in python i have a simply csv file like this: col1,col2,col3 house,55,600 cottage,88,100 I read in this way: with open("house.csv", "r+", newline="", encoding="UTF-8") as csv_file: file_r = csv.DictReader(csv_file) for row in file_r: print(row["col1"]) How can I sav...
Save a list from cvs.DictReader in python
i have a simply csv file like this: col1,col2,col3 house,55,600 cottage,88,100 I read in this way: with open("house.csv", "r+", newline="", encoding="UTF-8") as csv_file: file_r = csv.DictReader(csv_file) for row in file_r: print(row["col1"]) How can I save the result of row["col1"] to a list? Thanks I...
[ "When you write list(row[\"col1\"]) you are converting the string value in col1 in each row to a list.\nWhat you want is to append each value to a list:\ncol1_values = []\n\nfor row in file_r:\n col1_values.append(row[\"col1\"])\n\n" ]
[ 1 ]
[]
[]
[ "csv", "dictionary", "for_loop", "list", "python" ]
stackoverflow_0074245194_csv_dictionary_for_loop_list_python.txt
Q: How to plot with x in decreasing order? Sometimes y increases when x decreases: from sympy import symbols, plot p = symbols('p', positive=True) h = (3.731444 - p**0.1902631) / 0.841728e-4 p_low = 150 p_high = 1013.25 plot(h, (p, p_low, p_high), axis_center=(p_low,0)) It can be more convenient to have a curve ...
How to plot with x in decreasing order?
Sometimes y increases when x decreases: from sympy import symbols, plot p = symbols('p', positive=True) h = (3.731444 - p**0.1902631) / 0.841728e-4 p_low = 150 p_high = 1013.25 plot(h, (p, p_low, p_high), axis_center=(p_low,0)) It can be more convenient to have a curve growing towards the top-right corner, it is p...
[ "It can be achieved by swapping the order of the xlim:\nplot(h, (p, p_low, p_high), axis_center=(p_low,0), xlim=(max, min))\n\nUsing the plot's backend parameter you can access also to the matplolib backend. It has the advantage that you can inject your matplotlib commands. A subclass of BaseBackend is required.\nS...
[ 2 ]
[]
[]
[ "plot", "python", "sympy" ]
stackoverflow_0074244889_plot_python_sympy.txt
Q: Jupyter Notebook can't find Python module MDAnalysis I'm very sorry, this question has popped up quite a few times, yet I'm still struggling. I'm using Windows 11. I've installed Anaconda Navigator, created a new environment, and installed the required module (MDAnalysis, via Anaconda Navigator). I launched Juypte...
Jupyter Notebook can't find Python module MDAnalysis
I'm very sorry, this question has popped up quite a few times, yet I'm still struggling. I'm using Windows 11. I've installed Anaconda Navigator, created a new environment, and installed the required module (MDAnalysis, via Anaconda Navigator). I launched Juypter Notebook from the play icon of the desired environment i...
[ "Try installing the missing package directly from the Jupyter Notebook (with pip or conda) as explained here:\nhttps://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/\nEDIT:\nWe figured out that the package was correctly installed and accessible to the Jupyter Notebook environment. (See c...
[ 1 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074245512_jupyter_notebook_python.txt
Q: Python \n newline through Variable Posts \n instead of a new line My code gets the Content of the Message like so (works fine): try: s, message=nachricht.split("'content': '") message, s=message.split("', 'channel_id'") except: message="." Now in the Result we get a Variable like this: Hello i\nam\nDe...
Python \n newline through Variable Posts \n instead of a new line
My code gets the Content of the Message like so (works fine): try: s, message=nachricht.split("'content': '") message, s=message.split("', 'channel_id'") except: message="." Now in the Result we get a Variable like this: Hello i\nam\nDeployd or Hello i am Deployd. This is the Second part it uses the Variab...
[ "Fixed it by adding this code:\ns, message1=nachricht.split(\"'content': '\")\nmessage1, s=message1.split(\"', 'channel_id'\")\nmessage=\"\"\nfor value in message1.split('\\\\n'):\n message=f\"{message}\\n{value}\"\n\nChanched the massage Variable to massage1\nthen splitting it on every \\n and putting the split...
[ 0 ]
[]
[]
[ "newline", "python", "python_requests", "variables" ]
stackoverflow_0074245179_newline_python_python_requests_variables.txt
Q: My Pygame code for drawing a Tetris setup is not working `settings.screen_tile_width is 10. and settings.screen_tile_height is also 10. finally settings.screen_title is Tetris. import settings import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((settings.screen_tile_width * 50, setti...
My Pygame code for drawing a Tetris setup is not working
`settings.screen_tile_width is 10. and settings.screen_tile_height is also 10. finally settings.screen_title is Tetris. import settings import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((settings.screen_tile_width * 50, settings.screen_tile_height * 50)) pygame.display.set_caption(setti...
[ "You used range incorrectly. The arguments are start, stop and step. You cannot skip start if you want to use step:\nfor x in range(0, settings.screen_tile_width * 50, 50):\n for y in range(0, settings.screen_tile_height * 50, 50):\n\nHowever, for performace reasons, I suggest creating the Surfaces before the ap...
[ 1 ]
[]
[]
[ "macos", "pygame", "python", "python_3.x" ]
stackoverflow_0074245545_macos_pygame_python_python_3.x.txt
Q: how to use pretrained model CNN with real images various size? how to use pretrained model on 512x512 images on real images with different sizes like Yolo object detection on real image ? CNNs require fixed image sizes, so how do you manage to use the models on real images larger than the inputs? A: If it is jus...
how to use pretrained model CNN with real images various size?
how to use pretrained model on 512x512 images on real images with different sizes like Yolo object detection on real image ? CNNs require fixed image sizes, so how do you manage to use the models on real images larger than the inputs?
[ "If it is just about the image size, you could resize your image to have same size as model input. When you receive the output, assuming that you have bounding boxes or locations etc, you can always rescale them back to original image size. Many ML/DL frameworks provide this functionality\n" ]
[ 0 ]
[]
[]
[ "conv_neural_network", "python", "pytorch" ]
stackoverflow_0074245656_conv_neural_network_python_pytorch.txt
Q: count the amount of transactions that begin and end I have a this logfile: 19-3-2020 01:37:31.995 INFO 18 188 mailbox allocated for rsvp 19-3-2020 01:37:32.039 INFO 14 194 creating mailslot for dump 19-3-2020 01:37:32.082 INFO 18 194 out of INFO allcations 19-3-2020 01:37:32.119 INFO 18 188 cre...
count the amount of transactions that begin and end
I have a this logfile: 19-3-2020 01:37:31.995 INFO 18 188 mailbox allocated for rsvp 19-3-2020 01:37:32.039 INFO 14 194 creating mailslot for dump 19-3-2020 01:37:32.082 INFO 18 194 out of INFO allcations 19-3-2020 01:37:32.119 INFO 18 188 creating mailslot for RSVP client API 19-3-2020 01:37:32.157...
[ "You can do like following:\nfrom collections import defaultdict\n\ntransactions = defaultdict(dict)\nwith open('logfile.log', 'r') as f:\n lines = f.readlines()\n\n\nbeginnings = set()\nendings = set()\nfor line in lines:\n if \"transaction\" in line:\n if \"begin\" in line:\n transaction_i...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074245550_python.txt
Q: Is there a Python function that encodes output for JavaScript contexts? In Python 3.6+, is there a succinct way to encode output for JavaScript contexts? This means, if I start with any unsanitized input string, encode it properly, then replace VALUE below with it, all XSS attacks in the webpage will be prevented....
Is there a Python function that encodes output for JavaScript contexts?
In Python 3.6+, is there a succinct way to encode output for JavaScript contexts? This means, if I start with any unsanitized input string, encode it properly, then replace VALUE below with it, all XSS attacks in the webpage will be prevented. The input won't be able to break out of the JavaScript string, nor the HTML....
[ "One solution is to use a CDATA Section, which is valid in XML. A CDATA section is declared using <![CDATA[, continues until ]]>, and protects the input from breaking out of the HTML. This can simplify the code you have to write yourself. Here, VALUE is an XSS attack, which doesn't work because the input is within ...
[ 0 ]
[]
[]
[ "html", "python", "python_3.6", "python_3.x" ]
stackoverflow_0074241129_html_python_python_3.6_python_3.x.txt
Q: Does anyone know why I have an attribute error on a Python Discord bot? Discord.py bot attribute error I have a Discord.py bot that I have been making recently on Replit. It has a few humor commands and it also has some moderation commands, but it doesn't make sense to me. The main issue is one of the decorators I...
Does anyone know why I have an attribute error on a Python Discord bot?
Discord.py bot attribute error I have a Discord.py bot that I have been making recently on Replit. It has a few humor commands and it also has some moderation commands, but it doesn't make sense to me. The main issue is one of the decorators I used. I use the decorator for marking commands available to only a certain r...
[ "You have two definitions of commands in your code.\nThe first:\nfrom nextcord.ext import commands\n\nand the second:\n@bot.command(name='commands')\nasync def commands(ctx):\n await helpCommand(True)\n\nWhen you define that function, you're hiding the module that you've imported before.\n" ]
[ 1 ]
[]
[]
[ "discord", "discord.py", "nextcord", "python", "python_3.x" ]
stackoverflow_0074245441_discord_discord.py_nextcord_python_python_3.x.txt
Q: How to add non-repeating elements in value of dictionary I want to put every five members of my list in a list as the value of my dictionary but the duplicate numbers should not be added in the individual values and I need to implement this program in Python in the shortest possible order. For example if the list ...
How to add non-repeating elements in value of dictionary
I want to put every five members of my list in a list as the value of my dictionary but the duplicate numbers should not be added in the individual values and I need to implement this program in Python in the shortest possible order. For example if the list is lst = [9, 9, 9, 2, 3, 4, 5, 5, 6, 6], the result dictionary...
[ "You can use a dictionary comprehension:\ndef fn(lst, n):\n return {\n idx: list(dict.fromkeys(lst[i : i + n]))\n for idx, i in enumerate(range(0, len(lst), n), start=1)\n }\n\n\nprint(fn([9, 9, 9, 2, 3, 4, 5, 5, 6, 6], 5))\nprint(fn([8, 6, 1, 9, 1, 0, 2, 8], 5))\n\noutput:\n{1: [9, 2, 3], 2: [4...
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074245599_dictionary_list_python.txt
Q: AttributeError: partially initialized module 'cv2' has no attribute 'gapi_wip_gst_GStreamerPipeline' (most likely due to a circular import) This happened out of the blue, I was able to import cv2 but now I get 'AttributeError: partially initialized module 'cv2' has no attribute 'gapi_wip_gst_GStreamerPipeline' (mo...
AttributeError: partially initialized module 'cv2' has no attribute 'gapi_wip_gst_GStreamerPipeline' (most likely due to a circular import)
This happened out of the blue, I was able to import cv2 but now I get 'AttributeError: partially initialized module 'cv2' has no attribute 'gapi_wip_gst_GStreamerPipeline' (most likely due to a circular import)' error when I import it. The things I tried: 1-uninstalling and installing opencv. 2-In cmd, I typed "pip lis...
[ "I also had the same problem with opencv-python-4.6.0.66\nI solved this error by just downgrading opencv. you can follow this command.\npip install opencv-python==4.5.5.64\n\nHope this will help you.\n", "pip uninstall opencv-python\npip uninstall opencv-contrib-python\npip uninstall opencv-contrib-python-headles...
[ 39, 23, 2, 1, 1, 0, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0072706073_opencv_python.txt
Q: Trouble concatenating two appended arrays I'm having trouble combining two arrays I want to be able to print out together. I want one "account" of each to correspond with one "customer" but I do not know how to do this. The program takes in values from two account files into one array, and one customer file into o...
Trouble concatenating two appended arrays
I'm having trouble combining two arrays I want to be able to print out together. I want one "account" of each to correspond with one "customer" but I do not know how to do this. The program takes in values from two account files into one array, and one customer file into one array. def __init__(self) -> None: #...
[ "Use zip to combine two lists pairwise:\nfor customer, account in zip(self._customers, self._accounts):\n print(customer)\n print(account)\n\nThis is equivalent to iterating over both lists simultaneously by using the same index for each:\nfor i in range(min(len(self._customers), len(self._accounts))):\n p...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074245849_python.txt