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: Is the a easy way to print the :e format to 10^x format? I am writing some numerical value in a matplotlib textbox as textst = "$En_1={0:.4e}$".format( *popt) plt.text(.950, .100, textst, bbox=props, ha='right', va='bottom', transform=ax.t...
Is the a easy way to print the :e format to 10^x format?
I am writing some numerical value in a matplotlib textbox as textst = "$En_1={0:.4e}$".format( *popt) plt.text(.950, .100, textst, bbox=props, ha='right', va='bottom', transform=ax.transAxes) Problem is, I am getting the numerical value as,say...
[ "You just have to do it yourself. Note that I'm assuming you want something that can be interpreted as LaTeX:\nimport math\n\n\ndef custom_number_format(n: float, precision: int = 3) -> str:\n exp = math.floor(math.log10(n))\n decimal = round(n / 10**exp, precision)\n return rf\"{decimal} \\times 10^{{{exp...
[ 0, 0 ]
[]
[]
[ "format", "python" ]
stackoverflow_0074541759_format_python.txt
Q: I need help to find the correct output (convert word to lower case) Here is my my program: def word_frequencies(words): l=[] l=words.split() wordfreq=[l.count(p) for p in l] return(dict(zip(l,wordfreq))) if __name__ == '__main__': words = input("Enter a sentence: ") your_dictionary = word_...
I need help to find the correct output (convert word to lower case)
Here is my my program: def word_frequencies(words): l=[] l=words.split() wordfreq=[l.count(p) for p in l] return(dict(zip(l,wordfreq))) if __name__ == '__main__': words = input("Enter a sentence: ") your_dictionary = word_frequencies(words) sorted_keys = sorted(your_dictionary.keys()) f...
[ "Use the str.lower() function to make all words lowercase before counting them.\nFor example:\ndef word_frequencies(words):\n l = words.lower().split()\n # ...\n\n", "def word_frequencies(words):\n return {p: words.count(p) for p in set(words)}\n\nif __name__ == '__main__':\n words = input(\"Enter a s...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074540930_python.txt
Q: How to check if more than one model/library is installed if not install it? I want python to install model1 & model2 if they are not already installed if model1 or model2 doesn't exist then !pip install model1 & !pip install model2 A: The easiest way is to ensure that all modules can be loaded on all systems. En...
How to check if more than one model/library is installed if not install it?
I want python to install model1 & model2 if they are not already installed if model1 or model2 doesn't exist then !pip install model1 & !pip install model2
[ "The easiest way is to ensure that all modules can be loaded on all systems. Enclosing each import statement in a try block is the best solution and not un-Pythonic at all.\n> try:\n> import model1\n> print(\"module 'model1' is installed\") \n\n> except ModuleNotFoundError:\n> print(\"module 'model1' is...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074541938_python.txt
Q: Bypassing recaptcha v2 using python requests this is a web scraping project I'm working on. I need to send the response of this v2 recaptcha but it's not bringing the data I need ` headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,applicatio...
Bypassing recaptcha v2 using python requests
this is a web scraping project I'm working on. I need to send the response of this v2 recaptcha but it's not bringing the data I need ` headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'user-agent': '...
[ "If the website you're trying to scrape is reCaptcha protected, your best bet is to use a stealthy method for scraping. That means either Selenium (with at least selenium-stealth) or a third party web scraper, such as WebScrapingAPI, where I'm an engineer.\nThe advantage of using the third party service is that it ...
[ 0 ]
[]
[]
[ "2captcha", "python", "python_requests", "web_scraping" ]
stackoverflow_0074540568_2captcha_python_python_requests_web_scraping.txt
Q: Unable to import numpy/pandas/matplotlib packages in VScode I have used widely used packages(installed via pip) for a while in Jupyter notebook without any issues. I tried to do Python coding in VScode,but it somehow cannot load those packages. I have tried changing python interpreter, but it did solve the issue. ...
Unable to import numpy/pandas/matplotlib packages in VScode
I have used widely used packages(installed via pip) for a while in Jupyter notebook without any issues. I tried to do Python coding in VScode,but it somehow cannot load those packages. I have tried changing python interpreter, but it did solve the issue. Does anyone know how to resolve this issue?
[ "First make sure that you have the python interpreter installed on your computer. In your vscode UI you should see a terminal. You can install and upgrade pip through there if needed by using these commands:\npip install --upgrade pip\n\nFrom here you should be able to import using pip commands.\n" ]
[ 0 ]
[ "Hi you can use terminal for installation.\notherwise you can anaconda iDE its very good tool and user friendly.\n" ]
[ -1 ]
[ "package", "python", "visual_studio_code" ]
stackoverflow_0074541851_package_python_visual_studio_code.txt
Q: How to format a JSON in python create a json file the file should be formatted like this: {"name": "YOU", "items": { "item 1": "bread", "quantity of item 1": 2, "price of item1": "0.60", "item 2": "milk", "quantity of item 2": 10, "price of item2": "6.00" } } ...
How to format a JSON in python
create a json file the file should be formatted like this: {"name": "YOU", "items": { "item 1": "bread", "quantity of item 1": 2, "price of item1": "0.60", "item 2": "milk", "quantity of item 2": 10, "price of item2": "6.00" } } //I tried to use f.write( When I t...
[ "Python has the json library for formatting dictionaries into json formats:\nimport json\njson_string = json.dumps(items)\nprint(json_string)\n\nAnother issue is that you're defining key-value pairs within a list - you want to use {} instead of [] if you're giving values keys as well, and placing commas in some mis...
[ 1 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074542057_dictionary_json_python.txt
Q: How to change text when a button is pressed with PySimpleGUI I'm trying to make a calculator with PySimpleGUI as a school project and I have made a basic GUI with it but I am struggling to make the buttons functional. I made functions for all the buttons. import PySimpleGUI as sg def pressed_button_0(): butto...
How to change text when a button is pressed with PySimpleGUI
I'm trying to make a calculator with PySimpleGUI as a school project and I have made a basic GUI with it but I am struggling to make the buttons functional. I made functions for all the buttons. import PySimpleGUI as sg def pressed_button_0(): button0 = 0 def pressed_button_1(): button1 = 1 def pressed_bu...
[ "Variable buttonX is just a variable and nothing about the GUI, you have to call elemet.update(value=something) where the element can be found by window[element_key].\nimport PySimpleGUI as sg\n\nkeys = ['123÷', '456×', '789+', '.0=-']\nall_keys = ''.join(keys)\n\nsg.theme('DarkGrey13')\nsg.set_options(font=('Couri...
[ 0 ]
[]
[]
[ "pysimplegui", "python", "python_3.10", "user_interface" ]
stackoverflow_0074454414_pysimplegui_python_python_3.10_user_interface.txt
Q: Read flat list into multidimensional array/matrix in python I have a list of numbers that represent the flattened output of a matrix or array produced by another program, I know the dimensions of the original array and want to read the numbers back into either a list of lists or a NumPy matrix. There could be more...
Read flat list into multidimensional array/matrix in python
I have a list of numbers that represent the flattened output of a matrix or array produced by another program, I know the dimensions of the original array and want to read the numbers back into either a list of lists or a NumPy matrix. There could be more than 2 dimensions in the original array. e.g. data = [0, 2, 7, 6...
[ "Use numpy.reshape:\n>>> import numpy as np\n>>> data = np.array( [0, 2, 7, 6, 3, 1, 4, 5] )\n>>> shape = ( 2, 4 )\n>>> data.reshape( shape )\narray([[0, 2, 7, 6],\n [3, 1, 4, 5]])\n\nYou can also assign directly to the shape attribute of data if you want to avoid copying it in memory:\n>>> data.shape = shape...
[ 26, 6, 5, 0, 0 ]
[]
[]
[ "multidimensional_array", "numpy", "python" ]
stackoverflow_0003636344_multidimensional_array_numpy_python.txt
Q: How to get '7' attached to each string in a list in Python if it doesn't have 7 already in it? I have been trying to solve a problem where I am given a list as input and I need to show an output with 7 attached to each string value if it doesn't contain a 7 already. I have created a list and for the case of 7 not ...
How to get '7' attached to each string in a list in Python if it doesn't have 7 already in it?
I have been trying to solve a problem where I am given a list as input and I need to show an output with 7 attached to each string value if it doesn't contain a 7 already. I have created a list and for the case of 7 not included I have attached the '7' using the for loop. So for example: for the input ["a7", "g", "u"],...
[ "You can use a cleaner and more pythonic solution, no classes required, and much more concise:\n\ndef jazz(items):\n return [item if '7' in item else item+'7' for item in items]\n\nif __name__ == \"__main__\":\n lt = ['a7', 'g', 'u']\n p = jazz(lt)\n print(p)\n\n\nIf you want to modify the original list...
[ 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074542021_list_python.txt
Q: Replace the last line of a file in python I am working on a project where i use a text file to store the data. I have a label for the user to enter the name and i want the user's name to be saved on line 41 of the file, which is the last line. I tried append but that just keeps adding a last line so if the user ty...
Replace the last line of a file in python
I am working on a project where i use a text file to store the data. I have a label for the user to enter the name and i want the user's name to be saved on line 41 of the file, which is the last line. I tried append but that just keeps adding a last line so if the user types another name it wont replace it but add ano...
[ "Here you go:\n\n# == Ignore this part ==========================================================\n# `create_fake_course_info_file`, `FakeInputBox` and `FakeUsernameLabel` are just\n# placeholder classes to simulate the objects that `FakeCls.addUser` method\n# interacts with.\n\ndef create_fake_course_info_file(fi...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074541990_python.txt
Q: Tensorflow: How can I use tf.roll without wrapping? I want to independently shift the columns or rows of a 2-D tensor like: a = tf.constant([[1,2,3], [4,5,6]]) shift = tf.constant([2, -1]) b = shift_fn(a, shift) which gives me: b = [[0, 0, 1], [5, 6, 0]] I find that tf.roll() can do similar things but will wrap ...
Tensorflow: How can I use tf.roll without wrapping?
I want to independently shift the columns or rows of a 2-D tensor like: a = tf.constant([[1,2,3], [4,5,6]]) shift = tf.constant([2, -1]) b = shift_fn(a, shift) which gives me: b = [[0, 0, 1], [5, 6, 0]] I find that tf.roll() can do similar things but will wrap the elements. How can I pad zeros using it?
[ "One not-so-nice solution is to first pad the tensor using tf.pad, then use tf.roll inside tf.map_fn to independently shift each row (or column) of the padded tensor. And then finally, you can take the proper slice of the result. For example:\na = tf.constant([[1,2,3], [4,5,6]])\nshift = tf.constant([2, -1])\n\ncol...
[ 0, 0 ]
[]
[]
[ "python", "tensor", "tensorflow" ]
stackoverflow_0063347897_python_tensor_tensorflow.txt
Q: How to quickly calculate the sympy symol within the data frame I use pandas, numpy, sympy library in python. Is there a way to calculate the below for statement faster? import pandas as pd import numpy as np import sympy as sp df = pd.DataFrame(np.zeros(100 ** 2).reshape(100,100)) x = sp.symbols('x',real = True) ...
How to quickly calculate the sympy symol within the data frame
I use pandas, numpy, sympy library in python. Is there a way to calculate the below for statement faster? import pandas as pd import numpy as np import sympy as sp df = pd.DataFrame(np.zeros(100 ** 2).reshape(100,100)) x = sp.symbols('x',real = True) df.loc[99,99] = x for j in range(99,0,-1): for k in range(j-1,-1...
[ "Let's run your code, but with a reasonable size 4 (instead of 100):\nIn [7]: df = pd.DataFrame(np.zeros(4 ** 2).reshape(4,4))\n ...: x = sp.symbols('x',real = True)\n ...: df.loc[3,3] = x\n ...: \n ...: for j in range(3,0,-1):\n ...: for k in range(j-1,-1,-1):\n ...: df.loc[k,j] = df.loc[k+1,j...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "sympy" ]
stackoverflow_0074541290_numpy_pandas_python_sympy.txt
Q: How to move Jupyter notebook cells up/down using keyboard shortcut? Anyone knows keyboard shortcut to move cells up or down in Jupyter notebook? Cannot find the shortcut, any clues? A: The following solution works on JupyterLab (I currently have version 2.2.6): You must first open the Keyboard Shortcuts configur...
How to move Jupyter notebook cells up/down using keyboard shortcut?
Anyone knows keyboard shortcut to move cells up or down in Jupyter notebook? Cannot find the shortcut, any clues?
[ "The following solution works on JupyterLab (I currently have version 2.2.6):\nYou must first open the Keyboard Shortcuts configuration file. In JupyterLab you can find it in Settings -> Advanced Settings Editor then selecting the \"Keyboard Shortcuts\" option in the left panel and then editing the \"User Preferenc...
[ 18, 6, 5, 3, 0 ]
[ "Tab + arrow keys works for me in Windows.\n" ]
[ -3 ]
[ "jupyter_lab", "jupyter_notebook", "keyboard_shortcuts", "python" ]
stackoverflow_0062453756_jupyter_lab_jupyter_notebook_keyboard_shortcuts_python.txt
Q: Update a dict with duplicate keys and keeping the index of each key the same in Python I am trying to update the json payload with a dict type info and keeping the key position the same as before as it is required by the task I am working on. Note I understand that the implementation of type dict not allow duplica...
Update a dict with duplicate keys and keeping the index of each key the same in Python
I am trying to update the json payload with a dict type info and keeping the key position the same as before as it is required by the task I am working on. Note I understand that the implementation of type dict not allow duplicate keys, but I do need this done, so any work-around or hacky approach would helps. I have a...
[ "An operator for this was added in Python 3.9 as the Union operator:\npayload_with_info = payload | info\nprint(payload_with_info)\n>>>\n{\n 'address': '',\n 'age': ' ',\n 'ethnicities': 'Vulcan',\n 'name': 'Spock',\n 'option1': '',\n 'option2': '',\n 'select': 'maternal',\n 'sub-ethnicities...
[ 0 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074542230_dictionary_json_python.txt
Q: VSCode issue with setting python version to 3.10 on Azure function sample I am trying to run the Azure python function with Fast API locally and hit into this issue https://github.com/Azure-Samples/fastapi-on-azure-functions/issues/7 The last one suggests upgrading to the 3.10 version of python to solve the issue....
VSCode issue with setting python version to 3.10 on Azure function sample
I am trying to run the Azure python function with Fast API locally and hit into this issue https://github.com/Azure-Samples/fastapi-on-azure-functions/issues/7 The last one suggests upgrading to the 3.10 version of python to solve the issue. However when i try to upgrade in vs code , i get the errors below When i try ...
[ "Below are the python versions installed in my windows system:\n\nWhen creating the Azure Function Python App in the VS code, it is not showing the Python 3.10.x version interpreter:\n\nIn this step, click on Skip virtual environment and create the required trigger function.\nYou can select the Python 3.10.x versio...
[ 1 ]
[]
[]
[ "azure_function_async", "azure_functions", "python", "python_3.x", "visual_studio_code" ]
stackoverflow_0074536796_azure_function_async_azure_functions_python_python_3.x_visual_studio_code.txt
Q: Calculate number of function calls for any size N I'm trying to understand a way to write how many times the print statement for fun1 will be called for any size N. Written in summation form. This is more of an analysis question. I know I could just setup a count variable and print the result. S is an array of N i...
Calculate number of function calls for any size N
I'm trying to understand a way to write how many times the print statement for fun1 will be called for any size N. Written in summation form. This is more of an analysis question. I know I could just setup a count variable and print the result. S is an array of N items. N is the size. def myAlg(S,n): for i in range...
[ "For two first loops we have sum of arithmetic progression 1+2+3+...+n, and result is\nT(n) = n*(n+1)/2\n\nknown as trianglular numbers (1,3,6,10,15,21...)\nSo loop for k is executed T(n) times, and inner part is executed\nQ(n) = sum(T(i),i=1..n) = n*(n+1)*(n+2)/6\n\ntimes, sequence is known as tetrahedral numbers ...
[ 1 ]
[]
[]
[ "algorithm", "analysis", "python" ]
stackoverflow_0074541959_algorithm_analysis_python.txt
Q: detect and count the number of star symbol in opencv-python I need to count the occurrence of the stars at the right bottom corner in the image, I read this article Template Matching and used the following code to find the stars but My code doesn't work for detecting the stars in the image. What changes should I m...
detect and count the number of star symbol in opencv-python
I need to count the occurrence of the stars at the right bottom corner in the image, I read this article Template Matching and used the following code to find the stars but My code doesn't work for detecting the stars in the image. What changes should I make in the code? import cv2 as cv import numpy as np from matplot...
[ "It's because your template is bigger than the actual star on the image. Template matching is not scale invariant, so you need to be careful and match an almost same-size image. I cropped this from your target image:\n\nThis is the full working snippet:\nimport cv2\n\n# image path\npath = \"D://opencvImages//\"\n\...
[ 3 ]
[]
[]
[ "computer_vision", "object_detection", "opencv", "python" ]
stackoverflow_0074542090_computer_vision_object_detection_opencv_python.txt
Q: How to instal Python packages for Spyder I am using the IDE called Spyder for learning Python. I would like to know in how to go about in installing Python packages for Spyder? A: step 1. First open Spyder and click Tools --> Open command prompt. For more details click visit this link, https://miamioh.instructu...
How to instal Python packages for Spyder
I am using the IDE called Spyder for learning Python. I would like to know in how to go about in installing Python packages for Spyder?
[ "step 1. First open Spyder and click Tools --> Open command prompt.\n\n\n\nFor more details click visit this link,\nhttps://miamioh.instructure.com/courses/38817/pages/downloading-and-installing-packages\n", "I am running Spyder 4.2.4 and for me following solution turned out to be working:\n\nopen tools-> prefere...
[ 7, 5, 3, 0, 0, 0 ]
[]
[]
[ "installation", "package", "python", "spyder" ]
stackoverflow_0063109860_installation_package_python_spyder.txt
Q: How to access value in QuerySet Django I am creating a simple Pizza Delivery website and trying to add an option to choose a topping. When I want to print Ingredients it returns QuerySet and Values in it separated by a comma. Is there any option how can I get values based on their variable names (ex. ingredients.a...
How to access value in QuerySet Django
I am creating a simple Pizza Delivery website and trying to add an option to choose a topping. When I want to print Ingredients it returns QuerySet and Values in it separated by a comma. Is there any option how can I get values based on their variable names (ex. ingredients.all[0].toppingName -> cheese) or is there any...
[ "In Django, if you want to get only a specific column value you can use\nModel.objects.all().values('column_name')\n\nYou can also filter the queryset and get values as\nModel.objects.filter(condition).values('column_name')\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074540818_django_django_models_python.txt
Q: Replace Nested for loop in list-comprehension I want to combine my id list with my status list and I used list comprehension to do it: # id id_list = [ 1, # UAE1S 2, # UAE2S 3, # UAE3S ] # status status_list = [ 'okay', 'not okay', 'unknown', ] result = [ { 'id':id, '...
Replace Nested for loop in list-comprehension
I want to combine my id list with my status list and I used list comprehension to do it: # id id_list = [ 1, # UAE1S 2, # UAE2S 3, # UAE3S ] # status status_list = [ 'okay', 'not okay', 'unknown', ] result = [ { 'id':id, 'status':status, } for id in id_list ...
[ "itertools.product gives the cartesian product,\nimport itertools\nid_list = [1, 2, 3]\nstatus_list = ['okay','not okay','unknown',]\n[{'id': item[0], 'status': item[1]} for item in itertools.product(id_list, status_list)]\n\n[{'status': 'okay', 'id': 1}, {'status': 'not okay', 'id': 1}, {'status': 'unknown', 'id':...
[ 0 ]
[]
[]
[ "list_comprehension", "loops", "python" ]
stackoverflow_0074542197_list_comprehension_loops_python.txt
Q: multiple csv files data to single json file I had two csv files named mortality1 and mortality2 and i want to insert these two csv files data into a single json file...when i am inserting these data, i am unable give the two files at the same time to json file.and this is my code import csv import json import pand...
multiple csv files data to single json file
I had two csv files named mortality1 and mortality2 and i want to insert these two csv files data into a single json file...when i am inserting these data, i am unable give the two files at the same time to json file.and this is my code import csv import json import pandas as pd from glob import glob csvfile1 = open('C...
[ "If both of your csv data are having similar structure, then you can append the data frames to one another, and then convert it to a JSON.\nLike\nimport csv\nimport json\nimport pandas as pd\nfrom glob import glob\ncsvfile1 = open('C:/Users/DELL/Desktop/data/mortality1.csv', 'r')\ncsvfile2 = open('C:/Users/DELL/Des...
[ 0 ]
[]
[]
[ "csv", "json", "pandas", "python" ]
stackoverflow_0074542208_csv_json_pandas_python.txt
Q: I need to subtract 1 from each digit in the list .is It any easy way? This is the list I have : list_input = [432567,876323,124356] This is the Output I need : List_output = [321456,765212,013245] like so, for index, number in enumerate(list_input): one_number = list_lnput(index) one_digi...
I need to subtract 1 from each digit in the list .is It any easy way?
This is the list I have : list_input = [432567,876323,124356] This is the Output I need : List_output = [321456,765212,013245] like so, for index, number in enumerate(list_input): one_number = list_lnput(index) one_digit_list = list(one_number[0]) and I don't have Idea after this step
[ "This can be solved in a time complexity of O(1) since you're basically asking to subtract a number of 1's from an integer i, where the number is equal to the number of digits of that integer, which can be obtained by calculating int(math.log10(i)) + 1, with which you can produce the same number of 1's with (10 ** ...
[ 1, 0, 0 ]
[]
[]
[ "list", "loops", "python", "python_3.x" ]
stackoverflow_0074542144_list_loops_python_python_3.x.txt
Q: How to fix image_url error in odoo website template I get this error raise QWebException("Error to render compiling AST", e, path, node and etree.tostring(node[0], encoding='unicode'), name) odoo.addons.base.models.qweb.QWebException: 'NoneType' object has no attribute 'image_url' Traceback (most recent call last)...
How to fix image_url error in odoo website template
I get this error raise QWebException("Error to render compiling AST", e, path, node and etree.tostring(node[0], encoding='unicode'), name) odoo.addons.base.models.qweb.QWebException: 'NoneType' object has no attribute 'image_url' Traceback (most recent call last): File "/home/akoh/isodir/odoo/odoo/addons/base/models/...
[ "My issue was in the controller file that was rendering the template. I misspelled the keyword \"website='True'\". If it is not there then add the keyword, if it is then check that you wrote it properly. Hope it helps.\n" ]
[ 0 ]
[]
[]
[ "odoo", "odoo_14", "python" ]
stackoverflow_0070158835_odoo_odoo_14_python.txt
Q: How do I set up my Django urlpatterns within my app (not project) Let's say I've got the classic "School" app within my Django project. My school/models.py contains models for both student and course. All my project files live within a directory I named config. How do I write an include statement(s) within config...
How do I set up my Django urlpatterns within my app (not project)
Let's say I've got the classic "School" app within my Django project. My school/models.py contains models for both student and course. All my project files live within a directory I named config. How do I write an include statement(s) within config/urls.py that references two separate endpoints within school/urls.py? ...
[ "I would rather create two (or more) urls.py files and then point them separately.\n# directory structure\nschool/\n├── admin.py\n├── apps.py\n├── __init__.py\n├── migrations\n│   └── __init__.py\n├── models.py\n├── tests.py\n├── urls\n│   ├── course.py\n│   ├── __init__.py\n│   └── student.py\n└── views.py\n\n\n# ...
[ 1, 1 ]
[]
[]
[ "django", "python", "url_pattern" ]
stackoverflow_0074542115_django_python_url_pattern.txt
Q: TypeError: Function() missing 1 required positional argument: 'self' there is some problem I cant execute the function in main.py from another file it give's the error self argument missing The code from here I import the car Manger class store it in a object called car and and use car.create() in the while loop M...
TypeError: Function() missing 1 required positional argument: 'self'
there is some problem I cant execute the function in main.py from another file it give's the error self argument missing The code from here I import the car Manger class store it in a object called car and and use car.create() in the while loop MAIN.PY < import time from turtle import Screen from player import Player f...
[ "Instead of car = CarManager, which assigns the class CarManager itself to be the value of car, you wanted car = CarManager(), which creates an instance of type CarManager and assigns that to car. You then don't need to call .create() since __init__() already calls it.\nConsider just putting that code in __init__, ...
[ 0 ]
[]
[]
[ "oop", "python", "turtle_graphics", "user_interface" ]
stackoverflow_0074542309_oop_python_turtle_graphics_user_interface.txt
Q: Filtering a dataframe according to datetime column of other dataframe I have two dataframes, denoted by df1 and df2. The df1 has 6 columns and df2 has 4 columns. The df1 has a column date that the smallest unit is second, but in the df2 is the hour. I am going to filter the df1 according to the df2. It means, I ne...
Filtering a dataframe according to datetime column of other dataframe
I have two dataframes, denoted by df1 and df2. The df1 has 6 columns and df2 has 4 columns. The df1 has a column date that the smallest unit is second, but in the df2 is the hour. I am going to filter the df1 according to the df2. It means, I need to extract all records in a df1 that has the same hour as the df2. Sampl...
[ "Use boolean indexing with Series.dt.hour for extract hours with Series.isin:\ndf1['Date'] = pd.to_datetime(df1['Date'])\ndf2['Date'] = pd.to_datetime(df2['Date'])\n\n\ndf = df1[df1['Date'].dt.hour.isin(df2['Date'].dt.hour)]\nprint (df)\n Date\n0 2016-03-01 01:02:03\n1 2016-04-01 01:03:04\n\nIf need...
[ 2 ]
[]
[]
[ "filtering", "pandas", "python" ]
stackoverflow_0074542358_filtering_pandas_python.txt
Q: VScode jupyer not loading ipython instance installed in a conda environment I have noticed this both on Linux and MacOS. I have a conda environment for data science stuff, which I have installed ipython, ipykernel, jupyer, and a bunch of other data science dependencies. In VSCode, when I try to select a python int...
VScode jupyer not loading ipython instance installed in a conda environment
I have noticed this both on Linux and MacOS. I have a conda environment for data science stuff, which I have installed ipython, ipykernel, jupyer, and a bunch of other data science dependencies. In VSCode, when I try to select a python interpreter, it shows just fine. I have been able to run regular python files withou...
[ "This problem occurs in python 3.11.\n\nOpen the extension store and change the jupyter extension to pre-release version.\n\n\n\nUse command python -m pip install jupyter in the terminal.\nUse shortcuts \"Ctrl+Shift+P\" and search the following option:\n\n\n" ]
[ 0 ]
[]
[]
[ "ipython", "jupyter_notebook", "python", "visual_studio_code" ]
stackoverflow_0074541174_ipython_jupyter_notebook_python_visual_studio_code.txt
Q: Azure SDK ARM Template deployment: Could not find member 'id' I'm trying to deploy a vm through the python azure sdk with an arm template. I'm using the code provided by microsoft from here: https://learn.microsoft.com/en-us/samples/azure-samples/resource-manager-python-template-deployment/resource-manager-python-...
Azure SDK ARM Template deployment: Could not find member 'id'
I'm trying to deploy a vm through the python azure sdk with an arm template. I'm using the code provided by microsoft from here: https://learn.microsoft.com/en-us/samples/azure-samples/resource-manager-python-template-deployment/resource-manager-python-template-deployment/ But I get an error when trying to use the temp...
[ "I tried in my environment and got same type of error.\nConsole:\n\nMake sure you are passing correct Arm template template.json and also check it is in correct state.\nProvide the valid id or correct the templates according to Azure-VM templates using this MS-Docs.\nAfter I validated my templates using document th...
[ 0 ]
[]
[]
[ "arm_template", "azure", "azure_sdk", "json", "python" ]
stackoverflow_0074534876_arm_template_azure_azure_sdk_json_python.txt
Q: How can i destroy the surrounding of a collision? I have a protective wall of stacked rectangles that the player is behind. If the protective wall collides with a bomb, I not only want to destroy the one rectangle but also the side and bottom neighbors. Does anyone have an idea how to get the coordinates of the ne...
How can i destroy the surrounding of a collision?
I have a protective wall of stacked rectangles that the player is behind. If the protective wall collides with a bomb, I not only want to destroy the one rectangle but also the side and bottom neighbors. Does anyone have an idea how to get the coordinates of the neighbors? i create the wall with this code: for j in ran...
[ "I suggest to inflate the rectangles of the bombs before collision detection. A larger rectangle, hits more objects. Use inflate_ip to inflate the rectangles in place and shrink (inverse inflate) the remaining bombs after collision detection. You just need to find a good size by which you want to enlarge the rectan...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074541962_pygame_python.txt
Q: Pivoting column while retaining all other columns I have many columns in a table, but only one column that needs to be pivoted with its values. It looks like this: OrderNumber Item YearMonth Total 1 1 2019_01 20 1 2 2019_01 40 1 1 2019_02 30 2 1 ...
Pivoting column while retaining all other columns
I have many columns in a table, but only one column that needs to be pivoted with its values. It looks like this: OrderNumber Item YearMonth Total 1 1 2019_01 20 1 2 2019_01 40 1 1 2019_02 30 2 1 2019_02 50 The resulting output should be: Order...
[ "IIUC, you need a pivot_table + merge:\nout = (df\n .merge(df.pivot_table(index='OrderNumber', columns='YearMonth',\n values='Total', aggfunc='sum', fill_value=0),\n on='OrderNumber')\n #.drop(columns='YearMonth') # uncomment to drop unused 'YearMonth'\n )\n\nOutput:\n OrderNumbe...
[ 3, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071582184_pandas_python.txt
Q: Slow Kalman Filter - How to speed up calculating inverse of 2x2 matrix (np.linalg.inv())? I am currently working on an image processing project and I am using a Kalman filter for the algorithm, among other things. However, the computation time of the Kalman filter is very slow compared to other software components...
Slow Kalman Filter - How to speed up calculating inverse of 2x2 matrix (np.linalg.inv())?
I am currently working on an image processing project and I am using a Kalman filter for the algorithm, among other things. However, the computation time of the Kalman filter is very slow compared to other software components, despite the use of numpy. The predict function is very fast. The update function, however, is...
[ "You might get some speedup this way:\ndef __init__(self, dt, u_x,u_y, std_acc, x_std_meas, y_std_meas):\n \n # your existing code\n\n self.I = np.eye(self.H.shape[1])\n\nAnd,\ndef update(self, z):\n # you can cut down on 1 dot product if you save P@H.T in an intermediate variable\n P_HT = np.dot(sel...
[ 0 ]
[]
[]
[ "kalman_filter", "numpy", "performance", "python" ]
stackoverflow_0074541691_kalman_filter_numpy_performance_python.txt
Q: Why does my python run in vscode terminal but not vscode code I keep getting syntax error when using print(f"Addition: {num1} + {num2} = {num1 + num2}") in my code. The code also doesn't run when I double click and select 'Run python file in terminal' but it runs when I double click and select 'Run selection/line...
Why does my python run in vscode terminal but not vscode code
I keep getting syntax error when using print(f"Addition: {num1} + {num2} = {num1 + num2}") in my code. The code also doesn't run when I double click and select 'Run python file in terminal' but it runs when I double click and select 'Run selection/line in Python terminal'. I have the latest python installed through ...
[ "Functions like f-string is introduced from Python 3.6.\nTherefore, in order to solve this problem, you need to update to Python 3.6 or higher.\n" ]
[ 0 ]
[]
[]
[ "python", "terminal", "visual_studio_code" ]
stackoverflow_0074533488_python_terminal_visual_studio_code.txt
Q: Pyvis graph wont stop moving I'm trying to make a project where I create a graph from a python project. I have this code import os import sys import re import networkx as nx from pyvis.physics import Physics from radon.visitors import ComplexityVisitor from pyvis.network import Network rootDir ="/home/ask/Git/Ze...
Pyvis graph wont stop moving
I'm trying to make a project where I create a graph from a python project. I have this code import os import sys import re import networkx as nx from pyvis.physics import Physics from radon.visitors import ComplexityVisitor from pyvis.network import Network rootDir ="/home/ask/Git/Zeeguu-API" depth = int(sys.argv[1])...
[ "In the show_buttons function add all the buttons, and after creating the pik.html file, open the html file in Google Chrome. In the buttons option\nthere will be font category, there you can disable the physics option.\nFrom then on the nodes will not move and you can distribute the nodes as you want by moving the...
[ 0 ]
[]
[]
[ "python", "pyvis" ]
stackoverflow_0067548160_python_pyvis.txt
Q: 'DataFrame' object has no attribute 'flush' I'm trying to solve Boston house price prediction problem,but it has this error AttributeError: 'DataFrame' object has no attribute 'flush' and this: ` Cell In [53], line 7, in load_data() 5 def load_data(): 6 datafile= pd.read_csv("housing.csv",sep=',') ...
'DataFrame' object has no attribute 'flush'
I'm trying to solve Boston house price prediction problem,but it has this error AttributeError: 'DataFrame' object has no attribute 'flush' and this: ` Cell In [53], line 7, in load_data() 5 def load_data(): 6 datafile= pd.read_csv("housing.csv",sep=',') ----> 7 data = np.fromfile(datafile) 8 ...
[ "You are reading the housing.csv file with pd.read_csv, which converts it to a Dataframe object. This leads to the error, because np.fromfile expects a file (str or path), not a Dataframe.\nTo get rid of the error, replace the first to statements in the load_data function with a single suitable numpy function such ...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074532226_numpy_python.txt
Q: Is there a way to assign keyboard shortcuts to specific audio outputs on macOS? As far as functionality, I'd just like to assign multiple keyboard shortcuts to individual audio outputs. For instance: cmd+F12 --> Airpods cmd+F11 --> Macbook speakers cmd+F10 --> Headphones I'm very new to this and learning so I'm ...
Is there a way to assign keyboard shortcuts to specific audio outputs on macOS?
As far as functionality, I'd just like to assign multiple keyboard shortcuts to individual audio outputs. For instance: cmd+F12 --> Airpods cmd+F11 --> Macbook speakers cmd+F10 --> Headphones I'm very new to this and learning so I'm not looking for a specific answer on how to write it - I'm more interested in the con...
[ "\nInstall switchaudio-osx e.g. with brew install switchaudio-osx\n\nUse SwitchAudioSource -a to show me exactly how all my speakers are named.\n\nCreate some 1-line AppleScripts, saving them as applications:\n\n\ndo shell script \"/usr/local/bin/SwitchAudioSource -s 'MacBook Pro Speakers'\"\n\nUse Apptivate to giv...
[ 0 ]
[]
[]
[ "macos", "operating_system", "python", "user_interface" ]
stackoverflow_0074542511_macos_operating_system_python_user_interface.txt
Q: data only alternately gets fetched properly (inconsistently fetched) from a website I'm trying to get the data from a website, and here are the codes of what I did: These are the modules import bs4 import pandas as pd import numpy as np import random import requests from lxml import etree import time from tqdm.no...
data only alternately gets fetched properly (inconsistently fetched) from a website
I'm trying to get the data from a website, and here are the codes of what I did: These are the modules import bs4 import pandas as pd import numpy as np import random import requests from lxml import etree import time from tqdm.notebook import tqdm from selenium import webdriver from selenium.webdriver.common.by impo...
[ "Page is being loaded dynamically, as you scroll it down. The following code should solve your issue:\n[..]\nwait = WebDriverWait(driver, 15)\nurl='https://shopee.ph/Makeup-Fragrances-cat.11021036?facet=100664&page=1&sortBy=pop'\ndriver.get(url)\nrows= wait.until(EC.presence_of_all_elements_located((By.XPATH, '//di...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074540393_beautifulsoup_python_selenium_web_scraping.txt
Q: Can I add a non-editable field to the class based view UpdateView in Django class EmployeeView(generic.edit.UpdateView): model = Employee fields = '__all__' template_name = 'wfp/employee.html' def get_object(self, queryset=None): return Employee.objects.get(uuid=self.kwargs.get("employee_u...
Can I add a non-editable field to the class based view UpdateView in Django
class EmployeeView(generic.edit.UpdateView): model = Employee fields = '__all__' template_name = 'wfp/employee.html' def get_object(self, queryset=None): return Employee.objects.get(uuid=self.kwargs.get("employee_uuid")) has everything I need except the UUID that is on the employee which is n...
[ "Create a EmployeeModelForm class then you can control the process with ease.\n# forms.py\n\nfrom django import forms\n\n\nclass EmployeeModelForm(forms.ModelForm):\n class Meta:\n model = Employee\n exclude = [\"your_uuid_field\"]\n\nand then use the EmployeeModelForm class in your view with the h...
[ 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0074542551_django_forms_python.txt
Q: Send JSON from curl by POST to Python FastAPI I'm running following script: from fastapi import FastAPI from fastapi import Request import os import uvicorn app = FastAPI() @app.post("/") async def root(data: Request): try: res = await data.json() except Exception as ex: res = str(ex) ...
Send JSON from curl by POST to Python FastAPI
I'm running following script: from fastapi import FastAPI from fastapi import Request import os import uvicorn app = FastAPI() @app.post("/") async def root(data: Request): try: res = await data.json() except Exception as ex: res = str(ex) return res if __name__ == "__main__": prog =...
[ "On Windows, using single quotes around data (and in general) would not work, and you would thus need to escape double quotes. For example (adjust the port number as required):\ncurl -X \"POST\" \\\n \"http://127.0.0.1:8000/\" \\\n -H \"accept: application/json\" \\\n -H \"Content-Type: application/json\" \\\n ...
[ 1 ]
[]
[]
[ "curl", "fastapi", "post", "python" ]
stackoverflow_0074537444_curl_fastapi_post_python.txt
Q: How to update django database with a list of dictionary items? I have a list of key value pairs here. stat = [{'id': 1, 'status': 'Not Fixed'}, {'id': 2, 'status': 'Not Fixed'}, {'id': 4, 'status': 'Not Fixed'}, {'id': 5, 'status': 'Not Fixed'}, {'id': 6, 'status': 'Not Fixed'}, {'id': 7, 'status': 'Not Fixed'}...
How to update django database with a list of dictionary items?
I have a list of key value pairs here. stat = [{'id': 1, 'status': 'Not Fixed'}, {'id': 2, 'status': 'Not Fixed'}, {'id': 4, 'status': 'Not Fixed'}, {'id': 5, 'status': 'Not Fixed'}, {'id': 6, 'status': 'Not Fixed'}, {'id': 7, 'status': 'Not Fixed'}] The id in this list represents the id(primary key) of my django mo...
[ "EDIT:\nAs it's selected as correct answer I want to copy Hemal's answer https://stackoverflow.com/a/74541837/2281853 to use bulk_update, it's better for DB performance as it runs 1 query only\nupdate_objects = []\nfor update_item in stat:\n update_objects.append(bug(**update_item))\n\nbug.objects.bulk_update(up...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074541772_django_django_forms_django_models_django_views_python.txt
Q: ruamel.yaml cannot handle NamedTuple So I have the following piece of code: import sys from typing import NamedTuple import ruamel.yaml as ryaml class Loc(NamedTuple): lat: float long: float data = { "APAC": { "rating": 5, "leads": ["Jane", "John"], "locs": [Loc(1.0, 1.0), Lo...
ruamel.yaml cannot handle NamedTuple
So I have the following piece of code: import sys from typing import NamedTuple import ruamel.yaml as ryaml class Loc(NamedTuple): lat: float long: float data = { "APAC": { "rating": 5, "leads": ["Jane", "John"], "locs": [Loc(1.0, 1.0), Loc(2.0, 2.0)], }, "EMEA": { ...
[ "For some reason\nyou register the Loc class, but you don't tell ruamel.yaml how to dump that class, and that information is not automatically added, and relatively new features (like NamedTuple and e.g. DataClasses( are not explicitly recognised and handled in a special way by the ruamel.yaml codebase (if they wer...
[ 1 ]
[]
[]
[ "python", "ruamel.yaml" ]
stackoverflow_0074541869_python_ruamel.yaml.txt
Q: getting the text from attribute value in html I want to get the country code of the products form this website: https://www.skincarisma.com/products/olay/fresh-effects-s-wipe-out-refreshing-make-up-removal-cloths here is the html I tried country = driver.find_element(By.XPATH,'//div[@class="card-subtitle mb-2"]//i...
getting the text from attribute value in html
I want to get the country code of the products form this website: https://www.skincarisma.com/products/olay/fresh-effects-s-wipe-out-refreshing-make-up-removal-cloths here is the html I tried country = driver.find_element(By.XPATH,'//div[@class="card-subtitle mb-2"]//img[@alt]').text and country = driver.find_element(...
[ "The text is contained in the alt attribute, therefore:\ncountry = driver.find_element(By.XPATH,'//div[@class=\"card-subtitle mb-2\"]//img').get_attribute(\"alt\")\n\n", "A more reliable way of getting that information would be:\n[...]\nwait = WebDriverWait(driver, 25)\n\nurl = 'https://www.skincarisma.com/produc...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074542630_beautifulsoup_python_selenium_web_scraping.txt
Q: Parallelize pandas apply New to pandas, I already want to parallelize a row-wise apply operation. So far I found Parallelize apply after pandas groupby However, that only seems to work for grouped data frames. My use case is different: I have a list of holidays and for my current row/date want to find the no-of-da...
Parallelize pandas apply
New to pandas, I already want to parallelize a row-wise apply operation. So far I found Parallelize apply after pandas groupby However, that only seems to work for grouped data frames. My use case is different: I have a list of holidays and for my current row/date want to find the no-of-days before and after this day t...
[ "For the parallel approach this is the answer based on Parallelize apply after pandas groupby:\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\ndef get_nearest_dateParallel(df):\n df['daysBeforeHoliday'] = df.myDates.apply(lambda x: get_nearest_date(holidays.day[holidays.day < x], x))\n df['da...
[ 6, 4, 4, 0 ]
[]
[]
[ "apply", "embarrassingly_parallel", "pandas", "parallel_processing", "python" ]
stackoverflow_0039284989_apply_embarrassingly_parallel_pandas_parallel_processing_python.txt
Q: Dataframe fill rows with values based on condition Let's say I have this dataframe: A | B | C --------- n | b | c n | b | c n | b | c s | b | c n | b | c n | b | c n | b | c e | b | c n | b | c n | b | c s | b | c n | b | c n | b | c n | b | c e | b | c I want to fill and replace the column A rows values with 'x'...
Dataframe fill rows with values based on condition
Let's say I have this dataframe: A | B | C --------- n | b | c n | b | c n | b | c s | b | c n | b | c n | b | c n | b | c e | b | c n | b | c n | b | c s | b | c n | b | c n | b | c n | b | c e | b | c I want to fill and replace the column A rows values with 'x'. The rows to fill are the ones before 's' and after 'e'...
[ "First find the rows where a value is after 'e' or 's' with:\nA = d['A'] # enables shorter reference to df['A']\nA.where(A.isin(['e', 's'])).ffill().fillna('e')\n\n['e', 'e', 'e', 's', 's', 's', 's', 'e', 'e', 'e', 's', 's', 's', 's', 'e']\n\nThen find the 'n' where is it after a 's' and replace with 'x':\ndf['new_...
[ 3, 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0068926636_pandas_python.txt
Q: Pydroid3 opencv -215 assertion failed (permission issue) I have 2 xiaomi smartphones: Xiaomi Redmi 3 (lineageOS, Android 11) and Xiaomi Mi9 lite (MIUI, Android 10). (The goal is to use Redmi 3 on my pet project). I tried to run the same piece of code on both devices, but its work only with Mi9 lite. import cv2 cam...
Pydroid3 opencv -215 assertion failed (permission issue)
I have 2 xiaomi smartphones: Xiaomi Redmi 3 (lineageOS, Android 11) and Xiaomi Mi9 lite (MIUI, Android 10). (The goal is to use Redmi 3 on my pet project). I tried to run the same piece of code on both devices, but its work only with Mi9 lite. import cv2 cam = cv2.VideoCapture(0) s, img = cam.read() cv2.imwrite('qqq.jp...
[ "Looks like pydroid can work properly only with Camera 2 API.\n\nBut redmi 3 camera has not that technology:\n\n" ]
[ 0 ]
[]
[]
[ "android", "mobile", "opencv", "pydroid", "python" ]
stackoverflow_0074542697_android_mobile_opencv_pydroid_python.txt
Q: Generate a normal distribution of dates within a range I have a date range - say between 1925-01-01 and 1992-01-01. I'd like to generate a list of x dates between that range, and have those x dates generated follow a 'normal' (bell curve - see image) distribution. There are many many answers on stackoverflow about...
Generate a normal distribution of dates within a range
I have a date range - say between 1925-01-01 and 1992-01-01. I'd like to generate a list of x dates between that range, and have those x dates generated follow a 'normal' (bell curve - see image) distribution. There are many many answers on stackoverflow about doing this with integers (using numpy, scipy, etc), but I c...
[ "As per @sascha's comment, a conversion from the dates to a time value does the job:\n#!/usr/bin/env python3\n\nimport time\nimport numpy\n\n_DATE_RANGE = ('1925-01-01', '1992-01-01')\n_DATE_FORMAT = '%Y-%m-%d'\n_EMPIRICAL_SCALE_RATIO = 0.15\n_DISTRIBUTION_SIZE = 1000\n\ndef main():\n time_range = tuple(time.mkt...
[ 5, 0 ]
[]
[]
[ "date", "gaussian", "normal_distribution", "numpy", "python" ]
stackoverflow_0039260616_date_gaussian_normal_distribution_numpy_python.txt
Q: Cannot resolve keyword 'slug' into field Im making comment and reply system in my blog using Django. Now im trying to get queryset of comments that dont have reply comments(if I dont do this, reply comments will be displayed on a page as regular comments). Here is error that i got: FieldError at /post/fourh-news C...
Cannot resolve keyword 'slug' into field
Im making comment and reply system in my blog using Django. Now im trying to get queryset of comments that dont have reply comments(if I dont do this, reply comments will be displayed on a page as regular comments). Here is error that i got: FieldError at /post/fourh-news Cannot resolve keyword 'slug' into field. Choic...
[ "You need to be a bit of change in passing URL in HTML like this...\n<form method=\"POST\" action=\"{% url 'single_news' post.slug %}\">\n {% csrf_token %}\n <input type=\"hidden\" id=\"commentID\">\n <div class=\"comment\">\n <input type=\"text\" name=\"comment_content\" placeholder=\"Comment\" cla...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074502179_django_django_forms_django_models_django_views_python.txt
Q: How to solve "error: Microsoft Visual C++ 14.0 or greater is required" when installing Python packages? I'm trying to install a package on Python, but Python is throwing an error on installing packages. I'm getting an error every time I tried to install pip install google-search-api. Here is the error how can I su...
How to solve "error: Microsoft Visual C++ 14.0 or greater is required" when installing Python packages?
I'm trying to install a package on Python, but Python is throwing an error on installing packages. I'm getting an error every time I tried to install pip install google-search-api. Here is the error how can I successfully install it? error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Bu...
[ "Go to this link and download Microsoft C++ Build Tools:\nhttps://visualstudio.microsoft.com/visual-cpp-build-tools/\n\nOpen the installer, then follow the steps.\nYou might have something like this, just download it or resume.\n\nIf updating above doesn't work then you need to configure or make some updates here. ...
[ 122, 3, 2, 0, 0, 0, 0 ]
[ "Tried Prason's approach. Also tried the fix suggested here\n\nconda install -c conda-forge implicit\npip install --upgrade gensim\n\n", "I encounered the above-mentionned problem when using virtualenv. Using conda environment instead solved the problem. Conda automatically installs vs2015_runtime which compiles ...
[ -1, -1 ]
[ "python", "python_3.x", "visual_studio" ]
stackoverflow_0064261546_python_python_3.x_visual_studio.txt
Q: How to remove root element from xml file using python i have a a number of xml files with me, whose format is: <objects> <object> <record> <invoice_source>EMAIL</invoice_source> <invoice_capture_date>2022-11-18</invoice_capture_date> <document_type>INVOICE</document_type> ...
How to remove root element from xml file using python
i have a a number of xml files with me, whose format is: <objects> <object> <record> <invoice_source>EMAIL</invoice_source> <invoice_capture_date>2022-11-18</invoice_capture_date> <document_type>INVOICE</document_type> <data_capture_provider_code>00001</data_capture_provider...
[ "The direct way is shown below. If your real files are more complicated than one-object/one-record you'll have to be more specific with examples:\nfrom xml.etree import ElementTree as et\n\nxml = '''\\\n<objects>\n <object>\n <record>\n <invoice_source>EMAIL</invoice_source>\n <invoice_captu...
[ 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0074542597_python_xml.txt
Q: Why is Pycharm not highlighting TODO's? In my settings, I have the TODO bound to highlight in yellow, yet in the actual code it does not highlight. Here is a screenshot of my settings: Editor -> TODO Does anyone know how to fix this? EDIT: I even tried re-installing Pycharm and I still have the issue. EDIT 2: In t...
Why is Pycharm not highlighting TODO's?
In my settings, I have the TODO bound to highlight in yellow, yet in the actual code it does not highlight. Here is a screenshot of my settings: Editor -> TODO Does anyone know how to fix this? EDIT: I even tried re-installing Pycharm and I still have the issue. EDIT 2: In the TODO Window, it is saying "0 TODO items fo...
[ "Go to Preferences (or Settings), Project Structure, and make sure the folder with your files is not in the \"Excluded\" tab's list.\nClick the folder you want to include and click on the \"Sources\" tab. Click Apply, then OK!\nIt should work.\n", "I recently updated PyCharm Professional and my TODOs no longer wo...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "highlight", "pycharm", "python", "todo" ]
stackoverflow_0061678338_highlight_pycharm_python_todo.txt
Q: Scrape data by sending payload with an API in python I want to fetch list of articles from gfg based on a query. We can achieve this by using search box present in this site https://www.geeksforgeeks.org/ . They are using this api to display results "https://api.geeksforgeeks.org/post/api/googlesearch/" and they ...
Scrape data by sending payload with an API in python
I want to fetch list of articles from gfg based on a query. We can achieve this by using search box present in this site https://www.geeksforgeeks.org/ . They are using this api to display results "https://api.geeksforgeeks.org/post/api/googlesearch/" and they are passing search query in payload. This is the approa...
[ "The api takes a POST request you are sending a GET request try changing to this:\nimport requests\nd = {'page':3, 'sort':'relevance', 'type':'premium', 'query':'nump'}\nr=requests.post('https://api.geeksforgeeks.org/post/api/googlesearch/', data = d).json()\nprint(r)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_requests", "web_scraping" ]
stackoverflow_0074542992_python_python_requests_web_scraping.txt
Q: Is there a Python equivalent of the C# null-coalescing operator? In C# there's a null-coalescing operator (written as ??) that allows for easy (short) null checking during assignment: string s = null; var other = s ?? "some default value"; Is there a python equivalent? I know that I can do: s = None other = s if ...
Is there a Python equivalent of the C# null-coalescing operator?
In C# there's a null-coalescing operator (written as ??) that allows for easy (short) null checking during assignment: string s = null; var other = s ?? "some default value"; Is there a python equivalent? I know that I can do: s = None other = s if s else "some default value" But is there an even shorter way (where I...
[ "other = s or \"some default value\"\n\nOk, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.\nNote that the or operator does not return only True or False. Instea...
[ 607, 120, 58, 22, 12, 6, 2, 0, 0 ]
[ "For those like me that stumbled here looking for a viable solution to this issue, when the variable might be undefined, the closest i got is:\nif 'variablename' in globals() and ((variablename or False) == True):\n print('variable exists and it\\'s true')\nelse:\n print('variable doesn\\'t exist, or it\\'s false...
[ -1, -3, -5 ]
[ "null_coalescing_operator", "python" ]
stackoverflow_0004978738_null_coalescing_operator_python.txt
Q: How should I share data between CLI commands in Python? I want to make a CLI application in Python, but I find that I can't share data between commands. The global variable can't help. As a example, I get some videos by "xxx search", and I want to press "xxx download 1" to download the frist listed videos, but the...
How should I share data between CLI commands in Python?
I want to make a CLI application in Python, but I find that I can't share data between commands. The global variable can't help. As a example, I get some videos by "xxx search", and I want to press "xxx download 1" to download the frist listed videos, but the data just miss. I have tried saving data to a file by pickle...
[ "Your solution is perfectly valid, you can even use tempfile to store the file in a clean manner.\nAnother option is to make a shell within the application, so the it won't exit after every user prompt and create an interface like somewhat like this:\n$ xxx\n\n>>> search\n###\n### Your output here\n###\n>>> downloa...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074542649_python.txt
Q: Can't find hrefs of interest with BeautifulSoup I am trying to collect a list of hrefs from the Netflix careers site: https://jobs.netflix.com/search. Each job listing on this site has an anchor and a class: <a class=css-2y5mtm essqqm81>. To be thorough here, the entire anchor is: <a class="css-2y5mtm essqqm81" ro...
Can't find hrefs of interest with BeautifulSoup
I am trying to collect a list of hrefs from the Netflix careers site: https://jobs.netflix.com/search. Each job listing on this site has an anchor and a class: <a class=css-2y5mtm essqqm81>. To be thorough here, the entire anchor is: <a class="css-2y5mtm essqqm81" role="link" href="/jobs/244837014" aria-label="Manager,...
[ "That information is being fed dynamically in page, via XHR calls. You need to scrape the API endpoint to get jobs info. The following code will give you a dataframe with all jobs currently listed by Netflix:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nfrom tqdm import tqdm ## if Jup...
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "urllib" ]
stackoverflow_0074541937_beautifulsoup_html_python_urllib.txt
Q: when i am converting list of dicts to dataframe i am getting different format of dataframe I am converting list of dictionaries to data frame to store in database but I am not getting proper format of data frame my_list=[{'A': '1111', 'B': '2222', 'C': '3333'}, {'A': '4444', 'B': '5555', 'C': '6666'}] This is the ...
when i am converting list of dicts to dataframe i am getting different format of dataframe
I am converting list of dictionaries to data frame to store in database but I am not getting proper format of data frame my_list=[{'A': '1111', 'B': '2222', 'C': '3333'}, {'A': '4444', 'B': '5555', 'C': '6666'}] This is the dataframe format i am getting This is the dataframe i want The code i am using df=pd.DataFrame(...
[ "You can try\npd.DataFrame.from_dict(my_list)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "python" ]
stackoverflow_0074542893_dataframe_dictionary_python.txt
Q: cdktf grafana alerts python sample required I am looking for "working"/"syntactically correct" (python) samples for provisioning unified alerts to grafana. A have a pure terraform config file, provided by grafana, however, the python syntax complicates it further. A: I have not the time to post my code yet, howe...
cdktf grafana alerts python sample required
I am looking for "working"/"syntactically correct" (python) samples for provisioning unified alerts to grafana. A have a pure terraform config file, provided by grafana, however, the python syntax complicates it further.
[ "I have not the time to post my code yet, however the only problem is defining the model of RuleGroupRuleData.\nYou may want to copy the model of a GUI-defined alert from here:\n/api/ruler/grafana/api/v1/rules\n\nJust copy it using a heredoc-python string:\ngrafana_RuleGroupRuleData = [RuleGroupRuleData( ...
[ 0 ]
[]
[]
[ "alerts", "grafana", "python", "terraform_cdk" ]
stackoverflow_0074520622_alerts_grafana_python_terraform_cdk.txt
Q: OSError: Could not load shared object file: llvmlite.dll (SHAP related. What could be missing?) I want to use SHAP with Anaconda. Prequisites: llvmlite is installed: pip install llvmlite Requirement already satisfied: llvmlite in c:\users...\anaconda3\lib\site-packages (0.34.0) However, I get the error message i...
OSError: Could not load shared object file: llvmlite.dll (SHAP related. What could be missing?)
I want to use SHAP with Anaconda. Prequisites: llvmlite is installed: pip install llvmlite Requirement already satisfied: llvmlite in c:\users...\anaconda3\lib\site-packages (0.34.0) However, I get the error message in the supject, that llvmlite.dll could not be loaded: from sklearn.model_selection import train_test...
[ "in my case, following actions worked:\nconda uninstall llvmlite\nand then\nconda install llvmlite\n", "I did both\nconda uninstall llvmlite\npip install llvmlite\n\nand\nconda uninstall llvmlite\nconda install llvmlite\n\nbut can't get it work.\nI got it work with\nconda install -c numba numba\nconda install -c ...
[ 1, 1, 0, 0 ]
[]
[]
[ "feature_extraction", "machine_learning", "python", "python_3.x", "shap" ]
stackoverflow_0064541502_feature_extraction_machine_learning_python_python_3.x_shap.txt
Q: How to convert datetime.datetime to array? I have an array that contains datetime.datetime objects. They are as follows: array([datetime.datetime(2011, 1, 1, 0, 3, 32, 262000), datetime.datetime(2011, 1, 1, 0, 5, 7, 290000), datetime.datetime(2011, 1, 1, 0, 6, 45, 383000), datetime.datetime(20...
How to convert datetime.datetime to array?
I have an array that contains datetime.datetime objects. They are as follows: array([datetime.datetime(2011, 1, 1, 0, 3, 32, 262000), datetime.datetime(2011, 1, 1, 0, 5, 7, 290000), datetime.datetime(2011, 1, 1, 0, 6, 45, 383000), datetime.datetime(2011, 1, 1, 0, 8, 23, 335000)], dtype=object) I a...
[ "Convert the datetime.datetime to numpy.datetime64 first, then scipy seems to know how to handle the conversion:\nimport datetime\n\nimport numpy as np\nfrom scipy.io import savemat\n\ntime_array = np.array([datetime.datetime(2011, 1, 1, 0, 3, 32, 262000),\n datetime.datetime(2011, 1, 1, 0, 5, 7, 290000),\n ...
[ 1 ]
[]
[]
[ "datetime", "mat_file", "numpy", "python", "scipy" ]
stackoverflow_0074542391_datetime_mat_file_numpy_python_scipy.txt
Q: Python selenium error: no such element: Unable to locate element; clicking a button on the screen I've been trying to figure out this error for serveral hours until now.. I tried to click the red button on the screen, but somehow I can't use the xpath method. The error message waas given right this: Message: no su...
Python selenium error: no such element: Unable to locate element; clicking a button on the screen
I've been trying to figure out this error for serveral hours until now.. I tried to click the red button on the screen, but somehow I can't use the xpath method. The error message waas given right this: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="mapContainer"]"} (Sessio...
[ "I don't think you are doing much wrong. Adding explicit waits will always improve reliability as you are less vulnerable to timing issues:\niframe = WebDriverWait(dr, 10).until(EC.presence_of_element_located((By.ID, \"DivMapOpenLayers\")))\ndriver.switch_to.frame(iframe)\nCHOICE = {'경기':2, '강원':3, '충북':4, '충남':5,...
[ 0 ]
[]
[]
[ "python", "selenium", "web_crawler", "xpath" ]
stackoverflow_0074542058_python_selenium_web_crawler_xpath.txt
Q: Receiving permission denied error with Docker, nginx, uwsgi setup. I can manually write files inside the container I'm trying to setup a flask application to run in production using docker, nginx, and uwsgi. Docker file: # syntax=docker/dockerfile:1 FROM python:3.8-slim-buster WORKDIR /flask_app RUN apt-get cle...
Receiving permission denied error with Docker, nginx, uwsgi setup. I can manually write files inside the container
I'm trying to setup a flask application to run in production using docker, nginx, and uwsgi. Docker file: # syntax=docker/dockerfile:1 FROM python:3.8-slim-buster WORKDIR /flask_app RUN apt-get clean \ && apt-get -y update RUN apt-get -y install nginx \ && apt-get -y install python3-dev \ && apt-get -y ...
[ "The issue turned out to be a permissions issue with the user www-data not having write permissions.\nI changed the owner of the workdir to www-data and that fixed the issue\nRUN chown -R www-data:www-data /flask_app\n\n" ]
[ 1 ]
[]
[]
[ "docker", "dockerfile", "flask", "nginx", "python" ]
stackoverflow_0074540333_docker_dockerfile_flask_nginx_python.txt
Q: when record created, it wont autofill record field I'm trying to make autofill record from bank.account.account to account.journal but it seems it didn't work. I wonder where is the mistake in this code class BankAccounAccount(models.Model): _name = 'bank.account.account' _description = "Bank Account Accou...
when record created, it wont autofill record field
I'm trying to make autofill record from bank.account.account to account.journal but it seems it didn't work. I wonder where is the mistake in this code class BankAccounAccount(models.Model): _name = 'bank.account.account' _description = "Bank Account Account" _rec_name = 'acc_number' acc_number = field...
[ "1- Perhaps you should try not to use for rec in self:\nvals = {'acc_number': self.acc_number, 'bank_id': self.bank_id.id, e.t.c} \nself.env['account.journal'].create(vals)\n\n2- Rename the second values. It might help\nI am not sure when you create a new record in account.journal you are covering all required fiel...
[ 0, -1 ]
[]
[]
[ "odoo", "odoo_14", "python" ]
stackoverflow_0074528459_odoo_odoo_14_python.txt
Q: GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1 I am using the OpenCV package with the face_recognition package to detect faces on my laptop webcam. Whenever I run it, the code runs fine but I run into the same GStreamer error. from imutils.video import VideoStream import face_recog...
GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1
I am using the OpenCV package with the face_recognition package to detect faces on my laptop webcam. Whenever I run it, the code runs fine but I run into the same GStreamer error. from imutils.video import VideoStream import face_recognition import pickle import argparse import time import cv2 import imutils ap = argp...
[ "This is a bug from trying to use Gstreamer with OpenCV. It is mentioned in https://github.com/opencv/opencv/issues/10324 and https://github.com/opencv/opencv/pull/14834 (fix in the second link)\nEssentially, it is a problem that arised due to the way Gstreamer reads in frames and the way OpenCV tracks video frames...
[ 1, 0 ]
[]
[]
[ "cv2", "face_recognition", "gstreamer", "opencv", "python" ]
stackoverflow_0063091548_cv2_face_recognition_gstreamer_opencv_python.txt
Q: Django: Question regarding queries over a junction table/intermediary model My question concerns the many-to-many section of the django models docs: It is mentioned there that by using an intermediary model it is possible to query on the intermediary model's attributes like so: Person.objects.filter( group__na...
Django: Question regarding queries over a junction table/intermediary model
My question concerns the many-to-many section of the django models docs: It is mentioned there that by using an intermediary model it is possible to query on the intermediary model's attributes like so: Person.objects.filter( group__name='The Beatles', membership__date_joined__gt=date(1961,1,1)) However for th...
[ "\n\"The model that defines the ManyToManyField uses the attribute name of\nthat field itself, whereas the “reverse” model uses the lowercased\nmodel name of the original model, plus '_set' (just like reverse\none-to-many relationships).\" (docs: Many-to-many relationships)\n\nSo instead of\nGroup.objects.filter(pe...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074411349_django_python.txt
Q: Cannot update sklearn on Jupyter notebook I am on a Sagemaker Jupyter notebook and I need to use version 0.22 or above to train and pickle my model. However, I cannot update the version of sklearn. Updating via pip !pip3 install sklearn --upgrade Output: WARNING: pip is being invoked by an old script wrapper. Thi...
Cannot update sklearn on Jupyter notebook
I am on a Sagemaker Jupyter notebook and I need to use version 0.22 or above to train and pickle my model. However, I cannot update the version of sklearn. Updating via pip !pip3 install sklearn --upgrade Output: WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please ...
[ "From the error message it seems the following should work:\npython3 -m pip3 install --upgrade sklearn\n\n" ]
[ 2 ]
[ "pip install sklearn --upgrade \n\nor\npip install sklearn -U\n\n" ]
[ -2 ]
[ "amazon_sagemaker", "jupyter_notebook", "python", "scikit_learn" ]
stackoverflow_0062185684_amazon_sagemaker_jupyter_notebook_python_scikit_learn.txt
Q: Problem with multiple decimal points (Python) I have having a bit of a problem: I am trying to convert these numbers: -0.2179, -8.742.754.508, 1.698.516.678, to -0.22, -8.74, 1.70, But I am really not sure how I do this, when the number of decimal points is different? I have tried .split('.') but its difficult wit...
Problem with multiple decimal points (Python)
I have having a bit of a problem: I am trying to convert these numbers: -0.2179, -8.742.754.508, 1.698.516.678, to -0.22, -8.74, 1.70, But I am really not sure how I do this, when the number of decimal points is different? I have tried .split('.') but its difficult with changing decimal points. I was wondering if you g...
[ "If I understood your problem correctly, the split function would be enough as a solution if used like this:\ndata = [\"-0.2179\", \"-8.742.754.508\", \"1.698.516.678\"]\nfund = []\nfor number in data:\n split = number.split('.')\n integer_part = split[0]\n fractional_part = ''.join([split[i] for i in rang...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074543069_python.txt
Q: What's the difference between heapq and PriorityQueue in python? In python there's a built-in heapq algorithm that gives you push, pop, nlargest, nsmallest... etc that you can apply to lists. However, there's also the queue.PriorityQueue class that seems to support more or less the same functionality. What's the d...
What's the difference between heapq and PriorityQueue in python?
In python there's a built-in heapq algorithm that gives you push, pop, nlargest, nsmallest... etc that you can apply to lists. However, there's also the queue.PriorityQueue class that seems to support more or less the same functionality. What's the difference, and when would you use one over the other?
[ "Queue.PriorityQueue is a thread-safe class, while the heapq module makes no thread-safety guarantees. From the Queue module documentation:\n\nThe Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple...
[ 110, 22, 0 ]
[]
[]
[ "data_structures", "heap", "priority_queue", "python" ]
stackoverflow_0036991716_data_structures_heap_priority_queue_python.txt
Q: Training MNIST by loading my own img (with label of answer, load img 6 tell AI is 6) I have read through the following discussion (not saying how to load pic to MNIST database) MNIST trained network tested with my own samples I also planning to train my own mnist by input img, but most of the tutorial doen't teach...
Training MNIST by loading my own img (with label of answer, load img 6 tell AI is 6)
I have read through the following discussion (not saying how to load pic to MNIST database) MNIST trained network tested with my own samples I also planning to train my own mnist by input img, but most of the tutorial doen't teach how to load our personal img (with answer, teach AI to reconize) such as load all img "5"...
[ "cridet by this site, seems this is what you what for loading your own img to train\nhttps://blog.tanka.la/2018/10/28/build-the-mnist-model-with-your-own-handwritten-digits-using-tensorflow-keras-and-python/\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom...
[ 0 ]
[]
[]
[ "deep_learning", "keras", "numpy", "python", "tensorflow" ]
stackoverflow_0074528059_deep_learning_keras_numpy_python_tensorflow.txt
Q: Java Python Integration I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is...
Java Python Integration
I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate wi...
[ "Why not use Jython? The only downside I can immediately think of is if your library uses CPython native extensions.\nEDIT: If you can use Jython now but think you may have problems with a later version of the library, I suggest you try to isolate the library from your app (e.g. some sort of adapter interface). Go ...
[ 37, 21, 21, 7, 6, 4, 3, 3, 3, 2, 0, 0 ]
[]
[]
[ "integration", "java", "python" ]
stackoverflow_0001119696_integration_java_python.txt
Q: How to remove duplicate days with multiple tickers in a single dataframe? Imagine I have a dataframe that contains minute data for different symbols: timestamp open high low close volume trade_count vwap symbol volume_10_day 0 2022-09-26 08:20:00+00:00 1.58 1.59 1.34 1.34 ...
How to remove duplicate days with multiple tickers in a single dataframe?
Imagine I have a dataframe that contains minute data for different symbols: timestamp open high low close volume trade_count vwap symbol volume_10_day 0 2022-09-26 08:20:00+00:00 1.58 1.59 1.34 1.34 972 15 1.433220 ADA 2889145.1 1 2022-09-26 08:25:00+0...
[ "You can use pd.drop_duplicates:\ndf.drop_duplicates(subset=['timestamp', 'symbol'])\n\nBy default, it will take the first appearance of the combination of the values in the timestamp and symbol columns, but you can change this behavior.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074540576_dataframe_numpy_pandas_python.txt
Q: Is there a way to prevent ray.init() from hanging when using Python on Apple silicon (the M1 Max)? So I am trying to run ray[rllib] in a Jupyter notebook (in a Miniforge virtual environment) on Apple silicon (the M1 Max). Although I can import ray normally into the notebook, the very next step (of running ray.ini...
Is there a way to prevent ray.init() from hanging when using Python on Apple silicon (the M1 Max)?
So I am trying to run ray[rllib] in a Jupyter notebook (in a Miniforge virtual environment) on Apple silicon (the M1 Max). Although I can import ray normally into the notebook, the very next step (of running ray.init()) causes the notebook to hang. No error is returned--ray.init() never completes. Is there a fix for...
[ "I have found one of possibly several answers to my question. Changing the environment.yml file (described above) slightly to import ray[rllib] rather than ray[rllib]==1.11 enabled Jupyter notebook to run ray.init() normally and execute the remainder of the code in the notebook. It appears there was a bug in ray[...
[ 0 ]
[]
[]
[ "apple_m1", "mini_forge", "python", "ray", "tensorflow" ]
stackoverflow_0074541573_apple_m1_mini_forge_python_ray_tensorflow.txt
Q: How to scrape related searches on google? I'm trying to scrape google for related searches when given a list of keywords, and then output these related searches into a csv file. My problem is getting beautiful soup to identify the related searches html tags. Here is an example html tag in the source code: <div dat...
How to scrape related searches on google?
I'm trying to scrape google for related searches when given a list of keywords, and then output these related searches into a csv file. My problem is getting beautiful soup to identify the related searches html tags. Here is an example html tag in the source code: <div data-ved="2ahUKEwitr8CPkLT3AhVRVsAKHVF-C80QmoICKAV...
[ "@jakecohensol, as you've pointed out, the selector in p = soup.find_all is wrong. The correct CSS selector: .y6Uyqe .AB4Wff.\nChrome/100.0.4896.60 User-Agent header is incorrect. Google blocks requests with such an agent string. With the full User-Agent string Google returns a proper HTML response.\nGoogle Relate...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "google_chrome", "python", "selenium", "web_scraping" ]
stackoverflow_0072028100_beautifulsoup_google_chrome_python_selenium_web_scraping.txt
Q: Creating DataFrame based on two or more non equal lists I have two lists let's say list1 = ["apple","banana"] list2 = ["M","T","W","TR","F","S"] I want to create a data frame of two columns fruit and day so that the result will look something like this fruit day apple M apple T apple W apple TR apple F app...
Creating DataFrame based on two or more non equal lists
I have two lists let's say list1 = ["apple","banana"] list2 = ["M","T","W","TR","F","S"] I want to create a data frame of two columns fruit and day so that the result will look something like this fruit day apple M apple T apple W apple TR apple F apple S banana M and so on... currently, my act...
[ "try this:\nfrom itertools import product\nimport pandas as pd\n\n\nlist1 = [\"apple\",\"banana\"]\nlist2 = [\"M\",\"T\",\"W\",\"TR\",\"F\",\"S\"]\ndf = pd.DataFrame(\n product(list1, list2),\n columns=['fruit', 'day']\n)\nprint(df)\n>>>\n fruit day\n0 apple M\n1 apple T\n2 apple W\n3 apple...
[ 1, 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074540976_pandas_python_python_3.x.txt
Q: write formula to an excel column with for loop and if statement I intent to use python to write excel formula to a particular column 'M'. But i want to skip/ignore if another column name "Status" contain the word Closed. I'm open to all other method that works. My codes: for row in range(len(df["Status"])): ...
write formula to an excel column with for loop and if statement
I intent to use python to write excel formula to a particular column 'M'. But i want to skip/ignore if another column name "Status" contain the word Closed. I'm open to all other method that works. My codes: for row in range(len(df["Status"])): for x in range(len(df["Status"])): if str(df["Status"])...
[ "I cannot verify your excel formulas, however, this is the logic that I would apply to your code.\n\nOnly write the formula to rows which contain the Pending status\nIgnore the lines when the status is Closed\n\nfor row, status in enumerate(df.Status):\n if status == \"Pending\":\n dateFmt = workbook.add_...
[ 0 ]
[]
[]
[ "excel", "excel_formula", "python" ]
stackoverflow_0074517043_excel_excel_formula_python.txt
Q: List comprehension with complex conditions in python I was looking up for ways to make my loop fast,then I found about list comprehensions. I tried it on my own, but I don't fully understand it yet. From what I learned researching about list comprehensions, the code I like to execute would be on the left side, fol...
List comprehension with complex conditions in python
I was looking up for ways to make my loop fast,then I found about list comprehensions. I tried it on my own, but I don't fully understand it yet. From what I learned researching about list comprehensions, the code I like to execute would be on the left side, followed by the conditions then the for loop. So, it would ba...
[ "There are two kinds of optimization:\n\nmicro-optimization (statement level, e.g. f-strings are faster than format function)\nmacro optimization (algorithm, used data structures, etc)\n\nOptimizing algorithms may have much higher returns than spending the same effort on micro-optimizations.\nHere is my solution to...
[ 1 ]
[]
[]
[ "list_comprehension", "performance", "python", "python_3.x" ]
stackoverflow_0074406232_list_comprehension_performance_python_python_3.x.txt
Q: Showing an error of __init__() missing 6 required positional arguments: import time delay = 1.5 class Lawyers: I set up my constructor with the following code: def __init__(self, someName, someAge, someExperience, someCity, someCollege, someTotalCase): self.name = someName self.age = ...
Showing an error of __init__() missing 6 required positional arguments:
import time delay = 1.5 class Lawyers: I set up my constructor with the following code: def __init__(self, someName, someAge, someExperience, someCity, someCollege, someTotalCase): self.name = someName self.age = someAge self.experience = someExperience self.city = someCity...
[ "You need to init the object with the variables someName, someAge, someExperience, someCity, someCollege, someTotalCase\nlike this\nlawyers5 = Lawyers(\"Mac\", 12, 1, \"Annonay\", \"Cambridge\", 82)\n\nif you want to be able to fill these informations later on you need to fill default values:\nclass Lawyers:\n \...
[ 1 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0074543457_class_function_python.txt
Q: shifting up the column basis groupby Existing Dataframe : Id event time_spent_in_sec A in 0 A step_1 2.2 A step_2 3 A done 3 B in 0 B step_1 5 B step_2 8 B step...
shifting up the column basis groupby
Existing Dataframe : Id event time_spent_in_sec A in 0 A step_1 2.2 A step_2 3 A done 3 B in 0 B step_1 5 B step_2 8 B step_3 15 B done ...
[ "You can use numpy.roll\ndf['time_spent_in_sec'] = np.roll(df['time_spent_in_sec'], -1)\n\n", "You can use .fillna() to fill it with the original first number:\ndf.time_spent_in_sec.shift(-1).fillna(df.time_spent_in_sec[0])\n\nOr:\ndf.time_spent_in_sec.shift(-1, fill_value = df.time_spent_in_sec[0])\n\n", "Othe...
[ 2, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074543383_dataframe_pandas_python.txt
Q: Finding the intersection of a plane and a line without libraries Me and my friend are trying to make a 3D renderer without external libraries. We are trying to find the plane with the direction the User looking at as a normal vector and position of the User translated in the direction of the normal vector. So the ...
Finding the intersection of a plane and a line without libraries
Me and my friend are trying to make a 3D renderer without external libraries. We are trying to find the plane with the direction the User looking at as a normal vector and position of the User translated in the direction of the normal vector. So the plane Will always be in frot of the User with some distance. We planne...
[ "It is not clear how your plane is defined.\nIf you have normal vector n and some point p in plane, you can get free coefficient of generap plane equation (d) substituting p coordinates into this:\nd = nx * px + nx * py + nz * pz\n\nNow plane equation is\nnx * x + nx * y + nz * z - d = 0\n\nDefine line using parame...
[ 0 ]
[]
[]
[ "3d", "geometry", "intersection", "plane", "python" ]
stackoverflow_0074543327_3d_geometry_intersection_plane_python.txt
Q: How to sort Pivot Table with values? I am trying to transfer Google Search Console data into a Pivot Table in Pandas and sort it. I use the searchconsole module in Python to request this data from the API. Code report = webproperty.query.range(DATA).get().to_dataframe() #Name columns report.columns=['z...
How to sort Pivot Table with values?
I am trying to transfer Google Search Console data into a Pivot Table in Pandas and sort it. I use the searchconsole module in Python to request this data from the API. Code report = webproperty.query.range(DATA).get().to_dataframe() #Name columns report.columns=['zoekwoord','pagina','klikken','vertoningen'...
[ "You can use pandas.DataFrame.sort_values.\nTry this :\n(\n df.sort_values(by=[\"Page\", \"Query\", \"Clicks\"],\n ascending=[True, False, False],\n inplace=True,\n ignore_index=True)\n)\n\ndf.loc[df[\"Page\"].duplicated(), \"Page\"]= \"\"\n\n# Output :\nprin...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074543490_pandas_python.txt
Q: How can I use .format() with list in python? import excel2img import os filelist = [ '1R 1R 1R', '24 54 994', '9d 13 885', ] file_name = "C:/Users/3315/Desktop/fdifndfd.xlsx" img_name ='C:/Users/3315/Desktop/Weekly/company/{}.png' .format(filelist[1]) excel2img.export_img(file_name, img_name, "", "'{}'!A1:HO29"...
How can I use .format() with list in python?
import excel2img import os filelist = [ '1R 1R 1R', '24 54 994', '9d 13 885', ] file_name = "C:/Users/3315/Desktop/fdifndfd.xlsx" img_name ='C:/Users/3315/Desktop/Weekly/company/{}.png' .format(filelist[1]) excel2img.export_img(file_name, img_name, "", "'{}'!A1:HO29") .format(filelist[1]) i want to use list elem...
[ "You're formatting the output of your export _img function, not the string you put into it.\nThat can't work. It's also fundamentally different than what you do in the lines above.\n" ]
[ 1 ]
[]
[]
[ "format", "formatting", "grammar", "python", "python_3.x" ]
stackoverflow_0074543594_format_formatting_grammar_python_python_3.x.txt
Q: How to get a file from an S3 bucket then send it over email using Python? I've been working on a service where I must grab a csv file from an S3 bucket, then send it all using python. I've tried various different methods such as MIMEapplication, however all have encountered problems : ( I think the biggest issue i...
How to get a file from an S3 bucket then send it over email using Python?
I've been working on a service where I must grab a csv file from an S3 bucket, then send it all using python. I've tried various different methods such as MIMEapplication, however all have encountered problems : ( I think the biggest issue is that most examples define a path to a local directory, opposed to accessing t...
[ "You would first need to download the file from the Amazon S3 bucket to the local disk.\nFor example:\nimport boto3\n\ns3 = boto3.client('s3')\ns3.download_file('my-bucket', 'object-name', '/tmp/filename')\n\nAlternatively, you might be able to use smart-open · PyPI, which gives the ability to open() a file in Amaz...
[ 2 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "mime", "python" ]
stackoverflow_0074543448_amazon_s3_amazon_web_services_boto3_mime_python.txt
Q: How to display and edit all Jupyter shortcuts in vscode (similar to typical `jupyter-notebook`)? Within Visual Studio Code, I would like to be view and customize my Jupyter-notebook shortcuts e.g. ctrl-shift-c to clear cell content, etc. similar to what is available using the typical browser-based interface. Ho...
How to display and edit all Jupyter shortcuts in vscode (similar to typical `jupyter-notebook`)?
Within Visual Studio Code, I would like to be view and customize my Jupyter-notebook shortcuts e.g. ctrl-shift-c to clear cell content, etc. similar to what is available using the typical browser-based interface. However, I did not manage to find a way to do so. https://code.visualstudio.com/docs/python/jupyter-supp...
[ "To extend on Oliver.R's answer.\nGo to the keyboard shortcuts (with Ctrl+K, Ctrl+S or Ctrl+Shift+P and search for Open Keyboard Shortcuts and then search for notebook which should list all the available bindings for Jupyter.\nAlternatively, you could search for the shortcuts themselves (using the record key featur...
[ 4, 3, 0 ]
[]
[]
[ "jupyter_notebook", "python", "visual_studio_code", "vscode_settings" ]
stackoverflow_0059743718_jupyter_notebook_python_visual_studio_code_vscode_settings.txt
Q: How to check the status of docker-compose up -d command When we run docker-compose up-d command to run dockers using docker-compose.yml file, it starts building images or pulling images from the registry. We can see each and every step of this command on the terminal. I am trying to run this command from a python ...
How to check the status of docker-compose up -d command
When we run docker-compose up-d command to run dockers using docker-compose.yml file, it starts building images or pulling images from the registry. We can see each and every step of this command on the terminal. I am trying to run this command from a python script. The command starts successfully but after the command...
[ "You can view docker compose logs with following ways\n\nUse docker compose up -d to start all services in detached mode (-d)\n(you won't see any logs in detached mode)\nUse docker compose logs -f -t to attach yourself to the logs of all\nrunning services, whereas -f means you follow the log output and the\n-t opti...
[ 6, 2, 2, 0 ]
[]
[]
[ "docker", "docker_compose", "pexpect", "python" ]
stackoverflow_0048783546_docker_docker_compose_pexpect_python.txt
Q: How can I convert list of string to pandas DataFrame in Python I have .txt file containing data like this. The first element is the column names sepparated by whitespace, and the next element is the data. ['n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]', '1 71.085 ...
How can I convert list of string to pandas DataFrame in Python
I have .txt file containing data like this. The first element is the column names sepparated by whitespace, and the next element is the data. ['n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]', '1 71.085 4.6578 22.468 1.6971 0.0292 0.0000 0.0627 0.000...
[ "Use pandas.read_csv() with the delim_whitespace option :-)\nInput file data.txt\n n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]\n 1 71.085 4.6578 22.468 1.6971 0.0292 0.0000 0.0627 0.0000 1.1019 \n 2 71.444 4.0611 ...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074541705_dataframe_pandas_python.txt
Q: Adding Foreign Key to model - Django class Plans(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) plan_type = models.CharField(max_length=255) class Order(models.Model): id = models.IntegerField(primary_key=True) selected_plan_id = models.Intege...
Adding Foreign Key to model - Django
class Plans(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) plan_type = models.CharField(max_length=255) class Order(models.Model): id = models.IntegerField(primary_key=True) selected_plan_id = models.IntegerField(primary_key=True) Order's selected...
[ "First of all there are some bad ways to pointout:\n\ntwo fields cannot be primary keys in a table\nalso django as default includes primary key id in every table, so no need to add id field.\n\nYou should be doing this way:\nclass Order(models.Model):\n selected_plan_id = models.ForeignKey(Plans, on_delete=mode...
[ 2, 1, 0 ]
[]
[]
[ "database", "django", "foreign_keys", "model", "python" ]
stackoverflow_0074542097_database_django_foreign_keys_model_python.txt
Q: How to add "orderd data" wity apply method in pandas (not use for-loop) ID A B C D Orderd No1 8 9 5 2 D:2 C:5 A:8 B:9 No2 3 1 7 9 B:1 A:3 C:7 D:9 No3 29 34 5 294 C:5 A:29 B:34 D:294 I would like to add "Orderd" column with column of A, B, C and D. If I use for loop, I can do it as like for n in range(len(df)):...
How to add "orderd data" wity apply method in pandas (not use for-loop)
ID A B C D Orderd No1 8 9 5 2 D:2 C:5 A:8 B:9 No2 3 1 7 9 B:1 A:3 C:7 D:9 No3 29 34 5 294 C:5 A:29 B:34 D:294 I would like to add "Orderd" column with column of A, B, C and D. If I use for loop, I can do it as like for n in range(len(df)): df['Orderd'][n] = df.T.sort_values(by=n,ascending=True)[n].t...
[ "you can use apply directly on your dataframe, indicating the axis = 1\nimport pandas as pd\n\ncolumns = [\"ID\",\"A\",\"B\",\"C\",\"D\"]\ndata = [[\"No1\",8,9,5,2],\n [\"No2\",3,1,7,9],\n [\"No3\",29,34,5,294]]\n\ndf = pd.DataFrame(data=data, columns=columns)\ndf = df.set_index(\"ID\") # important to...
[ 0, 0 ]
[]
[]
[ "apply", "pandas", "python" ]
stackoverflow_0074543468_apply_pandas_python.txt
Q: mysql.connector.errors.NotSupportedError: Authentication plugin 'mysql_native_password' is not supported only with pyinstaller exe I am fighting to find a solution for my problem: When I start my Python application in my IDE, the database connection is working fine. But when I build an exe with pyinstaller with th...
mysql.connector.errors.NotSupportedError: Authentication plugin 'mysql_native_password' is not supported only with pyinstaller exe
I am fighting to find a solution for my problem: When I start my Python application in my IDE, the database connection is working fine. But when I build an exe with pyinstaller with the following command python3 -m PyInstaller .\home.py and start the application and trigger the connection to the db it gives me the foll...
[ "After I could not find an answer for my problem, I just switched to Postgres and used the corresponding Python driver. Now it works!\n" ]
[ 0 ]
[]
[]
[ "authentication", "docker", "mysql_connector_python", "pyinstaller", "python" ]
stackoverflow_0074476907_authentication_docker_mysql_connector_python_pyinstaller_python.txt
Q: Delete all columns for which value repents consecutively more than 3 times I have adf that looks like this: date stock1 stock2 stock3 stock4 stock5 stock6 stock7 stock8 stock9 stock10 10/20 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.9 11/20 0.1 0.9 0.3 0.4 0.3 0.5 0.3 0.2 0.4 0.1 12/20 0.1 0.6 0.9 0.5 0.6 0.7 0.8 0...
Delete all columns for which value repents consecutively more than 3 times
I have adf that looks like this: date stock1 stock2 stock3 stock4 stock5 stock6 stock7 stock8 stock9 stock10 10/20 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.9 11/20 0.1 0.9 0.3 0.4 0.3 0.5 0.3 0.2 0.4 0.1 12/20 0.1 0.6 0.9 0.5 0.6 0.7 0.8 0.7 0.9 0.1 10/20 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.9 11/20 0.8 0...
[ "You can set \"date\" aside as index, then check if the rows are different from the next one as use it to groupby+cumcount.\nThen compute the max count per column, if greater than N-1, drop the column:\ndf2 = df.set_index('date')\nN = 3\ndf2.loc[:, df2.apply(lambda c: c.groupby(c.ne(c.shift()).cumsum()).cumcount())...
[ 3, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071206247_pandas_python.txt
Q: Type hinting for scipy sparse matrices How do you type hint scipy sparse matrices, such as CSR, CSC, LIL etc.? Below is what I have been doing, but it doesn't feel right: def foo(mat: scipy.sparse.csr.csr_matrix): # Do whatever What do we do if our function can accept multiple types of scipy sparse matrices (...
Type hinting for scipy sparse matrices
How do you type hint scipy sparse matrices, such as CSR, CSC, LIL etc.? Below is what I have been doing, but it doesn't feel right: def foo(mat: scipy.sparse.csr.csr_matrix): # Do whatever What do we do if our function can accept multiple types of scipy sparse matrices (i.e any of them)?
[ "All of csr, csc, lil are types of scipy.sparse.base.spmatrix:\nfrom scipy import sparse\nc1 = sparse.lil.lil_matrix\nc2 = sparse.csr.csr_matrix\nc3 = sparse.csc.csc_matrix\n\nprint(c1.__bases__[0])\nprint(c2.__base__.__base__.__base__)\nprint(c3.__base__.__base__.__base__)\n\nOutput:\n<class 'scipy.sparse.base.spm...
[ 4, 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0071501140_python_scipy.txt
Q: openpyxl write another new sheet when a sheet reached 1048576 rows wb = openpyxl.Workbook() ws = wb.active ws.title = 'sheet_name_1' sheet_number = 1 for row_count in range(1,5242880): if row_count > 1000000: sheet_number = sheet_number + 1 wb.create_sheet(sheet_number) # maybe add code t...
openpyxl write another new sheet when a sheet reached 1048576 rows
wb = openpyxl.Workbook() ws = wb.active ws.title = 'sheet_name_1' sheet_number = 1 for row_count in range(1,5242880): if row_count > 1000000: sheet_number = sheet_number + 1 wb.create_sheet(sheet_number) # maybe add code to switch to new sheet when row is over # 1000000 row_coun...
[ "Not tested yet but you can try this :\nexcel_limit = 1048576\n\nwith pd.ExcelWriter('Final_ExcelFile.xlsx') as wr:\n for i in range(0, df.shape[0], excel_limit):\n df.iloc[i:i+excel_limit, :].to_excel(wr, sheet_name=f'Sheet_Number_{i}', index=False)\n\n" ]
[ 0 ]
[]
[]
[ "excel", "limit", "openpyxl", "python", "xlsx" ]
stackoverflow_0074543741_excel_limit_openpyxl_python_xlsx.txt
Q: Copy keyword breaks numpy's copy/view philosophy I have noticed that none of the methods that are used to convert between types of sparse matrices are using copy kwarg, supplied in the the method. Even though, copying in most cases actually happens, the data array (where it is valid) always has a base set, which m...
Copy keyword breaks numpy's copy/view philosophy
I have noticed that none of the methods that are used to convert between types of sparse matrices are using copy kwarg, supplied in the the method. Even though, copying in most cases actually happens, the data array (where it is valid) always has a base set, which means that it shows up as a view in the code. However, ...
[ "I only have scipy v 1.7.3, so don't have access to the major rewrite of the sparse module in 1.8 (e.g. not csr_array or _data.py file).\nWhether something has a base or not is not a reliable measure of whether a copy was made. Take your first example:\nIn [74]: a = np.arange(20).reshape(4, 5)\n ...: ...: csr...
[ 0 ]
[]
[]
[ "copy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0074542785_copy_python_scipy_sparse_matrix.txt
Q: How to scroll the element until a certain word appears? I'm scraping Google Maps and I need to know how to scroll the query column until the word appears "You've reached the end of the list". I am using selenium for scraping. Code I currently use: for a in range(100): barraRolagem = wait.until(EC.presence_of_e...
How to scroll the element until a certain word appears?
I'm scraping Google Maps and I need to know how to scroll the query column until the word appears "You've reached the end of the list". I am using selenium for scraping. Code I currently use: for a in range(100): barraRolagem = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@role='main']//div[cont...
[ "You can scroll in a loop until \"You've reached the end of the list\" text is visible.\nWhen text is found visible - break the loop. Otherwise do a scroll.\nSince in case element not visible exception is thrown try-except block is needed here.\nAdditional scroll is added after the element is found visible since Se...
[ 1 ]
[]
[]
[ "python", "selenium", "try_catch", "web_scraping", "webdriverwait" ]
stackoverflow_0074541474_python_selenium_try_catch_web_scraping_webdriverwait.txt
Q: Separate text between square brackets as a separate column in python I have the following the following columns, column_1 = ["Northern Rockies, British Columbia [9A87]", "Northwest Territories [2H89]", "Canada [00052A]", "Division No. 1, Newfoundland and Labrador [52A]"] column_2 = ["aa", "bb", "cc", "dd"] column_...
Separate text between square brackets as a separate column in python
I have the following the following columns, column_1 = ["Northern Rockies, British Columbia [9A87]", "Northwest Territories [2H89]", "Canada [00052A]", "Division No. 1, Newfoundland and Labrador [52A]"] column_2 = ["aa", "bb", "cc", "dd"] column_3 = [4, 4.5, 23, 1] zipped = list(zip(column_1 , column_2, column_3)) df ...
[ "\nHello, Salahuddin!\nFrom the column_1, I assumed that square brackets or any kind of brackets come always after the text. eg. Northern Rockies, British Columbia [9A87]\ndf[['column_1','column_4']] = df['column_1'].str.extract(r'(.*)[\\[\\{\\(](.*)[\\]\\}\\)]',flags=re.IGNORECASE)\n\nThis will work for any kind o...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074543221_python_regex.txt
Q: Return one field after creation via post-request in django rest framework This is my class-based view: class PurchaseAPICreate(generics.CreateAPIView): serializer_class = PurchaseSerializer and serializer: class PurchaseSerializer(serializers.ModelSerializer): class Meta: model = Purchase ...
Return one field after creation via post-request in django rest framework
This is my class-based view: class PurchaseAPICreate(generics.CreateAPIView): serializer_class = PurchaseSerializer and serializer: class PurchaseSerializer(serializers.ModelSerializer): class Meta: model = Purchase fields = "__all__" Get-request return me all fields, but I need only id. I tri...
[ "You can set write or read only in extra_kwargs in the Meta class of a serializer.\nE.g.\nclass PurchaseSerializer(serializers.ModelSerializer):\n class Meta:\n model = Purchase\n fields = \"__all__\"\n extra_kwargs = {\n 'field_1': {'write_only': True},\n 'field...N'...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "serialization" ]
stackoverflow_0071006750_django_django_rest_framework_python_serialization.txt
Q: Pandas : How to align/center a date column & aggregate other column on either direction of the date? How to align/center date-column of a dataframe (and its assoicated rows) based on an event (another column value). Explaining with example: I have a data frame as below. What I'm trying to do is the center the date...
Pandas : How to align/center a date column & aggregate other column on either direction of the date?
How to align/center date-column of a dataframe (and its assoicated rows) based on an event (another column value). Explaining with example: I have a data frame as below. What I'm trying to do is the center the date column based on event column. In this case 3/12/12 is the center. Then I need the average of values from ...
[ "You can use:\n# convert to datetime\ns = pd.to_datetime(df['Time'])\n\n# identify the center\ncenter = s[df['event'].eq('Yes')].iloc[0]\n\n# identify if the date is before/center/after\ngroup = (np.sign(s.sub(center).dt.days.astype(int))\n .map({-1: 'pre_center', 0: 'center', 1: 'post_center'})\n ...
[ 0 ]
[]
[]
[ "pandas", "python", "time_series" ]
stackoverflow_0074543893_pandas_python_time_series.txt
Q: No module named urllib3 I wrote a script to call an API and ran it successfully last week. This week, it won't run. I get back the following error message: Traceback (most recent call last): File "user_audit.py", line 2, in <module> import requests File "c:\Python27\lib\site-packages\requests\__init__.py",...
No module named urllib3
I wrote a script to call an API and ran it successfully last week. This week, it won't run. I get back the following error message: Traceback (most recent call last): File "user_audit.py", line 2, in <module> import requests File "c:\Python27\lib\site-packages\requests\__init__.py", line 60, in <module> fro...
[ "Either urllib3 is not imported or not installed.\nTo import, use\nimport urllib3\n\nat the top of the file. To install write:\npip install urllib3\n\ninto terminal.\nIt could be that you did not activate the environment variable correctly.\nTo activate the environment variable, write\nsource env/bin/activate\n\nin...
[ 17, 5, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_2.7", "urllib3", "xml" ]
stackoverflow_0042651145_python_python_2.7_urllib3_xml.txt
Q: How to separate flask files when two files depend on each other? I'm trying to develop a database driven flask app. I have an api.py file which has the flask app, api and SQLAlchemy db objects and a users.py file which contains the routes ands code to create a database table. In the users.py file, there's a UserMa...
How to separate flask files when two files depend on each other?
I'm trying to develop a database driven flask app. I have an api.py file which has the flask app, api and SQLAlchemy db objects and a users.py file which contains the routes ands code to create a database table. In the users.py file, there's a UserManager Resource which has the routes. I have to add this resource to th...
[ "This is a well known problem in flask. The solution is to use application factories.\nCookiecutter Flask does this really well and offers a good template. It is well worth to check out their repo and try to understand what they are doing.\nAssuming you have a folder app and this folder contains a file __init__.py ...
[ 0 ]
[]
[]
[ "api", "flask", "python", "rest", "sqlalchemy" ]
stackoverflow_0074542819_api_flask_python_rest_sqlalchemy.txt
Q: Replace list comprehension with vectorized method to build new features I have this dataframe, data. data = pd.DataFrame({'group':['A', 'A', 'B', 'C', 'C', 'B'], 'value':[0.2, 0.21, 0.54, 0.02, 0.001, 0.19]}) I want to build three new features. Below is my target output. pd.DataFrame({'group':['A', '...
Replace list comprehension with vectorized method to build new features
I have this dataframe, data. data = pd.DataFrame({'group':['A', 'A', 'B', 'C', 'C', 'B'], 'value':[0.2, 0.21, 0.54, 0.02, 0.001, 0.19]}) I want to build three new features. Below is my target output. pd.DataFrame({'group':['A', 'A', 'B', 'C', 'C', 'B'], 'value':[0.2, 0.21, 0.54, 0.02, 0.001,...
[ "Use DataFrame.join with DataFrame.pivot, DataFrame.add_prefix and DataFrame.fillna:\ndf = (data.join(data.reset_index()\n .pivot('index','group','value')\n .add_prefix('group_')\n .fillna(0)))\nprint (df)\n group value group_A group_B group_C\n0 A 0.200 0.20 0.00 0.0...
[ 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074543974_numpy_pandas_python.txt
Q: How to set x and y axis columns in python subplot matplotlib def plot(self): plt.figure(figsize=(20, 5)) ax1 = plt.subplot(211) ax1.plot(self.signals['CLOSE']) ax1.set_title('Price') ax2 = plt.subplot(212, sharex=ax1) ax2.set_title('RSI') ax2.plot(self.signals[['RSI']]) ax2.axhlin...
How to set x and y axis columns in python subplot matplotlib
def plot(self): plt.figure(figsize=(20, 5)) ax1 = plt.subplot(211) ax1.plot(self.signals['CLOSE']) ax1.set_title('Price') ax2 = plt.subplot(212, sharex=ax1) ax2.set_title('RSI') ax2.plot(self.signals[['RSI']]) ax2.axhline(30, linestyle='--', alpha=0.5, color='#ff0000') ax2.axhline(...
[ "With set_xticks you set, where the positions are, for example:\nax1.set_xticks([1, 2, 3])\n\nand with set_xticklabels you can define what it says there:\nax1.set_xticklabels(['one', 'two', 'three'])\n\nsee https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html for more options.\n", "...
[ 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074538722_matplotlib_python.txt
Q: Speed up Boto3 file transfer across buckets I want to copy a sub-subfolder in an S3 bucket into a different bucket using Python (boto3). However, the process is painfully slow. If I copy the folder "by hand" straight on S3 from the browser, the process takes 72 seconds (for a folder with around 140 objects, total ...
Speed up Boto3 file transfer across buckets
I want to copy a sub-subfolder in an S3 bucket into a different bucket using Python (boto3). However, the process is painfully slow. If I copy the folder "by hand" straight on S3 from the browser, the process takes 72 seconds (for a folder with around 140 objects, total size roughly 1.0 GB). However, if I try to copy i...
[ "Thanks to @Suyog Shimpi (who pointed to a similar SO post), I was able to significantly speed up the copying process.\nHere the code slightly readapted from the other post:\nimport os\nimport boto3\nimport botocore\nimport boto3.s3.transfer as s3transfer\nimport tqdm\n\ns3 = boto3.resource('s3')\n\n# define source...
[ 3, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python" ]
stackoverflow_0069223091_amazon_s3_amazon_web_services_boto3_python.txt
Q: Use Data Subscription through python in TDengine I'm trying data subscription feature of TDengine. I tested its Python demo. from taos.tmq import TaosConsumer # Syntax: `consumer = TaosConsumer(*topics, **args)` # # Example: consumer = TaosConsumer('topic1', 'topic2', td_connect_ip = "127.0.0.1", group_id = "loca...
Use Data Subscription through python in TDengine
I'm trying data subscription feature of TDengine. I tested its Python demo. from taos.tmq import TaosConsumer # Syntax: `consumer = TaosConsumer(*topics, **args)` # # Example: consumer = TaosConsumer('topic1', 'topic2', td_connect_ip = "127.0.0.1", group_id = "local") ... When executing the script, there is an error...
[ "I think you need to update the version of taospy on your system - taospy is the TDengine connector for Python.\nTry running pip install -U taospy to update it and then do your test again.\nMake sure you're running Python 3.7 or later.\n" ]
[ 0 ]
[]
[]
[ "database", "python", "tdengine" ]
stackoverflow_0074543552_database_python_tdengine.txt
Q: How to fix this python syntax error for the code segment given below enter image description here ` # Define output GEE Asset names change_primary_asset_name = f'users/{"Annanya"}/{"vegetation-change"}/vegetation_change_primary' change_secondary_asset_name = f'users/{"Annanya"}/{"vegetation-change"}/vegetation_cha...
How to fix this python syntax error for the code segment given below
enter image description here ` # Define output GEE Asset names change_primary_asset_name = f'users/{"Annanya"}/{"vegetation-change"}/vegetation_change_primary' change_secondary_asset_name = f'users/{"Annanya"}/{"vegetation-change"}/vegetation_change_secondary' # Check if GEE Asset already exists prior to export; prima...
[ "The error does give the reason.\nif(change_primary_asset:= ee.FeatureCollection(change_primary_asset_name))\n\nIs not valid syntax. If you are checking if two variables are equal you need to use == so in your example:\nif(change_primary_asset == ee.FeatureCollection(change_primary_asset_name)):\n\nI suspect this ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074543946_python_python_3.x.txt