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: TypeError: Can't instantiate abstract class <...> with abstract methods Here is my code: from abc import ABC from abc import abstractmethod class Mamifiero(ABC): """docstring for Mamifiero""" def __init__(self): self.alimentacion = 'carnivoro' @abstractmethod def __respirar(self): ...
TypeError: Can't instantiate abstract class <...> with abstract methods
Here is my code: from abc import ABC from abc import abstractmethod class Mamifiero(ABC): """docstring for Mamifiero""" def __init__(self): self.alimentacion = 'carnivoro' @abstractmethod def __respirar(self): print('inhalar... exhalar') class Perro(Mamifiero): """docstrin...
[ "By definition (read the docs), an abstract call is a class which CANNOT be instantiated until it has any abstract methods not overridden. So as in the Object-Oriented Programming by design.\nYou have an abstract method Perro.__respirar() not overridden, as inherited from the parent class. Or, override it with a me...
[ 3, 0 ]
[]
[]
[ "abstract_class", "abstract_methods", "python", "python_2.7", "python_3.x" ]
stackoverflow_0046505037_abstract_class_abstract_methods_python_python_2.7_python_3.x.txt
Q: Creating and saving a gif in python I have this code, that makes many plots of a trajectory defined by x, y and z. How do i make a gif out of all of those plots? Right now all I've been able to achieve is saving all n plots on my hard drive and using third party software to make them into a gif. for t in range(len...
Creating and saving a gif in python
I have this code, that makes many plots of a trajectory defined by x, y and z. How do i make a gif out of all of those plots? Right now all I've been able to achieve is saving all n plots on my hard drive and using third party software to make them into a gif. for t in range(len(theta)): fig = plt.figure('Parametri...
[ "I'm not near a machine to test, but you should be able to save the matplotlib figure into an io.BytesIO, i.e. a memory buffer, rewind it and open it as a PIL Image. You can then accumulate the PIL Images in a list and pass them to the save() function of PIL to write a GIF.\nUntested, but something like:\nfrom io i...
[ 0 ]
[]
[]
[ "animation", "gif", "plot", "python" ]
stackoverflow_0074508831_animation_gif_plot_python.txt
Q: Derive an answer that takes into all probabilities from a list If the 'choice' valiance contains 'a','b','c' at the list each character link a number ('1','2','3'). For example choice = ['a','b','c'] links the numbers '1','2','3'. choice = ['a','b','c'] def select(choice): if choice == ['a']: answer = '1...
Derive an answer that takes into all probabilities from a list
If the 'choice' valiance contains 'a','b','c' at the list each character link a number ('1','2','3'). For example choice = ['a','b','c'] links the numbers '1','2','3'. choice = ['a','b','c'] def select(choice): if choice == ['a']: answer = '1' elif choice == ['b']: answer = '2' elif choice == ['c'...
[ "You can map the choices to their values with a dictionary, and then just use a list-comprehension to get the answer from the choice:\nchoice2val = {'a': '1', 'b': '2', 'c': '3'}\ndef select(choice):\n answer = [v for k, v in choice2val.items() if k in choice]\n return answer\n\nchoice = ['a', 'c'] # example...
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074511889_list_python.txt
Q: Web scraping: .find doesn't find string in line of web page I am writing my first python program and hope that you can help me with my current problem. I try to extract data from a website and I checked the source of the page where a certain string (lets say "thisstring") is part of a line. In the HTML-code the st...
Web scraping: .find doesn't find string in line of web page
I am writing my first python program and hope that you can help me with my current problem. I try to extract data from a website and I checked the source of the page where a certain string (lets say "thisstring") is part of a line. In the HTML-code the string is listed under : <script> anotherstring; thisst...
[ "Based on your comments you can use re module to extract the variable:\nimport re\n\nhtml_text = \"\"\"\\\n<html>\n<script>\n otherscript;\n</script>\n\n<script>\n anotherstring;\n thisstring = {\"data1\": 1, \"data2\": 2};\n</script>\n</html>\"\"\"\n\n# or:\n# html_text = requests.get(...).text\n\ndat...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074511849_python_web_scraping.txt
Q: Why does python return None in this instance? I have this python practice question which is to return True if a word is an isogram (word with nonrepeating characters). It is also supposed to return True if the isogram is a blank string. My answer didn't work out. from string import ascii_lowercase def is_isogram(i...
Why does python return None in this instance?
I have this python practice question which is to return True if a word is an isogram (word with nonrepeating characters). It is also supposed to return True if the isogram is a blank string. My answer didn't work out. from string import ascii_lowercase def is_isogram(iso): for x in iso: return False if (iso...
[ "I would use a set operation. Using str.count repeatedly is expensive as you need to read the whole string over and over.\nIf your string only has unique characters, then its length equals that of its set of characters.\ndef is_isogram(iso):\n return len(set(iso)) == len(iso)\n\nprint(is_isogram('abc'))\nprint(i...
[ 0 ]
[ "I think the difference is that in the other code they are looping the letters in the word and return false if a false condition is met and only if they get to the end of the letters in the word without meeting a false condition they are returning true.\nIn your code because the return statement for any condition i...
[ -1 ]
[ "count", "for_loop", "if_statement", "python", "return" ]
stackoverflow_0074511050_count_for_loop_if_statement_python_return.txt
Q: How to make the square have blue lines and be at the front of the green line? I want to make the square appear at the start of the green line and be blue. How do I do that? from turtle import * color('green') begin_fill() forward(200) end_fill() import turtle turtle.color('blue') # Creating a for loop that wil...
How to make the square have blue lines and be at the front of the green line?
I want to make the square appear at the start of the green line and be blue. How do I do that? from turtle import * color('green') begin_fill() forward(200) end_fill() import turtle turtle.color('blue') # Creating a for loop that will run four times for j in range(4): turtle.forward(20) # Moving the turtle F...
[ "Put the begin_fill/end_fill around the drawing of the square, draw the square first, then the line:\nimport turtle as t\n\nt.color('blue')\n\nt.begin_fill()\nfor _ in range(4):\n t.forward(20)\n t.left(90)\nt.end_fill()\n\nt.color('green')\nt.forward(200)\n\nt.mainloop()\n\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.9", "python_turtle", "turtle_graphics" ]
stackoverflow_0074511861_python_python_3.9_python_turtle_turtle_graphics.txt
Q: Astropy FITS Image Manipulating I have a task for a course and I am working with NASA FITS files. I have two images and their dimensions which are being used in the projection of an image needed to be reshaped. What I mean from reshaping is that Filename: jw02107-o039_t018_miri_f1130w_i2d.fits No. Name Ve...
Astropy FITS Image Manipulating
I have a task for a course and I am working with NASA FITS files. I have two images and their dimensions which are being used in the projection of an image needed to be reshaped. What I mean from reshaping is that Filename: jw02107-o039_t018_miri_f1130w_i2d.fits No. Name Ver Type Cards Dimensions ...
[ "You need to use reproject (https://reproject.readthedocs.io/en/stable/). From the frontpage example:\nfrom reproject import reproject_interp\narray, footprint = reproject_interp(hdu2, hdu1.header)\n\nso you'd do:\nfrom astropy.io import fits\nhdu1 = fits.open('JWST_File1.fits')['SCI']\nhdu2 = fits.open('JWST_File...
[ 0 ]
[]
[]
[ "astropy", "fits", "jupyter_notebook", "python", "wcs" ]
stackoverflow_0074252157_astropy_fits_jupyter_notebook_python_wcs.txt
Q: Run streamlit locally without installing How can I run streamlit file without installing it? I have tried turning it into an exe and it told me that it wasn't a recognized command. A: Hi hope you are doing fine! I am not very sure if it will work in your case, but from my point of view, the easiest solution wil...
Run streamlit locally without installing
How can I run streamlit file without installing it? I have tried turning it into an exe and it told me that it wasn't a recognized command.
[ "Hi hope you are doing fine!\nI am not very sure if it will work in your case, but from my point of view, the easiest solution will be to make a Docker image from your \"app\" and then just run it as a Docker container instead of making a binary or exe file. The main benefit is that you will be able to easily run ...
[ 1 ]
[]
[]
[ "auto_py_to_exe", "python", "streamlit" ]
stackoverflow_0074506907_auto_py_to_exe_python_streamlit.txt
Q: Redirect non authenticated user to login page (for all views) I am looking to redirect my user to login page, if they have not logged in. I initally looked at the decorator @login_required(login_url='/accounts/login/'). But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorat...
Redirect non authenticated user to login page (for all views)
I am looking to redirect my user to login page, if they have not logged in. I initally looked at the decorator @login_required(login_url='/accounts/login/'). But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth. I am ...
[ "Found an alternative solution and thought I would leave it there.\nI used a tutorial on youtube (https://www.youtube.com/watch?v=axsaC62UQOc) which, with a few changes (the video is old), works like a charm. Its about 3 videos 30 minutes very well explained.\nHere it goes:\nsettings.py\nMIDDLEWARE = [\n\n '[you...
[ 1, 0 ]
[]
[]
[ "django", "django_middleware", "django_views", "python" ]
stackoverflow_0074503923_django_django_middleware_django_views_python.txt
Q: Python - called Tcl_FindHashEntry on deleted table when Pygame window is focused after using Tkinter So I was working on a larger project and testing on a Mac when I noticed some weird behavior. I'm using Python 3.9.1 and macOS 11.0.1 – the bug doesn't occur on Windows 7, and I haven't tested other versions of mac...
Python - called Tcl_FindHashEntry on deleted table when Pygame window is focused after using Tkinter
So I was working on a larger project and testing on a Mac when I noticed some weird behavior. I'm using Python 3.9.1 and macOS 11.0.1 – the bug doesn't occur on Windows 7, and I haven't tested other versions of macOS or Windows. I'm using Tkinter for an initial setup window and then switching to Pygame, and in between,...
[ "Using _pygame and tkinter in the same application is not fully featured (see Embedding a Pygame window into a Tkinter or WxPython frame). It a bad idea to mix frameworks. The frameworks may interact poorly with each other or conflict completely. If it works on your (operating) system, that doesn't mean it will wor...
[ 0 ]
[]
[]
[ "garbage_collection", "pygame", "python", "tkinter" ]
stackoverflow_0065473778_garbage_collection_pygame_python_tkinter.txt
Q: What is the range of the angle returned by minAreaRect? Checking the documentation and the posts related to cv2.minAreaRect, I have noticed that the returned angle value should be within the range [-90, 0). When I try to run minAreaRect for the following vertices, it returns the positive value: import numpy as np ...
What is the range of the angle returned by minAreaRect?
Checking the documentation and the posts related to cv2.minAreaRect, I have noticed that the returned angle value should be within the range [-90, 0). When I try to run minAreaRect for the following vertices, it returns the positive value: import numpy as np import cv2 vertices = np.array([[ 67.264, 357.4], ...
[ "It's not formally defined. Here's what one of the OpenCV contributors has said about it:\n\nangle range is unspecified (neither before nor after). Also algorithm's implementation doesn't define even width/height relations (can be swapped with 90 degree angle adjustment). For example, if we want to force width >= h...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074508074_opencv_python.txt
Q: Can't instantiate abstract class ... with abstract methods I'm working on a kind of lib, and for a weird reason i have this error. Here is my code. Of course @abc.abstractmethod have to be uncommented Here are my tests Sorry couldn't just copy and paste it I went on the basis that the code below works. test.py: ...
Can't instantiate abstract class ... with abstract methods
I'm working on a kind of lib, and for a weird reason i have this error. Here is my code. Of course @abc.abstractmethod have to be uncommented Here are my tests Sorry couldn't just copy and paste it I went on the basis that the code below works. test.py: import abc import six @six.add_metaclass(abc.ABCMeta) class Bas...
[ "Your issue comes because you have defined the abstract methods in your base abstract class with __ (double underscore) prepended. This causes python to do name mangling at the time of definition of the classes.\nThe names of the function change from __json_builder to _Base__json_builder or __xml_builder to _Base__...
[ 72, 0, 0 ]
[]
[]
[ "abstract_class", "abstract_methods", "python", "python_2.x", "python_3.x" ]
stackoverflow_0031457855_abstract_class_abstract_methods_python_python_2.x_python_3.x.txt
Q: Performing Boolean Logic in views and template am having two set of challenges. First, I have a model with field submit as Boolean field. I use model form and render it in template. There are two options as Boolean select i.e. 'Yes' and 'No' option for user to select whether he want to save the form or not. I want...
Performing Boolean Logic in views and template
am having two set of challenges. First, I have a model with field submit as Boolean field. I use model form and render it in template. There are two options as Boolean select i.e. 'Yes' and 'No' option for user to select whether he want to save the form or not. I want if this user select 'Yes', the form should be save....
[ "First question:\nI'm assuming the field is called sumit as per your question (apologies if this is a typo :-) )\nWhere you have\n form.instance.user = request.user\n sub = form.save()\n if sub.sumit ==True:\n\n if sub:\n messages.info(request, 'You have submitted you form successfully')\n ...
[ 0 ]
[]
[]
[ "django", "django_forms", "html", "python", "templates" ]
stackoverflow_0074510480_django_django_forms_html_python_templates.txt
Q: How to create a polars data frame from a dictionary which has unequal length values? I have a dictionary as: ex_dict = {'A': ['false', 'true', 'false', 'false', 'false', 'true', 'true', 'false', 'false'], 'B': ['false', 'false', 'true', 'false', 'false', 'false'], 'C': ['false', 'tru...
How to create a polars data frame from a dictionary which has unequal length values?
I have a dictionary as: ex_dict = {'A': ['false', 'true', 'false', 'false', 'false', 'true', 'true', 'false', 'false'], 'B': ['false', 'false', 'true', 'false', 'false', 'false'], 'C': ['false', 'true', 'true', 'false', 'false', 'false', 'false', 'false', 'true']} I'm crea...
[ "You can place each Series into its own DataFrame, and use a concat with how=\"horizontal\". This will automatically extend shorter Series with null values.\npl.concat(\n items=[pl.DataFrame({_name: _values})\n for _name, _values in ex_dict.items()],\n how=\"horizontal\",\n)\n\nshape: (9, 3)\n┌────...
[ 1 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074427780_python_python_polars.txt
Q: button class creates another screen to show buttons instead of displaying on exisiting screen I have created a screen in pygame and want to display command buttons on it. for that i have written a code containing button class but it creates another screen instead of displaying the buttons on the same screen. can a...
button class creates another screen to show buttons instead of displaying on exisiting screen
I have created a screen in pygame and want to display command buttons on it. for that i have written a code containing button class but it creates another screen instead of displaying the buttons on the same screen. can anyone tell me where i have gone wrong? # import the pygame module import pygame import sys pygame.i...
[ "You have 2 application loops. Remove the 1st application loop, but draw the background image in the second application loop:\n# DELETE\n#screen.blit(imp,(0,0))\n#pygame.display.flip()\n#status=True\n#while (status):\n# for i in pygame.event.get():\n# if i.type == pygame.QUIT:\n# status=False\n...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074502674_pygame_python.txt
Q: Await only for some time in Python So waiting for server can bring pain: import asyncio #... greeting = await websocket.recv() # newer ends I want to have something like greeting = await websocket.recv() for seconds(10) So how to await only for a limited amount of time in Python? A: await expr...
Await only for some time in Python
So waiting for server can bring pain: import asyncio #... greeting = await websocket.recv() # newer ends I want to have something like greeting = await websocket.recv() for seconds(10) So how to await only for a limited amount of time in Python?
[ "await expressions don't have a timeout parameter, but the asyncio.wait_for (thanks to AChampion) function does. My guess is that this is so that the await expression, tied to coroutine definition in the language itself, does not rely on having clocks or a specific event loop. That functionality is left to the asyn...
[ 8, 0 ]
[]
[]
[ "async_await", "python", "python_3.x" ]
stackoverflow_0045229304_async_await_python_python_3.x.txt
Q: Python googleapiclient cannot get more than 10 results With this code: import json from googleapiclient.discovery import build from pprint import pprint as pp NUM_RESULTS = 11 MY_SEARCH = 'bordben' MY_API_KEY = '...' MY_CSE_ID = '...' def google_search(search_term, api_key, cse_id, **kwargs): service = build...
Python googleapiclient cannot get more than 10 results
With this code: import json from googleapiclient.discovery import build from pprint import pprint as pp NUM_RESULTS = 11 MY_SEARCH = 'bordben' MY_API_KEY = '...' MY_CSE_ID = '...' def google_search(search_term, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=api_key) res = se...
[ "Found the answer here:\nhttps://gist.github.com/adambernier/0cc96d07691a635cc464d24c63caff39\neach API call not be greater then 10 results.\n" ]
[ 0 ]
[]
[]
[ "google_api_client", "python" ]
stackoverflow_0074510694_google_api_client_python.txt
Q: arbitrary polygon with transparency in pygame I know of pygame.draw.polygon() but that can only handle colors with no alpha value. Is there an analogous function somewhere that can? I searched for a bit and did not find anything, so I tried writing my own. somehow it misses pixels occasionally (it's worth noting i...
arbitrary polygon with transparency in pygame
I know of pygame.draw.polygon() but that can only handle colors with no alpha value. Is there an analogous function somewhere that can? I searched for a bit and did not find anything, so I tried writing my own. somehow it misses pixels occasionally (it's worth noting it only needs to work for convex quadrilaterals). he...
[ "Pygame cannot draw transparent shapes or draw and blend them simultaneously. The only way is to draw single shapes on pygame.Surface with an alpha channel (pygame.SRCALPHA) and blend that surface with the target surface. Also see Draw a transparent rectangles and polygons in pygame.\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0055892066_pygame_python.txt
Q: Is there a way to simplify this function using a one-line comprehension in python? simple question, as the title implies. I was hoping to use the zip function but can't get it to work for some reason. def tuple_sum(A, B): out = [] for a,b in [x for x in zip(A,B)]: out1 = [] for a1, b1 in zip(a, b): ...
Is there a way to simplify this function using a one-line comprehension in python?
simple question, as the title implies. I was hoping to use the zip function but can't get it to work for some reason. def tuple_sum(A, B): out = [] for a,b in [x for x in zip(A,B)]: out1 = [] for a1, b1 in zip(a, b): out1.append(a1+b1) out.append(out1) return out
[ "Maybe something like this?\nA = [[1, 2], [3, 4]]\nB = [[5, 6], [7, 8]]\ns = [[a1 + b1 for a1, b1 in zip(a, b)] for a, b in zip(A, B)]\nprint(s) # [[6, 8], [10, 12]]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074512101_python.txt
Q: How to use polars to get the rolling values for two dataframes col by col? For example, I have two dataframes like: X = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)}) Y = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)}) In pandas, the rolling calculation of two DFs col by col...
How to use polars to get the rolling values for two dataframes col by col?
For example, I have two dataframes like: X = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)}) Y = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)}) In pandas, the rolling calculation of two DFs col by col (the columns with same id) can be writen easily by: # rolling corr: X.rolling(5...
[ "Let's start with setting up the dataframe:\nimport polars as pl\nimport numpy as np\nX = pl.DataFrame({f\"id{i}\": np.random.randn(200) for i in range(100)})\n\nThere is currently no built-in rolling_covarance, in contrast to for instance rolling_var\nThus we need two things:\n\nset up the rolling bit. For this we...
[ 0, 0 ]
[]
[]
[ "data_processing", "python", "python_polars" ]
stackoverflow_0074418401_data_processing_python_python_polars.txt
Q: Not getting expected data from SQL Server in Python I've been following a course, and I want to change my data source from sqlite to mssql. I've made the connection, and i'm trying to list the users in my db. But when I do I get the result show below: <Users 2> <Users 3> Instead of showing the actual user data. Iv...
Not getting expected data from SQL Server in Python
I've been following a course, and I want to change my data source from sqlite to mssql. I've made the connection, and i'm trying to list the users in my db. But when I do I get the result show below: <Users 2> <Users 3> Instead of showing the actual user data. Ive uploaded the code to git: https://github.com/Desc83/fla...
[ "It appears as if you need to specify the __str__ for the Users class.\nAlternatively, you can explicitly indicate the fields you want to display in the template.\nInstead of this:\n{% for user in users %}\n<li>{{user}}</li>\n{% endfor %}\n\nTry this:\n{% for user in users %}\n<li>{{user.Username}}</li>\n{% endfo...
[ 1 ]
[]
[]
[ "flask", "python", "sql_server", "sqlalchemy" ]
stackoverflow_0074512125_flask_python_sql_server_sqlalchemy.txt
Q: Matplotlib Rectangle.Contains(event) always returns true I want to detect the button_press and button_release events on matplotlib.patches.Rectangle areas next to my figure to enable the user to move/rescale individual y-axes when using Twinx(). However, rectangle.Contains(event) always seems to return true, no ma...
Matplotlib Rectangle.Contains(event) always returns true
I want to detect the button_press and button_release events on matplotlib.patches.Rectangle areas next to my figure to enable the user to move/rescale individual y-axes when using Twinx(). However, rectangle.Contains(event) always seems to return true, no matter where I click. E.g: when click on the red bar in the figu...
[ "The problem was probably the fact that the width of the rectangle was zero in my code (lw does not seem to contribute to the click-hitbox). Although it is not entirely clear to me why this would always result in rectangle.contains(event) to evaluate to True.\nThis ended up working (although transformations are sti...
[ 0 ]
[]
[]
[ "contains", "events", "matplotlib", "python" ]
stackoverflow_0074511115_contains_events_matplotlib_python.txt
Q: How can i make python shuffleCards program output one of each card and not random amounts Python newbie How can i make the output be 52 cards but one of each and not randomly created cards. As of now output becomes for example 2 clover, 2 clover, 5 diamonds .. etc. I know its an issue with the shuffeling i am doin...
How can i make python shuffleCards program output one of each card and not random amounts
Python newbie How can i make the output be 52 cards but one of each and not randomly created cards. As of now output becomes for example 2 clover, 2 clover, 5 diamonds .. etc. I know its an issue with the shuffeling i am doing but i am not allowed to use "random.shuffle" import math import random def main(): creat...
[ "When you do deck[i] = deck[num] you overwrite the value at index i while keeping the same value at index num. You need to swap the values with deck[i], deck[num] = deck[num], deck[i]. But there's no need to write something like this yourself. Simply use one line of code with random.shuffle from Pythons standard li...
[ 0 ]
[]
[]
[ "math", "python", "random", "shuffle" ]
stackoverflow_0074512148_math_python_random_shuffle.txt
Q: Standard deviation of binned values with `scipy.stats.binned_statistic` When I bin my data accordingly to scipy.stats.binned_statistic (see here for example), how do I get the error (that is the standard deviation) on the average binned values? For example, if I bin my data as following: windspeed = 8 * np.random....
Standard deviation of binned values with `scipy.stats.binned_statistic`
When I bin my data accordingly to scipy.stats.binned_statistic (see here for example), how do I get the error (that is the standard deviation) on the average binned values? For example, if I bin my data as following: windspeed = 8 * np.random.rand(500) boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500) bin_means...
[ "The way to go about this is to construct a probability density estimate from the histogram (this is just a question of normalizing the histogram appropriately), and then computing the standard deviation or any other statistic for the estimated density.\nThe appropriate normalization is whatever is needed to get th...
[ 0, 0, 0 ]
[]
[]
[ "binning", "python", "statistics" ]
stackoverflow_0048997277_binning_python_statistics.txt
Q: Is there a faster method for multiplying very large integers or storing them in many caches/variables instead of one to improve performance? def exponentiation(base,n): if n == 0: return 1 if n % 2 == 0: return exponentiation(base*base, n/2) else: return base * exponentiation(base ...
Is there a faster method for multiplying very large integers or storing them in many caches/variables instead of one to improve performance?
def exponentiation(base,n): if n == 0: return 1 if n % 2 == 0: return exponentiation(base*base, n/2) else: return base * exponentiation(base * base, (n-1)/2) if __name__ == '__main__': print(len(str(exponentiation(2, 66666666)))) For very large integers, the computer becomes quite...
[ "Just use the built-in ** operator for this. It works significantly faster.\nbig_number_a = 2 ** 66666666\nbig_number_b = exponentiation(2, 66666666)\nbig_number_a == big_number_b # True\n\nAlso, don't try converting such a huge number to a decimal string with str unless you really have to. That part is super slow...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074512116_python.txt
Q: First Time Importing CSV into Python I am an R user and have recently been learning how to use Python! In R, I normally import CSV files like this: > getwd() [1] "C:/Users/me/OneDrive/Documents" my_file = read.csv("my_file.csv") Now, I am trying to learn how to do this in Python. I first tried this code and got ...
First Time Importing CSV into Python
I am an R user and have recently been learning how to use Python! In R, I normally import CSV files like this: > getwd() [1] "C:/Users/me/OneDrive/Documents" my_file = read.csv("my_file.csv") Now, I am trying to learn how to do this in Python. I first tried this code and got the following error: import pandas as pd ...
[ "Regarding the second error, make sure pandas module is installed in your system. You can run this code snippet in the terminal to install the module.\npip install pandas -U\n\nIn python \\somealphabet is represented as a Unicode character. What you can do is, you can either use \\\\somealphabet or replace \\ with ...
[ 1, 0 ]
[]
[]
[ "csv", "python", "r" ]
stackoverflow_0074505645_csv_python_r.txt
Q: Jax - vmap over batch of dataclasses In JAX, I am looking to vmap a function over a fixed length list of dataclasses, for example: import jax, chex from flax import struct @struct.dataclass class EnvParams: max_steps: int = 500 random_respawn: bool = False def foo(params: EnvParams): ... param_list ...
Jax - vmap over batch of dataclasses
In JAX, I am looking to vmap a function over a fixed length list of dataclasses, for example: import jax, chex from flax import struct @struct.dataclass class EnvParams: max_steps: int = 500 random_respawn: bool = False def foo(params: EnvParams): ... param_list = jnp.Array([EnvParams(max_steps=500), Env...
[ "vmap cannot process lists of objects, only a single object containing arrays. Here is an example:\nimport typing\nimport jax\nimport jax.numpy as jnp\n\nclass EnvParams(typing.NamedTuple):\n max_steps: int = 500\n random_respawn: bool = False\n\nparam_array = EnvParams(\n max_steps=jnp.array([500, 600]),\...
[ 0 ]
[]
[]
[ "flax", "jax", "python" ]
stackoverflow_0073765064_flax_jax_python.txt
Q: how to remove multiple headers I have a spreadsheet that is in a pdf where I extract these values and transform them into .csv with textract from aws using Python. However, when I extract the values, there are several headers and I would like to keep only the first header. account ;description ;old balance ;debit ...
how to remove multiple headers
I have a spreadsheet that is in a pdf where I extract these values and transform them into .csv with textract from aws using Python. However, when I extract the values, there are several headers and I would like to keep only the first header. account ;description ;old balance ;debit ;credit ;mov. ;balance ; **# --> fir...
[ "You can use re module to remove the duplicate headers. For example:\ntext = \"\"\"\\\naccount ;description ;old balance ;debit ;credit ;mov. ;balance ;\n1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;\n1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212....
[ 3 ]
[]
[]
[ "amazon_textract", "csv", "python" ]
stackoverflow_0074511931_amazon_textract_csv_python.txt
Q: Run aws cli from EC2 python script with variables I need to run AWS CLI Polly service from AWS EC2 using python, with additional variables. The problem is with the including variable in the cmd string import subprocess row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation...
Run aws cli from EC2 python script with variables
I need to run AWS CLI Polly service from AWS EC2 using python, with additional variables. The problem is with the including variable in the cmd string import subprocess row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation for top class rooms. We did Bajo Zero based on a recom...
[ "Rather than calling the aws program from Python, you can use the boto3 library to directly call AWS. In fact, the AWS CLI is written in Python and uses this library too!\nYou can then use boto3 to call Polly.\nFor example:\nimport boto3\n\nclient = boto3.client('polly')\n\nresponse = client.synthesize_speech(\n ...
[ 1 ]
[]
[]
[ "amazon_web_services", "aws_cli", "python" ]
stackoverflow_0074507794_amazon_web_services_aws_cli_python.txt
Q: How to "spread" a numpy array (opposite of slice with step size)? Is there a way to spread the values of a numpy array? Like an opposite to slicing with a step size > 1: >>> a = np.array([[1, 0, 2], [0, 0, 0], [3, 0, 4]]) >>> a array([[1, 0, 2], [0, 0, 0], [3, 0, 4]]) >>> b = a[::2, ::2] >>> b array...
How to "spread" a numpy array (opposite of slice with step size)?
Is there a way to spread the values of a numpy array? Like an opposite to slicing with a step size > 1: >>> a = np.array([[1, 0, 2], [0, 0, 0], [3, 0, 4]]) >>> a array([[1, 0, 2], [0, 0, 0], [3, 0, 4]]) >>> b = a[::2, ::2] >>> b array([[1, 2], [3, 4]]) In this example, is there an elegant way to ...
[ "You can create a zeros array with correct shape first and then assign with step size:\nimport numpy as np\nb = np.array([[1, 2], [3, 4]])\na = np.zeros((b.shape[0] * 2 - 1, b.shape[1] * 2 - 1), dtype='int')\na[::2, ::2] = b\na\n# array([[1, 0, 2],\n# [0, 0, 0],\n# [3, 0, 4]])\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "numpy_ndarray", "numpy_slicing", "python" ]
stackoverflow_0074512250_numpy_numpy_ndarray_numpy_slicing_python.txt
Q: Depending on the content's name, converting a text file into a list of dictionaries or a list I have a question, I'm not sure where to begin. I have a text file with all the contents of recipes and other things. I wonder if there's a straightforward way to replace the text file and make it into the example of the ...
Depending on the content's name, converting a text file into a list of dictionaries or a list
I have a question, I'm not sure where to begin. I have a text file with all the contents of recipes and other things. I wonder if there's a straightforward way to replace the text file and make it into the example of the function that I've pasted at the bottom. If not, does that imply that in order to turn some texts i...
[ "To make a list of dictionaries from the text you can do (text variable contains string from your question):\nout, current = [], None\nfor line in text.splitlines():\n if line.startswith(\"name:\"):\n if current:\n out.append(current)\n current = {\"name\": line.split(\":\", maxsplit=1)[...
[ 0 ]
[]
[]
[ "python", "replace", "text" ]
stackoverflow_0074512203_python_replace_text.txt
Q: Is there a python implementation to .net automapper? Automapper is a object-object mapper where we can use to project domain model to view model in asp.net mvc. http://automapper.codeplex.com/ Is there equivalent implementation in Python for use in Django(Template)/Pylons ? Or is there necessity for this in Pytho...
Is there a python implementation to .net automapper?
Automapper is a object-object mapper where we can use to project domain model to view model in asp.net mvc. http://automapper.codeplex.com/ Is there equivalent implementation in Python for use in Django(Template)/Pylons ? Or is there necessity for this in Python world?
[ "Yes, There is.\n\nObjectMapper is a class for automatic object mapping. It helps you to create objects between project layers (data layer, service layer, view) in a simple, transparent way.\n\nhttps://pypi.python.org/pypi/object-mapper\n", "This generally isn't necessary in Python. We have some pretty complex d...
[ 14, 2, 0, 0 ]
[]
[]
[ "automapper", "django", "pylons", "python" ]
stackoverflow_0003348925_automapper_django_pylons_python.txt
Q: Drop non-unique values in a range of columns based on a condition from a different range of columns This is a small part of a df. In this case, I have 3 y-values I need to map: 0.933883, 97.658330 and 1.650013 I have this df x y1 y2 y3 y4 d1 d2 d3 d4 23 5.3 NaN Na...
Drop non-unique values in a range of columns based on a condition from a different range of columns
This is a small part of a df. In this case, I have 3 y-values I need to map: 0.933883, 97.658330 and 1.650013 I have this df x y1 y2 y3 y4 d1 d2 d3 d4 23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN 25 5.3 NaN NaN NaN 97.658330 ...
[ "You can use:\ny = df.filter(regex=r'y\\d+')\nd = df.filter(regex=r'd\\d+')\n\n# target = [0.933883, 97.658330, 1.650013]\n\n# define the target values automatically\ns = y.stack()\ntarget = set(s[s.duplicated()])\n# {1.650013, 97.65833}\n\ndrop = set()\nfor x in target:\n s = d.where(y.eq(x).to_numpy()).stack()...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074511824_dataframe_pandas_python.txt
Q: How can I centre/detect the digits for MNIST Handwritten Digit Prediction? I am producing a mobile app and in the first part of it, the user will have to take a photo of a sudoku grid and the computer will scan and read it, using my trained TensorFlow Model. I have a big issue with the TensorFlow model though, it ...
How can I centre/detect the digits for MNIST Handwritten Digit Prediction?
I am producing a mobile app and in the first part of it, the user will have to take a photo of a sudoku grid and the computer will scan and read it, using my trained TensorFlow Model. I have a big issue with the TensorFlow model though, it seems to not be very good at its job, and I think it's not the model's fault but...
[ "Thanks to NickODell's helpful comments, my solution is going to be to find the centre of mass of each image and shift the images to centre them.\nHere is the link to the python solution I'm using:\ncenter of mass of pixels in grayscale image\n" ]
[ 1 ]
[]
[]
[ "digits", "image_processing", "mnist", "python", "tensorflow" ]
stackoverflow_0074512039_digits_image_processing_mnist_python_tensorflow.txt
Q: Pyspark Improve Repetitive Function Calls When Returning Dataframes I have a multiple dataframes that I need to apply different functions to and I want to know if there is a way better way to do this in pyspark ? I am doing the following right now: df1 = function_one(df1) df2 = function_one(df2) df3 = function_one...
Pyspark Improve Repetitive Function Calls When Returning Dataframes
I have a multiple dataframes that I need to apply different functions to and I want to know if there is a way better way to do this in pyspark ? I am doing the following right now: df1 = function_one(df1) df2 = function_one(df2) df3 = function_one(df3) df1 = function_two(df1, dfx, 0) df2 = function_two(df2, dfx, 1) df3...
[ "This is just something I wrote quickly (not tested)\nJust a suggestion, not sure if it's more convenient than what you're doing already (obviously it is if you have more dfs)\ndef make_changes(df):\n df = func(df)\n df = func2(df)\n return df\n\nnew_df_list = []\ndf_list = [df1, df2, df3]\nfor dfs in df_list...
[ 0 ]
[]
[]
[ "automation", "dataframe", "loops", "pyspark", "python" ]
stackoverflow_0074512259_automation_dataframe_loops_pyspark_python.txt
Q: Redirection to previous page after login using LoginRequiredMiddleware I used to use next_param = request.POST.get('next') to redirect users to their previous page after they log in. I however, decided to go fancier with my code and now force any unauthenticated user to login by using LoginRequiredMiddleware: user...
Redirection to previous page after login using LoginRequiredMiddleware
I used to use next_param = request.POST.get('next') to redirect users to their previous page after they log in. I however, decided to go fancier with my code and now force any unauthenticated user to login by using LoginRequiredMiddleware: users are automatically redirected to login page if not authenticated. This allo...
[ "You could place it in a session variable\nIn your middleware\n request.session['next_param'] = path\n return redirect(settings.LOGIN_URL)\n\nThen in your login page\n ... \n if user is not None:\n login(request, user)\n #next_param = request.POST.get('next')\n url...
[ 1 ]
[]
[]
[ "django", "django_middleware", "django_views", "python" ]
stackoverflow_0074511980_django_django_middleware_django_views_python.txt
Q: How to make while loop a function in python? I created a While Loop that works perfectly fine on its own. However, once I try to store it as a function, it no longer works. Below is a simple example of my problem. import random money = 100 bet = 0 while bet < 10: outcome = random.randint(0,1) bet = bet + 1 ...
How to make while loop a function in python?
I created a While Loop that works perfectly fine on its own. However, once I try to store it as a function, it no longer works. Below is a simple example of my problem. import random money = 100 bet = 0 while bet < 10: outcome = random.randint(0,1) bet = bet + 1 if outcome == 1: money = money + 10 if out...
[ "You make a simple mistake with an indent - your return is in while loop, so it returns after first iteration. Move it back a bit ;)\ndef loop():\n money = 100\n bet = 0\n \n while bet < 10:\n outcome = random.randint(0,1)\n bet = bet + 1\n\n if outcome == 1:\n money = money + 10\n\n if outcome...
[ 1 ]
[]
[]
[ "probability", "python", "while_loop" ]
stackoverflow_0074512382_probability_python_while_loop.txt
Q: Switch/Change the version of Python in pyscript I am just started looking/experimenting pyscript as per the current python code which is running on Python 3.6.0. But looks like pyscript loads the python version along with Pyodide and it is retuning the latest stable version based on the Pyodide version. Problem St...
Switch/Change the version of Python in pyscript
I am just started looking/experimenting pyscript as per the current python code which is running on Python 3.6.0. But looks like pyscript loads the python version along with Pyodide and it is retuning the latest stable version based on the Pyodide version. Problem Statement : Is there any way we can change/switch the p...
[ "YOu cannot as Python is built into Pyodide. You would need to rebuild Pyodide to change the version of Python. I also do not think that Python 3.6 will work with the current version of PyScript and Pyodide. Your only practical option is to make your application work with the Pyodide version of Python.\n" ]
[ 0 ]
[]
[]
[ "pyodide", "pyscript", "python" ]
stackoverflow_0074509113_pyodide_pyscript_python.txt
Q: Displaying Outliers Using The any() function I have created a dataframe of five columns and 500 rows. The dataframe holds random integer values by executing the following Python code: RandomValues = pd.DataFrame(np.random.randint(0, 100, size=(500, 5)), columns=['Name', 'State', 'Age', 'Experienc...
Displaying Outliers Using The any() function
I have created a dataframe of five columns and 500 rows. The dataframe holds random integer values by executing the following Python code: RandomValues = pd.DataFrame(np.random.randint(0, 100, size=(500, 5)), columns=['Name', 'State', 'Age', 'Experience', 'Annual Income']) The following is the data f...
[ "When you just do a comparison like this, you're creating a boolean series, which is the same shape as your Annual Income column, but containing True/False values\nhighOutliers_locations = RandomValues['Annual Income'] > upper_limit\nlowOutliers_locations = RandomValues['Annual Income'] < lower_limit\n\nThis is a u...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074512328_dataframe_pandas_python.txt
Q: MNLogit fit and summary displays all nan I am new to ML world. Trying to do Logistic regression from Stats model. However, when I execute I get current Function Value as nan I tried checking if dataframe is finite as I saw it might be cause. But that turns out to be ok. Referred the below link, but did not work in...
MNLogit fit and summary displays all nan
I am new to ML world. Trying to do Logistic regression from Stats model. However, when I execute I get current Function Value as nan I tried checking if dataframe is finite as I saw it might be cause. But that turns out to be ok. Referred the below link, but did not work in my case. update : Still did not figure it out...
[ "After reviewing your problem and the solution identified in referred link#1. {FYI it gives the same error as shown in your screen capture.}\nIt seems like you need to identify a different solving method.\nIn your code you can try to do the following to have the same solution as link#1.\nresult=logit_model.fit(meth...
[ 0 ]
[]
[]
[ "machine_learning", "pandas", "python", "statsmodels" ]
stackoverflow_0074470088_machine_learning_pandas_python_statsmodels.txt
Q: How to "skip" a character in a string in Python? I just stated learning Python. My teacher asked me to take this string "quick brown fox, jumps over the lazy dog!", iterate all letter using i in range() function, and whenever I find a whitespace in the string I need to make the next character uppercase. So that th...
How to "skip" a character in a string in Python?
I just stated learning Python. My teacher asked me to take this string "quick brown fox, jumps over the lazy dog!", iterate all letter using i in range() function, and whenever I find a whitespace in the string I need to make the next character uppercase. So that the final output would be Quick Brown Fox, Jumps Over Th...
[ "Iterating over indices using for i in range(len(container)) is frowned upon in python. Instead use for element in container to get the elements directly. If you need the index, you can use enumerate to get the element and index.\nAs for your question: one approach would be to create a variable that remembers if yo...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074512381_python.txt
Q: Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list? I've noticed that many operations on lists that modify the list's contents will return None, rather than returning the list itself. Examples: >>> mylist = ['a', 'b', 'c'] >>> empty...
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
I've noticed that many operations on lists that modify the list's contents will return None, rather than returning the list itself. Examples: >>> mylist = ['a', 'b', 'c'] >>> empty = mylist.clear() >>> restored = mylist.extend(range(3)) >>> backwards = mylist.reverse() >>> with_four = mylist.append(4) >>> in_order = my...
[ "The general design principle in Python is for functions that mutate an object in-place to return None. I'm not sure it would have been the design choice I'd have chosen, but it's basically to emphasise that a new object is not returned.\nGuido van Rossum (our Python BDFL) states the design choice on the Python-Dev...
[ 33, 16, 5, 3, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0011205254_list_python.txt
Q: How to check if a 2D list contains a list that partly contains another list I'm trying to find out if my Tabu list (2D) contains a list that partly contains another list. Like: Tabu = [[1, 2, 3], [3, 2, 1, 0]] Test = [3, 2, 1] Test2 = [1, 3, 2] Here Tabu contains a list: [3, 2, 1, 0] that contains [3, 2, 1], so T...
How to check if a 2D list contains a list that partly contains another list
I'm trying to find out if my Tabu list (2D) contains a list that partly contains another list. Like: Tabu = [[1, 2, 3], [3, 2, 1, 0]] Test = [3, 2, 1] Test2 = [1, 3, 2] Here Tabu contains a list: [3, 2, 1, 0] that contains [3, 2, 1], so Tabu contains Test, but doesn't contain Test2 as there are no lists in Tabu that c...
[ "you need to iterate through the Tabu and check if all element of the Test list are in the sublist of Tabu\n>>> Tabu = [[1, 2, 3], [4, 5, 6, 0]]\n>>> Test = [4, 5, 6]\n>>> \n>>> result = any(all(i in sublist for i in Test) for sublist in Tabu)\n>>> result\nTrue\n>>> \n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074512493_list_python.txt
Q: Python Tornado TCPServer - TCPClient alternative to interface with other objects through Queues? I have a Tornado TCPServer which is acting as a "bridge" between two Python programs on different computers that need to exchange data (streaming & files) and commands. There is only ever one client at a time. Since th...
Python Tornado TCPServer - TCPClient alternative to interface with other objects through Queues?
I have a Tornado TCPServer which is acting as a "bridge" between two Python programs on different computers that need to exchange data (streaming & files) and commands. There is only ever one client at a time. Since the TCPServer runs using IOLoop I have it in a separate thread to avoid blocking other server actions. C...
[ "Adding a partial answer to address the potential cross-communication of requests and responses in one Queue:\nclass OnDemandQueue(Queue):\n def __init__(self, *args, **kwargs):\n super(OnDemandQueue, self).__init__(*args, **kwargs)\n # Create and share new temporary queues as-needed via a single e...
[ 0 ]
[]
[]
[ "multithreading", "python", "tornado" ]
stackoverflow_0074512019_multithreading_python_tornado.txt
Q: python enums with attributes Consider: class Item: def __init__(self, a, b): self.a = a self.b = b class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd') Is there a way to adapt the ideas for simple enums to this case? (see this question) Ideally, as in Java, I would like to cram it a...
python enums with attributes
Consider: class Item: def __init__(self, a, b): self.a = a self.b = b class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd') Is there a way to adapt the ideas for simple enums to this case? (see this question) Ideally, as in Java, I would like to cram it all into one class. Java model: enu...
[ "Python 3.4 has a new Enum data type (which has been backported as enum34 and enhanced as aenum1). Both enum34 and aenum2 easily support your use case:\n\naenum (Python 2/3)\n import aenum\n class EnumWithAttrs(aenum.AutoNumberEnum):\n _init_ = 'a b'\n GREEN = 'a', 'b'\n BLUE = 'c', 'd'\n\n\nenum3...
[ 51, 36, 35, 24, 2, 2, 2, 1, 0 ]
[]
[]
[ "enums", "python" ]
stackoverflow_0012680080_enums_python.txt
Q: Combine elements of a list of lists into a string I have to combine these 2 lists: dots = [['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '...
Combine elements of a list of lists into a string
I have to combine these 2 lists: dots = [['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'...
[ "You know how to use zip to simultaneously iterate over two lists, so do that and create a list of strings containing a dot and space for each \"row\":\nlines = [\n \"\".join(\n dot + space \n for dot, space in zip(row_dots, row_spaces)\n )\n for row_dots, row_sp...
[ 4, 1 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0074512509_list_list_comprehension_python.txt
Q: FIFO function - manual approach Python novice here. I am working on an assignment that has me a bit stumped. The goal is set up a simple FIFO system, without using any imported libraries. My attempt so far is incorrect and I am looking for some suggestions on how to fix it. Attempt: requests = [4, 32, 5, 8, 7, 4, ...
FIFO function - manual approach
Python novice here. I am working on an assignment that has me a bit stumped. The goal is set up a simple FIFO system, without using any imported libraries. My attempt so far is incorrect and I am looking for some suggestions on how to fix it. Attempt: requests = [4, 32, 5, 8, 7, 4, 8] # Will be any random integer input...
[ "Given the text in the comments at the bottom of your code, it would appear that this is closer to what is required:\ndef f(requests, cache):\n for page in requests:\n if page in cache:\n cache.remove(page)\n print(page, \"hit\")\n else:\n print(page, \"miss\")\n ...
[ 0 ]
[]
[]
[ "fifo", "list", "python" ]
stackoverflow_0074512448_fifo_list_python.txt
Q: Applying Functions in Python I am an R User that is trying to learn more about Python. I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser I was able to try an example over here: from ez_address_parser import AddressParser ap = AddressParser() re...
Applying Functions in Python
I am an R User that is trying to learn more about Python. I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser I was able to try an example over here: from ez_address_parser import AddressParser ap = AddressParser() result = ap.parse("290 Bremner Blvd,...
[ "Define a custom function that returns a Series and join the output:\ndef parse(x):\n return pd.Series({k:v for v,k in ap.parse(x)})\n\nout = df.join(df['ADDRESS'].apply(parse))\n\nprint(out)\n\n", "If you use pd.DataFrame.apply, Then you don't have to remember to change it into a series!\nBut rather can use a...
[ 4, 1 ]
[]
[]
[ "data_manipulation", "pandas", "python" ]
stackoverflow_0074512363_data_manipulation_pandas_python.txt
Q: How to calculate percentage and average of test scores in a 2D list without using libraries like pandas or numpy I have a csv data of a test scores. The current program is able to read this data into a 2D list with the test out of marks. I later created a function to remove test out of row so only the student's ma...
How to calculate percentage and average of test scores in a 2D list without using libraries like pandas or numpy
I have a csv data of a test scores. The current program is able to read this data into a 2D list with the test out of marks. I later created a function to remove test out of row so only the student's marks can be displayed. I'm now struggling to write a function which can print the scores so that each student's percent...
[ "Of course, there are many ways to do this, but here is one possible solution. I used only Lists and Tuple. Using dictionaries you would have a more elegant way accessing data.\nstudents = []\nreference_scores = []\n\ndef get_data():\n with open(\"./data/testscores.csv\", \"r\") as file:\n lineArray = fil...
[ 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074511906_csv_python.txt
Q: How to make recursive function hold it's original parameter value? I'm trying to write a function that calculates the determinant of a square matrix using recursion. The parameter of the oldest function - the first one called - changes to the matrix returned by scale_down() and I don't know why. def la_place(matri...
How to make recursive function hold it's original parameter value?
I'm trying to write a function that calculates the determinant of a square matrix using recursion. The parameter of the oldest function - the first one called - changes to the matrix returned by scale_down() and I don't know why. def la_place(matrix): if len(matrix) == 2: return matrix[0][0] * matrix[1][1] ...
[ "I figured it out. It turns out that var = matrix does not make var independent of matrix. I imported the \"copy\" library and used var = copy.deepcopy(matrix) to make var independent of matrix. Here is the solution:\nimport copy\n\n\ndef la_place(matrix):\n var = copy.deepcopy(matrix)\n if len(var) == 2:\n ...
[ 0 ]
[]
[]
[ "matrix", "python", "recursion" ]
stackoverflow_0074512365_matrix_python_recursion.txt
Q: How do I fetch the KML's style information using fastkml? I am parsing a KML and need to split features depending on the style given to each feature. I've managed to parse the features and grab the styleUrl of each feature. Here is roughly how I grab the styleUrls as well as the attributes from the features : from...
How do I fetch the KML's style information using fastkml?
I am parsing a KML and need to split features depending on the style given to each feature. I've managed to parse the features and grab the styleUrl of each feature. Here is roughly how I grab the styleUrls as well as the attributes from the features : from fastkml import kml with open( os.path.join(tmp_root,'doc.kml')...
[ "I believe you can say list(style.styles())[0].color in order to get what you want.\n" ]
[ 0 ]
[]
[]
[ "kml", "performance", "python", "xml_parsing" ]
stackoverflow_0073463672_kml_performance_python_xml_parsing.txt
Q: How do i sort my list of tuples in ascending order e.g. my_list = [(6,4), (3,4)] to produce (3,4) (4,6) How can i sort the below list of tuples to produce tuples of (3,4) (4,6) my_list = [(6,4), (3,4)] I have tried the following items= [(3,4),(6,4)] sorted_items= sorted(items) print(sorted_items) and my_list = [...
How do i sort my list of tuples in ascending order e.g. my_list = [(6,4), (3,4)] to produce (3,4) (4,6)
How can i sort the below list of tuples to produce tuples of (3,4) (4,6) my_list = [(6,4), (3,4)] I have tried the following items= [(3,4),(6,4)] sorted_items= sorted(items) print(sorted_items) and my_list = [(6,4), (3,4)] my_list.sort(key=lambda tup: (tup[0], tup[1]), reverse=False) print(my_list) Thanks
[ "You can use two calls to sorted() to generate the desired output:\nsorted(tuple(sorted(tup)) for tup in my_list)\n\nThis outputs:\n[(3, 4), (4, 6)]\n\n" ]
[ 0 ]
[]
[]
[ "function", "python", "sorting", "tuples" ]
stackoverflow_0074512668_function_python_sorting_tuples.txt
Q: Getting a bug when trying to add two lists in Python I've been trying to debug this simple code for 20 minutes and it's driving me crazy, I'm starting to think there's a bug in Python. What I want to do is add two lists, element by element (there probably is some more efficient way to do this or even an in-build f...
Getting a bug when trying to add two lists in Python
I've been trying to debug this simple code for 20 minutes and it's driving me crazy, I'm starting to think there's a bug in Python. What I want to do is add two lists, element by element (there probably is some more efficient way to do this or even an in-build function, I'm just doing it as an exercise): def add(l1,l2)...
[ "When you use comparison operators on lists you do not compare the length of them but the content, look:\nl1 = [1, 2]\nl2 = [2, 1]\nassert l1 < l2 (because l1[0] < l2[0])\n\nWhat you want to use is len builtin:\nif len(l1) >= len(l2):\n ...\n\n", "You did an elementwise compare when really you wanted to know w...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074512645_list_python.txt
Q: Flask Rest API View Returning Invalid Response I am trying to test an endpoint in postman for a flask API, and I am having this error below TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers). The function is g...
Flask Rest API View Returning Invalid Response
I am trying to test an endpoint in postman for a flask API, and I am having this error below TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers). The function is given below auth = Blueprint("auth", __name__, url_pr...
[ "well you forgot to add a , in the below code\n if not validators.email(email):\n return jsonify({'error': \"Email is not valid\"})\n HTTP_400_BAD_REQUEST\n\nthis is causing this Typeerror\njust change this to\nreturn jsonify({'error': \"Email is not valid\"}),\n HTTP_400_BAD_REQUEST\n\n" ...
[ 2 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074512567_flask_python.txt
Q: Merging pandas dataframes on potentially different join keys I have a dataframe A with columns like so: ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME Acme Inc Acme, Inc. Acme Donut Heaven None Doughnut Heaven Super Foods Sooper Foods None I want to merge on additional columns but I am not sure if this additiona...
Merging pandas dataframes on potentially different join keys
I have a dataframe A with columns like so: ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME Acme Inc Acme, Inc. Acme Donut Heaven None Doughnut Heaven Super Foods Sooper Foods None I want to merge on additional columns but I am not sure if this additional data was captured using ACCOUNT_NAME, SFDC_ACCOUNT_NA...
[ "Given:\n# df\n\n ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME\n0 Acme Inc Acme, Inc. Acme\n1 Donut Heaven NaN Doughnut Heaven\n2 Super Foods Sooper Foods NaN\n\n# df1\n\n CAPTURED_COMPANY_NAME value1 value2\n0 Acme Inc 2 3...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074512686_pandas_python.txt
Q: python subprocess.call() doesn't work with multiline shell commands I would like to run this multiline shell commands: echo 'a=?' read a echo "a=$a" from a python script, using the subprocess.call() method. I wrote this, in test.py file: import shlex, subprocess args = ["echo", 'a=?',"read", "a", "echo", "a=$a"]...
python subprocess.call() doesn't work with multiline shell commands
I would like to run this multiline shell commands: echo 'a=?' read a echo "a=$a" from a python script, using the subprocess.call() method. I wrote this, in test.py file: import shlex, subprocess args = ["echo", 'a=?',"read", "a", "echo", "a=$a"] subprocess.call(args) and when I execute it, I have in terminal this re...
[ "There are a couple of issues with your approach here.\nFirst, if what you're trying to do is prompt the user for input from the command line, then you can use Python builtins instead of a subprocess:\na = input('a=?')\nprint(a)\n\nIf you do want to call a subprocess with multiple commands, you need to either make ...
[ 0 ]
[]
[]
[ "multiline", "python", "shell", "subprocess" ]
stackoverflow_0074512575_multiline_python_shell_subprocess.txt
Q: Defining a function that only accepts an integer as an input My approach with this function is that it only accepts an integer as an input, otherwise if the person enters a letter or something else it goes back to the while loop and continues asking for the input until it receives the correct input which in this c...
Defining a function that only accepts an integer as an input
My approach with this function is that it only accepts an integer as an input, otherwise if the person enters a letter or something else it goes back to the while loop and continues asking for the input until it receives the correct input which in this case it can only be 1-9. import string string.ascii_letters def pla...
[ "First solution using simple checkings\ndef player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if position.isdecimal() and len(position) == 1 and position != '0':\n position = int(position)\n break\n return position\n\nSecond soluti...
[ 1 ]
[ "Use typing.\ndef whatever(param: int):\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0074512558_python.txt
Q: mqtt paho library running test with docker i've been trying to make this example running for many hours. I was building an example so my friend can learn some python but i've end up frustrated on my own. My python knowledge is quite limited. Something is causing the program thread to finish no matter how much I tr...
mqtt paho library running test with docker
i've been trying to make this example running for many hours. I was building an example so my friend can learn some python but i've end up frustrated on my own. My python knowledge is quite limited. Something is causing the program thread to finish no matter how much I try delaying the execution with time.sleep (i've r...
[ "I was using loop_forever without too much success bcoz print() calls were not logging anything since the main thread was blocked so I couldn't see if my code was working.\nEDIT: previous paragraph is just not correct. loop_forever will work taking this into account: Python app does not print anything when running ...
[ 0 ]
[]
[]
[ "docker", "mosquitto", "mqtt", "paho", "python" ]
stackoverflow_0074510148_docker_mosquitto_mqtt_paho_python.txt
Q: How to detect in Tkinter that whole window is moved (esspecially to the other screen)? I want to change scaling depend on screen. I know how to scale but I do not know how to detect that windows is move from screen 1 to screen 2. What event and bind is need for it? A: Basically I have to disappointing you, there...
How to detect in Tkinter that whole window is moved (esspecially to the other screen)?
I want to change scaling depend on screen. I know how to scale but I do not know how to detect that windows is move from screen 1 to screen 2. What event and bind is need for it?
[ "Basically I have to disappointing you, there is no such binding to detect that. There is however a long history of trying to get a cross platform specific solution working, without fully success. You can read something about it in the tcler's-wiki where I have the basic idea from.\nThe only way to track your windo...
[ 1 ]
[]
[]
[ "dpi", "python", "python_3.x", "tk_toolkit", "tkinter" ]
stackoverflow_0074512770_dpi_python_python_3.x_tk_toolkit_tkinter.txt
Q: Behaviour of set-intersection of objects I stumbled upon this uncertainty in one of my programs: Suppose we have a Class deriving from int with a custom attribute. class A(int): def __new__(cls, value, *args, **kwargs): return super(cls, cls).__new__(cls, value) def __init__(self, _, a): s...
Behaviour of set-intersection of objects
I stumbled upon this uncertainty in one of my programs: Suppose we have a Class deriving from int with a custom attribute. class A(int): def __new__(cls, value, *args, **kwargs): return super(cls, cls).__new__(cls, value) def __init__(self, _, a): self.a = a Objects of this class are now used ...
[ "You intrigued me so much that I looked into source code and it became quite logical. We looped over smaller set and search every element in bigger one. When both sets has equal size, the order matters (that's why you get different results in your case), otherwise the elements taken will always belong to smaller se...
[ 1 ]
[]
[]
[ "class", "python", "set" ]
stackoverflow_0074512734_class_python_set.txt
Q: Python - trouble pivoting, grouping, and summing dataframe columns I have this code. I need to group by CustomerName and then sum the filegroups. def consolidated_df(): df = breakdown_df() df.pivot_table(index='CustomerName', columns='FileGroup', aggfunc="sum") return df breakdown_df() looks like ID ...
Python - trouble pivoting, grouping, and summing dataframe columns
I have this code. I need to group by CustomerName and then sum the filegroups. def consolidated_df(): df = breakdown_df() df.pivot_table(index='CustomerName', columns='FileGroup', aggfunc="sum") return df breakdown_df() looks like ID CustomerName FileGroup Size Size(Bytes) 1 CustomerA ...
[ "If you don't explicitly set values, it'll try to use all remaining columns...\nout = df.pivot_table(index='CustomerName', columns='FileGroup', values='Size(Bytes)', aggfunc='sum')\nprint(out)\n\nOutput:\nFileGroup Backup Database Site\nCustomerName \nCustomerA 209...
[ 1, 1 ]
[]
[]
[ "pandas", "pivot", "python" ]
stackoverflow_0074512819_pandas_pivot_python.txt
Q: How to get raw value of the QuerySet I'm trying to return the raw value "Alberto Santos", but in my HTML, the function returns a array. <QuerySet [<Funcionarios: Alberto Santos>]> My function "funcionarios_nome" class ListaFuncionariosView(ListView): model = Funcionarios template_name = '../templates/funci...
How to get raw value of the QuerySet
I'm trying to return the raw value "Alberto Santos", but in my HTML, the function returns a array. <QuerySet [<Funcionarios: Alberto Santos>]> My function "funcionarios_nome" class ListaFuncionariosView(ListView): model = Funcionarios template_name = '../templates/funcionarios/lista_funcionarios.html' pagin...
[ "if you are passing data from views to template , it's recommend to use a context\nuseful links :\nWhat is a context in Django?\nIf you expect a queryset to already return one row, you can use get() without any arguments to return the object for that row:\nex:\n Funcionarios.objects.filter(EmpresaCodigo=1).get()\...
[ 2 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074512834_django_django_views_python.txt
Q: Returning a subset of list and dictionaries, from a list of dictionaries Im trying to return a subset of list of dictionaries, derived from a list of dictionaries. Input: dicts = [ {'name': 'Sam', 'age': 12}, {'name': 'Pete', 'age': 14}, {'name': 'Sarah', 'age': 16} ] Im trying to get this output: re...
Returning a subset of list and dictionaries, from a list of dictionaries
Im trying to return a subset of list of dictionaries, derived from a list of dictionaries. Input: dicts = [ {'name': 'Sam', 'age': 12}, {'name': 'Pete', 'age': 14}, {'name': 'Sarah', 'age': 16} ] Im trying to get this output: res = [ {'name': 'Sam'}, {'name': 'Pete'}, {'name': 'Sarah'} ] So ...
[ "With list comprehension you can do:\n[{'name': x['name']} for x in dicts]\n\n", "The safer method (That won't fail if one of your dicts doesn't have a name value):\n[{'name': x['name']} for x in dicts if 'name' in x]\n\n" ]
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074510706_pandas_python.txt
Q: What is the use of python-dotenv? Need an example and please explain me the purpose of python-dotenv. I am kind of confused with the documentation. A: From the Github page: Reads the key,value pair from .env and adds them to environment variable. It is great of managing app settings during development and in pr...
What is the use of python-dotenv?
Need an example and please explain me the purpose of python-dotenv. I am kind of confused with the documentation.
[ "From the Github page:\n\nReads the key,value pair from .env and adds them to environment variable. It is great of managing app settings during development and in production using 12-factor principles.\n\nAssuming you have created the .env file along-side your settings module.\n.\n├── .env\n└── settings.py\n\nAdd t...
[ 211, 68, 9, 0, 0 ]
[]
[]
[ "environment_variables", "python" ]
stackoverflow_0041546883_environment_variables_python.txt
Q: Dropping rows based on a string in a table Code to drop rows based on a partial string is not working. Very simple code, and it runs fine but doesn't drop the rows I want. The original table in the pdf looks like this: Chemical Value Unit Type Fluoride 0.23 ug/L Lab Mercury 0.15 ug/L Lab Sum of Long Chained Po...
Dropping rows based on a string in a table
Code to drop rows based on a partial string is not working. Very simple code, and it runs fine but doesn't drop the rows I want. The original table in the pdf looks like this: Chemical Value Unit Type Fluoride 0.23 ug/L Lab Mercury 0.15 ug/L Lab Sum of Long Chained Polymers 0.33 Partialsum of Short Chai...
[ "You are close. You did drop the rows, but you didn't save the result.\nimport pandas as pd\n\nexample = {'Chemical': ['Fluoride', 'Mercury', 'Sum of Long Chained Polymers',\n 'Partialsum of Short Chained Polymers'], \n 'Value': [0.23, 0.15, 0.33, 0.4], \n 'Unit': ['ug/L', 'ug/L...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "pdf", "python", "tabula" ]
stackoverflow_0074510620_dataframe_pandas_pdf_python_tabula.txt
Q: Extracting duplicates from a list of dictionaries in Python I have a huge list of dictionaries (I have shortened it here for clarity), where some values are duplicates (let's assume 'ID' is my target). How can I print the dictionary/ies where the ID occurs more than once? [{'ID': 2501, 'First Name': 'Edward', ...
Extracting duplicates from a list of dictionaries in Python
I have a huge list of dictionaries (I have shortened it here for clarity), where some values are duplicates (let's assume 'ID' is my target). How can I print the dictionary/ies where the ID occurs more than once? [{'ID': 2501, 'First Name': 'Edward', 'Last Name': 'Crawford', 'Email': 'c.crawford@randatmail.com', ...
[ "I'd suggest constructing a helper function where you have the flexibility of choosing the field that you're looking for duplicates in. Incorporating an intermediate dictionary (such as that from @Andrej Kesely's answer) is an efficient way of searching for duplicates, and this can be generalized in a function. I...
[ 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "list_comprehension", "python" ]
stackoverflow_0074512771_dictionary_list_comprehension_python.txt
Q: Read excel autofilter with python I'd like to read the autofilter rules from an excel sheet in python. Suppose this kind of input: original input then I filter with excel autofilter one column, for example: filtered input Is there a way to retrieve the applied autofilter rule in python? Currently the only option I...
Read excel autofilter with python
I'd like to read the autofilter rules from an excel sheet in python. Suppose this kind of input: original input then I filter with excel autofilter one column, for example: filtered input Is there a way to retrieve the applied autofilter rule in python? Currently the only option I know, it is to set the autofilter via ...
[ "With Xlwings you should be able to duplicate what VBA can do so it's usually the better for this type of query.\nYou should be able to show the Filter set from Criteria1 as shown below;\nimport xlwings as xw\n\n# Open the workbook\nworkbook = xw.Book(r\"C:\\Users\\Desktop\\Example.xlsx\")\n\n# Set Autofilter\nwork...
[ 0 ]
[]
[]
[ "excel", "filter", "pandas", "python", "xlwings" ]
stackoverflow_0074510217_excel_filter_pandas_python_xlwings.txt
Q: How can I make it loop properly? It won't work when trying to loop so it can restart at the end when asked. def inputPass(message): while True: try: userInput = int(input(message)) except ValueError: print("Not an integer! Try again.") continue else: return userInput def ...
How can I make it loop properly?
It won't work when trying to loop so it can restart at the end when asked. def inputPass(message): while True: try: userInput = int(input(message)) except ValueError: print("Not an integer! Try again.") continue else: return userInput def inputDefer(message): while True: ...
[ "Its kind of difficult to answer since your question is very unclear. You have a lot of repeated code which can be tided up. If the code below doesnt answer your question hopefully it puts you on the right track to solve your problem. If your still struggling please update the question with more clear details.\nVAL...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074512984_python_python_3.x.txt
Q: how to merge pd.to_json file and dictionary? this is the transformed json file that using pd.to_json and this is dictionary format I want these two looks like this I forced to merge those with like print('['+str(dict({'Message1':'Hello','Message2':'word'}))+','+df1[1:]) but the java won't accept this format. M...
how to merge pd.to_json file and dictionary?
this is the transformed json file that using pd.to_json and this is dictionary format I want these two looks like this I forced to merge those with like print('['+str(dict({'Message1':'Hello','Message2':'word'}))+','+df1[1:]) but the java won't accept this format. Maybe I have to send the format with pd.to_json..
[ "Use pd.DataFrame.to_dict not pd.DataFrame.to_json, then it's simply a matter of:\nprint([{'Message1':'Hello','Message2':'word'}, *df.to_dict('records')])\n\nOr if it's very particular about the output:\nimport json\n\nd = {'Message1':'Hello','Message2':'word'}\n\nout = [d, *df.to_dict('records')]\nprint(json.dumps...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074513071_python.txt
Q: How to execute python file inside another with specific parameters? In terminal I would type something close to: python main.py --something-something parameter1 --something- parameter2 Because that's how the program works. I need to run main.py in another python script but also need to have "--something-something...
How to execute python file inside another with specific parameters?
In terminal I would type something close to: python main.py --something-something parameter1 --something- parameter2 Because that's how the program works. I need to run main.py in another python script but also need to have "--something-something parameter1 --something- parameter2" as part of it. I have already looked...
[ "Create the string you will use first\npythonCall = 'python main.py --something-something {} --something- {}'.format(dog, ID)\nos.system(pythonCall)\n\n" ]
[ 0 ]
[]
[]
[ "parameters", "python", "terminal" ]
stackoverflow_0074513189_parameters_python_terminal.txt
Q: Looking For Simple Python Scraping Help: Having Trouble Identifying Sections and Class with BeautifulSoup I am trying to learn how to scrape data. I am very new to Python, so bare with me. Upon searching YouTube, I found a tutorial and tried to scrape some data off of "https://www.pgatour.com/competition/2022/hero...
Looking For Simple Python Scraping Help: Having Trouble Identifying Sections and Class with BeautifulSoup
I am trying to learn how to scrape data. I am very new to Python, so bare with me. Upon searching YouTube, I found a tutorial and tried to scrape some data off of "https://www.pgatour.com/competition/2022/hero-world-challenge/leaderboard.html" from bs4 import BeautifulSoup import requests SCRAPE = requests.get("http...
[ "Data is loaded dynamically by JavaScript and bs4 can't render JS that's why your code is printing nothing but you can pull the required data from API.\nExample:\nimport pandas as pd\nimport requests\n\napi_url= 'https://lbdata.pgatour.com/2022/r/478/leaderboard.json?userTrackingId=eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2...
[ 1 ]
[]
[]
[ "beautifulsoup", "pandas", "python", "web_scraping" ]
stackoverflow_0074513130_beautifulsoup_pandas_python_web_scraping.txt
Q: Why do I get None in output in second line while using eval function? I am executing this line of code - print(eval("print(2 +3)")) but this instead of giving output as 5 gives output- 5 None A: When you try to get eval of something like eval("2") you are actually going to get type int. But trying to evaluate p...
Why do I get None in output in second line while using eval function?
I am executing this line of code - print(eval("print(2 +3)")) but this instead of giving output as 5 gives output- 5 None
[ "When you try to get eval of something like\neval(\"2\")\nyou are actually going to get type int.\nBut trying to evaluate print expression gives you None type. Print will be executed but type of\neval(\"print(2+3)\")\nwill be None.\n", "This is because you are giving eval() within print().\neval(\"(2 +3)\")\n\nTh...
[ 0, 0, 0 ]
[]
[]
[ "eval", "function", "python", "python_3.x" ]
stackoverflow_0066901984_eval_function_python_python_3.x.txt
Q: How would I convert a format string with quotes into an f-string with nested quotes? I've seen this question but I think I have more nested quotes and it's doing my head in. How would I convert the following line into an f-string? file.write('python -c "{code}"'.format(code="open('test.txt', 'w');")) A: There's ...
How would I convert a format string with quotes into an f-string with nested quotes?
I've seen this question but I think I have more nested quotes and it's doing my head in. How would I convert the following line into an f-string? file.write('python -c "{code}"'.format(code="open('test.txt', 'w');"))
[ "There's barely anything to do here:\ncode=\"open('test.txt', 'w');\"\nfile.write(f'python -c \"{code}\"')\n\nYou can of course also put the value of the variable in the f-string, but that would be silly:\nfile.write(f'python -c \"{\"open(\\'test.txt\\', \\'w\\');\"}\"')\n\nBecause replacing a string with a string ...
[ 1 ]
[]
[]
[ "f_string", "python" ]
stackoverflow_0074513205_f_string_python.txt
Q: Why is appending my list of tuples changing their content? I am trying to make a list of tuples that contain a string and a dictionary. The string is a filename and the dictionary is a frequency list of n-grams. ('story.txt', {'back': 12, 'been': 13, 'bees': 58, 'buzz': 13, 'cant': 30, 'come': 12, 'do...
Why is appending my list of tuples changing their content?
I am trying to make a list of tuples that contain a string and a dictionary. The string is a filename and the dictionary is a frequency list of n-grams. ('story.txt', {'back': 12, 'been': 13, 'bees': 58, 'buzz': 13, 'cant': 30, 'come': 12, 'dont': 64, 'down': 16, 'from': 22, ...}) For what I'm doin...
[ "There is no problem with code you presented, I speculate that you left hard coded file name somewhere in map_maker.make_map or you reusing result variable doc_map inside make_map (it's static or member of map_maker, beware of default arguments for mutable types in python)\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "n_gram", "python" ]
stackoverflow_0074513202_dictionary_list_n_gram_python.txt
Q: VsCode/Python in console: file not found In my workingdirectory I have many folders with a python script modifying data in the same folder. When running Python in VsCode I need to give a relative path from the working directory into the folder. For example using os.getcwd(), test.py is in D:\Workingdirectory\Folde...
VsCode/Python in console: file not found
In my workingdirectory I have many folders with a python script modifying data in the same folder. When running Python in VsCode I need to give a relative path from the working directory into the folder. For example using os.getcwd(), test.py is in D:\Workingdirectory\Folder1: VsCode says, D:\Workingdirectory. Running ...
[ "This is caused by vscode using workspace as root floder.\nThis will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.\nYou can open your settings and search Python > Terminal: Execute In File Dir then check it.\n\nYou can also...
[ 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074491233_python_visual_studio_code.txt
Q: Running VBA code from Python: macros may be disabled Trying to run an Excel macro via Python I get the following error: Traceback (most recent call last): File ".\test.py", line 17, in <module> xlApp.Application.Run(MACRO) File "<COMObject <unknown>>", line 14, in Run File "C:\Users\twaucho...
Running VBA code from Python: macros may be disabled
Trying to run an Excel macro via Python I get the following error: Traceback (most recent call last): File ".\test.py", line 17, in <module> xlApp.Application.Run(MACRO) File "<COMObject <unknown>>", line 14, in Run File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\...
[ "xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.\n" ]
[ 0 ]
[]
[]
[ "excel", "python", "vba", "win32com" ]
stackoverflow_0049972988_excel_python_vba_win32com.txt
Q: Conda dependency range specifiction: ResolvePackageNotFound I have an environment.yaml with this content (MWE) name: the-env dependencies: - pandas>=1.5.0,<2.0.0 I run conda env create -f environment.yaml I get Collecting package metadata (repodata.json): done Solving environment: failed ResolvePackageNotFound...
Conda dependency range specifiction: ResolvePackageNotFound
I have an environment.yaml with this content (MWE) name: the-env dependencies: - pandas>=1.5.0,<2.0.0 I run conda env create -f environment.yaml I get Collecting package metadata (repodata.json): done Solving environment: failed ResolvePackageNotFound: - pandas[version='>=1.5.0,<2.0.0'] Why. Docu is useless for...
[ "Currently, only Conda Forge provides any builds satisfying pandas>=1.5.0. So, the YAML should use:\nname: the-env\nchannels:\n - conda-forge\ndependencies:\n - pandas>=1.5.0,<2.0.0\n\n\n\"Should the latter not work if the former works...?\"\n\npandas>=1.5.0,<2.0.0 is a subset of pandas<2.0.0, so the former being...
[ 0 ]
[]
[]
[ "anaconda", "conda", "dependencies", "environment", "python" ]
stackoverflow_0074406399_anaconda_conda_dependencies_environment_python.txt
Q: Google Sheets API Wont Let Me Write Data into My Google Sheet Code is below. this isnt the full code but the basis of it. Im trying to take data from Twitter's API and Write it to my Google Sheets API. Below is the Code. from googleapiclient import discovery from google.oauth2 import service_account from google.oa...
Google Sheets API Wont Let Me Write Data into My Google Sheet
Code is below. this isnt the full code but the basis of it. Im trying to take data from Twitter's API and Write it to my Google Sheets API. Below is the Code. from googleapiclient import discovery from google.oauth2 import service_account from google.oauth2.credentials import Credentials from googleapiclient.discovery...
[ "I think that the reason for your current issue of \"Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8\" is due to body={\"values\": 8}. In this case, it is required to use a 2-dimensional array. So, please modify it as follows.\nFrom:\nrequest = sheet.values().update(spreadsheetId =...
[ 0 ]
[]
[]
[ "google_cloud_platform", "google_sheets", "google_sheets_api", "python" ]
stackoverflow_0074511522_google_cloud_platform_google_sheets_google_sheets_api_python.txt
Q: Beautiful Soup data extract Have an local .html from which I am extracting point data, parsed with BeautifulSoup but I don't know how to extract the date that is inside a div, the parse array is the following: <div class="_a6-p"><div><div><a href="https://www.instagram.com/chuckbasspics" target="_blank">chuckbassp...
Beautiful Soup data extract
Have an local .html from which I am extracting point data, parsed with BeautifulSoup but I don't know how to extract the date that is inside a div, the parse array is the following: <div class="_a6-p"><div><div><a href="https://www.instagram.com/chuckbasspics" target="_blank">chuckbasspics</a></div><div>Jan 7, 2013, 5:...
[ "You can use bs4 API or CSS selector:\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"<div class=\"_a6-p\"><div><div><a href=\"https://www.instagram.com/chuckbasspics\" target=\"_blank\">chuckbasspics</a></div><div>Jan 7, 2013, 5:41 AM</div></div></div><div class=\"_3-94 _a6-o\"></div></div><div class=\"pam _3-9...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0074513306_beautifulsoup_html_python.txt
Q: Udacity Self Driving Car Simulator I am working on Udacity's self-driving car simulator. I am facing a problem in this when I run the drive.py file with my model as argument model.h5 nothing happens in the simulator. The model has been trained completely without any errors but still, there is no response from the ...
Udacity Self Driving Car Simulator
I am working on Udacity's self-driving car simulator. I am facing a problem in this when I run the drive.py file with my model as argument model.h5 nothing happens in the simulator. The model has been trained completely without any errors but still, there is no response from the simulator. Here is the drive.py python c...
[ "This is due to the socketio version. Use 4.2.1, that should fix your problem\n" ]
[ 0 ]
[]
[]
[ "python", "simulator" ]
stackoverflow_0073705466_python_simulator.txt
Q: Trying to dockerize Django app, Docker cannot find ft2build.h I'm new to Docker and I'm trying to dockerize a Django app but when I run docker build -t sometag . I receive the following error: #9 23.05 Preparing metadata (setup.py): started #9 23.32 Preparing metadata (setup.py): finished with status 'error' #...
Trying to dockerize Django app, Docker cannot find ft2build.h
I'm new to Docker and I'm trying to dockerize a Django app but when I run docker build -t sometag . I receive the following error: #9 23.05 Preparing metadata (setup.py): started #9 23.32 Preparing metadata (setup.py): finished with status 'error' #9 23.33 error: subprocess-exited-with-error #9 23.33 #9 23.33 ×...
[ "\nI'm not sure if it is related to ft2build.h.I'm I missing something on my dockerfile?\n\nTo solve the problem with the error ft2build.h. in the compile process, you need the freetype library installed\nI assume you are using the last version of Alpine, and I can see you can install pip packages without problems....
[ 0 ]
[]
[]
[ "django", "docker", "python" ]
stackoverflow_0074512564_django_docker_python.txt
Q: How to add new rows to a dataframe based on ranges of two columns in the same dataframe? I have a dataframe that summarizes the segments of track within a bigger network. These segments have specific segement_ids and it looks like this: import pandas as pd import numpy as np my_dict = { 'segment_id':['a', 'b',...
How to add new rows to a dataframe based on ranges of two columns in the same dataframe?
I have a dataframe that summarizes the segments of track within a bigger network. These segments have specific segement_ids and it looks like this: import pandas as pd import numpy as np my_dict = { 'segment_id':['a', 'b', 'c', 'd', 'e'], 'km_start':[2,4,9,15,20], 'km_end':[3,7,11,16,22], 'min_km_start'...
[ "Try this\nstarts = pd.concat([pd.Series(df['min_km_start'].iloc[0]), df['km_end']]).reset_index(drop=True)\nends = pd.concat([df['km_start'], pd.Series(df['max_km_end'].iloc[0])]).reset_index(drop=True)\nmask = ~starts.isin(df['km_start'])\npd.concat([df, pd.DataFrame({'km_start': starts[mask], 'km_end': ends[mask...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074513220_pandas_python.txt
Q: Why does VSCode Python always put two tabs instead of one? In my VSCode settings, I have Tab Size set to 2 and in Prettier I have it set to 2 spaces as well. It works fine, whenever I go to the next line, it indents by 1 tab (2 spaces) and whenever I press tab it places a tab where my cursor was. But when I save m...
Why does VSCode Python always put two tabs instead of one?
In my VSCode settings, I have Tab Size set to 2 and in Prettier I have it set to 2 spaces as well. It works fine, whenever I go to the next line, it indents by 1 tab (2 spaces) and whenever I press tab it places a tab where my cursor was. But when I save my file, all of the single tabs for indenting turn into 2 tabs. H...
[ "\nI want to indent using tabs but when I save it indents with 2 tabs and that's annoying\n\n\n\nClick the Select Indentation option in the lower right corner.\n\n\n\nChoose Indent Using Tabs\n\n\n\nChoose 2.\n\nYou can also change the settings by searching tab size:\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "save", "visual_studio_code" ]
stackoverflow_0074502151_python_python_3.x_save_visual_studio_code.txt
Q: Weighted Mean Squared Error in TensorFlow I created a neural network for Quickest Detection. The input is a list of 10 observation and the output is the change time predicted. I want to modify the Probability of false alarms using a Weighted MSE. I created this neural network: model = k.Sequential(\[ k.layers.Dens...
Weighted Mean Squared Error in TensorFlow
I created a neural network for Quickest Detection. The input is a list of 10 observation and the output is the change time predicted. I want to modify the Probability of false alarms using a Weighted MSE. I created this neural network: model = k.Sequential(\[ k.layers.Dense(window_size, activation = k.activations.relu,...
[ "You can achieve this by creating a custom loss function:\n def custom_loss(y_true, y_pred):\n loss = k.mean(k.square(y_true - y_pred), axis=-1) # MSE\n loss = k.where((y_pred - y_true) < 0.0, loss, loss * 0.5) # higher loss for false alarms\n return loss\n model.compile(optimizer = 'Adam', loss = ...
[ 0 ]
[]
[]
[ "artificial_intelligence", "deep_learning", "neural_network", "python", "tensorflow" ]
stackoverflow_0074511992_artificial_intelligence_deep_learning_neural_network_python_tensorflow.txt
Q: Python recursive generator breaks when using list() and append() keywords I have only recently learned about coroutines using generators and tried to implement the concept in the following recursive function: def _recursive_nWay_generator(input: list, output={}): ''' Helper function; used to generate param...
Python recursive generator breaks when using list() and append() keywords
I have only recently learned about coroutines using generators and tried to implement the concept in the following recursive function: def _recursive_nWay_generator(input: list, output={}): ''' Helper function; used to generate parameter-value pairs to submit to the model for the simulation. Parameters...
[ "The problem with your code is reusing the same mutable output dict during the iteration and recursive calls. That is, you yield output and then later on you modify it with output[par_name] = par_value but it's the same dict in each case - so you're modifying the instance which was already returned! If you append e...
[ 0 ]
[]
[]
[ "coroutine", "generator", "list", "python", "recursion" ]
stackoverflow_0074513316_coroutine_generator_list_python_recursion.txt
Q: How do I extract a value from quarterly cashflow using python and yfinance import yfinance as yf ticker = yf.Ticker("AAPL) q_cashflow = ticker_quarterly_cashflow print(q_cashflow) Some output below. How do I extract for instance the value of 'Change To Liabilities' on '2021-06-26' which is 3.070000e+08? Sorry I am...
How do I extract a value from quarterly cashflow using python and yfinance
import yfinance as yf ticker = yf.Ticker("AAPL) q_cashflow = ticker_quarterly_cashflow print(q_cashflow) Some output below. How do I extract for instance the value of 'Change To Liabilities' on '2021-06-26' which is 3.070000e+08? Sorry I am beginning to learn programming. Thanks in advance. ...
[ "It is just a Pandas dataframe. You can use the usual way that you use to extract a value from a Pandas dataframe. For example, q_cashflow.loc[row_index_name, column_name]\n" ]
[ 0 ]
[]
[]
[ "python", "yfinance" ]
stackoverflow_0072818954_python_yfinance.txt
Q: Get softmax output and raw output of the last layer of a model When creating a neural network for image classification, I want to get the classification on one hand and the raw output on the other hand to determine if the image really contains one of the images I want to classify or not. If not then the raw output...
Get softmax output and raw output of the last layer of a model
When creating a neural network for image classification, I want to get the classification on one hand and the raw output on the other hand to determine if the image really contains one of the images I want to classify or not. If not then the raw output should contain very low values for all classes. But if the image re...
[ "You can use functional API and implement your model in a next way:\n inputs = tf.keras.Input(shape=(80, 80, 3))\n x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(inputs)\n x = tf.keras.layers.MaxPooling2D((2, 2))(x)\n x = tf.keras.layers.Dropout(0.3)(x)\n x = tf.keras.layers.Conv2D(16, (3, 3), activ...
[ 1 ]
[]
[]
[ "classification", "deep_learning", "neural_network", "python", "tensorflow" ]
stackoverflow_0074508999_classification_deep_learning_neural_network_python_tensorflow.txt
Q: i cant figure out my python game keep crashing please help when i press space, e, or f my game crashes but i cant find out why also can you help me make this dam block move upwards. please help me i will go insane if i cant figure this out. ` # import the pygame module import pygame import keyboard import time xb...
i cant figure out my python game keep crashing
please help when i press space, e, or f my game crashes but i cant find out why also can you help me make this dam block move upwards. please help me i will go insane if i cant figure this out. ` # import the pygame module import pygame import keyboard import time xb = 30 yb = 670 x = 30 y = 670 o = 0 # Define the ba...
[ "In PyGame, the 0,0 co-ordinate is in the upper-left corner of the window. In your game the player is positioned at the bottom, so the projectile moves up the display, going from a large y-coordinate to a smaller one, and eventually negative once off-screen.\nAs @Chris Doyle points out in a comment, your code has ...
[ 1 ]
[]
[]
[ "keyboard", "pygame", "python" ]
stackoverflow_0074513113_keyboard_pygame_python.txt
Q: SLY python can't parse simple tokens I'm working on making a simple interpreted programming language using SLY to generate a AST which I will interpret without using SLY. Currently I have been able to generate all my tokens and giving them to the parser, but it can't recognize any rule, only empty ones. Lexer: fro...
SLY python can't parse simple tokens
I'm working on making a simple interpreted programming language using SLY to generate a AST which I will interpret without using SLY. Currently I have been able to generate all my tokens and giving them to the parser, but it can't recognize any rule, only empty ones. Lexer: from .sly.lex import Lexer class ALexer(Lexe...
[ "As far as I can see, your code works fine up to the point at which you attempt to parse the second statement. I tried it with the input x=2 as suggested in your comment, and it produced the following result (pretty-printed with the pprint module):\n{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,\n 'values': ( { 'op': <...
[ 1 ]
[]
[]
[ "parsing", "ply", "python", "sly", "token" ]
stackoverflow_0074509434_parsing_ply_python_sly_token.txt
Q: Having a difficult time reading a certain Binary file with Python I am working on a mod for a game and all of the games strings are in a file called a .dat file. Its a binary file and I'm pretty sure I am missing quite a few strings that I need to add. I have a way to add them into the file I just don't have a way...
Having a difficult time reading a certain Binary file with Python
I am working on a mod for a game and all of the games strings are in a file called a .dat file. Its a binary file and I'm pretty sure I am missing quite a few strings that I need to add. I have a way to add them into the file I just don't have a way to search for every instance of a missing string. So I decided to writ...
[ "Since it's binary you need to know exact format of data. Looking at file I see there is some header and then at offset 0x0038790 string block begins.\nGoogle for <game title> file format to get idea how to properly parse it or reverse engineer it yourself (there is guide how to do it for another game). btw I think...
[ 0 ]
[]
[]
[ "binaryfiles", "python" ]
stackoverflow_0074513380_binaryfiles_python.txt
Q: Validation Error when filtering by UUID Django I am attempting to return all the friends of friends of a certain user who is the author of the relationship. However, I keep getting this error: ValidationError at /author/posts ["“[UUID('8c02a503-7784-42f0-a367-1876bbfad6ff')]” is not a valid UUID."] class Author(Ab...
Validation Error when filtering by UUID Django
I am attempting to return all the friends of friends of a certain user who is the author of the relationship. However, I keep getting this error: ValidationError at /author/posts ["“[UUID('8c02a503-7784-42f0-a367-1876bbfad6ff')]” is not a valid UUID."] class Author(AbstractUser): ... uuid = models.UUIDField(pri...
[ "I'm seeing two things to fix here:\n\nThe lookup should be friend__in 'cause you are passing a list o UUIDs.\nYou need to convert the UUID object to a string using friend.friend.uuid)\n\nThe solution proposed is the follwing:\nfoafs = Friend.objects.filter(friend__in=[str(friend.friend.uuid) for friend in friends]...
[ 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python", "validation" ]
stackoverflow_0060795135_django_django_models_django_rest_framework_python_validation.txt
Q: Pandas dataframe plot 's' argument I have the statement and I really don't understand the s= part. I know it sets the area of the plot but is it taking the data from pop_2007 and raising it to 1^6 to create the area ? df.plot(kind='scatter', x='gdp_2007', y='lifeExp_2007', s=df['pop_2007']/1e6) I'm trying to und...
Pandas dataframe plot 's' argument
I have the statement and I really don't understand the s= part. I know it sets the area of the plot but is it taking the data from pop_2007 and raising it to 1^6 to create the area ? df.plot(kind='scatter', x='gdp_2007', y='lifeExp_2007', s=df['pop_2007']/1e6) I'm trying to understand the area of a plot better and th...
[ "The 's' parameter in the pandas dataframe plot function is changing the size of the markers in your scatter plot. See these two outputs where I change the 's' value from 1 to 100. So right now, your plot is taking the value in the df['pop_2007'] column and dividing it by 1e6 to get your value for the marker size.\...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074513477_matplotlib_pandas_plot_python.txt
Q: 4D heat map in matplotlib I want to plot a 4D heatmap in Python through matplotlib, like this 4d map. I have already a set of 3D grid points (x,y,z) and its corresponding function value f. I am thinking of plotting it using plot_surface with x, y, z as the three required arrays, and alter the color gradient usin...
4D heat map in matplotlib
I want to plot a 4D heatmap in Python through matplotlib, like this 4d map. I have already a set of 3D grid points (x,y,z) and its corresponding function value f. I am thinking of plotting it using plot_surface with x, y, z as the three required arrays, and alter the color gradient using f. There is a way here to us...
[ "Your data is of a slightly different form I imagine, but as long as you have a point for every thing you need to be plotted you could use something like they did here:\nHow to make a 4d plot using Python with matplotlib\n", "There aren't great existing ways to visualize true 4D functions (where the third dimensi...
[ 1, 0 ]
[]
[]
[ "4d", "matplotlib", "python" ]
stackoverflow_0042250095_4d_matplotlib_python.txt
Q: Checking if a function from the sources of a website is executed With the "Inspect Element" option in a common browser it is possible to access the "Sources" tab and, not only see the files which the website uses, but also mark a line of code (as shown in the image below at line 463 with a .js file), which will ma...
Checking if a function from the sources of a website is executed
With the "Inspect Element" option in a common browser it is possible to access the "Sources" tab and, not only see the files which the website uses, but also mark a line of code (as shown in the image below at line 463 with a .js file), which will make the browser pause when that line of code is executed (essentially a...
[ "Selenium tests are intended to be \"black box\". That is, you load a page and only access the things that are available in the browser window to verify that behavior is correct. You should NOT try to verify that specific parts of code were written. Even if you can figure out a way to do this, it will make your tes...
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074513493_python_python_3.x_selenium_selenium_webdriver_web_scraping.txt
Q: Need help to solve a calculation issue and how to make a continuous list of elements for same input Need help to solve a calculation issue and how to make a continuous list of elements for same input Code itself ` for T in range(12): AskP1= str(input("Did the first player win, draw or lose, pick the correspod...
Need help to solve a calculation issue and how to make a continuous list of elements for same input
Need help to solve a calculation issue and how to make a continuous list of elements for same input Code itself ` for T in range(12): AskP1= str(input("Did the first player win, draw or lose, pick the correspoding letter: W,L,D ")) AskP2 = str(input("Did the second player win, draw or lose, pick the correspodi...
[ "if X == \"W\" or \"w\":\nChanged to\nif X == \"W\" or X == \"w\":\nBecause bool('w') always equals True\nHere's my adjusted program\nP1A = []\nP2A = []\nP1 = 0\nP2 = 0\ntimes = 3\nfor T in range(times):\n X = str(\n input(\n \"Did the first player win, draw or lose, pick the correspoding lette...
[ 0 ]
[]
[]
[ "arrays", "input", "list", "output", "python" ]
stackoverflow_0074513290_arrays_input_list_output_python.txt
Q: How do I return the rows of DataFrame where every Country in each Continent has a Population of less of than 100? df = pd.DataFrame({ "Continent": list("AAABBBCCD"), "Country": list("FGHIJKLMN"), "Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]}) As explained, I want to return all of the rows, w...
How do I return the rows of DataFrame where every Country in each Continent has a Population of less of than 100?
df = pd.DataFrame({ "Continent": list("AAABBBCCD"), "Country": list("FGHIJKLMN"), "Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]}) As explained, I want to return all of the rows, where all countries in each continent are less than 100. Continent Country Population 0 A F 90...
[ "here is one way to do it\n# groupby on continent\n# using makes the row True/False, whether max for the group is below 100\nout=df[df.groupby(['Continent'])['Population'].transform(lambda x: x.max()<100)]\nout\n\n\nContinent Country Population\n3 B I 80\n4 B J 80\n5 B K 70\n8 D N 50\n...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "pandas_loc", "python" ]
stackoverflow_0074513188_dataframe_pandas_pandas_loc_python.txt
Q: kwargs different behavior Dear pythonist that question is for you! I don't ask to solve my task, just ask for explaining why it happens) I know what is args and kwargs when they using but has been really shoked, when have found one thing. So, please check my example, here we pass arguments to the function def firs...
kwargs different behavior
Dear pythonist that question is for you! I don't ask to solve my task, just ask for explaining why it happens) I know what is args and kwargs when they using but has been really shoked, when have found one thing. So, please check my example, here we pass arguments to the function def firstFunc(*args, **kwargs): pri...
[ "You're passing the list and the dictionary as two positional arguments, so those two positional arguments are what shows up in your *args in the function body, and **kwargs is an empty dictionary since no keyword arguments were provided.\nIf you want to pass each element of the list as its own positional argument,...
[ 1 ]
[ "Thank you guys !\nI found the difference when I passing arguments, that for first function I didn't passed ** with argument(applied expanding), but for second functtion I passed it(applied expanding), just my syntax mistake. but what conclusion when we can make - that if u passing dictionarie as kwargs always use ...
[ -1 ]
[ "function", "keyword_argument", "python" ]
stackoverflow_0074513447_function_keyword_argument_python.txt
Q: Better way to write this code? 3D position update of an object I have an array for the position of the particle in cartesian coordinates and velocity in 3D. So that position[0] represents the x component of the position and so on. I'm curious if there is a better way to write this code, maybe shorter, maybe faster...
Better way to write this code? 3D position update of an object
I have an array for the position of the particle in cartesian coordinates and velocity in 3D. So that position[0] represents the x component of the position and so on. I'm curious if there is a better way to write this code, maybe shorter, maybe faster. ` def update_position(self): self.position[0] = self.position[0] +...
[ "def update_position(self):\n for i in range(3):\n self.position[i] += self.velocity[i] * self.tick\n\n", "Just use the numpy library. It's a lot faster and easier to use. Here's an example of how to use it:\nimport numpy as np\n...\ndef __init__(self):\n self.position = np.array([0.0, 0.0, 0.0])\n se...
[ 0, 0 ]
[]
[]
[ "multidimensional_array", "optimization", "python" ]
stackoverflow_0074513537_multidimensional_array_optimization_python.txt
Q: Perl to python open() command translation How do I write open(SCRPT, ">$script") or die...; in python?? Im trying to run a script in python to automate a slurm job. For that, I am trying to create and open a file names SCRPT and write a block of code to be read and executed. Is it SCRPT = open(script) with open(SC...
Perl to python open() command translation
How do I write open(SCRPT, ">$script") or die...; in python?? Im trying to run a script in python to automate a slurm job. For that, I am trying to create and open a file names SCRPT and write a block of code to be read and executed. Is it SCRPT = open(script) with open(SCRPT)
[ "The builtin open is typically used to create a filehandle. open raises IOError if anything goes wrong. The functional equivalent of open(SCRIPT,\">$script\") or die $error_message would be\nimport sys\ntry:\n script = open(\"script\", \"w\")\nexcept IOError as ioe:\n print(error_message, file=sys.stderr)\n ...
[ 2, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0074513104_perl_python.txt
Q: ValueError: 'images' must have either 3 or 4 dimensions. in Colab I do object detection with tensorflow in Google Colab. I'm trying to get video from the webcam. This is the last stage. But I am getting the error below continent.How can I size the pictures? ValueError: in user code: <ipython-input-49-1e7efe91...
ValueError: 'images' must have either 3 or 4 dimensions. in Colab
I do object detection with tensorflow in Google Colab. I'm trying to get video from the webcam. This is the last stage. But I am getting the error below continent.How can I size the pictures? ValueError: in user code: <ipython-input-49-1e7efe9130ee>:11 detect_fn * image, shapes = detection_model.preproces...
[ "Verify that you are getting an image frame from the following line:\nret, frame = cap.read()\n\nWhen I got the same error (albeit slightly different code), I was pointing to a non-existent directory rather than an image.\n", "cap = cv2.VideoCapture(0)\n\nTry to listen with different values ranging between 0,1,2....
[ 2, 1, 0, 0, 0, 0, 0 ]
[ "So let me explain this. This is not any error, its just lag in between your laptop's webcam and programming accessing it. Just restart your laptop. It will work fine. I faced the same problem...and just restarting solved it.\n" ]
[ -2 ]
[ "object_detection", "python", "tensorflow" ]
stackoverflow_0066356797_object_detection_python_tensorflow.txt