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: Change vlc media_player process name Is it possible to change the display name of the python-vlc module in the volume window? I'm using this sample code import vlc inst = vlc.Instance() player = inst.media_player_new() media = inst.media_new('track.opus') player.set_media(media) player.play() And the volume proce...
Change vlc media_player process name
Is it possible to change the display name of the python-vlc module in the volume window? I'm using this sample code import vlc inst = vlc.Instance() player = inst.media_player_new() media = inst.media_new('track.opus') player.set_media(media) player.play() And the volume process on windows is displayed like this And ...
[ "It works via instance. Try: set_user_agent(name, http)\nvlc_instance = vlc.Instance()\nvlc_instance.set_user_agent(\"Application Name\", \"HTTP/User/Agent\")\n\nSee https://www.olivieraubert.net/vlc/python-ctypes/doc/vlc.Instance-class.html\n" ]
[ 1 ]
[]
[]
[ "libvlc", "pyinstaller", "python", "vlc" ]
stackoverflow_0054975213_libvlc_pyinstaller_python_vlc.txt
Q: I need to calculate the area of each pizza slice from on how many slices there are and how to end the program when the number 0 by itself is entered import math # Constants for the minimum and maximum values MINIMUM_PIZZA_DIAMETER = 8 MAXIMUM_PIZZA_DIAMETER = 24 # Constants for the number of slices in different ...
I need to calculate the area of each pizza slice from on how many slices there are and how to end the program when the number 0 by itself is entered
import math # Constants for the minimum and maximum values MINIMUM_PIZZA_DIAMETER = 8 MAXIMUM_PIZZA_DIAMETER = 24 # Constants for the number of slices in different sized pizzas EXTRA_SMALL_PIZZA_SLICES = 6 SMALL_PIZZA_SLICES = 8 MEDIUM_PIZZA_SLICES = 10 LARGE_PIZZA_SLICES = 12 EXTRA_LARGE_PIZZA_SLICES = 16 # Constan...
[ "There's no need for the while is_valid: loop.\nAnd the loop for checking if the input is valid should just be around the input() call, not everything. You don't need the continue_input variable, just use break to end the loop.\nTo show all the different slice sizes, you need to loop over slices_possible.\nDon't re...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074198834_python.txt
Q: How to sort this error: random_sample() takes at most 1 positional argument (2 given)? ##Try to add noise to an image noisemask = np.random.random_sample(0,1,size=img.shape) A: you need two parenthesis like this : np.random.random_sample((2,2)) The function random_sample can only take one argument, but this can...
How to sort this error: random_sample() takes at most 1 positional argument (2 given)?
##Try to add noise to an image noisemask = np.random.random_sample(0,1,size=img.shape)
[ "you need two parenthesis like this :\nnp.random.random_sample((2,2))\n\nThe function random_sample can only take one argument, but this can be tuple. \nExample :\n>>> np.random.random_sample((3, 2, 2))\narray([[[0.31023678, 0.42002874],\n [0.19361976, 0.69127369]],\n\n [[0.33898072, 0.70568721],\n [0.13130...
[ 0 ]
[]
[]
[ "image", "image_processing", "python" ]
stackoverflow_0074199361_image_image_processing_python.txt
Q: How to reverse spinbox selection in PyQt5? I have a spinbox in PyQt5 like below. How can I make the selection reversed? i.e. If I click down arrow, the value goes up, vice versa. A: A possible solution is to override the stepBy() and stepEnabled() methods: import sys from PyQt5 import QtWidgets class ReverseSpi...
How to reverse spinbox selection in PyQt5?
I have a spinbox in PyQt5 like below. How can I make the selection reversed? i.e. If I click down arrow, the value goes up, vice versa.
[ "A possible solution is to override the stepBy() and stepEnabled() methods:\nimport sys\nfrom PyQt5 import QtWidgets\n\n\nclass ReverseSpinBox(QtWidgets.QSpinBox):\n def stepEnabled(self):\n if self.wrapping() or self.isReadOnly():\n return super().stepEnabled()\n ret = QtWidgets.QAbstra...
[ 1, 0 ]
[]
[]
[ "pyqt5", "python", "qspinbox" ]
stackoverflow_0062821244_pyqt5_python_qspinbox.txt
Q: Solving a system of equations by brute force within a given range without sympy nor numpy nor matrices, python I am attempting to create a program to solve a specific system of equations using brute force with python. I solved for one equation and substituted it into the second equation. Variables a through f are ...
Solving a system of equations by brute force within a given range without sympy nor numpy nor matrices, python
I am attempting to create a program to solve a specific system of equations using brute force with python. I solved for one equation and substituted it into the second equation. Variables a through f are given by user input, and I am trying to output values for x and y within a range of -10 to 10 if they exist. Any hel...
[ "To fix the issue of the else statement printing for each iteration of the if statement I created a check and set it to false. I set a condition that set the variable to true if any of the numbers within the range satisfied the condition. Then set an if statement to print 'No solution' if the variable was still fal...
[ 1, 0, 0 ]
[ "You're saying \"No solution\" without complely looping through all the choices.\nCode should be\nfor x in range(-10, 10, 1):\n for y in range(-10, 10, 1):\n if a * x + b * y == c and d * x + e * y == f:\n print(x, y)\nelse:\n print('No solution')\n\n", "This is the way I did it and it works...
[ -1, -1 ]
[ "equation_solving", "python" ]
stackoverflow_0062271257_equation_solving_python.txt
Q: Pandas : InvalidIndexError: Reindexing only valid with uniquely valued Index objects I have two pandas dataframe of different shapes that I am attempting to concat. df1 price side code 0.7286 2 1451865675631331 0.7286 2 1451865675631400 0.7286 2 1451865675631861 0.7286 2 1451865675631...
Pandas : InvalidIndexError: Reindexing only valid with uniquely valued Index objects
I have two pandas dataframe of different shapes that I am attempting to concat. df1 price side code 0.7286 2 1451865675631331 0.7286 2 1451865675631400 0.7286 2 1451865675631861 0.7286 2 1451865675631866 df2 price side code col1 col2 0.7284 2 4000000 0.7285 10...
[ "You could try this:\ncolumns_to_retain = set(df1.columns).intersection(set(df2.columns))\n\ndf = pd.concat([df1[columns_to_retain], df2[columns_to_retain]], ignore_index=True)\n\nprint(df)\n# Output\n code side price\n0 1451865675631331 2 0.7286\n1 1451865675631400 2 0.7286\n2 1451865...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0070647044_pandas_python.txt
Q: How to create a matrix like below using Numpy Matrix is like [0, 1, 2] [1, 2, 3] [2, 3, 4] For clarification, it's not just to create one such matrix but many other different matrices like this. [0, 1, 2, 3] [1, 2, 3, 4] [2, 3, 4, 5] A: You can use a sliding_window_view from numpy.lib.stride_tricks import slidi...
How to create a matrix like below using Numpy
Matrix is like [0, 1, 2] [1, 2, 3] [2, 3, 4] For clarification, it's not just to create one such matrix but many other different matrices like this. [0, 1, 2, 3] [1, 2, 3, 4] [2, 3, 4, 5]
[ "You can use a sliding_window_view\nfrom numpy.lib.stride_tricks import sliding_window_view as swv\n\ncols = 4\nrows = 3\n\nout = swv(np.arange(cols+rows-1), cols).copy()\n\nNB. because this is a view, you need .copy() to make it a mutable array, it's not necessary if a read-only object is sufficient (e.g., for dis...
[ 2, 0, 0 ]
[]
[]
[ "array_broadcasting", "numpy", "python" ]
stackoverflow_0074199050_array_broadcasting_numpy_python.txt
Q: Understanding hangman blank letter generator I have this line of code in a hangman program word_list = [letter if letter in used_letters else '-' for letter in word] and it takes the word that was picked and puts '-' in place of the letters that weren't guessed yet. I just don't understand how the line works. How...
Understanding hangman blank letter generator
I have this line of code in a hangman program word_list = [letter if letter in used_letters else '-' for letter in word] and it takes the word that was picked and puts '-' in place of the letters that weren't guessed yet. I just don't understand how the line works. How is there an if statement and a for loop inside a ...
[]
[]
[ "True if True else False => True\nTrue if False else False => False\nIf you take it apart, your cycle looks something like this:\nword_list = []\nfor letter in word:\n if letter in used_letters:\n word_list.append(letter)\n else:\n word_list.append('-')\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074199480_python.txt
Q: get the nearest nested list from a given nested list So I have a 2 values [-82.819309,40.081296] and a list of multiple nested values like [[-83.0347849999999, 39.945993], [-82.957851, 40.060118], [-82.994303, 40.013227], [-82.8265609999999, 39.9207779999999], [-82.9984709999999, 39.887616], ...] Now I want ...
get the nearest nested list from a given nested list
So I have a 2 values [-82.819309,40.081296] and a list of multiple nested values like [[-83.0347849999999, 39.945993], [-82.957851, 40.060118], [-82.994303, 40.013227], [-82.8265609999999, 39.9207779999999], [-82.9984709999999, 39.887616], ...] Now I want to get the list from the nested list whose difference from...
[ "You can use very simple code:\nimport numpy as np\n\nmylist = [[-83.0347849999999, 39.945993],\n [-82.957851, 40.060118],\n [-82.994303, 40.013227],\n [-82.8265609999999, 39.9207779999999],\n [-82.9984709999999, 39.887616],\n ...]\n\ndef item_of_min_norm(target_coordinate):\n norms = [np.linalg.norm(np.array(t...
[ 2 ]
[]
[]
[ "list", "nested", "nested_lists", "python" ]
stackoverflow_0074198680_list_nested_nested_lists_python.txt
Q: Why does this function have exponential complexity big O instead of quadratic? The following function has been given: def genSubsets(L): res = [] if len(L) == 0: return [[]] smaller = genSubsets(L[:-1]) extra = L[-1:] new = [] for small in smaller: new.append(small+extra) ...
Why does this function have exponential complexity big O instead of quadratic?
The following function has been given: def genSubsets(L): res = [] if len(L) == 0: return [[]] smaller = genSubsets(L[:-1]) extra = L[-1:] new = [] for small in smaller: new.append(small+extra) return smaller+new From my understanding, i making a copy of a list is (O n), the...
[ "\nFrom my understanding, i making a copy of a list is (O n)\n\nYou are correct that making a copy of a list of n items takes time O(n). And in this case, each of the lists that's being copied is a subset of the original list, which has length n, so each list copied does take time O(n).\n\nthen looping is (O n) as ...
[ 2 ]
[]
[]
[ "big_o", "python" ]
stackoverflow_0074199427_big_o_python.txt
Q: Groupby mean doesn't display all data I want to see all the means of the numerical columns, grouped by position, using dfMockPos.groupby(['Position']).mean() When I do this I only get 3 of the many columns The other columns are all integers or floats, and they have no NAs. If I do dfMockPos['Weight'].mean() The...
Groupby mean doesn't display all data
I want to see all the means of the numerical columns, grouped by position, using dfMockPos.groupby(['Position']).mean() When I do this I only get 3 of the many columns The other columns are all integers or floats, and they have no NAs. If I do dfMockPos['Weight'].mean() Then I get the correct output. How can I displ...
[ "You can try using the Aggregate function on groupby.\nFor example:\ndfMockPos.groupby(['Position']).agg({\"relative_age\":'mean',\n \"Height\": 'mean',\n \"Success_score\": \"mean\",\n ...
[ 2 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074199201_group_by_pandas_python.txt
Q: How to detect black object on black background using Python OpenCV I am trying to detect a black tape on a black background. No tape, with tape (cropped pictures): I have first cropped the area of the tape from the original image and then performing thresholding on it. Below is the image when there is no tape: Yo...
How to detect black object on black background using Python OpenCV
I am trying to detect a black tape on a black background. No tape, with tape (cropped pictures): I have first cropped the area of the tape from the original image and then performing thresholding on it. Below is the image when there is no tape: You can notice there is an almost solid line. Black tape is placed right n...
[ "No way to write a stable image processing software here.\nIn this industrial environment you get differences in ambient light, reflexion, shadows, light different presentation angles, sun light etc. This will impact the brightness of your image partial or global much more than the presence of a nearly invisible ta...
[ 0 ]
[]
[]
[ "computer_vision", "image_processing", "opencv", "python" ]
stackoverflow_0071808083_computer_vision_image_processing_opencv_python.txt
Q: LSTM Model Multivariate input and single output I am trying to understand in depth LSTM. I am trying to predict the power generation of a wind power plant. For this prediction I am using the historical power from the plant and 4 weather variables, The interval from these variables is hours. Is it possible to predi...
LSTM Model Multivariate input and single output
I am trying to understand in depth LSTM. I am trying to predict the power generation of a wind power plant. For this prediction I am using the historical power from the plant and 4 weather variables, The interval from these variables is hours. Is it possible to predict the next 24 hours based on the last 24 hours of da...
[ "For this, you have to store the information of hidden_states, and then you will use that information for predicting future states,\nTry this code, for your future 24 hours predictions...\ntf.keras.backend.clear_session()\n_input = tf.keras.layers.Input(shape=(6,5))\nx = LSTM(128, activation='relu', return_sequence...
[ 0 ]
[]
[]
[ "deep_learning", "keras", "lstm", "python", "tensorflow" ]
stackoverflow_0074197828_deep_learning_keras_lstm_python_tensorflow.txt
Q: Coloring Nodes of a NumPy Matrix I'm a beginner python programmer, could someone help me? I have a graph file, I am trying to store it in a matrix and color each node a different color than each adjacent node, but I'm getting an error: Please see associated files at this file link where you can see logs etc. impo...
Coloring Nodes of a NumPy Matrix
I'm a beginner python programmer, could someone help me? I have a graph file, I am trying to store it in a matrix and color each node a different color than each adjacent node, but I'm getting an error: Please see associated files at this file link where you can see logs etc. import re import numpy as np import pandas...
[ "Instead of using or or and -> use | or & respectively (when working with pandas)\nReason: or or and require truth-values. Whereas with pandas objects (Series in your case) are considered ambiguous so you should use | (or) or & (and) bitwise operations\n" ]
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074199588_numpy_pandas_python.txt
Q: python pyside6 qtextedit synchronize error I have a pyside6 app which has 2 TextEdit widgets and I want the 2 TextEdits to scroll in sync. The following code is used for this function: self.scrollconnect1 = self.TextEdit_1.verticalScrollBar().valueChanged.connect( self.TextEdit_2.verticalScrollBar().se...
python pyside6 qtextedit synchronize error
I have a pyside6 app which has 2 TextEdit widgets and I want the 2 TextEdits to scroll in sync. The following code is used for this function: self.scrollconnect1 = self.TextEdit_1.verticalScrollBar().valueChanged.connect( self.TextEdit_2.verticalScrollBar().setValue) self.scrollconnect2 = self.TextEdit_...
[ "Test Script:\nfrom PySide6 import QtCore, QtGui, QtWidgets\n\nclass ScrollBar(QtWidgets.QScrollBar):\n valueUpdated = QtCore.Signal(int)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setTracking(True)\n self.actionTriggered.connect(self.handleAction)...
[ 1 ]
[]
[]
[ "connect", "pyside", "python", "scrollbar", "synchronization" ]
stackoverflow_0074161615_connect_pyside_python_scrollbar_synchronization.txt
Q: Downloading file with a specific substring from AWS S3 python I have a python function to download csv files from AWS S3 Bucket. The folder I want to download from has a lot of csv files with various naming conventions and out of all those, I want to download files that contain a certain substring. The files I wan...
Downloading file with a specific substring from AWS S3 python
I have a python function to download csv files from AWS S3 Bucket. The folder I want to download from has a lot of csv files with various naming conventions and out of all those, I want to download files that contain a certain substring. The files I want to download are named as: BANK_NIFTY_5MINs_2020-01-01.csv BANK_N...
[ "There is no command in Amazon S3 to download objects via a wildcard. At some stage, your code would need to make an API call to S3 with the exact name (Key) of the object you want to download.\nTherefore, your code would need to call list_objects_v2() to obtain a listing of objects in the S3 bucket. Then, you can ...
[ 3 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "python" ]
stackoverflow_0074199744_amazon_s3_amazon_web_services_python.txt
Q: Can't iterate through a list and click on checkbox selenium python <div> <ul class="nav border rounded p-2"> <li class="nav-item col-12"> <input type="checkbox" /> <span>Paediatrics</span> </li> <li class="nav-item col-12"> <input type="checkbox" /> <span>Gynaecology</span> </li> ...
Can't iterate through a list and click on checkbox selenium python
<div> <ul class="nav border rounded p-2"> <li class="nav-item col-12"> <input type="checkbox" /> <span>Paediatrics</span> </li> <li class="nav-item col-12"> <input type="checkbox" /> <span>Gynaecology</span> </li> <li class="nav-item col-12"> <input type="checkbox" /> <span>Inter...
[ "Try this:\nfor item in items:\n if item.text == \"Paediatrics\":\n checkbox = item.find_elements_by_class_name(\"input\")[0]\n checkbox.click()\n\n" ]
[ 0 ]
[]
[]
[ "automation", "python", "selenium", "webautomation" ]
stackoverflow_0074199824_automation_python_selenium_webautomation.txt
Q: What's the meaning of clip_box in Matplotlib Artist? I am testing the clip_box feature of Artist using the code snippet below: import matplotlib.pyplot as plt from matplotlib.transforms import Bbox import numpy as np fig = plt.figure() ax = fig.subplots(1, 2) x = [1, 2, 3, 4] y = [3, 8, 5, 2] line_a, = ax[0].pl...
What's the meaning of clip_box in Matplotlib Artist?
I am testing the clip_box feature of Artist using the code snippet below: import matplotlib.pyplot as plt from matplotlib.transforms import Bbox import numpy as np fig = plt.figure() ax = fig.subplots(1, 2) x = [1, 2, 3, 4] y = [3, 8, 5, 2] line_a, = ax[0].plot(x, y, color='red', linewidth=3.0) line_b, = ax[1].plot(...
[ "I've spent some time reading about Bboxes in Matplotlib and they are pretty complicated. The set_clip_box method you refer to has not got very helpful documentation, and the examples of its use both use the bbox of an Axes, which is a nested transformation; ie _, ax = plt.subplots(); ax.bbox is a TransformedBbox b...
[ 1, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0073934908_matplotlib_python.txt
Q: How to make 2 deep copy of a list? I am making 2 deep copies of a list. The problem is that first deep copy behaves fine, but second deep copy of the list is being altered based on changes on my original list. import copy def findThreeLargestNumbers(array): # Write your code here. org_array2=copy.deepcopy...
How to make 2 deep copy of a list?
I am making 2 deep copies of a list. The problem is that first deep copy behaves fine, but second deep copy of the list is being altered based on changes on my original list. import copy def findThreeLargestNumbers(array): # Write your code here. org_array2=copy.deepcopy(array) org_array1=copy.deepcopy(ar...
[ "Your copies are actually fine. The issue is that you have only removed the second largest value from org_array2. So when your logic looks for the largest value, it finds 514 again. Here's your code with that logic corrected:\nimport copy\n\ndef findThreeLargestNumbers(array):\n # Write your code here.\n o...
[ 1, 0, 0 ]
[]
[]
[ "deep_copy", "list", "python", "python_3.x" ]
stackoverflow_0074198043_deep_copy_list_python_python_3.x.txt
Q: How to connect to an Oracle database on a on premise server remotely using Python How would you connect to an Oracle database on a on premise server remotelly using Python? I've tried with the library cx_Oracle but I can't figure out how to connect to a database that's not on my local computer nor the cloud A: A...
How to connect to an Oracle database on a on premise server remotely using Python
How would you connect to an Oracle database on a on premise server remotelly using Python? I've tried with the library cx_Oracle but I can't figure out how to connect to a database that's not on my local computer nor the cloud
[ "Assuming that the network and firewall allow connections, then I'd do:\npython -m pip install oracledb\n\nAnd then use a script like:\nimport oracledb\nimport traceback\nimport os\n\nun = os.environ.get('PYTHON_USERNAME')\npw = os.environ.get('PYTHON_PASSWORD')\ncs = os.environ.get('PYTHON_CONNECTSTRING')\n\ntry:\...
[ 2 ]
[]
[]
[ "cx_oracle", "oracle", "python" ]
stackoverflow_0074198881_cx_oracle_oracle_python.txt
Q: Why is print concatenated dataframes not working as expected? The columns appear stacked and "\" is displayed I want to concatenate the columns of several dataframes (consisting of one column of 50 rows each). For this I created a list (pdList). I save the resulting dataframe in a .dat file pd.set_option('display....
Why is print concatenated dataframes not working as expected? The columns appear stacked and "\" is displayed
I want to concatenate the columns of several dataframes (consisting of one column of 50 rows each). For this I created a list (pdList). I save the resulting dataframe in a .dat file pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pdList = [df41,df42,df43,df44,df45,df46,df47,df48,df4...
[ "len(\"0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 \")\n\nreturns 79. There is a line break every 79 characters. If you refer to PEP8, you would see that all lines are to be limited to exactly 79 characters and the backslash character is used for line continuation, so this appears...
[ 1 ]
[]
[]
[ "concatenation", "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074195508_concatenation_dataframe_pandas_python_python_3.x.txt
Q: Read timeout in pd.read_parquet from S3, and understanding configs I'm trying to simplify access to datasets in various file formats (csv, pickle, feather, partitioned parquet, ...) stored as S3 objects. Since some users I support have different environments with limited options for upgrading (big company, don't a...
Read timeout in pd.read_parquet from S3, and understanding configs
I'm trying to simplify access to datasets in various file formats (csv, pickle, feather, partitioned parquet, ...) stored as S3 objects. Since some users I support have different environments with limited options for upgrading (big company, don't ask), I need to develop multiple solutions that achieve similar use cases...
[ "i recommend before calling read_parquet() to check if file is present, in this way you wont need to rely on the default or custom timeout\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "pandas", "pyarrow", "python", "python_s3fs" ]
stackoverflow_0072133714_amazon_s3_pandas_pyarrow_python_python_s3fs.txt
Q: Combination of CalibratedClassifierCV with RandomOverSampler When using a classifier like GaussianNB(), the resulting .predict_proba() values are sometimes poorly calibrated; that's why I'd like to wrap this classifier into sklearn's CalibratedClassifierCV. I have now a binary classification problem with only a ve...
Combination of CalibratedClassifierCV with RandomOverSampler
When using a classifier like GaussianNB(), the resulting .predict_proba() values are sometimes poorly calibrated; that's why I'd like to wrap this classifier into sklearn's CalibratedClassifierCV. I have now a binary classification problem with only a very few positive samples - so few that CalibratedClassifierCV fails...
[ "I guess I understand my conceptual error: the cross-validation split has to happen BEFORE upsampling and not after (otherwise there would be information leakage from validation to training). But if it happens before, I cannot have more folds than samples of the positive class... Thus, oversampling does not save me...
[ 0 ]
[]
[]
[ "calibration", "cross_validation", "oversampling", "python", "scikit_learn" ]
stackoverflow_0074193663_calibration_cross_validation_oversampling_python_scikit_learn.txt
Q: How to confirm or validate the inputted word from the list on Python? I had an issue validating the inputted word from the list before proceeding to the next function for the text to be created. while True: try: services = ['Conference','Dinner','Lodging','Membership Renewal'] for i in range(0,...
How to confirm or validate the inputted word from the list on Python?
I had an issue validating the inputted word from the list before proceeding to the next function for the text to be created. while True: try: services = ['Conference','Dinner','Lodging','Membership Renewal'] for i in range(0,4): print(f"{services[i] : <14}") hotel_services = str(...
[ "You can check if a string exists in a list using the in keyword as such:\nif hotel_services in services:\n print('Valid!')\nelse:\n print('Invalid!')\n\n\n", "Your code can be rewritten as\nwhile True:\n try:\n services = ['Conference','Dinner','Lodging','Membership Renewal']\n for service...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074199790_list_python.txt
Q: dictionary with a network of friends I don't know the process to do this; here is my question: Modeling a network through a dictionary For the rest, we prefer to use a social network modelling by a dictionary where the keys are given names of the people in the network and the value associated with a key is the ta...
dictionary with a network of friends
I don't know the process to do this; here is my question: Modeling a network through a dictionary For the rest, we prefer to use a social network modelling by a dictionary where the keys are given names of the people in the network and the value associated with a key is the table of friends of the person indicated by ...
[ "When you access the dictionary using the key \"Joel\"\nx = dictionary[\"Joel\"]\nIt will return the value, which is the list of Joel's friends\nThen you need to iterate through that list and run each of his friends' names in the dictionary to get their corresponding code. As you are doing that, create a new dictio...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074199918_dictionary_python.txt
Q: Do an AND operation between elements of lists in a list (element by element) The problem I'm facing is that I have a list of lists. a = [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 1], [1, 0, 0, 1, 0, 0]] I want to do AND/OR/Majority-voting operations on the elements of the lists inside the list a. I want to get...
Do an AND operation between elements of lists in a list (element by element)
The problem I'm facing is that I have a list of lists. a = [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 1], [1, 0, 0, 1, 0, 0]] I want to do AND/OR/Majority-voting operations on the elements of the lists inside the list a. I want to get a single list result by, for example, doing an AND operation index by index so it...
[ "Here's one way to generalize your code. This script is written so that in the event of a tie, the result for maj_op defaults to zero.\na = [[1, 1, 1, 0, 0, 0],\n [1, 1, 1, 0, 1, 1], \n [1, 0, 0, 1, 0, 0]]\n\ndef and_op(alist):\n return_list = []\n for tup in zip(*alist):\n return_list.append(int...
[ 0 ]
[]
[]
[ "list", "list_comprehension", "matrix", "python" ]
stackoverflow_0074199727_list_list_comprehension_matrix_python.txt
Q: How do I use Pandas to get unique values in a column while summing certain values in another column? My question is related to another post here How do I Pandas group-by to get sum? but it does not answer my question. I have this dataframe: Fruit Name Number Apples Bob 7 Apples Bob 8 Apples Mike ...
How do I use Pandas to get unique values in a column while summing certain values in another column?
My question is related to another post here How do I Pandas group-by to get sum? but it does not answer my question. I have this dataframe: Fruit Name Number Apples Bob 7 Apples Bob 8 Apples Mike 9 Apples Steve 10 Apples Bob 1 Oranges Bob 2 Oranges Tom 15 Oranges Mike 57 Oranges Bob ...
[ "Try using a pivot_table\npivot = df.pivot_table(index='Fruit', columns='Name',\n values='Number', aggfunc=sum)\n\nName Bob Mike Steve Tom Tony\nFruit \nApples 16.0 9.0 10.0 NaN NaN\nGrapes 35.0 NaN NaN 87.0 15.0\nMelons NaN 10.0...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074199818_dataframe_pandas_python.txt
Q: Python library not recognized in visual studio code even after installation and restarting I am trying to follow this tutorial for a simple python web application: https://www.youtube.com/watch?v=n6I58WJiKGU. I have copied the code into a python file and tried to run it in VS Code on my Windows computer, but I kee...
Python library not recognized in visual studio code even after installation and restarting
I am trying to follow this tutorial for a simple python web application: https://www.youtube.com/watch?v=n6I58WJiKGU. I have copied the code into a python file and tried to run it in VS Code on my Windows computer, but I keep getting an error that the module cannot be found. Here is the beginning of the code: import py...
[]
[]
[ "You have to install the module first using pip in your computer's terminal, not all libraries come with the Python installation. To install PyWebIO you have to open a terminal, command prompt for example and type \"pip install pywebio\". You will have to restart Visual Studio Code for it to work.\n" ]
[ -1 ]
[ "python", "windows" ]
stackoverflow_0074199981_python_windows.txt
Q: Pandas random n samples of consecutive rows / pairs I have panda dataframe indexed by ID and sorted by value. I want to create a sample size of n=20000 where there are 40000 rows in total and 2 rows are consecutive/paired. I want to perform additional calculations on these 2 consecutive / paired rows e.g. If I say...
Pandas random n samples of consecutive rows / pairs
I have panda dataframe indexed by ID and sorted by value. I want to create a sample size of n=20000 where there are 40000 rows in total and 2 rows are consecutive/paired. I want to perform additional calculations on these 2 consecutive / paired rows e.g. If I say sample size n=2 I want to randomly pick and find the dif...
[ "If it doesn't matter to always have (even, odd) pairs (which decreases a bit randomness), you can select n odd rows and get the next even:\nN = 20000\n# get the indices of N random ODD rows\nidx = df.loc[::2].sample(n=N).index\n\n# create a boolean mask to identify the rows\nm = df.index.to_series().isin(idx)\n\n#...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074199513_dataframe_pandas_python.txt
Q: Create an unnamed column pandas How to append to an existing dataframe an unnamed column with random data? df.insert requires a name of column df['column_name'] = ... obviously require column name too A: As per panda's official documentation, columns: Index or array-like Column labels to use for resulting frame...
Create an unnamed column pandas
How to append to an existing dataframe an unnamed column with random data? df.insert requires a name of column df['column_name'] = ... obviously require column name too
[ "As per panda's official documentation,\n\ncolumns: Index or array-like\nColumn labels to use for resulting frame when data does not have them,\ndefaulting to RangeIndex(0, 1, 2, …, n). If data contains column\nlabels, will perform column selection instead.\n\nIf a column does not have a column label, it would be a...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074194940_dataframe_pandas_python.txt
Q: Why do my async functions get stuck in infinite loop? I'm trying to setup some functions to continuously fetch and send data back and forth. However, after sending, there needs to be a brief rest period (which is why I have asyncio.sleep(10)). So, I want to be continuously fetching data in my loop during this wait...
Why do my async functions get stuck in infinite loop?
I'm trying to setup some functions to continuously fetch and send data back and forth. However, after sending, there needs to be a brief rest period (which is why I have asyncio.sleep(10)). So, I want to be continuously fetching data in my loop during this waiting time. My problem is once task #1 starts sleeping and ta...
[ "You are not awaiting anything in your fetcher, hence it is essentially blocking and doesn't give other coroutines the Chance to do some work. You can add await asyncio.sleep(0) which should help. Apart from this, you should also await the sleep in sender() as otherwise, it will not actually sleep 10 seconds, but j...
[ 2, 0, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074166331_python_python_asyncio.txt
Q: How do I get rid of b' if I want to parse a bash output using python? At my python application I'm doing the following to get some values from a larger JSON ffgrading_json = exec_command(f'{options["path_ffprobe"]} -loglevel quiet -print_format json -read_intervals "%+#2" -select_streams v:0 -show_entries side_dat...
How do I get rid of b' if I want to parse a bash output using python?
At my python application I'm doing the following to get some values from a larger JSON ffgrading_json = exec_command(f'{options["path_ffprobe"]} -loglevel quiet -print_format json -read_intervals "%+#2" -select_streams v:0 -show_entries side_data "{path}" | egrep -m 1 -A 10 "Mastering display metadata" | grep -v "Maste...
[ "you need to use .decode() on the output.stdout the output is in bytes so this will convert it to a string\nwhen you print bytes python tries to convert what it can into ascii characters but it will display b'' around the printed data to indicate that the variable you printed contains bytes and it is not a string\n...
[ 1 ]
[]
[]
[ "line_breaks", "python" ]
stackoverflow_0074200132_line_breaks_python.txt
Q: Overwrite value in cell based on condition, without overwriting some of the existing values The goal would be to overwrite a value depending on other conditions, but if a value is certain string don't overwrite it. I've just began to code and am not sure how to solve this, or if my approach is the most efficient. ...
Overwrite value in cell based on condition, without overwriting some of the existing values
The goal would be to overwrite a value depending on other conditions, but if a value is certain string don't overwrite it. I've just began to code and am not sure how to solve this, or if my approach is the most efficient. This is what I'm currently trying: for cell_value in df['col1']: if cell_value == 'a': ...
[ "i think you don't need to a loop. Can be done with np.where(). This will work if i understood the question correctly.\nimport numpy as np\ndf['col1']=np.where(((df['col1']!='a') & (df['col2'] == 'red') & ((df['number']) == 0) & ((df['col_4'].str.contains(\"color\")))),'This is red',df['col1'])\n\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074199910_pandas_python_python_3.x.txt
Q: Output list as "x1, x2, ... 'and xN'" I can do this fruits=['mango','fig','apple'] for fruit in fruits: print (fruit , end=" ") OUTPUT: mango fig apple How to rewrite this using a loop? fruits=['mango','fig','apple'] print(f"i have {fruits[0]},{fruits[1]} and {fruits[2]}") expectation : i have mango,fig a...
Output list as "x1, x2, ... 'and xN'"
I can do this fruits=['mango','fig','apple'] for fruit in fruits: print (fruit , end=" ") OUTPUT: mango fig apple How to rewrite this using a loop? fruits=['mango','fig','apple'] print(f"i have {fruits[0]},{fruits[1]} and {fruits[2]}") expectation : i have mango,fig and apple
[ "If you want to use with loop,\nprint('I have', end=\" \")\nfor idx, i in enumerate(fruits):\n if idx == len(fruits) - 1:\n print(f\"and {i}\", end=\" \") \n else:\n print(i, end=\", \")\n# I have mango, fig, and apple \n\n", "You could do something like:\nprint(f\"i have {', '.join(fruits[...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074199711_list_python.txt
Q: I am learning Python and trying to understand writing to a CSV. I need it to be in a header / row set up and keep getting a float error import csv FILENAME = "trip.csv" def save_data(miles, gallons, mpg): header = ["Distance", "Gallons", "MPG"] data = [miles, gallons, mpg] with open(FILENAME, 'w', ne...
I am learning Python and trying to understand writing to a CSV. I need it to be in a header / row set up and keep getting a float error
import csv FILENAME = "trip.csv" def save_data(miles, gallons, mpg): header = ["Distance", "Gallons", "MPG"] data = [miles, gallons, mpg] with open(FILENAME, 'w', newline="") as file: writer = csv.writer(file) writer.writerow(header) with open(FILENAME, 'a', newline="") as file: ...
[ "The problem is that you are using writerows on the second call, which expects an iterable of iterables of values, whereas you're only passing it an iterable of values. There's two ways to fix it:\n\nUse writerow:\n\nwriter.writerow(data)\n\n\nActually pass in an iterable of iterables, most easily by creating anot...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074200099_python.txt
Q: Replacing NaN values on dataframe I have a df with some NaN values and I want to replace them with the mean of the values on the adjacents columns (at the same line). How can I do it? I'm trying to iterate over all the elements of the dataframe but I'm not going anywhere. Can someone please help me? Example: in th...
Replacing NaN values on dataframe
I have a df with some NaN values and I want to replace them with the mean of the values on the adjacents columns (at the same line). How can I do it? I'm trying to iterate over all the elements of the dataframe but I'm not going anywhere. Can someone please help me? Example: in this df, I would like to replace the NaN ...
[ "A good way to do this would be:\nmean = df[\"columnName\"].mean()\ndf[\"columnName\"].fillna(mean,inplace=True)\n\nThe inplace=True modifies the original dataframe.\nEDIT:\nFor a justification on why to not use inplace=True, you can find it here: Why You Should Probably Never Use pandas inplace=True\n", "Use int...
[ 0, 0 ]
[]
[]
[ "dataframe", "loops", "nan", "pandas", "python" ]
stackoverflow_0074200040_dataframe_loops_nan_pandas_python.txt
Q: Numpy matrix multiplication with scalar results in negative zeros I have a random nxn matrix A with floating points, then I call X = np.eye(A.shape[0]) matrix nxn which has diagonal values (0 elsewhere) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 now I want to multiply every even row with -2 so I do X[0::2] *= -2 however i...
Numpy matrix multiplication with scalar results in negative zeros
I have a random nxn matrix A with floating points, then I call X = np.eye(A.shape[0]) matrix nxn which has diagonal values (0 elsewhere) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 now I want to multiply every even row with -2 so I do X[0::2] *= -2 however it returns 2 0 0 0 -0 -2 -0 -0 0 0 2 0 -0 -0 -0 -2 Why do the ...
[ "SOLUTION\nAs someone pointed out, the np.eye function returns float matrix by default, fixed by adding np.eye(A.shape[0],dtype=int)\n", "The issue is that the numbers are float types so the '0' is not actually 0 but a very small number so when you multiply the number by -1, you actually multiplying the small num...
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074196818_numpy_python.txt
Q: Strange numpy divide behaviour for scalars I have been trying to upgrade a library which has a bunch of geometric operations for scalars so they will work with numpy arrays as well. While doing this I noticed some strange behaviour with numpy divide. In original code checks a normalised difference between to varia...
Strange numpy divide behaviour for scalars
I have been trying to upgrade a library which has a bunch of geometric operations for scalars so they will work with numpy arrays as well. While doing this I noticed some strange behaviour with numpy divide. In original code checks a normalised difference between to variables if neither variable is zero, swapping acros...
[ "It looks like a bug to me. But I think you'd want to short-circuit the calls to ufuncs in the case of scalars for performance reasons anyway, so its a question of trying to keep it from being too messy. Since either a or b could be scalars, you need to check them both. Put that check into a function that condition...
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074187097_numpy_python.txt
Q: PyQt: How to connect QComboBox to function with Arguments QComboBox is connected to a function using following syntax: myComboBox.activated.connect(self.myFunction ) But I need to be able to send the arguments from ComboBox to myFunction(). But if I use: myComboBox.activated.connect(self.myFunction(myArg1, myArg2...
PyQt: How to connect QComboBox to function with Arguments
QComboBox is connected to a function using following syntax: myComboBox.activated.connect(self.myFunction ) But I need to be able to send the arguments from ComboBox to myFunction(). But if I use: myComboBox.activated.connect(self.myFunction(myArg1, myArg2 ) I am getting TypeError: connect() slot argument should be ...
[ "After I posted a question Stachoverflow suggested a link which explained a lot. Here is the answer:\nfrom PyQt4 import QtCore, QtGui\n\nclass MyClass(object):\n def __init__(self, arg):\n super(MyClass, self).__init__()\n self.arg = arg \n\nclass myWindow(QtGui.QWidget):\n def __init__(s...
[ 10, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0023116763_pyqt_python.txt
Q: python variables as index I have a file with different sheets and column-heading but same structure. I want to convert to json. but already now I have a problem. How can I index, my first column(with different heading) to pandas? import pandas; datapath = 'myfile.xlsx' datasheet = 'testsheet' data = pandas.read_e...
python variables as index
I have a file with different sheets and column-heading but same structure. I want to convert to json. but already now I have a problem. How can I index, my first column(with different heading) to pandas? import pandas; datapath = 'myfile.xlsx' datasheet = 'testsheet' data = pandas.read_excel(datapath, sheet_name=datas...
[ "I don't seem to understand your question. Do you mean you want to set the first column as the index? Doesn't data.set_index(index_1,inplace=True) work?\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074200092_pandas_python.txt
Q: How to extract a segmented object or change the background of the original image? I am doing a detection with Mask R-CNN of one model available at Train Mask R-CNN for Image Segmentation. Code I # Load Image img = cv2.imread("/content/image.jpg") test_model, inference_config = load_inference_model(1, "/content/...
How to extract a segmented object or change the background of the original image?
I am doing a detection with Mask R-CNN of one model available at Train Mask R-CNN for Image Segmentation. Code I # Load Image img = cv2.imread("/content/image.jpg") test_model, inference_config = load_inference_model(1, "/content/mask_rcnn.h5") image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Detect results r = test_...
[ "I can't test it but if you have mask as numpy.array with the same size as image then you can use it to replace pixels in image\nimage[ ~mask ] = [0,0,0]\n\nFor example\npython - Can anyone tell me how can I change mask the foreground if I know the color range of background in RGB? - Stack Overflow\nFinding red col...
[ 1 ]
[]
[]
[ "image_segmentation", "mask_rcnn", "python" ]
stackoverflow_0074186090_image_segmentation_mask_rcnn_python.txt
Q: during time loop, how to get data generated in first round and so on in python I'm creating a code in python that repeats 10 times, but at the end of the code I would like the data generated in it to be added to the second round for sum, in the third round to take the data generated in the two and so on.... I want...
during time loop, how to get data generated in first round and so on in python
I'm creating a code in python that repeats 10 times, but at the end of the code I would like the data generated in it to be added to the second round for sum, in the third round to take the data generated in the two and so on.... I want the values ​​of the variable ano2 to be added. my code is as follows: time = 10 whi...
[ "Could you maintain a variable outside the loop to keep track of your sum/previous loops? This could also be a list of lists that if you swap your loop condition around can be indexed and used in later loops. Hope this helps!\ntime = 0\ntotal = 0\nl_total = []\n\nwhile time < 10:\n total = total + 1\n time = ...
[ 0 ]
[]
[]
[ "loops", "python", "while_loop" ]
stackoverflow_0074198663_loops_python_while_loop.txt
Q: Copy of file from S3 to SFTP server using python I want to copy a file from AWS S3 to SFTP server without downloading to local using python,any help on this can be appreciated, thank you. Sample python code to run. A: There is no command in Amazon S3 to 'send' a file to a destination. It is only possible to 'dow...
Copy of file from S3 to SFTP server using python
I want to copy a file from AWS S3 to SFTP server without downloading to local using python,any help on this can be appreciated, thank you. Sample python code to run.
[ "There is no command in Amazon S3 to 'send' a file to a destination. It is only possible to 'download' (or 'read') the contents of a file.\nTherefore, the only way to accomplish your goal is to download the file from S3, then upload to the SFTP server.\nYou could take advantage of the features of smart-open · PyPI,...
[ 0, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "python", "sftp" ]
stackoverflow_0074197844_amazon_s3_amazon_web_services_python_sftp.txt
Q: Prevent calling a function more than once if the parameters have been used before I would like a way to limit the calling of a function to once per values of parameters. For example def unique_func(x): return x >>> unique_func([1]) [1] >>> unique_func([1]) *** wont return anything *** >>> unique_func([2]) [2]...
Prevent calling a function more than once if the parameters have been used before
I would like a way to limit the calling of a function to once per values of parameters. For example def unique_func(x): return x >>> unique_func([1]) [1] >>> unique_func([1]) *** wont return anything *** >>> unique_func([2]) [2] Any suggestions? I've looked into using memoization but not established a solution ju...
[ "Memoization uses a mapping of arguments to return values. Here, you just want a mapping of arguments to None, which can be handled with a simple set.\ndef idempotize(f):\n cache = set()\n def _(x):\n if x in cache:\n return\n cache.add(x)\n return f(x)\n return _\n\n\n@idem...
[ 3, 1, 0 ]
[]
[]
[ "memoization", "python" ]
stackoverflow_0060283609_memoization_python.txt
Q: How to use a polars column with offset string to add to another date column Suppose you have df=pl.DataFrame( { "date":["2022-01-01", "2022-01-02"], "hroff":[5,2], "minoff":[1,2] }).with_column(pl.col('date').str.strptime(pl.Date,"%Y-%m-%d")) and you want to make a new column that adds the hour and m...
How to use a polars column with offset string to add to another date column
Suppose you have df=pl.DataFrame( { "date":["2022-01-01", "2022-01-02"], "hroff":[5,2], "minoff":[1,2] }).with_column(pl.col('date').str.strptime(pl.Date,"%Y-%m-%d")) and you want to make a new column that adds the hour and min offsets to the date column. The only thing I saw was the dt.offset_by method....
[ "Use pl.duration:\nimport polars as pl\n\ndf = pl.DataFrame({\n \"date\": pl.Series([\"2022-01-01\", \"2022-01-02\"]).str.strptime(pl.Datetime(time_zone=\"UTC\"), \"%Y-%m-%d\"),\n \"hroff\": [5, 2],\n \"minoff\": [1, 2]\n})\n\nprint(df.select(\n pl.col(\"date\") + pl.duration(hours=pl.col(\"hroff\"), mi...
[ 2 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074200120_python_python_polars.txt
Q: panda unable to read the csv file ? showing this error TF_MODEL_URL = 'https://tfhub.dev/google/on_device_vision/classifier/landmarks_classifier_asia_V1/1' mo = hub.Module('https://tfhub.dev/google/on_device_vision/classifier/landmarks_classifier_asia_V1/1') IMAGE_SHAPE = (321,321) df= pd.read_csv(LABLE_MAP_URL) ...
panda unable to read the csv file ? showing this error
TF_MODEL_URL = 'https://tfhub.dev/google/on_device_vision/classifier/landmarks_classifier_asia_V1/1' mo = hub.Module('https://tfhub.dev/google/on_device_vision/classifier/landmarks_classifier_asia_V1/1') IMAGE_SHAPE = (321,321) df= pd.read_csv(LABLE_MAP_URL) the error is if self.low_memory: --> 230 chunks = se...
[ "The traceback is from pandas IO tools, so the error likely occured when you are reading the .csv. As you didn't show the file and this is not a reproducible example, you should check the file and see what went wrong. You also didn't show the entire traceback so it is difficult to tell what kind of error it is, but...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074186338_dataframe_pandas_python.txt
Q: expected str, bytes or os.PathLike object, not reader I wrote this code from a book in order to practise. However, when I tried to run it, it didn't work and I keep having the same error "expected str, bytes or os.PathLike object, not reader". It would be nice and friendly if you guys could check it out and tell m...
expected str, bytes or os.PathLike object, not reader
I wrote this code from a book in order to practise. However, when I tried to run it, it didn't work and I keep having the same error "expected str, bytes or os.PathLike object, not reader". It would be nice and friendly if you guys could check it out and tell me, what went wrong. I'd appreciate it. Thanks in advance! i...
[ "You don't need to call open() twice. Just call it once, with the filename as the argument, in the with statement.\nwith open(r\"C:\\Users\\ronald\\Documents\\PYTHON DATA\\importes.csv\", encoding='latin1') as fichero_csv:\n lector = csv.reader(fichero_csv)\n next(lector, None)\n importe_total = 0\n for...
[ 0 ]
[]
[]
[ "csv", "python", "python_3.x" ]
stackoverflow_0074200275_csv_python_python_3.x.txt
Q: Function to view a Binary Tree / Binary Search Tree in an actual Tree format? Is there a way to view a BT/BST in such a manner: 5 / \ 2 7 / \ / \ 1 3 6 8 I've browsed the internet an came across a method which displays the Tree, but it is ti...
Function to view a Binary Tree / Binary Search Tree in an actual Tree format?
Is there a way to view a BT/BST in such a manner: 5 / \ 2 7 / \ / \ 1 3 6 8 I've browsed the internet an came across a method which displays the Tree, but it is tilted to the left as such: 8 7 6 ...
[ "I provide below a program that will generate an output like this:\n 100\n ┌───────┴───────┐\n 12 230\n┌──┴──┐ ┌──┴───┐\n8 32 205 323\n└─┐ └─┐ ┌──┴──┐ └─┐\n 10 43 201 213 999\n ┌─┘ └─┐\n 39 225\n ┌─┘\n 38\n ┌─┘\n 37\n\...
[ 0 ]
[]
[]
[ "binary_search_tree", "printing", "python", "tree" ]
stackoverflow_0074185181_binary_search_tree_printing_python_tree.txt
Q: Finding a match in a list and displaying span using regex So I am trying to search through a list for this sequence of characters using regex rbd = RVQPTESIVRFPNITNLCPFGEVFNATRFASVYAWNRKRISNCVADYSVLYNSASFSTFKCYGVSPTKLNDLCFTNVYADSFVIRGDEVRQIAPGQTGKIADYNYKLPDDFTGCVIAWNSNNLDSKVGGNYNYLYRLFRKSNLKPFERDISTEIYQAGSTPCNGVEG...
Finding a match in a list and displaying span using regex
So I am trying to search through a list for this sequence of characters using regex rbd = RVQPTESIVRFPNITNLCPFGEVFNATRFASVYAWNRKRISNCVADYSVLYNSASFSTFKCYGVSPTKLNDLCFTNVYADSFVIRGDEVRQIAPGQTGKIADYNYKLPDDFTGCVIAWNSNNLDSKVGGNYNYLYRLFRKSNLKPFERDISTEIYQAGSTPCNGVEGFNCYFPLQSYGFQPTNGVGYQPYRVVVLSFELLHAPATVCGPKKSTNLVKNKCVNF the r...
[ "You have line breaks inside the string.\nTo fix the issue, you can remove the line breaks with\nrbd = re.finditer(r'RV[NVSFGYLPTAKRICDQEWH]{219,219}NF',seqs.replace(\"\\n\", \"\"))\n\nOr, you may remove any whitespace using\nrbd = re.finditer(r'RV[NVSFGYLPTAKRICDQEWH]{219,219}NF', \"\".join(seqs.split()))\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074200320_python_regex.txt
Q: how to properly plot a bar using float numbers using matplotlib? I've got 2 float number in a list named students, one is 1000000 and 1050000, but the plot shows the incorrect numbers. import matplotlib.pyplot as plt fig= plt.figure() ax=fig.add_axes([0,0,1,1]) langs=['ripley', 'paris'] students = [ripley_product_...
how to properly plot a bar using float numbers using matplotlib?
I've got 2 float number in a list named students, one is 1000000 and 1050000, but the plot shows the incorrect numbers. import matplotlib.pyplot as plt fig= plt.figure() ax=fig.add_axes([0,0,1,1]) langs=['ripley', 'paris'] students = [ripley_product_price1, paris_product_price1] ax.bar(langs,students) plt.show()
[ "Your plot is correct. The values of tick labels need to be multiplied by the number in the red box (1E6).\n\n" ]
[ 1 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074200140_jupyter_notebook_python.txt
Q: Pandas dataframe with MultiIndex: exclude level values I have a multi-indexed pandas dataframe like the following one. import numpy as np import pandas as pd arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']), ...
Pandas dataframe with MultiIndex: exclude level values
I have a multi-indexed pandas dataframe like the following one. import numpy as np import pandas as pd arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']), np.array(['blo', 'bla', 'bla', 'blo', 'blo', 'blu'...
[ "IIUC, maybe you can mask your subset with:\nsubset = subset.iloc[subset.index.get_level_values(2) != 'blo']\n\n", "You can do it this way:\nIn [263]:\nsubset.loc[subset.index.get_level_values(2) != 'blo']\n\nOut[263]:\n 0 1 2 3\nbar one bla -1.039335 -1.124656 0.057114...
[ 8, 4, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0034788118_dataframe_pandas_python.txt
Q: NumPy / Python - Scalars to rows broadcasting in an element-wise multiplicaiton I am searching for an elegant solution for multiplying each i-th row of the matrix by the corresponding i-th value of the vector (element-wise). This can be done by iterating the rows of the matrix and the vector of scalars at the same...
NumPy / Python - Scalars to rows broadcasting in an element-wise multiplicaiton
I am searching for an elegant solution for multiplying each i-th row of the matrix by the corresponding i-th value of the vector (element-wise). This can be done by iterating the rows of the matrix and the vector of scalars at the same time (as illustrated in the code snippet below) - but I am wondering whether there i...
[ "You can use plain broadcasting\nmatrix / matrix.sum(axis=1)[:, None]\n\nor alternatively the maybe more intuitive einsum:\nnp.einsum('ij,i->ij', matrix, 1/matrix.sum(axis=1))\n\n", "Thank you for answering!\nI forgot that the matrix.sum(axis=1) will yield an array of a shape (m,) not (m, 1) -> thus, broadcasting...
[ 3, 0 ]
[]
[]
[ "array_broadcasting", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074200015_array_broadcasting_numpy_numpy_ndarray_python.txt
Q: Delete multiple postgreSQL records with python My problem is that when I try to delete records from a table in postgreSQL with python I can't do it, the method I created deletes 1 by 1, but when I want to delete 2 or more at once I get an error, which is this, TypeError: PersonaDAO.delete() takes 2 positional argu...
Delete multiple postgreSQL records with python
My problem is that when I try to delete records from a table in postgreSQL with python I can't do it, the method I created deletes 1 by 1, but when I want to delete 2 or more at once I get an error, which is this, TypeError: PersonaDAO.delete() takes 2 positional arguments but 3 were given The method I create to delete...
[ "i don't know your framework, but i'd try this\nthe problem is in delete():\nOne way of doing it:\n@classmethod\ndef delete (cls, *people):\n with Conexion.getConexion():\n with Conexion.getCursor() as cursor:\n count = 0\n for person in people:\n values = (person.id_p...
[ 0, 0 ]
[]
[]
[ "postgresql", "python", "sql_delete", "sql_update" ]
stackoverflow_0074196233_postgresql_python_sql_delete_sql_update.txt
Q: How to create folder and subfolders if they don't exist with remote send I need to send the images downloaded from one server to another. However, I need to save the images in folder with "year" , "month . Here's an example: ftp = ftplib.FTP('ftp-server','userftp','*********') file = open('download-torrent-filme....
How to create folder and subfolders if they don't exist with remote send
I need to send the images downloaded from one server to another. However, I need to save the images in folder with "year" , "month . Here's an example: ftp = ftplib.FTP('ftp-server','userftp','*********') file = open('download-torrent-filme.webp','rb') ftp.storbinary('STOR year/month/download-torrent-filme.webp', fil...
[ "Useful function of the library ftplib:\n\nnlst() lists an array for all files in ftp server.\nmkd() create a folder on the ftp server.\n\nTry the code below (I'm sorry but I didn't test it):\nimport ftplib\nfrom datetime import date\n\nyear = date.today().year\nmonth = date.today().month\n\n# here I use exactly yo...
[ 1 ]
[]
[]
[ "ftplib", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074200419_ftplib_python_python_2.7_python_3.x.txt
Q: Getting summary statistics from a class I am coding in Python and I have to code in a class that takes a list of numbers and returns the size of the list, the mean of the list, and the min and max of the list list_1 = [0,1,2,3,4,5,6,7] class SummaryStats: def __init__(self, list_x): self.list_x = list_...
Getting summary statistics from a class
I am coding in Python and I have to code in a class that takes a list of numbers and returns the size of the list, the mean of the list, and the min and max of the list list_1 = [0,1,2,3,4,5,6,7] class SummaryStats: def __init__(self, list_x): self.list_x = list_x #self.mean = sum(list_x) / len(list...
[ "For len, max and min you need to need to write a method. You can archive like this,\nclass SummaryStats:\n def __init__(self, list_x):\n self.size = len(list_x)\n self.mean = self.sample_mean(list_x)\n self.min = min(list_x)\n self.max = max(list_x)\n \n def sample_mean(self, l...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074200425_python.txt
Q: Creating a tuple without using tuple function I have to create a list of tuples without using the tuple() function. The input is a list of lists where each list contains a profile ID and the calendar date on which the user went of a date. The output is a list of tuples showing the profile ID and the number of date...
Creating a tuple without using tuple function
I have to create a list of tuples without using the tuple() function. The input is a list of lists where each list contains a profile ID and the calendar date on which the user went of a date. The output is a list of tuples showing the profile ID and the number of dates the user went on. The final output should be a li...
[ "You can get the expected output with collections.Counter:\nfrom collections import Counter\n\nlst = [\n [\"B111\", \"10/2/2022\"],\n [\"B222\", \"9/25/2022\"],\n [\"B333\", \"8/1/2022\"],\n [\"B222\", \"9/2/2022\"],\n]\n\nc = Counter(v for v, _ in lst)\nprint(list(c.items()))\n\nPrints:\n[('B111', 1), ...
[ 3, 0, -2 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074200331_python_tuples.txt
Q: How to combine multiple rows into one row WITHOUT group by in Python Pandas? I tried searching it on stack overflow, and I got a lot of similar titles but the problem isn't quite the same (it appears very different). Also, read some of the documentation (not all from Pandas) but couldn't find any method to do this...
How to combine multiple rows into one row WITHOUT group by in Python Pandas?
I tried searching it on stack overflow, and I got a lot of similar titles but the problem isn't quite the same (it appears very different). Also, read some of the documentation (not all from Pandas) but couldn't find any method to do this. Suppose I have a dataframe like: How do I combine this into one row in Pandas? ...
[ "rows=[] #initiate a list to store each row\n\nfor i in range(len(df)):\n temp=df.loc[[i]] #extract each row\n temp.columns=np.arange(i*len(temp.columns),(i+1)*len(temp.columns)) #rename column of each row\n temp.reset_index(drop=True, inplace=True) #drop index\n rows=rows+[temp] #add it to the list of ...
[ 1 ]
[]
[]
[ "data_science", "pandas", "python" ]
stackoverflow_0074200345_data_science_pandas_python.txt
Q: PYTHON Script not using OS Commands Within a UBUNTU VM, using GNS3 I created code that is an attempt to after the user's input perform one of 3 different outcomes, however, the if statements don't work, the python files can't be found which I was trying to point to this the cd/home.. command. And the curl commands...
PYTHON Script not using OS Commands
Within a UBUNTU VM, using GNS3 I created code that is an attempt to after the user's input perform one of 3 different outcomes, however, the if statements don't work, the python files can't be found which I was trying to point to this the cd/home.. command. And the curl commands are apparently the incorrect syntax even...
[ "You are using single quotes to quote something that already has single quotes. By doing so, what should be an opening quote in your curl command is now effectively a closing quote in your Python, and Python doesn't understand why there is now a random ( there where Python code should continue.\nI underlined what i...
[ 0 ]
[]
[]
[ "onos", "operating_system", "python", "ryu", "ubuntu" ]
stackoverflow_0074200444_onos_operating_system_python_ryu_ubuntu.txt
Q: Sorting counter dictionary to get list of keys and values I have a list of values and i would like to plot the values and its frequency on a pie chart that is, i would like to plot only the two highest values on a piechart Value_list = [1, 3, 2, 4, 5, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 5, 2, 2, 2, 2, 1, 1] A: You ...
Sorting counter dictionary to get list of keys and values
I have a list of values and i would like to plot the values and its frequency on a pie chart that is, i would like to plot only the two highest values on a piechart Value_list = [1, 3, 2, 4, 5, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 5, 2, 2, 2, 2, 1, 1]
[ "You can do this with matplotlib and collections.Counter,\nvalue_list = [1, 3, 2, 4, 5, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 5, 2, 2, 2, 2, 1, 1]\n\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\nmost_common_2 = Counter(value_list).most_common(2) # taking most 2 common values\n\nlabels = []\nvalues = ...
[ 2 ]
[]
[]
[ "pie_chart", "python" ]
stackoverflow_0074200378_pie_chart_python.txt
Q: Creating twitch irc bot (Login authentication failed) I am using Python 2.7 and i'm trying to create IRC bot for twitch but i have a problem. I created bot in other IRC like "webchat.freenode.net" and everything was ok..My code for twitch : import time import socket HOST = "irc.twitch.tv" PORT = 6667 BOTNICK = "t...
Creating twitch irc bot (Login authentication failed)
I am using Python 2.7 and i'm trying to create IRC bot for twitch but i have a problem. I created bot in other IRC like "webchat.freenode.net" and everything was ok..My code for twitch : import time import socket HOST = "irc.twitch.tv" PORT = 6667 BOTNICK = "thebot" PASSWORD = "oauth:nph788dap10fu6ozlzv1b32fzm4r8q" C...
[ "Finally , i found the problem with my code!! So, i will write the steps to create twitch bot with 2 ways!\nFirst way :\n\nYou must create an account to twitch \nimport socket\nimport re\n\n\nHOST = \"irc.twitch.tv\"\n\nPORT = 6667\n\nNICK = \"botname\" #The account Name\n\nPASS = \"The password here\" #http://www....
[ 1, 0, 0 ]
[]
[]
[ "bots", "irc", "python", "python_2.7", "twitch" ]
stackoverflow_0041621457_bots_irc_python_python_2.7_twitch.txt
Q: How to extract digits from a number from left to right? I know that I can extract digits from a number from right to left by implementing something like: while (number => 10) digit = number modulo 10 number = number / 10 But is there a way to do it from left to right that works similar to this one, simply by ...
How to extract digits from a number from left to right?
I know that I can extract digits from a number from right to left by implementing something like: while (number => 10) digit = number modulo 10 number = number / 10 But is there a way to do it from left to right that works similar to this one, simply by using stuff like the modulo value?
[ "If you don't have problem with recursion approach then here is a solution with little change in your code:- \ndef get_digit(num):\n if num < 10:\n print(num)\n else:\n get_digit(num // 10)\n print(num % 10)\n\nUsage\n>>> get_digit(543267)\n5\n4\n3\n2\n6\n7\n\n", "You can do something l...
[ 14, 4, 3, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0041321533_math_python.txt
Q: How to flatten columns in pandas dataframe with some columns as json? I try to flatten some columns in my dataframe, but unfurtunately it does not work. What would be the correct way of doing this? created_at tweet_hashtag tweet_cashtag 2022-07-23 [{'start': 16, 'end': 27, 'tag': 'blockchain'}, {'start': 28, 'en...
How to flatten columns in pandas dataframe with some columns as json?
I try to flatten some columns in my dataframe, but unfurtunately it does not work. What would be the correct way of doing this? created_at tweet_hashtag tweet_cashtag 2022-07-23 [{'start': 16, 'end': 27, 'tag': 'blockchain'}, {'start': 28, 'end': 32, 'tag': 'btc'}, {'start': 33, 'end': 37, 'tag': 'eth'}, {'star...
[ "you can use:\ndef get_values(a,b):\n x_values=[]\n for i in range(0,len(a)):\n x_values.append(a[i]['tag'])\n y_values=[]\n for j in range(0,len(b)):\n y_values.append(b[j]['tag'])\n return ','.join(x_values),','.join(y_values)\n\ndf[['tweet_hashtag','tweet_cashtag']]=df[['tweet_hashta...
[ 0 ]
[]
[]
[ "json", "python", "twarc2" ]
stackoverflow_0074200151_json_python_twarc2.txt
Q: DFS of a large dataset but maximum recursion limit reached I am doing DFS search using python. I am using networkx library to store the nodes in a graph data structure. The dataset contains 5000000 nodes. Then i converted the stored data into adjacency list using to_dict_to_list() function. Now when i call dfs() f...
DFS of a large dataset but maximum recursion limit reached
I am doing DFS search using python. I am using networkx library to store the nodes in a graph data structure. The dataset contains 5000000 nodes. Then i converted the stored data into adjacency list using to_dict_to_list() function. Now when i call dfs() function error : maximum recursion depth limit increased. I tried...
[ "The depth-first search algorithm works by maintaining a stack of nodes. In your implementation, you are using the call stack as your stack, with recursive functions serving as the push and pop operations. This runs into trouble, as you've noticed, on large graphs where the call stack is limited.\nAnother option is...
[ 0 ]
[]
[]
[ "data_structures", "graph", "python", "python_3.x" ]
stackoverflow_0074197552_data_structures_graph_python_python_3.x.txt
Q: Struggling to scrape a website using Scrapy I've recently started my first project in Python. I'm keen on trains, and I hadn't found any CSV data on the website of my country's rail company, so I decided to do web scraping in Scrapy. However, when using the fetch command in my terminal to test the response I keep ...
Struggling to scrape a website using Scrapy
I've recently started my first project in Python. I'm keen on trains, and I hadn't found any CSV data on the website of my country's rail company, so I decided to do web scraping in Scrapy. However, when using the fetch command in my terminal to test the response I keep stumbling upon DEBUG: Crawled (403). Terminal fre...
[ "Your first link is working fine, I was able to successfully extract all of the information from the table by using the spider in my example below, and no extra middleware was needed to access it. Your second link was a dead end though both in scrapy and when attempting to visit it using the browser. You may want ...
[ 0 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074196259_python_scrapy_web_scraping.txt
Q: Django double curly braces tag not loading in html templates I am new here so I may have worded the title wrong I apologize if I did so. So I created a checkout page in my django project for the user to purchase coins but it wont render the variable attribute on the browser it just shows up empty. Here's the coinp...
Django double curly braces tag not loading in html templates
I am new here so I may have worded the title wrong I apologize if I did so. So I created a checkout page in my django project for the user to purchase coins but it wont render the variable attribute on the browser it just shows up empty. Here's the coinpack model.py code. ` class Coinpack (models.Model): amount= mod...
[ "You used the different variables in the template. Try this,\n<body>\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-lg\">\n <br>\n <img src=\"{{checkout.image_url}}\">\n </div>\n <div class=\"col-lg\">\n <b...
[ 1 ]
[]
[]
[ "checkout", "django", "python", "web" ]
stackoverflow_0074200521_checkout_django_python_web.txt
Q: Pydeequ throwing Py4JJavaError I have the following installation of Pydeequ: In an anaconda environment, I have installed pyspark 3.0.0, pydeequ last release and sagemaker_pyspark last release. from pyspark.sql import SparkSession import os os.environ["SPARK_VERSION"] = r"3.0.0" import pydeequ import sagemaker_p...
Pydeequ throwing Py4JJavaError
I have the following installation of Pydeequ: In an anaconda environment, I have installed pyspark 3.0.0, pydeequ last release and sagemaker_pyspark last release. from pyspark.sql import SparkSession import os os.environ["SPARK_VERSION"] = r"3.0.0" import pydeequ import sagemaker_pyspark from pyspark.sql import Spark...
[ "Have you tried github.com/canimus/cuallee\nDrop in replacement for pydeequ, that does not require any additional jars, is tested on M1, and it runs 2x faster than pydeequ?\n" ]
[ 1 ]
[]
[]
[ "amazon_deequ", "pydeequ", "python" ]
stackoverflow_0073755721_amazon_deequ_pydeequ_python.txt
Q: Transform a pandas Dataframe, move headers into columns Inp: data = { "Name_1" : [2, 6, 3], "Name_2": [8, 20, 12], "Name_3": [7, 3, 1], } df = pd.DataFrame(data) date = ['21/10/2022','22/10/2022','23/10/2022'] df = df.set_index([date]) df Out: Name_1 Name_2 Name_3 21/10/2022 2 8 ...
Transform a pandas Dataframe, move headers into columns
Inp: data = { "Name_1" : [2, 6, 3], "Name_2": [8, 20, 12], "Name_3": [7, 3, 1], } df = pd.DataFrame(data) date = ['21/10/2022','22/10/2022','23/10/2022'] df = df.set_index([date]) df Out: Name_1 Name_2 Name_3 21/10/2022 2 8 7 22/10/2022 6 20 3 23/10/2022 3 12 ...
[ "Try:\nout = df.stack().reset_index(level=1)\nout.columns = [\"A\", \"B\"]\nprint(out)\n\nPrints:\n A B\n21/10/2022 Name_1 2\n21/10/2022 Name_2 8\n21/10/2022 Name_3 7\n22/10/2022 Name_1 6\n22/10/2022 Name_2 20\n22/10/2022 Name_3 3\n23/10/2022 Name_1 3\n23/10/2022 Name_2 12\n2...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python", "transform" ]
stackoverflow_0074200674_dataframe_group_by_pandas_python_transform.txt
Q: image rectification on pressure gauge, rotate it vertically im currently trying to implement a paper of reading pressure gauges. There is a step where i dont know what to do. It says: "The display contour is then rotated to vertically align the long axis of the ellipse and inscribed in a rectangle used to crop the...
image rectification on pressure gauge, rotate it vertically
im currently trying to implement a paper of reading pressure gauges. There is a step where i dont know what to do. It says: "The display contour is then rotated to vertically align the long axis of the ellipse and inscribed in a rectangle used to crop the gauge image." So im not sure how i can rotate this image vertica...
[ "Here is how to get the image D from the image C:\n\nFind the binary mask\n\n\n\nFind an ellipse (center, width, height, angle)\n\n\n\nFind 4 points on opposite sides of the ellipse\n\n\n\nUse these 4 points to get perspective transform that can be used to warp the rotated gauge image to rectangular image. The fina...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074199045_image_processing_opencv_python.txt
Q: Django Shell Command Does Not Execute For Loop I have a Django project going on, containing some functions and creating/updating a database. From time to time, I need to update the staticfiles in the project therefore I created a .py file in the same folder as the project named updatefiles.py I am running the scri...
Django Shell Command Does Not Execute For Loop
I have a Django project going on, containing some functions and creating/updating a database. From time to time, I need to update the staticfiles in the project therefore I created a .py file in the same folder as the project named updatefiles.py I am running the script as python manage.py shell <updatefiles.py. Inside...
[ "I think what you really want to do is build a custom Django command:\nhttps://docs.djangoproject.com/en/4.1/howto/custom-management-commands/\nPutting a function inside the settings.py is not a good idea.\n" ]
[ 0 ]
[]
[]
[ "django", "django_manage.py", "manage.py", "python", "shell" ]
stackoverflow_0074146369_django_django_manage.py_manage.py_python_shell.txt
Q: Can I use a Dictionary to create a menu in Python I want to build a menu in Python (using the latest version). For example: menu_options = { 1: {'Option 1', 'regular'}, 2: {'Option 2', 'regular'}, 3: {'Option 3', 'admin'} } I will have 2 types of users, regular and admin. So when I print this menu, I...
Can I use a Dictionary to create a menu in Python
I want to build a menu in Python (using the latest version). For example: menu_options = { 1: {'Option 1', 'regular'}, 2: {'Option 2', 'regular'}, 3: {'Option 3', 'admin'} } I will have 2 types of users, regular and admin. So when I print this menu, I will check what type is my user, and then either print...
[ "This is not that dictionaries are magic. You're just using an inappropriate data type for the values stored in the dictionary.\nUse lists or tuples instead of sets.\nOther than that, a dictionary is not what you need if you want to just enumerate elements by their position. A list of a tuple can already do that.\n...
[ 3 ]
[]
[]
[ "dictionary", "menu", "python", "types" ]
stackoverflow_0074200755_dictionary_menu_python_types.txt
Q: how to stop iterating after the condition is done I have print(list_games) array([[77, 63], [94, 49], [58, 98], ..., [ 7, 0], [68, 22], [ 1, 32]], dtype=int64) I need to print the first pair and their index, which satisfy the condition, but my code print all pairs. How ...
how to stop iterating after the condition is done
I have print(list_games) array([[77, 63], [94, 49], [58, 98], ..., [ 7, 0], [68, 22], [ 1, 32]], dtype=int64) I need to print the first pair and their index, which satisfy the condition, but my code print all pairs. How can I fix it? for i in range(len(list_games)): for ...
[ "You can use a boolean to control if the first loop also should break or not.\nloop = True\nfor i in range(len(list_games)):\n for j in range(len(list_games)):\n if list_games[i][0] + list_games[j][1] == 131:\n print(list_games[i][0], list_games[j][1])\n loop = False\n bre...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074200762_python.txt
Q: implement the filter function to remove certain elements from a list I have the following function whose function is to return a list with the indices of the neighbors of each element in a list. example: in the following list l = [1, 2, 3, 4, 5] the indices of the neighbors of the element in position 0 would be 1,...
implement the filter function to remove certain elements from a list
I have the following function whose function is to return a list with the indices of the neighbors of each element in a list. example: in the following list l = [1, 2, 3, 4, 5] the indices of the neighbors of the element in position 0 would be 1, the indices of the neighbors of the element in position 1 would be 0 and ...
[ "As to your question: your filtering function probably fails because\n\nyou used \"and\" instead of \"or\".\n\nThe removal part:\n for index in indices:\n indices.remove(indices_delete)\n\nshould be\n for index in indices_delete:\n indices.remove(index)\n\n\n\nSo either fix the filtering part, or simply repla...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074200622_python.txt
Q: Python code for gcloud beta services identity create --service=$api --project=$project_id I have a bash code for gcp identity creation as below : gcloud beta services identity create --service=$api --project=$project_id I need corresponding python code, I have tried the below code but it is throwing exception def ...
Python code for gcloud beta services identity create --service=$api --project=$project_id
I have a bash code for gcp identity creation as below : gcloud beta services identity create --service=$api --project=$project_id I need corresponding python code, I have tried the below code but it is throwing exception def generateServiceIdentity(self, services): service = discovery.build( 'servic...
[ "As stated in the comments, you can run gcloud inside Python's os library:\nimport os \nos.system('gcloud beta services identity create --service={} --project={}'.format(api,project_id))\n\n" ]
[ 0 ]
[]
[]
[ "bash", "gcloud", "google_cloud_platform", "python", "unix" ]
stackoverflow_0074200009_bash_gcloud_google_cloud_platform_python_unix.txt
Q: Why is JAX's `split()` so slow at first call? jax.numpy.split can be used to segment an array into equal-length segments with a remainder in the last element. e.g. splitting an array of 5000 elements into segments of 10: array = jnp.ones(5000) segment_size = 10 split_indices = jnp.arange(segment_size, array.shape...
Why is JAX's `split()` so slow at first call?
jax.numpy.split can be used to segment an array into equal-length segments with a remainder in the last element. e.g. splitting an array of 5000 elements into segments of 10: array = jnp.ones(5000) segment_size = 10 split_indices = jnp.arange(segment_size, array.shape[0], segment_size) segments = jnp.split(array, spl...
[ "This is slow because there are tradeoffs in the implementation of split(), and your function happens to be on the wrong side of the tradeoff.\nThere are several ways to compute slices in XLA, including XLA:Slice (i.e. lax.slice), XLA:DynamicSlice (i.e. lax.dynamic_slice), and XLA:Gather (i.e. lax.gather).\nThe mai...
[ 5, 2 ]
[]
[]
[ "jax", "performance", "python" ]
stackoverflow_0074199437_jax_performance_python.txt
Q: Fine Tuning Stable Diffusion I'm trying to use the fine tuning method for stable diffusion to generate AI art ths is the google colab link if required https://colab.research.google.com/drive/1yGiI2TYkFMuETm4Rh5bh3-k6yY1C38w0?usp=sharing#scrollTo=60jVYSk0BGC8&uniqifier=3 #@title Setup and check the images you ha...
Fine Tuning Stable Diffusion
I'm trying to use the fine tuning method for stable diffusion to generate AI art ths is the google colab link if required https://colab.research.google.com/drive/1yGiI2TYkFMuETm4Rh5bh3-k6yY1C38w0?usp=sharing#scrollTo=60jVYSk0BGC8&uniqifier=3 #@title Setup and check the images you have just added import requests impo...
[ "It's from PIL and make sure the function is imported with \\Image.\nfrom PIL import Image\n\n" ]
[ 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0073916442_performance_python.txt
Q: NameError: name 'join' is not defined I used this code: randomstr = '',join((random.choice(chars)) for x in range(10)) It comes up with this error: NameError: name 'join' is not defined I expected a picture file to be saved after being uploaded. A: You made a mistake putting "," , the join comes after the "." ...
NameError: name 'join' is not defined
I used this code: randomstr = '',join((random.choice(chars)) for x in range(10)) It comes up with this error: NameError: name 'join' is not defined I expected a picture file to be saved after being uploaded.
[ "You made a mistake putting \",\" , the join comes after the \".\"\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074200879_python.txt
Q: Need someone to figure out what I am doing wrong a,b = input().split() # a and b are in strings for x in range(1,10): for y in range(2,10): if (x*y)*y == int(a+str(x)+b) : print(x,y) else: print("No") What am I doing wrong here? I want to print out the value of x and y when (x*y)*y is equal...
Need someone to figure out what I am doing wrong
a,b = input().split() # a and b are in strings for x in range(1,10): for y in range(2,10): if (x*y)*y == int(a+str(x)+b) : print(x,y) else: print("No") What am I doing wrong here? I want to print out the value of x and y when (x*y)*y is equal to the number of int("a"+str(x)+"b") I was expecting ...
[ "Not exactly sure if this is what you want, but if you put it in a function you can return the first values that match\na, b = input().split()\n\n# a and b are in strings\n\ndef find_x_y(a, b):\n for x in range(1, 10):\n for y in range(2, 10):\n if (x*y)*y == int(a+str(x)+b):\n r...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074200835_python.txt
Q: Can't build Cython code even with correct Visual C++ Build Tools installed I've been trying to build a basic test file with Cython, but I keep getting error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/. I have...
Can't build Cython code even with correct Visual C++ Build Tools installed
I've been trying to build a basic test file with Cython, but I keep getting error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/. I have a setup.py file: from setuptools import setup from Cython.Build import cythoniz...
[ "I was able to get it working by typing the command:\nSET DISTUTILS_USE_SDK=1 & \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Auxiliary\\Build\\vcvarsall.bat\" x64\n\nbefore building. Both setup.py build_ext --inplace and cythonize -i now work.\nYou will have to change the vcvarsall path...
[ 0 ]
[]
[]
[ "cython", "cythonize", "python", "visual_c++" ]
stackoverflow_0074192524_cython_cythonize_python_visual_c++.txt
Q: Get transparent background by using mask, I get white background def combined_display(image, matte): # calculate display resolution w, h = image.width, image.height rw, rh = 800, int(h * 800 / (3 * w)) # obtain predicted foreground image = np.asarray(image) if len(image.shape) == 2: image = imag...
Get transparent background by using mask, I get white background
def combined_display(image, matte): # calculate display resolution w, h = image.width, image.height rw, rh = 800, int(h * 800 / (3 * w)) # obtain predicted foreground image = np.asarray(image) if len(image.shape) == 2: image = image[:, :, None] if image.shape[2] == 1: image = np.repeat(image, 3...
[ "Suppose you have a 3-channel image and a 1-channel mask. Then you can stack them together into a 4-channel image where the last channel is responsible for transparency.\nimport numpy as np\nfrom PIL import Image\n\nimage = Image.open('image.png')\nmask = Image.open('mask.png').convert('L')\n\nimage_with_transparen...
[ 1 ]
[]
[]
[ "image_processing", "machine_learning", "mask", "numpy", "python" ]
stackoverflow_0074197555_image_processing_machine_learning_mask_numpy_python.txt
Q: How come nothing is showing up on the screen? Nothing at all is showing up on the screen. I've had this problem with another project but forgot how to fix it. Here is what I have so far. #----- To-Do -----# # Init # import pygame import time import random pygame.display.set_caption('Cake Clicker') RE...
How come nothing is showing up on the screen?
Nothing at all is showing up on the screen. I've had this problem with another project but forgot how to fix it. Here is what I have so far. #----- To-Do -----# # Init # import pygame import time import random pygame.display.set_caption('Cake Clicker') RESOLUTION = (192, 108) pygame.init() from pygame.loc...
[ "My code was missing a pygame.update() function!\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074200848_pygame_python.txt
Q: Value is printing twice rather than once I have this code. The count of values from the first url always displays twice. But the sum is right. So I get 4 4 2 6 Instead of 4 2 6 def count_blocklist_entries(): urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt'] entry_dict = {} for ur...
Value is printing twice rather than once
I have this code. The count of values from the first url always displays twice. But the sum is right. So I get 4 4 2 6 Instead of 4 2 6 def count_blocklist_entries(): urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt'] entry_dict = {} for url in urls: response = requests.get(url...
[ "Simply move the sum printing to the actual end of the code, after the \"for\" loop:\ndef count_blocklist_entries():\n urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt']\n entry_dict = {}\n for url in urls:\n response = requests.get(url)\n lengthers = len(response.text.spl...
[ 1, 0 ]
[]
[]
[ "printing", "python", "python_requests" ]
stackoverflow_0074200957_printing_python_python_requests.txt
Q: Python how to sum all the numbers in a dictionary I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value. Example of what I'm trying to do: list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]} 'area1': [395.0 * 212.0], 'area2': [...
Python how to sum all the numbers in a dictionary
I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value. Example of what I'm trying to do: list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]} 'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0] 'area1': [83740], 'area2': [18150] tot...
[ "You can use a generator expression to multiply the pairs of values in your dictionary, then sum the output of that:\nlst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}\ntotal = sum(v[0]*v[1] for v in lst.values())\n# 101890.0\n\n", "The answer with sum, map, and a lambda is probally the best for just areas...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074200925_python_python_3.x.txt
Q: Assign week numbers based on date ranges from another Pandas Dataframe I am trying to add a Week # Column to df1. I want to assign week numbers based on date ranges found in df2. df1 WorkDate 2022-05-03 2022-05-16 2022-05-24 df2 Week # Week Start Week End 1 2022-05-01 2022...
Assign week numbers based on date ranges from another Pandas Dataframe
I am trying to add a Week # Column to df1. I want to assign week numbers based on date ranges found in df2. df1 WorkDate 2022-05-03 2022-05-16 2022-05-24 df2 Week # Week Start Week End 1 2022-05-01 2022-05-07 2 2022-05-08 2022-05-14 3 2022-05-15 ...
[ "Try pd.merge_asof (Note: the dataframes must be sorted):\ndf1[\"WorkDate\"] = pd.to_datetime(df1[\"WorkDate\"])\ndf2[\"Week Start\"] = pd.to_datetime(df2[\"Week Start\"])\n\nx = pd.merge_asof(df1, df2, left_on=\"WorkDate\", right_on=\"Week Start\")\nprint(x[[\"WorkDate\", \"Week #\"]])\n\nPrints:\n WorkDate We...
[ 2, 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074200509_dataframe_datetime_pandas_python.txt
Q: python select through loop from a list by value position I'm newbie in python self-learning, I'm trying to make a menu that select from a list, I managed to select from the list by the value, but what I actually need is to select by value position, like my first example "Mango", any solution with explanations is h...
python select through loop from a list by value position
I'm newbie in python self-learning, I'm trying to make a menu that select from a list, I managed to select from the list by the value, but what I actually need is to select by value position, like my first example "Mango", any solution with explanations is highly appreciated # importing libraries from PyQt5.QtWidgets i...
[ "I see one problem: you use the same name jox_menu for three elements\n\nlist jox_menu = [...],\nfunction def jox_menu(self),\nargument in def onChange(self, jox_menu):\n\nand all this can make mess because you use jox_menu[2] probably to get item from list jox_menu but it gets single char from argument jox_menu.\n...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074193558_python_python_3.x.txt
Q: Combine string in a column based on groups in a pandas DataFrame I have a Pandas DataFrame, DF: Column A Column B Column C Apple red Texas Apple red California Banana yellow Indiana Banana yellow Florida I would like to get it in a dictionary in the form: { "Apple red" : ['Texas', 'California'], "Banana yell...
Combine string in a column based on groups in a pandas DataFrame
I have a Pandas DataFrame, DF: Column A Column B Column C Apple red Texas Apple red California Banana yellow Indiana Banana yellow Florida I would like to get it in a dictionary in the form: { "Apple red" : ['Texas', 'California'], "Banana yellow" : ['Indiana', 'Florida'] } where Key = concatenation ...
[ "Try:\nx = dict(\n df.groupby(df[\"Column A\"] + \" \" + df[\"Column B\"])[\"Column C\"].agg(list)\n)\n\nprint(x)\n\nPrints:\n{'Apple red': ['Texas', 'California'], 'Banana yellow': ['Indiana', 'Florida']}\n\n", "One option, which should be performant as well, is with a default dictionary:\nfrom collections im...
[ 3, 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074200986_dataframe_group_by_pandas_python.txt
Q: Split a dictionary with n values per key into n dictionaries How can I split a dictionary with 2 values per key into two dictionaries, one for the first value and one for the second value? That is, how do I turn this d = {'a':['val1', 'val2'], 'b': ['val1', 'val2']} into: d1 = {"a": "val1", "b": "val1"} d2 = {"a":...
Split a dictionary with n values per key into n dictionaries
How can I split a dictionary with 2 values per key into two dictionaries, one for the first value and one for the second value? That is, how do I turn this d = {'a':['val1', 'val2'], 'b': ['val1', 'val2']} into: d1 = {"a": "val1", "b": "val1"} d2 = {"a": "val2", "b": "val2"} Python 3.7
[ "If you'll always have two values, this is pretty straightforward with two dict comprehensions:\n>>> d1 = {k: v[0] for k, v in d.items()}\n>>> d2 = {k: v[1] for k, v in d.items()}\n>>> d1\n{'a': 'val1', 'b': 'val1'}\n>>> d2\n{'a': 'val2', 'b': 'val2'}\n\n", "Here's a simple list comprehension over all the values ...
[ 2, 2, 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074201070_dictionary_python.txt
Q: How to cluster PyTorch predictions I'm trying to find road lanes from road images and then make predictions out of the images. So far, I've trained a model that finds road lanes. But most of the predictions are scattered. I'm trying to cluster PyTorch predictions that we get from these road images. These dots are ...
How to cluster PyTorch predictions
I'm trying to find road lanes from road images and then make predictions out of the images. So far, I've trained a model that finds road lanes. But most of the predictions are scattered. I'm trying to cluster PyTorch predictions that we get from these road images. These dots are the predictions of model where the road ...
[ "If you only want to remove dots then you can try to use morphological operations such as Opening (erode+dilate) to postprocess your mask.\nThe resulting mask without dots:\n\nCode:\nimport cv2\nimport numpy as np\n\nmask = cv2.imread('road_mask.jpg', cv2.IMREAD_GRAYSCALE)\nmask = cv2.resize(mask, (120, 80))\n\nmas...
[ 1 ]
[]
[]
[ "cluster_analysis", "image_processing", "knn", "python", "pytorch" ]
stackoverflow_0074195216_cluster_analysis_image_processing_knn_python_pytorch.txt
Q: MongoDB InvalidDocument: Cannot encode object I am using scrapy to scrap blogs and then store the data in mongodb. At first i got the InvalidDocument Exception. So obvious to me is that the data is not in the right encoding. So before persisting the object, in my MongoPipeline i check if the document is in 'utf-8 ...
MongoDB InvalidDocument: Cannot encode object
I am using scrapy to scrap blogs and then store the data in mongodb. At first i got the InvalidDocument Exception. So obvious to me is that the data is not in the right encoding. So before persisting the object, in my MongoPipeline i check if the document is in 'utf-8 strict', and only then i try to persist the object ...
[ "Finally I figured it out. The problem was not with encoding. It was with the structure of the documents. \nBecause i went off on the standard MongoPipeline example which does not deal with nested scrapy items. \nWhat i am doing is:\n BlogItem:\n \"url\"\n ...\n comments = [CommentItem]\nSo my BlogIte...
[ 14, 3, 1, 0, 0 ]
[]
[]
[ "encoding", "mongodb", "python", "scrapy" ]
stackoverflow_0033524517_encoding_mongodb_python_scrapy.txt
Q: How to add a line of inputted text next column over and over until the person prompts to quit on Python My code works fine for the salesperson to enter the following criteria until the file is created with one list after being prompted to continue or quit writing the .txt file. def write_text(): print("Welcome...
How to add a line of inputted text next column over and over until the person prompts to quit on Python
My code works fine for the salesperson to enter the following criteria until the file is created with one list after being prompted to continue or quit writing the .txt file. def write_text(): print("Welcome to a Costco Hotel Text Creator.") print('-'*20) #This serves no purpose but to make the terminal look cl...
[ "When you use with open(...) as .. it closes the file as soon as you exit the code block, and since you are using the w file mode you are overwriting your previous entries every time your loop goes back to the top. You also don't need to wrap input statements with str(). The return value of input will always be a ...
[ 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074201137_list_python_python_3.x.txt
Q: How to select specific csv files from a folder in python? this is a 2 part question. I have a folder (existing in the same directory as the python script) with a lot of csv files and I want to read only specific csv files from the folder into python in order to later merge it into one data frame. I do not want to...
How to select specific csv files from a folder in python?
this is a 2 part question. I have a folder (existing in the same directory as the python script) with a lot of csv files and I want to read only specific csv files from the folder into python in order to later merge it into one data frame. I do not want to read all the csv files from the folder, just the csv files tha...
[ "If you want to use relative path:\nimport os\n\ncurrentDir = os.path.dirname(__file__) \nabsolutePath = os.path.join(currentDir, \"the/relative/path\")\n\nFor the file name, RegEx should work fine, but maybe a simple solution like this will work better:\nfor file in os.listdir(currentDir):\n if filename.startsw...
[ 1 ]
[]
[]
[ "file", "pandas", "python" ]
stackoverflow_0074200710_file_pandas_python.txt
Q: How do I retrieve phrases from a NLTK.tree using custom node labels? Given a NLTK tree produced using the code below, how do I retrieve the leaf values (phrases) that potentially match all of the node labels assigned using the nltk.RegexParser (e.g. those phrases which match the Present_Indefinite or Present_Perfe...
How do I retrieve phrases from a NLTK.tree using custom node labels?
Given a NLTK tree produced using the code below, how do I retrieve the leaf values (phrases) that potentially match all of the node labels assigned using the nltk.RegexParser (e.g. those phrases which match the Present_Indefinite or Present_Perfect tense)? from nltk import word_tokenize, pos_tag import nltk text = "#N...
[ "I've created a get_phrases_using_tense_label() function which takes:\n\nthe parse tree returned from your check_grammar() function (I've renamed it to get_parse_tree() as this is more meaningful in terms of what the function is doing), and\na list of tense labels based on your grammar.\n\nThe tense labels are retr...
[ 1 ]
[]
[]
[ "nlp", "nltk", "parse_tree", "part_of_speech", "python" ]
stackoverflow_0074196558_nlp_nltk_parse_tree_part_of_speech_python.txt
Q: Create column from dictionary key and merging on list similarity pandas python I have a dictionary like: {'A':['John','Mark','Jane'],'B':['Mike','Rob','James']} and a dataframe like: Name x y John --- --- Jane --- --- I would like to add another column, let's call it 'Group', that fills the dictionary key val...
Create column from dictionary key and merging on list similarity pandas python
I have a dictionary like: {'A':['John','Mark','Jane'],'B':['Mike','Rob','James']} and a dataframe like: Name x y John --- --- Jane --- --- I would like to add another column, let's call it 'Group', that fills the dictionary key value if Name matches any one of the inner list items. Ideally will end like...
[ "One solution can be creating inverse dictionary and then use pd.Series.map:\ndct = {\"A\": [\"John\", \"Mark\", \"Jane\"], \"B\": [\"Mike\", \"Rob\", \"James\"]}\n\n# 1. create inverse dictionary from dct\ninv_dct = {v: k for k, l in dct.items() for v in l} #inv_dct = {'John': 'A', 'Mark': 'A', 'Jane': 'A', 'Mi...
[ 1 ]
[]
[]
[ "dictionary", "list", "numpy", "pandas", "python" ]
stackoverflow_0074201173_dictionary_list_numpy_pandas_python.txt
Q: Take a variables into array and find maximun value Using numpy I have this variables: A01 = 10 A02 = 8 A03 = 3 A04 = 4 A05 = 12 And this comparisons C01 = abs(A01-A02) C02 = abs(A01-A03) C03 = abs(A01-A04) C04 = abs(A01-A05) C05 = abs(A01-A06) I need take C01, C02, C03, C04, C05 into array and find maxim...
Take a variables into array and find maximun value
Using numpy I have this variables: A01 = 10 A02 = 8 A03 = 3 A04 = 4 A05 = 12 And this comparisons C01 = abs(A01-A02) C02 = abs(A01-A03) C03 = abs(A01-A04) C04 = abs(A01-A05) C05 = abs(A01-A06) I need take C01, C02, C03, C04, C05 into array and find maximun value, How I to do this? My objetive is find the max...
[ "You create an array with those variables, and compare the first index to the rest via slicing. Then you can use np.abs and np.max to evaluate the entire array.\nimport numpy as np\nA0, A1, A2, A3, A4 = 10, 8, 3, 4, 12\ncompare = np.array([A0, A1, A2, A3, A4])\nmax_val = np.max(np.abs(compare[0]-compare[1:]))\nprin...
[ 1 ]
[]
[]
[ "arrays", "max", "numpy", "python", "variables" ]
stackoverflow_0074201041_arrays_max_numpy_python_variables.txt
Q: Discord.gateway warning "Shard ID None heartbeat blocked for more than... (Only my vps & win 11) At the beginning I will add that I know about the existence of similar topics. However, it is nowhere said that this only happens on certain devices. A problem like this topic Warning discord.getaway "discord.gateway: ...
Discord.gateway warning "Shard ID None heartbeat blocked for more than... (Only my vps & win 11)
At the beginning I will add that I know about the existence of similar topics. However, it is nowhere said that this only happens on certain devices. A problem like this topic Warning discord.getaway "discord.gateway: Shard ID None heartbeat blocked for more than 10 seconds." Discord.gateway warning "Shard ID None hear...
[ "The problem seems to be resolved. After many hours and many different attempts.\nI solved it quite unconventionally. Manually reinstalled discord site-packages from old computer to new and VPS.\nI don't understand why my current package discord.py wasn't working properly. It was correctly downloaded by pip\n" ]
[ 1 ]
[]
[]
[ "bots", "discord", "discord.py", "gateway", "python" ]
stackoverflow_0074198821_bots_discord_discord.py_gateway_python.txt
Q: Is there a way to make an inherited abstract property a required constructor argument in a Python dataclass? I'm using Python dataclasses with inheritance and I would like to make an inherited abstract property into a required constructor argument. Using an inherited abstract property as a optional constructor arg...
Is there a way to make an inherited abstract property a required constructor argument in a Python dataclass?
I'm using Python dataclasses with inheritance and I would like to make an inherited abstract property into a required constructor argument. Using an inherited abstract property as a optional constructor argument works as expected, but I've been having real trouble making the argument required. Below is a minimal workin...
[ "So, the thing is, you declared an abstract property. Not an abstract constructor argument, or an abstract instance dict entry - abc has no way to specify such things.\nAbstract properties are really supposed to be overridden by concrete properties, but the abc machinery will consider it overridden if there is a no...
[ 1 ]
[]
[]
[ "abstract_class", "python", "python_dataclasses", "required_field" ]
stackoverflow_0074200729_abstract_class_python_python_dataclasses_required_field.txt
Q: Python: get next item from a list on a schedule This is my first posted question; I am a new coder who is trying to make a fun quiz app for a friend using Flask, Jinja, and Python. In the quiz, you get 6 different clues each day that point you towards a specific answer (not multiple choice, a specific answer). I h...
Python: get next item from a list on a schedule
This is my first posted question; I am a new coder who is trying to make a fun quiz app for a friend using Flask, Jinja, and Python. In the quiz, you get 6 different clues each day that point you towards a specific answer (not multiple choice, a specific answer). I have a list with all the answers, and I am currently t...
[ "Consider where you define variables and in which area they are valid. In the last attempts, for this reason, the iterators do not maintain their state. They are recreated each time the function is called and disappear again when the function is exited.\nThe following example defines a global iterator that starts o...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074198953_flask_python.txt
Q: Python add column with new value when 2 conditions match I am trying to add a new column to my data with a FIPS code in it (5 digit number). Basically when County from maindata.csv matches County from fipsdata.tsv, I want the FIPS code (fipsCountyFIPS) to land in a new column i.e. data[fips] (so if County in maind...
Python add column with new value when 2 conditions match
I am trying to add a new column to my data with a FIPS code in it (5 digit number). Basically when County from maindata.csv matches County from fipsdata.tsv, I want the FIPS code (fipsCountyFIPS) to land in a new column i.e. data[fips] (so if County in maindata matches County in fipsdata THEN write the corresponding fi...
[ "Is this what you're looking for?\n# 1. Check if all the counties in the data are in the FIPS data.\n# If so, add a new column to `data` with each county corresponding FIPS code.\nif data.County.isin(fips.CountyName.unique()).all():\n data = (\n # 2. Merge the data with the FIPS data\n data.merg...
[ 1 ]
[]
[]
[ "fips", "pandas", "python" ]
stackoverflow_0074201009_fips_pandas_python.txt
Q: Are we able to change the font of the console? I was working on some code and I had a question pop up. How could I change the font, size or things like that of a user input? I was just testing out a question with some simple code: Change_font = input(‘Enter some words: ’) print(Change_font) How to change the fon...
Are we able to change the font of the console?
I was working on some code and I had a question pop up. How could I change the font, size or things like that of a user input? I was just testing out a question with some simple code: Change_font = input(‘Enter some words: ’) print(Change_font) How to change the font of the user input above? I don’t really have any u...
[ "That's out of control of the program showing its output in the terminal emulator.\nSo, as long as you're using a console to interact with the user, you will have to use whatever that console gives you.\nA few things are indeed manipulable: for example, some consoles support setting colors. But that will need some ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074201259_python.txt
Q: Meaning of sparse=False pre-processing data with OneHotEncoder I came across the meaning of setting sparse=False pre-processing my data with a OneHotEncoder. I did: ct = ColumnTransformer([ ("scaling", StandardScaler(), sca_col), #sca_col containing 3 columns ("onehot", OneHotEncoder(sparse=False, handle_u...
Meaning of sparse=False pre-processing data with OneHotEncoder
I came across the meaning of setting sparse=False pre-processing my data with a OneHotEncoder. I did: ct = ColumnTransformer([ ("scaling", StandardScaler(), sca_col), #sca_col containing 3 columns ("onehot", OneHotEncoder(sparse=False, handle_unknown='ignore'), ohe_col)]) #ohe_col containing 15 columns Then I ...
[ "By setting this flag, you choose to represent your data in a sparse formatting. This saves a lot of memory when you have an array where most of the elements are zero.\nFrom Scikit-learn's ColumTransformer documentation:\n\nsparse_thresholdfloat, default=0.3\nIf the output of the different\ntransformers contains sp...
[ 2, 1, 0 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0066580608_python_scikit_learn.txt
Q: Pandas - How to add a counter column based on date after a groupby? I have a dataframe in the following format (working with sports data): Team Player Date GameID Bears John 2022-10-01 A1 Bears Dave 2022-10-01 A1 Bears Steve 2022-10-01 A1 Bulls Connor 2022-10-01 C2 Bulls Jack 2022-10-01 C2 Bears John 2022-1...
Pandas - How to add a counter column based on date after a groupby?
I have a dataframe in the following format (working with sports data): Team Player Date GameID Bears John 2022-10-01 A1 Bears Dave 2022-10-01 A1 Bears Steve 2022-10-01 A1 Bulls Connor 2022-10-01 C2 Bulls Jack 2022-10-01 C2 Bears John 2022-10-03 A3 Basically, I want to be able to sort by team name ...
[ "here is one way to do it\n#create a dictionary of GameNum, with key being the index of the dataframe\n\nd=dict(df.loc[~df.duplicated(subset=['Team','Date'])] # choose unique Team and Date\n .groupby(['Team'], as_index=False) # groupby Team\n .cumcount()+1) # ...
[ 3, 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074201039_dataframe_pandas_python.txt