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: How to yield key and value in a dictionary if conditional is met Here is my current code guests = {'Jane': 35, 'Kyle': 20, 'Justin': 43, 'Ayla': 22} age_check = (key, value for key, value in guests.items() if value >= 21) for guest in age_check: print(guest) I am curious how I would get the output of every key...
How to yield key and value in a dictionary if conditional is met
Here is my current code guests = {'Jane': 35, 'Kyle': 20, 'Justin': 43, 'Ayla': 22} age_check = (key, value for key, value in guests.items() if value >= 21) for guest in age_check: print(guest) I am curious how I would get the output of every key and value where the value is over than or equal to 21 using a generat...
[ "From Displays for lists, sets and dictionaries: The comprehension consists of a single expression followed by at least one for clause. In your case, the expression key, value is ambiguous in this context (is that a tuple being generated or is the second value in the tuple a generator) so must be encased in parenth...
[ 0 ]
[]
[]
[ "generator", "generator_expression", "python" ]
stackoverflow_0074330373_generator_generator_expression_python.txt
Q: Change the confidence level in t-test scipy? I took this code from the official scipy documentation: from scipy import stats import numpy as np rng = np.random.default_rng() rvs = stats.uniform.rvs(size=50, random_state=rng) stats.ttest_1samp(rvs, popmean=0.5) In R, it's possible change the confidence level (90%,...
Change the confidence level in t-test scipy?
I took this code from the official scipy documentation: from scipy import stats import numpy as np rng = np.random.default_rng() rvs = stats.uniform.rvs(size=50, random_state=rng) stats.ttest_1samp(rvs, popmean=0.5) In R, it's possible change the confidence level (90%, 94%, 99%, as example), but there is no mention of...
[ "The version where you can do it directly isn't released yet.\nHere is the link https://scipy.github.io/devdocs/reference/generated/scipy.stats.ttest_1samp.html\nTo compute confidence intervals in Python check this answer Compute a confidence interval from sample data\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python", "scipy" ]
stackoverflow_0074283536_numpy_pandas_python_scipy.txt
Q: How to make the time from len of array How to make time from len of array... Picture 1: Picture 2: How to make the picture 1 as picture 2 Picture 1 come from below: ` x=[] colors=['red','green','brown','teal','gray','black','maroon','orange','purple'] colors2=['green','red','orange','black','maroon','teal','blue...
How to make the time from len of array
How to make time from len of array... Picture 1: Picture 2: How to make the picture 1 as picture 2 Picture 1 come from below: ` x=[] colors=['red','green','brown','teal','gray','black','maroon','orange','purple'] colors2=['green','red','orange','black','maroon','teal','blue','gray','brown'] for i in range(0,1950): ...
[ "Your x array is essentially just a number of iterations. The iteration number divided by whatever your time step is should give you time, so when calling plt.plot() use x/dt instead of x\n", "@ahrensaj's answer makes sense.\nHere is your code modified to rescale the time scale.\nx=[]\ncolors=['red','green','brow...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074330374_python.txt
Q: How can one use conda, without using Anaconda prompt, and without adding to the PATH? Anaconda no longer recommends it be added to the PATH, and it instead recommends using Anaconda Prompt. Well Anaconda Prompt lacks the features of good alternatives (i.e. tabs, and many more). So to use an alternative to Anaconda...
How can one use conda, without using Anaconda prompt, and without adding to the PATH?
Anaconda no longer recommends it be added to the PATH, and it instead recommends using Anaconda Prompt. Well Anaconda Prompt lacks the features of good alternatives (i.e. tabs, and many more). So to use an alternative to Anaconda Prompt, how would one still access the conda (and pip, etc.) package manager, without viol...
[ "If you wanted to achieve something such as creating a terminal profile to directly open conda prompt in the windows terminal, without adding it to path, you can do it in the following way:\nfirst, create a new profile on the windows terminal and set the startup directory to your anaconda folder. (Usually, c:/Users...
[ 0 ]
[]
[]
[ "anaconda", "cmd", "conda", "python", "windows" ]
stackoverflow_0045492047_anaconda_cmd_conda_python_windows.txt
Q: Python emulate clicking number button i have problem with clicking number button in python, when i try to simulate click (whatever button I like), it works but when i try to put Key.number it doesn't works. (bottom line's of code) import pyautogui from pynput.keyboard import Key, Controller as KeyboardController f...
Python emulate clicking number button
i have problem with clicking number button in python, when i try to simulate click (whatever button I like), it works but when i try to put Key.number it doesn't works. (bottom line's of code) import pyautogui from pynput.keyboard import Key, Controller as KeyboardController from pynput.mouse import Button, Controller ...
[ "When using keyboard.press() the parameter needs to have '' around it, keyboard.press('.')\n" ]
[ 0 ]
[]
[]
[ "numbers", "pyautogui", "pynput", "python" ]
stackoverflow_0074327945_numbers_pyautogui_pynput_python.txt
Q: Django: save() vs update() to update the database? I'm writing a Django app, and I need a function to update a field in the database. Is there any reason to do one of these methods rather than the other? def save_db_field(name,field,value): obj = MyModel.objects.get(name=name) obj.field = value obj.sa...
Django: save() vs update() to update the database?
I'm writing a Django app, and I need a function to update a field in the database. Is there any reason to do one of these methods rather than the other? def save_db_field(name,field,value): obj = MyModel.objects.get(name=name) obj.field = value obj.save() def update_db_field(name,field,value): MyModel...
[ "There are several key differences.\nupdate is used on a queryset, so it is possible to update multiple objects at once.\nAs @FallenAngel pointed out, there are differences in how custom save() method triggers, but it is also important to keep in mind signals and ModelManagers. I have build a small testing app to s...
[ 67, 43, 13, 9, 6, 4, 0, 0, 0 ]
[]
[]
[ "database", "django", "django_models", "python", "python_3.x" ]
stackoverflow_0030449960_database_django_django_models_python_python_3.x.txt
Q: Needing help creating a function which returns true when n is divisible by 11 I'm currently working on a problem which requires me to return true if n is divisible by 11 without using the division or modulous operator. It's mentioned that if we add and subtract the digits alternatively and it adds up to be 0, -11 ...
Needing help creating a function which returns true when n is divisible by 11
I'm currently working on a problem which requires me to return true if n is divisible by 11 without using the division or modulous operator. It's mentioned that if we add and subtract the digits alternatively and it adds up to be 0, -11 or 11 it means that it is divisible by 11: Example1: 121 1 - 2 + 1 = 0 Example 2: 5...
[ "That happens because you're trying to slice an integer, not a list.\nYou can solve this problem by changing the integer to a list, and then try using slicing.\nThis can be done by the code below.\nlistNum = list(map(int, str(num)))\n\nuse this listNum instead of n in your code.\n", "You need to repeat the proces...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074330471_python.txt
Q: Read a CSV two rows at a time, combine values, write to new CSV How do I read an input CSV two rows at a time, combine some values into a new single row, and then write that row to a new CSV? In the input below I want to read two rows, take price1 from the second row and make it price2 in a new, combined, row, the...
Read a CSV two rows at a time, combine values, write to new CSV
How do I read an input CSV two rows at a time, combine some values into a new single row, and then write that row to a new CSV? In the input below I want to read two rows, take price1 from the second row and make it price2 in a new, combined, row, then repeat for the next two rows: input date, name, qt, price1 9/12/22,...
[ "cat price_old.csv \ndate,name,qt,price1\n9/12/22,AB,2,5.00\n9/12/22,AB,2,5.08\n9/12/22,BC,1,2.00\n9/12/22,BC,1,2.03 \n\nwith open(\"price_old.csv\") as old_csv:\n ...
[ 1, 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074323516_csv_python.txt
Q: Running Python script from a package... or not So I have this little script that I want to run: do_something.py from do_something import do_it do_it() Now this 'do_something' package has three files in it: do_something/__init__.py from .things_to_do import do_it do_something/things_to_do.py from .the_thing impo...
Running Python script from a package... or not
So I have this little script that I want to run: do_something.py from do_something import do_it do_it() Now this 'do_something' package has three files in it: do_something/__init__.py from .things_to_do import do_it do_something/things_to_do.py from .the_thing import the_thing def do_it(): print(f"Do it with {t...
[ "the correct solution is to use do_something.py and run python -m do_something, and have do_something.py directory on your PYTHONPATH or current directory.\nthe bad solution is to create a file do_something that has no extension next to your do_something.py and have the code inside do_something run your do_somethi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074330524_python.txt
Q: Python. How to replace everything in a string that is not in quotes how to replace everything in a string that is not in quotes python. The string has a replacement method, but how to make it so that when replacing, for example, 1 with 2, 1, which is in quotes, is not replaced I tried to do something like this wit...
Python. How to replace everything in a string that is not in quotes
how to replace everything in a string that is not in quotes python. The string has a replacement method, but how to make it so that when replacing, for example, 1 with 2, 1, which is in quotes, is not replaced I tried to do something like this with a for loop but it didn't work
[ "I just made this :\nsomeText = \" Some texte in quote 'The quote text' and other quote \"\nfinalText = \"\"\nsplitedText = someText.split(\"'\")\nfor idx, text in enumerate(splitedText):\n if not (idx % 2):\n text = text.replace(\"quote\", \"replace\") # replace your text here\n finalText += text\n\nI...
[ 0 ]
[]
[]
[ "python", "replace", "string" ]
stackoverflow_0074330474_python_replace_string.txt
Q: Can we detect whether a live udp stream packet contains a key frame or not? Is there a way to detect whether there is a key frame within a video packet or not? What I want do is I want to cut the live udp stream into seperate 30 second .ts files, and then concatenate the files including several other .ts file usin...
Can we detect whether a live udp stream packet contains a key frame or not?
Is there a way to detect whether there is a key frame within a video packet or not? What I want do is I want to cut the live udp stream into seperate 30 second .ts files, and then concatenate the files including several other .ts file using ffmpeg and restream to rtmp (youtube). I can achieve this but the only problem ...
[ "I love threefive. :)\nUse https://github.com/futzu/x9k3\ntell it to cut you 30 second segments like this:\nx9k3 -i udp://1.2.3.4:5678 -t 30 \n\nx9k3 speaks SCTE35 too.\n" ]
[ 0 ]
[]
[]
[ "ffmpeg", "python" ]
stackoverflow_0067497465_ffmpeg_python.txt
Q: Can anyone help me out with discount coupons in Django? Currently I am working on a E-Commerce Website, I Need to Implement these Offers on add to cart as the Products are being added, the Price should be discounted according to the Offer Provided. The Offers are as follows: Offer 1- Buy one get one free, Offer 2...
Can anyone help me out with discount coupons in Django?
Currently I am working on a E-Commerce Website, I Need to Implement these Offers on add to cart as the Products are being added, the Price should be discounted according to the Offer Provided. The Offers are as follows: Offer 1- Buy one get one free, Offer 2- 50% off on more than 2000 buy, Offer 3- 30% off on selectin...
[ "idk how are your models and what's exactly your problem but let's say price_all is a field in your cart model and count is how many products of one type are in cart.\nfor Offer 1 easily you can divide price(this is not price_all this field belongs to your product) into 2.or you can just double the count and I thin...
[ 0 ]
[]
[]
[ "discount", "django", "e_commerce", "python", "web_site_project" ]
stackoverflow_0074329942_discount_django_e_commerce_python_web_site_project.txt
Q: While grouping two columns into a new dataframe , how do I create another column in the new dataframe labeling where each value came from? See example I am currently using the following code to combine Col A and Col B to get Col A & B in DataFrame B below: out = (df .groupby('Col A', group_keys=False, sort=Fals...
While grouping two columns into a new dataframe , how do I create another column in the new dataframe labeling where each value came from? See example
I am currently using the following code to combine Col A and Col B to get Col A & B in DataFrame B below: out = (df .groupby('Col A', group_keys=False, sort=False) .apply(lambda d: d.iloc[:, ::-1].unstack().drop_duplicates()) .reset_index(drop=True).to_frame(name='Col A&B') ) My question is: how can I create ...
[ "You might want to use stack + drop_duplicates instead of groupby:\ndf.stack().reset_index(level=1).drop_duplicates().rename(columns={0: 'Col A & B', 'level_1': 'Col C'})\n\n Col C Col A & B\n0 Col A 100\n0 Col B 10\n1 Col B 20\n2 Col A 200\n2 Col B 30\n3 Col B ...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074330510_dataframe_pandas_python.txt
Q: How can I set a default value for an enum attribute of a recordclass dataobject? recordclass dataobjects can handle enum attributes just fine, unless you need to set a default value, which results in a SyntaxError (as of version 0.17.5): In [1]: from enum import Enum, auto In [2]: from recordclass import dataobj...
How can I set a default value for an enum attribute of a recordclass dataobject?
recordclass dataobjects can handle enum attributes just fine, unless you need to set a default value, which results in a SyntaxError (as of version 0.17.5): In [1]: from enum import Enum, auto In [2]: from recordclass import dataobject In [3]: class Color(Enum): ...: RED = auto() ...: In [4]: class Point...
[ "Assuming the example in the question is accurate, you'll need to override the stardand Enum.__repr__():\nclass Color(Enum):\n #\n def __repr__(self):\n return f'{self.__class__.__name__}.{self._name_}'\n #\n RED = auto()\n\n", "Since 0.18 one may use default value of any type.\nfrom recordclas...
[ 1, 1 ]
[]
[]
[ "enums", "python", "recordclass" ]
stackoverflow_0074060902_enums_python_recordclass.txt
Q: How to print only value in a sql statement? SQL statement prints key as well as value, only want value Trying to make a log in system, so have the code : datapassword = conn.execute("SELECT Password From NewUsers WHERE Username = ?", [username_login]).fetchall() but printing it gets me: [{'Password': '1'}] when i ...
How to print only value in a sql statement?
SQL statement prints key as well as value, only want value Trying to make a log in system, so have the code : datapassword = conn.execute("SELECT Password From NewUsers WHERE Username = ?", [username_login]).fetchall() but printing it gets me: [{'Password': '1'}] when i want it to just be '1' How can i do this?
[ "Usually you get a cursor instance from the connection and then you use that to execute your query, so I am not sure which library you are using. See How to create a Minimal, Reproducible Example.\ncursor = conn.cursor() # Get a cursor\n# Execute query and fetch all the rows:\nrows = cursor.select(\"SELECT Password...
[ 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0074329816_python_sql.txt
Q: include self relation data in query in django i have comment model and i want to include all child comment in list query. in this modal a comment can have parent comment class Comment(models.Model): user = models.ForeignKey( "accounts.CustomUser", on_delete=models.CASCADE) post = models.ForeignKey(...
include self relation data in query in django
i have comment model and i want to include all child comment in list query. in this modal a comment can have parent comment class Comment(models.Model): user = models.ForeignKey( "accounts.CustomUser", on_delete=models.CASCADE) post = models.ForeignKey(Blog, on_delete=models.CASCADE) body = models.T...
[ "Your precise use case could help but from what i understand there is two possibilties.\nEither you really want (or do not mind) a list of dict. In that case you want to take a look at DRF Serializers\nhttps://www.django-rest-framework.org/api-guide/serializers/\nclass CommentParentSerializer(serializers.Serializer...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074329606_django_python.txt
Q: tweepy not giving result when using time parameters I want to get data between two dates but when I use max_id it is not giving me any results. does someone have any solution to this. my code date1 = datetime.datetime.now() - datetime.timedelta(days=180) date1 = date1.strftime("%Y-%m-%d") date2 = date...
tweepy not giving result when using time parameters
I want to get data between two dates but when I use max_id it is not giving me any results. does someone have any solution to this. my code date1 = datetime.datetime.now() - datetime.timedelta(days=180) date1 = date1.strftime("%Y-%m-%d") date2 = datetime.datetime.now() - datetime.timedelta(days=90) dat...
[ "Quoting from Tweepy docs:\n\"Twitter’s standard search API only “searches against a sampling of recent Tweets published in the past 7 days.”\nIf you’re specifying an ID range beyond the past 7 days or there are no results from the past 7 days, then no results will be returned.\"\nA search into the last 90 days wou...
[ 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0074330558_python_tweepy_twitter.txt
Q: What is the correct way to resize an image in pygame? I have an image in pygame and my code detects if this image is clicked on. It worked fine and I decided to resize the image, but when I did that the image randomly disappeared. Here was the code before the image disappeared: import pygame pygame.init() width = ...
What is the correct way to resize an image in pygame?
I have an image in pygame and my code detects if this image is clicked on. It worked fine and I decided to resize the image, but when I did that the image randomly disappeared. Here was the code before the image disappeared: import pygame pygame.init() width = 500 height = 500 screen = pygame.display.set_mode((width, h...
[ "\nYou have to get the rectangle from the scaled iamge\n\npygame.Surface.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. A Surface is blit at a position on the screen. The position of the rectangle can be specified by a keyword...
[ 0 ]
[]
[]
[ "image", "image_resizing", "pygame", "python", "resize" ]
stackoverflow_0074330537_image_image_resizing_pygame_python_resize.txt
Q: Tkinter pass a button as argument I'm new to Tkinter and as my first project I wanted to create a Tic Tac Toe. I want to create 9 buttons, that will change their background image when I click on them, the problem is that I dont want to create a function for every single button but one function that will take the b...
Tkinter pass a button as argument
I'm new to Tkinter and as my first project I wanted to create a Tic Tac Toe. I want to create 9 buttons, that will change their background image when I click on them, the problem is that I dont want to create a function for every single button but one function that will take the button in argument and will change its b...
[ "One way you can do it is to separate the creation of the button from the assignment using the .config method.\nb1 = tk.Button(app, text=\"\", image=white)\nb1.config(command=lambda btn_id=b1: play(btn_id))\n\nThis is not really the best way to go about it, it's better to instead pass something that defines the but...
[ 1, 1, 0 ]
[]
[]
[ "button", "image", "python", "tkinter" ]
stackoverflow_0074328035_button_image_python_tkinter.txt
Q: SyntaxError: positional argument follows keyword argument in rokomari.com In the web scrapping in python, I face this problem. Please help me to solve my problem. I am totally new in python programming. How can I solve this problem easily A: You have a syntax error. It should be driver.find_element(By.XPATH, "yo...
SyntaxError: positional argument follows keyword argument in rokomari.com
In the web scrapping in python, I face this problem. Please help me to solve my problem. I am totally new in python programming. How can I solve this problem easily
[ "You have a syntax error.\nIt should be\ndriver.find_element(By.XPATH, \"your_xpath_expression\")\n\nIt should be a dot . after By, not a comma\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074330720_python_selenium_selenium_webdriver_web_scraping.txt
Q: Compare xml strings and list out difference in Python I've been looking around, and though there are several options, none of them really fit my current problem. I get two XML strings, str1 and str2 that have "User" nodes with childnodes detailing things like name, age, address, etc. From there I need to create a ...
Compare xml strings and list out difference in Python
I've been looking around, and though there are several options, none of them really fit my current problem. I get two XML strings, str1 and str2 that have "User" nodes with childnodes detailing things like name, age, address, etc. From there I need to create a third XML File3 that exclusively contains the fields that h...
[]
[]
[ "You can use ElementTree for this.\nParse both XML strings into ElementTree objects, use iter() to iterate over the user elements in both, and compare the text of each element:\nimport xml.etree.ElementTree as ET\n\ntree1 = ET.fromstring(str1)\ntree2 = ET.fromstring(str2)\n\nresult = ET.Element('users')\n\nfor user...
[ -1 ]
[ "bash", "python", "xml", "xmldiff" ]
stackoverflow_0074330759_bash_python_xml_xmldiff.txt
Q: Plotting a tangent plane in matplotlib using gradients Can anyone point me in the right direction? I'm not sure why I am getting an error that traces back to my grad function. When I remove the tangent plane surface, I will get the other surface just fine. A: Try this: z = lambda x, y : (-(x**2 + y**2)) ax.plot...
Plotting a tangent plane in matplotlib using gradients
Can anyone point me in the right direction? I'm not sure why I am getting an error that traces back to my grad function. When I remove the tangent plane surface, I will get the other surface just fine.
[ "Try this:\nz = lambda x, y : (-(x**2 + y**2))\nax.plot_surface(x, y, z(x, y), cmap = 'jet')\n\n...instead of:\nz = (-(x**2 + y**2))\nax.plot_surface(x, y, z, cmap = 'jet')\n\nThat gives me:\nresult\nYou are defining \"z\" as a Numpy array, calculated based on two other Numpy arrays \"x\" and \"y\". \"z\" is theref...
[ 0 ]
[]
[]
[ "calculus", "python" ]
stackoverflow_0074330243_calculus_python.txt
Q: How can I create a copy of a virtualenv in pyenv? I used pyenv to create a virtualenv and activate it, pyenv virtualenv myenv pyenv activate myenv then proceeded to perform a complicated and time-consuming installation of various Python packages in that virtual environment. Now I'd like to clone or duplicate or c...
How can I create a copy of a virtualenv in pyenv?
I used pyenv to create a virtualenv and activate it, pyenv virtualenv myenv pyenv activate myenv then proceeded to perform a complicated and time-consuming installation of various Python packages in that virtual environment. Now I'd like to clone or duplicate or copy this virtualenv somehow, so that I can deactivate m...
[ "When you create an environment in pyenv, it stores it in the directory $(pyenv root)/versions/ Where pyenv root is the installation area of pyenv. On Ubuntu 20.04 for me, it is /home/username/.pyenv.\nNow you can copy the env you want from the versions and give it a new name to have an exact copy of that env. So y...
[ 0 ]
[]
[]
[ "pyenv", "python" ]
stackoverflow_0074284116_pyenv_python.txt
Q: How to allocate a portion of numbers to an item, using RNG? So my following code sets the x a random number with the help of the randint from random library, and then i loop while is not a specific number and how many times until it finds it. from random import * x = randint(1, 1000) i = 1 while (x!=1): i = i+...
How to allocate a portion of numbers to an item, using RNG?
So my following code sets the x a random number with the help of the randint from random library, and then i loop while is not a specific number and how many times until it finds it. from random import * x = randint(1, 1000) i = 1 while (x!=1): i = i+1 x = randint(1, 1000) print(i) So what i want to do is havi...
[ "You can use the random.choices function with the weights argument.\nFor example:\nrandom.choices([\"Red\", \"White\"], weights=[10, 1])\nThis meaning Red will be more likely than White.\nNote that you can choose between the weights argument or the cum_weights argument.\n\nIf a weights sequence is specified, select...
[ 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074330719_python_random.txt
Q: Python: difference class with __init__ and class without it I'm learning how classes works and I got stuck on a thing which I can't explain, I also didn't find a solution on the Internet so here am I with my first question on StackOverflow. class Swords: damage = 5 Here is a class with only one line, with att...
Python: difference class with __init__ and class without it
I'm learning how classes works and I got stuck on a thing which I can't explain, I also didn't find a solution on the Internet so here am I with my first question on StackOverflow. class Swords: damage = 5 Here is a class with only one line, with attribute damage. Let's make an instance of the class: sharp_sword =...
[ "The way you've set this up, via some odd sequence you'll sort of get the result you expect either way, but it's mostly due to int being immutable.\nSo, let's look at a mutable type instead:\nclass Sword:\n pass\n\nclass Spear:\n pass\n\n# All players get a sword by default\nclass Items:\n weapons = [Sword()]\n ...
[ 2, 0, 0 ]
[]
[]
[ "class", "init", "instance", "python" ]
stackoverflow_0074330211_class_init_instance_python.txt
Q: Plot a binary timeline in matplotlib I'm trying to plot a binary timeline using matplotlib (I might be able to consider alternative libraries, though). Now, by "binary timeline" I mean the "display of chronological events, where the event space is made of two opposite events". An example of such an event space cou...
Plot a binary timeline in matplotlib
I'm trying to plot a binary timeline using matplotlib (I might be able to consider alternative libraries, though). Now, by "binary timeline" I mean the "display of chronological events, where the event space is made of two opposite events". An example of such an event space could be {no_one_in_the_team_is_sick, at_leas...
[ "You may use broken_barhto plot a binary timeline. \n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates\n\n#create a time series s with dates as index and 0 and 1 for events\ndates = pd.date_range(\"2017-04-01\",\"2017-06-15\", freq=\"D\")\nevents = np.random.random_...
[ 7, 2, 0 ]
[]
[]
[ "matplotlib", "plot", "python", "timeline" ]
stackoverflow_0044951911_matplotlib_plot_python_timeline.txt
Q: How to properly return a list from a pytest fixture for use in parametrize? I am attempting to build a little pytest test to ensure all expected keys exist in redis. I have a list of expected keys, that I am storing as a YML file. The test itself will query against redis to ensure each of the expected keys from th...
How to properly return a list from a pytest fixture for use in parametrize?
I am attempting to build a little pytest test to ensure all expected keys exist in redis. I have a list of expected keys, that I am storing as a YML file. The test itself will query against redis to ensure each of the expected keys from the list exists. Initially, I had this set up as a giant list in the test_keys.py f...
[ "In the same situation and the only way I found is to refuse the fixture and call the function directly.\ndef expected_keys_fixture():\n with open('expected_keys.yml', 'r') as f:\n return yaml.safe_load(f)['keys']\n\n\n@pytest.mark.parametrize(\"expected_key\",\n expected_keys_fixt...
[ 7, 0, 0 ]
[]
[]
[ "fixtures", "parametrized_testing", "pytest", "python" ]
stackoverflow_0056672179_fixtures_parametrized_testing_pytest_python.txt
Q: Tensorflow iterate over tensor with one dimension = None I am working on a custom keras layer in tensorflow, and I need to iterate over a tensor. The problem is the tensor has shape (None, ... , ..., ...). I am not sure how to iterate over this. I tried for i in range(len(x[:, 0, 0, 0])): and even tf.map_fn but b...
Tensorflow iterate over tensor with one dimension = None
I am working on a custom keras layer in tensorflow, and I need to iterate over a tensor. The problem is the tensor has shape (None, ... , ..., ...). I am not sure how to iterate over this. I tried for i in range(len(x[:, 0, 0, 0])): and even tf.map_fn but both would run an infinite number of times. How do I run iterat...
[ "I think adding more information would be helpful. What is the tensor? Your training data? tf.map_fn should still work but maybe you need to disable eager execution first like this:\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\n\n" ]
[ 1 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074330588_keras_python_tensorflow.txt
Q: ValueError: Missing staticfiles manifest entry for 'favicon.ico' I'm getting a ValueError when running python manage.py test. My project is named fellow_go, and I'm currently working on an App called pickup. Please note that this error is added in a relatively recent commit to Django: Fixed #24452 -- Fixed HashedF...
ValueError: Missing staticfiles manifest entry for 'favicon.ico'
I'm getting a ValueError when running python manage.py test. My project is named fellow_go, and I'm currently working on an App called pickup. Please note that this error is added in a relatively recent commit to Django: Fixed #24452 -- Fixed HashedFilesMixin correctness with nested paths.. ============================...
[ "Try running:\npython manage.py collectstatic\n\nDoes the test work now? If so, this might be the configuration causing a problem:\nSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\n\nas of whitenoise v4 this will fail and you should use:\nSTATICFILES_STORAGE = 'whitenoise.storage.Compressed...
[ 96, 41, 33, 32, 8, 5, 5, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "django_staticfiles", "django_views", "python", "static" ]
stackoverflow_0044160666_django_django_staticfiles_django_views_python_static.txt
Q: Counting identical elements running in a row The task is: there is a list of two different values, here 0 and 1(in a real problem, string values). You need to make a list of the number of zeros going in a row (something like a "combo" of zeros). So if data is: [0, 1, 1, 0, 0, 0, 1, 0, 0,] resul must be: [1, 3, 2] ...
Counting identical elements running in a row
The task is: there is a list of two different values, here 0 and 1(in a real problem, string values). You need to make a list of the number of zeros going in a row (something like a "combo" of zeros). So if data is: [0, 1, 1, 0, 0, 0, 1, 0, 0,] resul must be: [1, 3, 2] (the number of "combos" of zeros) My code using a ...
[ "Your function is pretty good as it runs in O(n) time complexity. That means your code scales linearly - the more items in a list, the longer it will take.\nSo from an algorithmic standpoint, I don't think there is anything to improve. Regarding the actual time it takes in python, I can't think of any built-in func...
[ 0 ]
[]
[]
[ "for_loop", "if_statement", "numpy", "performance", "python" ]
stackoverflow_0074330618_for_loop_if_statement_numpy_performance_python.txt
Q: Passing a prefetch dataset into a model I have the following data ([train][1] (518 MB), [test][2] (129MB)). I load them using tensorflow in the following manner:- import tensorflow as tf train_data = tf.data.experimental.make_csv_dataset("flight_2018_train.csv", batch_...
Passing a prefetch dataset into a model
I have the following data ([train][1] (518 MB), [test][2] (129MB)). I load them using tensorflow in the following manner:- import tensorflow as tf train_data = tf.data.experimental.make_csv_dataset("flight_2018_train.csv", batch_size = 10000, ...
[ "You need to define your input shape for the incoming data in the first layer. Since you have 16 inputs do this:\nsda_1 = tf.keras.Sequential([\n tf.keras.layers.Dense(64, activation=\"relu\", input_shape=(16,)),\n tf.keras.layers.Dense(64, activation=\"relu\"),\n tf.keras.layers.Dense(64, activation=\"rel...
[ 0 ]
[]
[]
[ "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074329793_python_tensorflow_tensorflow2.0.txt
Q: Decorators and a condition def telegram_notifier(func): def wrapper(): print("Notified by Telegram") func() return wrapper def facebook_notifier(func): def wrapper(): print("Notified by Facebook") func() return wrapper def email_notifier(func): def wr...
Decorators and a condition
def telegram_notifier(func): def wrapper(): print("Notified by Telegram") func() return wrapper def facebook_notifier(func): def wrapper(): print("Notified by Facebook") func() return wrapper def email_notifier(func): def wrapper(): print("Notified...
[]
[]
[ "https://stackoverflow.com/a/10724898/20408740\nmaybe this solution will work for you\ndef conditional_decorator(dec, condition):\ndef decorator(func):\n if not condition:\n # Return the function unchanged, not decorated.\n return func\n return dec(func)\nreturn decorator\n\n\n@conditional_decor...
[ -1 ]
[ "python" ]
stackoverflow_0074330936_python.txt
Q: Using Selenium with Python not working in google chrome i have code it opens website in chrome for this code but it does not go further from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome("C:\Drivers\chromedriver_win3...
Using Selenium with Python not working in google chrome
i have code it opens website in chrome for this code but it does not go further from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome("C:\Drivers\chromedriver_win32 (2)\chromedriver.exe") driver.get('https://opensource-demo...
[ "The way you are initializing your webdriver and selecting the input elements seem to be the problem.\nTry doing it this way instead.\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by im...
[ 0 ]
[]
[]
[ "google_chrome", "python", "selenium" ]
stackoverflow_0074330812_google_chrome_python_selenium.txt
Q: How can a turn a list of dicts into a struct field column in pyspark? So basically I have a column called "my_views". This column looks like this: id views 1 [{name=view1, id=0123-abc-4567}, {name=view2, id=9876-xyz-5432}] 2 [{name=view3, id=4589-adc-5467}, {name=view4, id=4476-add-5434}] 3 [{name=view5, id=69...
How can a turn a list of dicts into a struct field column in pyspark?
So basically I have a column called "my_views". This column looks like this: id views 1 [{name=view1, id=0123-abc-4567}, {name=view2, id=9876-xyz-5432}] 2 [{name=view3, id=4589-adc-5467}, {name=view4, id=4476-add-5434}] 3 [{name=view5, id=6987-fha-4997}, {name=view6, id=9161-asd-1199}] 4 [{name=view7, id=...
[ "The initial step in your case is to turn the content of views column into a valid JSON and then parse it using from_json method. I've added a UDF that for that, that captures all relevant sections of the views string and adds double quotes so that it parses nicely (excuse my parsing logic - it's a bit sloppy and i...
[ 2 ]
[]
[]
[ "dataframe", "pyspark", "python" ]
stackoverflow_0074323455_dataframe_pyspark_python.txt
Q: How to sum a numpy along the row axis by including only certain values per row according to variable length indices? For the following array: array = [ [1, 5, 6, 8, 10, 3], [3, 2, 4, 9, 11, 7], [8, 0, 9, 6, 23, 4] ] How could we sum the elements (per row) as indicated by these indices: indices = [ [2, 4, ...
How to sum a numpy along the row axis by including only certain values per row according to variable length indices?
For the following array: array = [ [1, 5, 6, 8, 10, 3], [3, 2, 4, 9, 11, 7], [8, 0, 9, 6, 23, 4] ] How could we sum the elements (per row) as indicated by these indices: indices = [ [2, 4, 5], [1, 3], [4] ] that is to say that: for the first row only the values on indices [2, 4, 5] will be considered whe...
[ "Try this:\narr = np.array(array)\nout = np.array([arr[idx, ind].sum() for idx, ind in enumerate(indices)])\nout\n\nOutput : array([19, 11, 23])\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074330965_numpy_python.txt
Q: Failed building wheel for bcrypt when running pip install flask-bcrypt I'm trying to run pip install flask-bcrypt for my flask application but i'm running into the following error =============================DEBUG ASSISTANCE============================= If you are seeing a compilation error, please try the follow...
Failed building wheel for bcrypt when running pip install flask-bcrypt
I'm trying to run pip install flask-bcrypt for my flask application but i'm running into the following error =============================DEBUG ASSISTANCE============================= If you are seeing a compilation error, please try the following steps to successfully install bcrypt: 1) Upgrade to the latest pip and t...
[ "The issue was caused by a lack of package management. I swapped from windows to ubuntu and created a virtual environment and the problem was resolved.\n" ]
[ 0 ]
[]
[]
[ "bcrypt", "python" ]
stackoverflow_0074214140_bcrypt_python.txt
Q: AttributeError: module 'tensorflow' has no attribute 'WholeFileReader' I have been trying to implement this piece of code and realized a lot has been deprecated and updated in TensorFlow V2. CODE filenames=['images/000001.jpg','images/000002.jpg','images/000003.jpg','images/000004.jpg'] labels=[1,0,1,0] filename_...
AttributeError: module 'tensorflow' has no attribute 'WholeFileReader'
I have been trying to implement this piece of code and realized a lot has been deprecated and updated in TensorFlow V2. CODE filenames=['images/000001.jpg','images/000002.jpg','images/000003.jpg','images/000004.jpg'] labels=[1,0,1,0] filename_queue=tf.train.string_input_producer(filenames) reader=tf.WholeFileReader()...
[ "You probably should be able to find it here:\ntf.io.WholeFileReader()\n\ninstead of\ntf.WholeFileReader()\n\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "filereader", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074322019_attributeerror_filereader_python_tensorflow_tensorflow2.0.txt
Q: How do I use an instance of a class in another file in another class? inside main.py file from Level_Class import Level from Player_Class import Player level = Level(level_map) inside Level_Class.py file class Level: def __init__(self, map): self.tile_list = [] for row_index, row in enumerat...
How do I use an instance of a class in another file in another class?
inside main.py file from Level_Class import Level from Player_Class import Player level = Level(level_map) inside Level_Class.py file class Level: def __init__(self, map): self.tile_list = [] for row_index, row in enumerate(map): for col_index, col in enumerate(row): #...
[ "Your Player_Class.py file imports level from main.py, which imports Player from Player_Class.py. That results in circular import. You have to carefully check your imports and (if you can't remove any) place some of them in nested scope (inside class functions or somewhere)\n" ]
[ 0 ]
[]
[]
[ "class", "import", "oop", "python" ]
stackoverflow_0074331055_class_import_oop_python.txt
Q: Input 0 of layer "sequential" is incompatible with the layer: ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 455, 30), found shape=(None, 30) completely new to ML, starting a beginner project, unsure why the shape has changed and what i can do to make the model load...
Input 0 of layer "sequential" is incompatible with the layer:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 455, 30), found shape=(None, 30) completely new to ML, starting a beginner project, unsure why the shape has changed and what i can do to make the model load. Here is my code for reference. import pandas as pd import numpy a...
[ "your input shape is wrong because you are giving the whole dataset as input shape. It should only be: input_shape= x_train[1].shape which is the 30 features you are giving the model. the 455 are the 455 train data points you have but the model only needs to know the feature shape.\n" ]
[ 0 ]
[]
[]
[ "keras", "machine_learning", "neural_network", "python", "tensorflow" ]
stackoverflow_0074321601_keras_machine_learning_neural_network_python_tensorflow.txt
Q: How to mock an AWS Lambda with moto I created a code to invoke a AWS lambda function created somewhere else. I would like to use moto for testing it, but I don't really understand how to do it and I continue to obtain errors. This is a simple example of the main code: import boto3 import json class SimpleLambda: ...
How to mock an AWS Lambda with moto
I created a code to invoke a AWS lambda function created somewhere else. I would like to use moto for testing it, but I don't really understand how to do it and I continue to obtain errors. This is a simple example of the main code: import boto3 import json class SimpleLambda: def __init__(self): self.aws...
[ "Moto also validates whether the IAM role exists, just like AWS does.\nSo make sure that the IAM role is created first:\nwith mock_iam():\n iam = boto3.client(\"iam\", region_name=\"eu-west-2\")\n iam_role = iam.create_role(\n RoleName=\"my-role\",\n AssumeRolePolicyDocument=\"some policy\",\n ...
[ 1 ]
[]
[]
[ "amazon_web_services", "boto3", "moto", "python" ]
stackoverflow_0074330844_amazon_web_services_boto3_moto_python.txt
Q: Web Scraping 'Advice to management" not printing from Glassdoor I'm new to python and web scraping. I have trouble printing the "advice to management" part in the review from Glassdoor. Everything else is printing expect for "advice to management". If you check below in the review we have 'advice to management' bu...
Web Scraping 'Advice to management" not printing from Glassdoor
I'm new to python and web scraping. I have trouble printing the "advice to management" part in the review from Glassdoor. Everything else is printing expect for "advice to management". If you check below in the review we have 'advice to management' but in the output it's not getting scrapped with the rest of the datapo...
[ "To get \"Advice to management\" you need to click on the link \"Continue reading\"\nTherefore, one of the possible solutions could be for example Selenium:\nimport csv\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074253197_beautifulsoup_html_python_web_scraping.txt
Q: How to set a wake up word for an virtual assistant using Vosk offline speech recognition (or any other fast offline speech recognizer) I want a fast offline speech recognizer (like vosk or sphinx) as a wake-up word for google speech recognition so it doesn't always hear what we say. Want wake up word for this: def...
How to set a wake up word for an virtual assistant using Vosk offline speech recognition (or any other fast offline speech recognizer)
I want a fast offline speech recognizer (like vosk or sphinx) as a wake-up word for google speech recognition so it doesn't always hear what we say. Want wake up word for this: def takeCommand(): # mic input r = sr.Recognizer() with sr.Microphone() as source: print("Hearing...") # r.pause_threshold = 1 r.c...
[ "Vosk should work well for a fast wake-up word. Choose a wake-up word/phrase that is covered by its language model and doesn't come up frequently in normal conversation. Then use the partial callback for it to return a low-latency match.\nYou can get a quick idea of how well it will work by just browsing to https:/...
[ 0 ]
[]
[]
[ "artificial_intelligence", "python", "speech_recognition", "vosk" ]
stackoverflow_0069173800_artificial_intelligence_python_speech_recognition_vosk.txt
Q: AttributeError: 'str' object has no attribute 'size' using PIL I was writing a script to convert an image into ASCII art however when I run this script the console outputs the error AttributeError: 'str' object has no attribute 'size' in my resize image function. The traceback is as follows: Traceback (most recent...
AttributeError: 'str' object has no attribute 'size' using PIL
I was writing a script to convert an image into ASCII art however when I run this script the console outputs the error AttributeError: 'str' object has no attribute 'size' in my resize image function. The traceback is as follows: Traceback (most recent call last): File "C:\Users\Alfie\Desktop\Python\ASCII MOVIE GENER...
[ "In your try-except block, you overwrite image (a str with the path to your file) with the result of PIL.Image.open (presumably not a str, but something with a size attribute).\nThe traceback shows you're trying to access the size attribute of a str, so what's happening is your except block is running - and then ex...
[ 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074331044_python_python_imaging_library.txt
Q: Python - Re-Order CSV columns to match DataFrame Assume I have a table/dataframe with the following columns: Now, I have a csv file that has values that can be added to this table, but not in the right order: Is there a way to order the columns in the csv to match the format of the Table/Dataframe? (Assume this ...
Python - Re-Order CSV columns to match DataFrame
Assume I have a table/dataframe with the following columns: Now, I have a csv file that has values that can be added to this table, but not in the right order: Is there a way to order the columns in the csv to match the format of the Table/Dataframe? (Assume this applies for many columns/rows of data.)
[ "Assuming both dataframes have the same columns, you can just read the csv file and try this:\ndf2 = df2[df1.columns]\n\nOr:\ndf2 = df2.reindex(df1.columns, axis=1)\n\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074330643_apache_spark_csv_dataframe_pandas_python.txt
Q: How to write Pyspark DataFrame to XML Format? I'm working on a Glue ETL Job that basically reads a dataframe in Pyspark and should output data in XML Format. I've searched a lot for the solution and the code fails at the particular write statement shown below: df.write.format('com.databricks.spark.xml').options(ro...
How to write Pyspark DataFrame to XML Format?
I'm working on a Glue ETL Job that basically reads a dataframe in Pyspark and should output data in XML Format. I've searched a lot for the solution and the code fails at the particular write statement shown below: df.write.format('com.databricks.spark.xml').options(rowTag='book', rootTag='books').save('newbooks.xml') ...
[ "First see what is the Scala version for your Spark.\nif it is 2.11 then go with spark-xml_2.11-0.7.0\nor if it is 2.12 then go with spark-xml_2.12-0.14.0 likewise the rest.\nnow spark-xml have the dependencies with the other jars as well. Try to use that as well with your spark-xml jar.\n\ncommons-io version - 2.1...
[ 2 ]
[]
[]
[ "apache_spark", "apache_spark_xml", "aws_glue", "pyspark", "python" ]
stackoverflow_0071795402_apache_spark_apache_spark_xml_aws_glue_pyspark_python.txt
Q: Python | Nested loops | Sum of Sublists My goal with this is to generate the sum of each sublist separately using nested loops This is my list called sales_data sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]] The sublist can be represented by any variable but for the purpose of this exercise, we will call it...
Python | Nested loops | Sum of Sublists
My goal with this is to generate the sum of each sublist separately using nested loops This is my list called sales_data sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]] The sublist can be represented by any variable but for the purpose of this exercise, we will call it scoops_sold, which I have set to 0 scoops_so...
[ "You can easily solve it using sum():\nprint(list(map(sum, sales_data)))\n\nIf you insist on loops:\nsums = []\nfor location in sales_data:\n sold = 0\n for element in location:\n sold += element\n sums.append(sold)\nprint(sums)\n\n", "How about\n[sum(sub_list) for sub_list in sales_data]\n# [51, 15, 30]\n\...
[ 0, 0, 0 ]
[ "sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]\nscoops_sold = 0\n\nfor location in sales_data:\n print(location)\n for element in location:\n scoops_sold += element\n\nprint(scoops_sold)\n\n" ]
[ -1 ]
[ "nested_loops", "python", "sum" ]
stackoverflow_0072282717_nested_loops_python_sum.txt
Q: Can't set colors in quiver matplotlib with strings I am trying to plot with quiver (matplotlib). My arrows indicates correlation, so I would like to change its colors according to pvalue. When I create an np.ndarray with strings ("w" or "k") that indicates the colors of each arrow, I get this error: ufunc 'isfini...
Can't set colors in quiver matplotlib with strings
I am trying to plot with quiver (matplotlib). My arrows indicates correlation, so I would like to change its colors according to pvalue. When I create an np.ndarray with strings ("w" or "k") that indicates the colors of each arrow, I get this error: ufunc 'isfinite' not supported for the input types, and the inputs co...
[ "\nDon't worry, let Matplotlib do their stuff, it knows how to color the arrows in a quiver plot according to another parameter.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN=50\n# the positions, random points in 0,1; 0,1.\nx = np.random.rand(N)\ny = np.random.rand(N)\n\n# random directions, 0.025 = 0.5...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074329545_matplotlib_python.txt
Q: Why is this way of plotting colourful lines so slow? I'm playing around with recursive fractals in Python and wanted to add some colour. However, the code that I wrote to make the curve display with a gradient of colour makes the program run much slower than without it. I'm not sure why and I'm still pretty new to...
Why is this way of plotting colourful lines so slow?
I'm playing around with recursive fractals in Python and wanted to add some colour. However, the code that I wrote to make the curve display with a gradient of colour makes the program run much slower than without it. I'm not sure why and I'm still pretty new to Python, so I would appreciate any tips to improve my code...
[ "It is slow because you are plotting 2345 different lines.\nTo improve performance, you should use matplotlib's LineCollection which allows to create a gradient-colored line. Think of it as a collection of segments (conceptually, this is very similar to what you did in your code).\nTo assign a color to each segment...
[ 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "python" ]
stackoverflow_0074327055_jupyter_notebook_matplotlib_python.txt
Q: Print nested list as a matrix i have a list which i need to print as a matrix! nestedList = [[1,2,3],[4,5,6],[7,8,9]] **i want the output to be** [1,2,3] [4,5,6] [7,8,9] A: That will do a thing (although there is clearly no explanation why you need this) "[" + "\n".join(str(i) for i in [[1,2,3]...
Print nested list as a matrix
i have a list which i need to print as a matrix! nestedList = [[1,2,3],[4,5,6],[7,8,9]] **i want the output to be** [1,2,3] [4,5,6] [7,8,9]
[ "That will do a thing (although there is clearly no explanation why you need this)\n\"[\" + \"\\n\".join(str(i) for i in [[1,2,3],[4,5,6],[7,8,9]]) + \"]\"\n\n" ]
[ 0 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0074331202_nested_lists_python.txt
Q: create uniform distribution over a specific sequence with noise what is the best way to draw samples x that have this distribution with size n? if it was uniformly c = [0.5,0.6,0,0,0.4,0,0.2,0.2,0.1,0.1,0.1] with n = 11 in case I want to increase the noise could of use this np.random.rand(n)? A: numpy.random.un...
create uniform distribution over a specific sequence with noise
what is the best way to draw samples x that have this distribution with size n? if it was uniformly c = [0.5,0.6,0,0,0.4,0,0.2,0.2,0.1,0.1,0.1] with n = 11 in case I want to increase the noise could of use this np.random.rand(n)?
[ "numpy.random.uniform will let you generate \"n\" unformly distributed samples between a given \"low\" and \"high\" limit.\nFor example:\nimport numpy as np\n\nlower_limit = 3\nupper_limit = 7\nnumber_of_samples = 11\n\nc = np.random.uniform(lower_limit, upper_limit, number_of_samples)\n\nprint (c)\n\nproduces:\n[6...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074331187_numpy_python.txt
Q: asyncio: pass object trough loops and threads python i'm just learning asyncio and threads, so if someting is wrong, sorry this is my code: async def callback_onlyAlert(update: Update, context): await update.message.reply_text('Ok! \nI will send you a message only when you can withdraw your USDN') #run ale...
asyncio: pass object trough loops and threads python
i'm just learning asyncio and threads, so if someting is wrong, sorry this is my code: async def callback_onlyAlert(update: Update, context): await update.message.reply_text('Ok! \nI will send you a message only when you can withdraw your USDN') #run alert t = threading.Thread(target=middleware_alert, args...
[ "Passing objects through loops and threads\nBoth thread and async functions share objects if you use Lock properly.\nI am not sure about the rest part of your code, but it seems you're trying to have a loop per thread which is not possible. But if you really was trying to have multiple event loops for some reason, ...
[ 1, 1 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074329829_python_python_asyncio.txt
Q: "NULL" instead of null values in PySpark I have a dataframe df, but because 3 of its columns that should normally be "double" have values like "NULL", the automatic type is cast as string. df = col_0 col_1 col_2 col_3 Word 73452 3859.0 4734.0000000 Word1 23452 3859.0 ...
"NULL" instead of null values in PySpark
I have a dataframe df, but because 3 of its columns that should normally be "double" have values like "NULL", the automatic type is cast as string. df = col_0 col_1 col_2 col_3 Word 73452 3859.0 4734.0000000 Word1 23452 3859.0 NULL Word2 73452 NULL ...
[ "You can try and replacing the strings with value NULL with the Python's None type and then casting to correct types, like this:\ndf = spark.createDataFrame([(\"Word1\", 23452, 3859.0, \"NULL\"), (\"Word2\", 73452, \"NULL\", 4758.0000000)], \"col_0: string, col_1: int, col_2: string, col_3: string\")\nprint(df.dtyp...
[ 1 ]
[]
[]
[ "dataframe", "double", "pyspark", "python", "string" ]
stackoverflow_0074318089_dataframe_double_pyspark_python_string.txt
Q: ValueError: could not convert string to float - Mutual Information I have a data base with categorical values, and i'm trying to use the feature selection based on mutual information. And just in the beggining i'm getting this error: ValueError: could not convert string to float: 'Mr. Michael Hall' ` This was wha...
ValueError: could not convert string to float - Mutual Information
I have a data base with categorical values, and i'm trying to use the feature selection based on mutual information. And just in the beggining i'm getting this error: ValueError: could not convert string to float: 'Mr. Michael Hall' ` This was what I am trying to do: from sklearn.feature_selection import mutual_info_...
[ "\ncould not convert string to float\n\nYou are getting this error because it expects a float data type.\nFloat data type contains value like 1.00,2.21,3.14,1234.42132,12413.1241413... and so on.\nData which you are passing is of type string.\nTo get mutual information you need to pass float data type instead of st...
[ 0 ]
[]
[]
[ "feature_selection", "mutual_information", "python" ]
stackoverflow_0074331205_feature_selection_mutual_information_python.txt
Q: How can I print the input values in between a line? name = input(enter name) age = input(age) print(“My name is print(name). I’m print(age) years old.”) Nobbie experiment. Beginner level task. And the above query came to my mind. A: name = input("enter name: ") age = input("age: ") print(f"My name is {name}. I...
How can I print the input values in between a line?
name = input(enter name) age = input(age) print(“My name is print(name). I’m print(age) years old.”) Nobbie experiment. Beginner level task. And the above query came to my mind.
[ "name = input(\"enter name: \")\nage = input(\"age: \")\nprint(f\"My name is {name}. I am {age} years old\")\n\n", "Study and try to understand Keshav V. answer using f-strings, this is the \"modern\" approach and will serve you well time after after time.\nA more long handed approach would be to rewrite your pro...
[ 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "input", "python", "variables" ]
stackoverflow_0074331141_input_python_variables.txt
Q: How to select a tags and scrape href value? I'm having trouble getting hyperlinks for tennis matches listed on a webpage, how do I go about fixing the code below so that it can obtain it through print? To note: I'm applying this code in Visual Studio 2022. import requests from bs4 import BeautifulSoup res...
How to select a tags and scrape href value?
I'm having trouble getting hyperlinks for tennis matches listed on a webpage, how do I go about fixing the code below so that it can obtain it through print? To note: I'm applying this code in Visual Studio 2022. import requests from bs4 import BeautifulSoup response = requests.get("https://www.betexplorer.com...
[ "Change the last line to\nprint([a['href'] for a in soup.findAll('a')])\n\nSee a full tutorial here: https://pythonprogramminglanguage.com/get-links-from-webpage/\n", "In newer code avoid old syntax findAll() instead use find_all() or select() with css selectors - For more take a minute to check docs\nSelect your...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "hyperlink", "python", "web_scraping" ]
stackoverflow_0074331146_beautifulsoup_hyperlink_python_web_scraping.txt
Q: How to simulate human keyboard input of a long text using Python? I would like to simulate typing of huge text. I've tried to use pyautogui to do that, but I't didn't worked properly since the computer was not detecting the keys being pressed: pyautogui.typewrite('I love python! It is such an amazing language.') ...
How to simulate human keyboard input of a long text using Python?
I would like to simulate typing of huge text. I've tried to use pyautogui to do that, but I't didn't worked properly since the computer was not detecting the keys being pressed: pyautogui.typewrite('I love python! It is such an amazing language.') I couldn't think of another way to do that than using pynput.keyboard l...
[ "You can simply use the python keyboard module.\nimport keyboard as kbd # importing keyboard module\nimport time\nstring = \"I love python! It is such an amazing language.\"\ntime.sleep(3) # 3 second gap to avoid unwanted actions\nkbd.write(string, 0.1) # 0.1 second typewrite effect\n\nYou can omit lines 2 and 4. I...
[ 2, 1 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0074322676_pyautogui_python.txt
Q: Count minimum time to finish the given tasks I have an array of tasks [begin, end, period]. Each task needs to be completed within the time range from begin to end, and the period is the length of time required to finish the task. The period can be discontinuous time The begin and end are included We can handle a...
Count minimum time to finish the given tasks
I have an array of tasks [begin, end, period]. Each task needs to be completed within the time range from begin to end, and the period is the length of time required to finish the task. The period can be discontinuous time The begin and end are included We can handle an unlimited number of tasks at the same time. Fin...
[ "you can find the sweepline solution code below\nhttps://leetcode.com/discuss/interview-question/2770147/an-interesting-oa-question-expedia/1671632\nlogic\nwe split the starting and ending pts for each task, and sort them by time.\nwhen we meet a starting pt, we store when it starts and how many time it needs.\nwhe...
[ 2 ]
[ "I think you're over-complicating this. I think the following solution is enough:\nint process(List<Integer> list) {\n Set<Integer> s = new HashSet<>();\n for(List<Integer> p : list) {\n int period = p.get(p.size()-1);\n int s = p.get(0);\n int e = p.get(1);\n for(int i=s; i<=e; i+...
[ -1 ]
[ "algorithm", "java", "python" ]
stackoverflow_0074304267_algorithm_java_python.txt
Q: Cannot find xpath element to click with webdriver I'm using the https://www.perlego.com/ website to do some scraping for books, my current problem is that i'm trying to search using the isbn Number of the book so the webdriver gets this following page for example https://www.perlego.com/search?query=9780717183241 ...
Cannot find xpath element to click with webdriver
I'm using the https://www.perlego.com/ website to do some scraping for books, my current problem is that i'm trying to search using the isbn Number of the book so the webdriver gets this following page for example https://www.perlego.com/search?query=9780717183241 However, using page inspection on the website, i cannot...
[ "The following code closes the cookies banner and clicks on the book link and opens it\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.commo...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "webdriver" ]
stackoverflow_0074331374_python_selenium_selenium_webdriver_web_scraping_webdriver.txt
Q: Is there a way to read lines from a csv file split it and sort each row alphabetically then store it as a new CSV file? This is a sample of the CSV file I have : {'coffee', 'poultry', 'juice', 'dishwashing liquid'} {'aluminum foil', 'poultry', 'pasta', 'dinner rolls', 'dinner rolls'} Each row corresponds to a per...
Is there a way to read lines from a csv file split it and sort each row alphabetically then store it as a new CSV file?
This is a sample of the CSV file I have : {'coffee', 'poultry', 'juice', 'dishwashing liquid'} {'aluminum foil', 'poultry', 'pasta', 'dinner rolls', 'dinner rolls'} Each row corresponds to a person's shopping cart. There are no headers and no other information. and I tried this : with open("dataset_three.csv", "rt") a...
[]
[]
[ "Use strip('{}\\n') to remove leading/trailing braces and '\\n' combine with literal_eval to safely evaluate string literal to tuple. From there, use sorted() to sort and ','.join() to join the tuple back to string. Also, add '\\n' back to end of the line when writting to a new file:\nfrom ast import literal_eval\n...
[ -1 ]
[ "python" ]
stackoverflow_0074330111_python.txt
Q: String index out of range when reading data For this problem, I have a separate txt file which contains a list of values down below: Years+1900 Populationx106 0 1650 10 1750 20 1860 30 2070 40 2300 50 2560 60 3040 70 3710 80 4450 90 5280 100 6080 110 6870 For the problem I'm working on, I'm supposed to obtain...
String index out of range when reading data
For this problem, I have a separate txt file which contains a list of values down below: Years+1900 Populationx106 0 1650 10 1750 20 1860 30 2070 40 2300 50 2560 60 3040 70 3710 80 4450 90 5280 100 6080 110 6870 For the problem I'm working on, I'm supposed to obtain that file and path name to then use to do calcul...
[ "Let's assume you are correct and passing the first line of your text file to your function is breaking it.\nYou can \"throw away\" the first line of the text file by reading it as a single line (but doing nothing with it) and then reading the data you actually want like this..\ndef get_data(path,name):\n with ope...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074331139_python.txt
Q: not equal to returning the incorrect result for a project im working on im checking if a user inputted string is one of 4 strings, it checks if the user inputed one of these 4 strings if not it asks the user again. although when i try to run it, if i enter str1 or any of the other ones it doesnt end the loop. exam...
not equal to returning the incorrect result
for a project im working on im checking if a user inputted string is one of 4 strings, it checks if the user inputed one of these 4 strings if not it asks the user again. although when i try to run it, if i enter str1 or any of the other ones it doesnt end the loop. example = input('enter string') while example != 'str...
[ "You're really looking for the opposite of example == 'str1' or example == 'str2' or example == 'str3' or example == 'str4', which is example != 'str1' and example != 'str2' and example != 'str3' and example != 'str4', because of De Morgan's laws which are very useful to know for a programmer.\nIn your code, if exa...
[ 2, 1, 0 ]
[ "Simply replace or by and everywhere (in your 1st snippet).\nYou could simplify the code by :\n\nusing the in keyword\nset example to None before entering the loop\n\nexample = None\nwhile example not in ('str1', 'str2', 'str3', 'str4'):\n example = input('enter string')\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074328020_python.txt
Q: Calculating neighbor-distances for all grid points in NumPy Imagine a 3-dimensional grid in space, where each grid point has a binary value. The values of the grid points are represented by a 3d numpy array. For each grid point that has a value of 1, we want to know where the nearest 0-valued point is located, in ...
Calculating neighbor-distances for all grid points in NumPy
Imagine a 3-dimensional grid in space, where each grid point has a binary value. The values of the grid points are represented by a 3d numpy array. For each grid point that has a value of 1, we want to know where the nearest 0-valued point is located, in 14 different directions (±x, ±y, ±z, and 8 diagonals). That means...
[ "Here's a way that should work for all the non-diagonal cases. The example is just in 1d, but should work along each axis in 3d. This just computes the distance to the nearest 0 to the left:\na = np.array([0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1])\nn = len(a)\nzero_index = np.arange(0, n) * (1 - a)\none_index = np....
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074330383_arrays_numpy_python.txt
Q: Decorator returning object after running method I just started learning OOP in Python and came across interesting problem. In short, it's about running a method in the same line as object is initialised - the proposed solution was to return object after each method which we need to "oneline" that way. My question ...
Decorator returning object after running method
I just started learning OOP in Python and came across interesting problem. In short, it's about running a method in the same line as object is initialised - the proposed solution was to return object after each method which we need to "oneline" that way. My question is, is there a way to create decorator which will do ...
[ "Thanks to @Barmar pointing out that self is always first argument passed to function (hence, also decorator), I was able to come up with properly working decorator code:\ndef Returning(func):\n\n @functools.wraps(func)\n def wrapper_func(*args, **kwargs):\n func(*args, **kwargs)\n return args[0...
[ 0 ]
[]
[]
[ "python", "python_decorators" ]
stackoverflow_0074331155_python_python_decorators.txt
Q: How to verify if a pixel is above another What is the best way to know the amount of white pixels that are anove the red areas using python and OpenCV? I imagine drawing a straight vertical line from each white pixel to height Y = 512 might be one of the ways, but I have no idea how to make that happen A: If I ...
How to verify if a pixel is above another
What is the best way to know the amount of white pixels that are anove the red areas using python and OpenCV? I imagine drawing a straight vertical line from each white pixel to height Y = 512 might be one of the ways, but I have no idea how to make that happen
[ "If I understood it well, what you want is to, for every white pixel (even those in the same x coordinate) cast a ray downwards and count how many of them intersects those red lake thingy, right?\nIf so, only numpy should be enough. Imagine applying gravity to white pixels, making them fall to the ground and counti...
[ 1, 1 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074330458_image_processing_opencv_python.txt
Q: Unable to select the correct div from a webpage I am trying to parse song titles from a website, but can't figure out how to grab the specific div that has them. I've tried about a dozen different methods but always get back an empty list. If you go to the url and inspect one of the youtube videos there, you will...
Unable to select the correct div from a webpage
I am trying to parse song titles from a website, but can't figure out how to grab the specific div that has them. I've tried about a dozen different methods but always get back an empty list. If you go to the url and inspect one of the youtube videos there, you will find a div with a class of single-post-oembed-youtub...
[ "Please try this:\nsoup = BeautifulSoup(browser.page_source, 'html.parser')\ntitles = soup.find_all(\".single-post-oembed-youtube-wrapper+div p strong\")\n\nThis will give you all the titles there\n", "You can also try to retrieve the data directly from the HTML source, thus avoiding Selenium.\nimport requests\nf...
[ 3, 2, 2 ]
[]
[]
[ "beautifulsoup", "css_selectors", "python", "selenium" ]
stackoverflow_0074331208_beautifulsoup_css_selectors_python_selenium.txt
Q: Client.__init__() missing 1 required keyword-only argument: 'intents' I was trying to make a quick bot for discord and I used this code: import discord from discord.ui import button, view from discord.ext import commands client = discord.Client() @client.event async def on_ready(): print('Autenticazione rius...
Client.__init__() missing 1 required keyword-only argument: 'intents'
I was trying to make a quick bot for discord and I used this code: import discord from discord.ui import button, view from discord.ext import commands client = discord.Client() @client.event async def on_ready(): print('Autenticazione riuscita. {0.user} è online!'.format(client)) But this error pops up: Client._...
[ "You could use the default Intents unless you have a particular one to specify\nclient = discord.Client(intents=discord.Intents.default())\n\nSee Intents for more details\n", "client = discord.Client(intents=discord.Intents.default())\n\nI tried this but I'm still having the same error, I even tried\nbot = comman...
[ 18, 3, 1, 0, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0071959420_discord.py_python.txt
Q: Python not working when using pass in loop I am making simple program that adds a piece of text to every file in the folder however this code is also adding text to my python file so I made a if statement that stops this from happening. But now the script does not work at all. import os def main(): for file i...
Python not working when using pass in loop
I am making simple program that adds a piece of text to every file in the folder however this code is also adding text to my python file so I made a if statement that stops this from happening. But now the script does not work at all. import os def main(): for file in os.listdir(): if file == 'main.py' or ...
[ "this setup works for me:\nmain.py\nimport os\n\ndef main():\n for file in os.listdir():\n if file == 'main.py':\n pass\n else:\n with open(file, 'a') as file:\n try:\n file.write(\"hello\")\n print(\"sucess\")\n ...
[ 0 ]
[]
[]
[ "file", "for_loop", "python", "python_3.x" ]
stackoverflow_0074331527_file_for_loop_python_python_3.x.txt
Q: Ordering 5 inputted dates chronologically I need to take 5 inputted dates in the format "january 1" and order them chronologically. one = input('birthday 1: ') two = input('birthday 2: ') three = input('birthday 3: ') four = input('birthday 4: ') five = input('birthday 5: ') months=['january', 'february', 'march',...
Ordering 5 inputted dates chronologically
I need to take 5 inputted dates in the format "january 1" and order them chronologically. one = input('birthday 1: ') two = input('birthday 2: ') three = input('birthday 3: ') four = input('birthday 4: ') five = input('birthday 5: ') months=['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'sep...
[ "I suggest you rely on Python's buitin \"datetime\" module. The following code should do what you want above, with a lot less effort:\nfrom datetime import datetime \none = input('birthday 1: ')\ntwo = input('birthday 2: ')\nthree = input('birthday 3: ')\nfour = input('birthday 4: ')\nfive = input('birthday 5: '...
[ 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0074331425_date_python.txt
Q: Multiple keywords return multiple seperate index arrays I have a very large matrix (70k x 700k) with numeric values, is the column name for the matrix. I want to be able to calculate the row average fo each keyword. For example, below will calculate only for keyword 'Heart'. names = ["heart", "braininjured", "hea...
Multiple keywords return multiple seperate index arrays
I have a very large matrix (70k x 700k) with numeric values, is the column name for the matrix. I want to be able to calculate the row average fo each keyword. For example, below will calculate only for keyword 'Heart'. names = ["heart", "braininjured", "heartarmleg"] matrix = [[1, 2, 3], [4, 5, 6], ...
[ "Here's my code:\nnames = [\"heart\", \"braininjured\", \"heartarmleg\"]\nnames_dict = {name: i for i, name in enumerate(names)}\n\nprint(names_dict) # for testing\n\nmatrix = [[1, 2, 3], \n [4, 5, 6], \n [7, 8, 9]]\n\nkeywords = [\"Heart\", \"Brain\", \"Arm\"]\n\nindices = { kw:{names_dict[name] ...
[ 1 ]
[]
[]
[ "arrays", "matrix", "performance", "processing_efficiency", "python" ]
stackoverflow_0074331251_arrays_matrix_performance_processing_efficiency_python.txt
Q: Error in python Flask-Mail, I have KeyError MAIL_DEFAULT_SENDER or other ` import re import os from flask import Flask, request, render_template, current_app from flask_mail import Mail, Message app = Flask(__name__) app.config['MAIL_DEFAULT_SENDER'] = os.environ['MAIL_DEFAULT_SENDER'] app.config["MAIL_PASSWORD"...
Error in python Flask-Mail, I have KeyError MAIL_DEFAULT_SENDER or other
` import re import os from flask import Flask, request, render_template, current_app from flask_mail import Mail, Message app = Flask(__name__) app.config['MAIL_DEFAULT_SENDER'] = os.environ['MAIL_DEFAULT_SENDER'] app.config["MAIL_PASSWORD"] = os.environ["MAIL_PASSWORD"] app.config["MAIL_PORT"] = 587 app.config["MAIL...
[ "If the environment MAIL_DEFAULT_SENDER does not exist then you will get a KeyError when running os.environ['MAIL_DEFAULT_SENDER']. I think that is what is happening here.\nA solution for this may be to use os.environ.get(). Here is how you might do this\napp.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEF...
[ 0, 0 ]
[]
[]
[ "flask", "flask_mail", "python" ]
stackoverflow_0074331366_flask_flask_mail_python.txt
Q: How to plot Mann-Whitney U test (Wilcoxon rank sum test) based on a column in dataframe? I want to plot the Mann-Whitney U test (Wilcoxon rank sum test) based on the subtype column, which contains normal, KIRP, KIRC, KICH data. I'm new to using Python for statistics. import pandas as pd import plotly.express as px...
How to plot Mann-Whitney U test (Wilcoxon rank sum test) based on a column in dataframe?
I want to plot the Mann-Whitney U test (Wilcoxon rank sum test) based on the subtype column, which contains normal, KIRP, KIRC, KICH data. I'm new to using Python for statistics. import pandas as pd import plotly.express as px from scipy.stats import mannwhitneyu normal = df.iloc[:,7:-2][df['subtype'] == "normal"] ki...
[ "The mannwhitneyu method takes 2 arrays of samples. You get the error because the third parameter of the fuction (use_continuity) can be True or False. If you want to compare kirp, kirc and kich to the normal samples, you can do so as follows:\nu_kirp, p_kirp = mannwhitneyu(normal, kirp, method=\"exact\")\nu_kirc, ...
[ 0 ]
[]
[]
[ "python", "scipy", "statistics" ]
stackoverflow_0074331424_python_scipy_statistics.txt
Q: Using huggingface transformers trainer method for hugging face datasets I am trying to train a transformer(Salesforce codet5-small) using the huggingface trainer method and on a hugging face Dataset (namely, "eth_py150_open"). However, I'm encountering a number of issues. Here is the relevant code snippet: import ...
Using huggingface transformers trainer method for hugging face datasets
I am trying to train a transformer(Salesforce codet5-small) using the huggingface trainer method and on a hugging face Dataset (namely, "eth_py150_open"). However, I'm encountering a number of issues. Here is the relevant code snippet: import torch import transformers from datasets import load_dataset_builder from data...
[ "You need to tokenize the dataset before you can pass it to the model. Below I have added a preprocess() function to tokenize. You'll also need a data_collator to collate the tokenized sequences. Since T5 is a seq2seq model I am guessing you are trying to generate the license string hence I have replaced Trainer wi...
[ 0 ]
[]
[]
[ "huggingface", "huggingface_transformers", "nlp", "python", "transformer_model" ]
stackoverflow_0074223324_huggingface_huggingface_transformers_nlp_python_transformer_model.txt
Q: Example of update_item in dynamodb boto3 Following the documentation, I'm trying to create an update statement that will update or add if not exists only one attribute in a dynamodb table. I'm trying this response = table.update_item( Key={'ReleaseNumber': '1.0.179'}, UpdateExpression='SET', ConditionE...
Example of update_item in dynamodb boto3
Following the documentation, I'm trying to create an update statement that will update or add if not exists only one attribute in a dynamodb table. I'm trying this response = table.update_item( Key={'ReleaseNumber': '1.0.179'}, UpdateExpression='SET', ConditionExpression='Attr(\'ReleaseNumber\').eq(\'1.0.17...
[ "Found working example here, very important to list as Keys all the indexes of the table, this will require additional query before update, but it works.\nresponse = table.update_item(\n Key={\n 'ReleaseNumber': releaseNumber,\n 'Timestamp': result[0]['Timestamp']\n },\n UpdateExpression=\"se...
[ 76, 41, 26, 21, 4, 1, 1, 0 ]
[ "using previous answer from eltbus , it worked for me , except for minor bug,\nYou have to delete the extra comma using update_expression[:-1]\n" ]
[ -1 ]
[ "amazon_dynamodb", "boto3", "botocore", "python" ]
stackoverflow_0034447304_amazon_dynamodb_boto3_botocore_python.txt
Q: Having an issue with CSV file not creating chars = list(range(0,10)) numbers_list = list(range(0,25)) for comb in itertools.combinations_with_replacement(chars, 5): for A in numbers_list: pure = str(A) + ':' + str(comb) B = pure.replace(")", "").replace("(", "").replace("'", "")....
Having an issue with CSV file not creating
chars = list(range(0,10)) numbers_list = list(range(0,25)) for comb in itertools.combinations_with_replacement(chars, 5): for A in numbers_list: pure = str(A) + ':' + str(comb) B = pure.replace(")", "").replace("(", "").replace("'", "").replace(",", "").replace(" ", "") C...
[ "John Gordon is correct, you need to retain each row in a list, then loop through that list when writing each row to the csv file\nthis script works for me\nimport itertools, hashlib, csv\n\ndata = []\nchars = list(range(0,10)) \nnumbers_list = list(range(0,25))\nfor comb in itertools.combinations_with_replacement(...
[ 1, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074331438_csv_python.txt
Q: BeautifulSoup extract desired information in custome-made list from different html snippets Apologies in advance for such a long and basic question! Given the following three html snippets which are part of a bigger part as follows: <html> <body> <span _ngcontent-ont-c199="" class="font-weight-bold"> <span _...
BeautifulSoup extract desired information in custome-made list from different html snippets
Apologies in advance for such a long and basic question! Given the following three html snippets which are part of a bigger part as follows: <html> <body> <span _ngcontent-ont-c199="" class="font-weight-bold"> <span _ngcontent-ont-c199="" class="ng-star-inserted"> <span _ngcontent-ont-c199="" translate=""> ...
[ "You might just define a list of selectors corresponding to desired_list:\nselectors = [\n 'span.badge.badge-secondary.ng-star-inserted', #badge \n 'span.font-weight-bold span.ng-star-inserted:has(span[translate])', #issue \n 'span.font-wei...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074317095_beautifulsoup_python_web_scraping.txt
Q: Generate a directory tree in python with self made class Treenode (Problem of recursion) I wan to create a python script that print out a directory tree. I'm aware there are tons of information about the topic, and many ways to achieve it. Still, my problem really is about recursion. In order to face the problem i...
Generate a directory tree in python with self made class Treenode (Problem of recursion)
I wan to create a python script that print out a directory tree. I'm aware there are tons of information about the topic, and many ways to achieve it. Still, my problem really is about recursion. In order to face the problem i choosed a OOP way: Create a Class TreeNode Store some props and methods calling in the os.wal...
[ "This will do what you want:\ndef build_tree(parent, dir_path):\n child_list = os.listdir(dir_path)\n child_list.sort()\n\n for child in child_list:\n node = Treenode(child)\n parent.add_child(node)\n\n child_path = os.path.join(dir_path, child)\n if os.path.isdir(child_path):\n...
[ 0, 0 ]
[]
[]
[ "parent_child", "python", "recursion", "tree" ]
stackoverflow_0074331415_parent_child_python_recursion_tree.txt
Q: How to call a Class within a Class? How would I call this class within a class? I'm getting the 'class' is not defined error. class testArray: class testObject: blah = 0 def __init__(self, number): self.number = 1 # Problem here object = testObject() object.blah = ...
How to call a Class within a Class?
How would I call this class within a class? I'm getting the 'class' is not defined error. class testArray: class testObject: blah = 0 def __init__(self, number): self.number = 1 # Problem here object = testObject() object.blah = self.number
[ "I think all you have to do is this. testArray.testObject(), and if you had a function in there all you would have to do is this testArray.testObject.myFunction()\n", "Further reading on nested/inner classes: https://www.pythonpool.com/nested-classes-python/\nclass testArray:\n class testObject:\n blah ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074331626_python.txt
Q: Python MySql Connector Not enough parameters for the SQL statement Can't Insert Values into MySql Database Using This Piece Of Code: def CreateUser(Name, Password, Email, Version): global user print(Password) user = [tuple(Name), tuple(Email), tuple(Password), tuple("User"), tuple("0"), tuple(Version)]...
Python MySql Connector Not enough parameters for the SQL statement
Can't Insert Values into MySql Database Using This Piece Of Code: def CreateUser(Name, Password, Email, Version): global user print(Password) user = [tuple(Name), tuple(Email), tuple(Password), tuple("User"), tuple("0"), tuple(Version)] my_cursor.executemany(f"INSERT INTO users (usersUid, usersEmail, us...
[ "Problem Solved! If Anyone Had The Same Problem There's The Solve:\ndef CreateUser(Name, Password, Email, Version):\n global user\n print(Password)\n user = [(Name, Email, Password, \"User\", \"0\", Version)]\n my_cursor.executemany(f\"INSERT INTO users (usersUid, usersEmail, usersPwd, UsersPerms, users...
[ 0 ]
[]
[]
[ "mysql", "mysql_connector", "mysql_python", "python" ]
stackoverflow_0074270674_mysql_mysql_connector_mysql_python_python.txt
Q: How can I execute multiple cmd commands using Python code Hello I am having this problem where i want to automatically check the system32 file folder with the sfc cmd commands like sfc /verifyonly but the problem is that I can execute only one line in the cmd but I need to execute two and don't know how to execute...
How can I execute multiple cmd commands using Python code
Hello I am having this problem where i want to automatically check the system32 file folder with the sfc cmd commands like sfc /verifyonly but the problem is that I can execute only one line in the cmd but I need to execute two and don't know how to execute a second one import os os.system("start /B start cmd.exe @cmd...
[ "If you look at the docs for os.system they mention the subprocess module as being a more recent development within python that supports multiple systems level processes\n" ]
[ 1 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0074331625_cmd_python.txt
Q: How to count number of outputs? I have a simple problem, for which I have to find how many numbers in a specified interval where the digits of one number are all different. I wrote the code to find these numbers but can't count how many outputs? for example, 244 is not acceptable as two digits are similar, 243 is ...
How to count number of outputs?
I have a simple problem, for which I have to find how many numbers in a specified interval where the digits of one number are all different. I wrote the code to find these numbers but can't count how many outputs? for example, 244 is not acceptable as two digits are similar, 243 is acceptable because all digits are dif...
[ "You could create an int variable and after the output is printed +1 to the variable. Make sure the variable isn't in the for loop because it will reset the variable every iteration.\n#NEW CODE\ncount = 0\n#END OF NEW CODE\nlist = []\nfor i in range(234,567):\n list.append (i)\nfor n in list:\n x=[int(a) for ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074331014_python.txt
Q: iam getting an error on when i chose option 2 for login, with NameError: name 'profiles' is not defined on line 81 anyone to help me with a serious problem am facing here, its about python, login, signup, and password reset for my assignment am having trouble with the login code, it keeps on throwing errors ill sh...
iam getting an error on when i chose option 2 for login, with NameError: name 'profiles' is not defined on line 81
anyone to help me with a serious problem am facing here, its about python, login, signup, and password reset for my assignment am having trouble with the login code, it keeps on throwing errors ill share the code here for the two files..... this is the signup code import datetime from task2 import * # collecting data ...
[ "Since you don't tell us which script is which or how you execute this code, I'll just make up some names. I'm going to call that first one script.py and assume that its the .py file you execute. I'll call that second one m1.py assuming its an imported module.\nPython does not have a truly global namespace. Each mo...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074330307_python.txt
Q: How can I retrieve the current seed of NumPy's random number generator? The following imports NumPy and sets the seed. import numpy as np np.random.seed(42) However, I'm not interested in setting the seed but more in reading it. random.get_state() does not seem to contain the seed. The documentation doesn't show ...
How can I retrieve the current seed of NumPy's random number generator?
The following imports NumPy and sets the seed. import numpy as np np.random.seed(42) However, I'm not interested in setting the seed but more in reading it. random.get_state() does not seem to contain the seed. The documentation doesn't show an obvious answer. How do I retrieve the current seed used by numpy.random, a...
[ "The short answer is that you simply can't (at least not in general).\nThe Mersenne Twister RNG used by numpy has 219937-1 possible internal states, whereas a single 64 bit integer has only 264 possible values. It's therefore impossible to map every RNG state to a unique integer seed.\nYou can get and set the inter...
[ 106, 34, 2, 2, 2, 2 ]
[]
[]
[ "mersenne_twister", "numpy", "python", "random", "random_seed" ]
stackoverflow_0032172054_mersenne_twister_numpy_python_random_random_seed.txt
Q: Pyomo Compatibility with Python 3.11 Is there a known compatibility issue with pyomo and python 3.11? Just trying out the latest/greatest python release and importing pyomo is failing with pyomo v 6.4.2: Python 3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin Type "h...
Pyomo Compatibility with Python 3.11
Is there a known compatibility issue with pyomo and python 3.11? Just trying out the latest/greatest python release and importing pyomo is failing with pyomo v 6.4.2: Python 3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin Type "help", "copyright", "credits" or "license" ...
[ "Pyomo 6.4.2 isn't compatible with python 3.11. You need to update to 6.4.3, which was released on 28th November 2022.\nPrevious answer - before 6.4.3 update\nVerion 6.4.2 does some stuff with pickle and the __getstate__/__setstate__ functions. However, Python 3.11 introduced a default implementation for these func...
[ 2 ]
[]
[]
[ "pyomo", "python", "python_3.x" ]
stackoverflow_0074331573_pyomo_python_python_3.x.txt
Q: Comparing results between 2 dataframes I have 2 dataframes: Dataframe 1: Contains a number of unique securities with its current price. Dataframe 2: Contains new prices from Bloomberg (hypothetically) within a pricing window for the called securities in df1. The challenge I am trying to solve is to obtain a new ...
Comparing results between 2 dataframes
I have 2 dataframes: Dataframe 1: Contains a number of unique securities with its current price. Dataframe 2: Contains new prices from Bloomberg (hypothetically) within a pricing window for the called securities in df1. The challenge I am trying to solve is to obtain a new price for each security held in df1 from df2...
[ "I start at df after you merge df1 and df2.\ndf.sort_values(by=['Security_ID', 'PriceDff'], inplace=True)\nout = df.groupby('Security_ID')[['OldPrice', 'BB_NewPrice', 'PriceDff']].first().reset_index().copy()\nout['BB_NewPrice'] = np.where(out['PriceDff'] <= 1.0, out['BB_NewPrice'], np.NaN)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074331413_dataframe_pandas_python_python_3.x.txt
Q: Tracking Django sessions with custom cookies I am looking for a way to track the time users spend on the site. I have found the package django-tracking2, which tracks visitors by the Django session. However, my session expiry is set to 2 weeks, which makes it useless to track daily activity. My thoughts are that I...
Tracking Django sessions with custom cookies
I am looking for a way to track the time users spend on the site. I have found the package django-tracking2, which tracks visitors by the Django session. However, my session expiry is set to 2 weeks, which makes it useless to track daily activity. My thoughts are that I can create a different cookie that expires every ...
[ "If you want to generate only 24 hours or x duration token and don't want precise time\nUse JWT token\nYou can also generate refresh tokens but it's lifespan is too short.\nTo track precise time\nWhat you can do is create your random value and separate it with . (dot)\nAfter dot you should add current time and then...
[ 0 ]
[]
[]
[ "cookies", "django", "python" ]
stackoverflow_0074330864_cookies_django_python.txt
Q: Scrapy regexp for sitemap_follow if you have a sitemap.xml containing: abc.com/sitemap-1.xml abc.com/sitemap-2.xml abc.com/image-sitemap.xml how do i write sitemap_follow to read only the sitemap-xxx sitemaps and not image-sitemap.xml? I tried with ^sitemap with no luck. What should I do? negate "image"? How? E...
Scrapy regexp for sitemap_follow
if you have a sitemap.xml containing: abc.com/sitemap-1.xml abc.com/sitemap-2.xml abc.com/image-sitemap.xml how do i write sitemap_follow to read only the sitemap-xxx sitemaps and not image-sitemap.xml? I tried with ^sitemap with no luck. What should I do? negate "image"? How? Edit: Scrapy code: self._follow = [rege...
[ "To answer your question naively and directly I offer this code. In other words, I can match each of the items in the sitemap index file using the regex ^.$.\n>>> import re\n>>> sitemap_index_file_content = [\n... 'abc.com/sitemap-1.xml',\n... 'abc.com/sitemap-2.xml',\n... 'abc.com/image-sitemap.xml'\n... ]\n>>> fo...
[ 1, 1 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0045096317_python_scrapy.txt
Q: Why min Heap of Python is not returning the minimum value here? I printed out every iteration. The contents of the list are perfect. But for some reason heappop is returning -8 val even though there is -15 in the list. Help me out class FoodRatings: def __init__(self, foods: List[str], cuisines: List[str], ra...
Why min Heap of Python is not returning the minimum value here?
I printed out every iteration. The contents of the list are perfect. But for some reason heappop is returning -8 val even though there is -15 in the list. Help me out class FoodRatings: def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): self.find_cuisine = defaultdict()...
[ "A heapq list is a tree that just happens to be stored in a list, not a sorted list. Python won't stop you from removing an element from the middle of it using list.remove, but doing that can scramble the tree so that it no longer gives the right results. One way to fix that is to call heapq.heapify on the list aft...
[ 0, 0 ]
[]
[]
[ "heap", "list", "python", "python_3.x" ]
stackoverflow_0074331644_heap_list_python_python_3.x.txt
Q: how improve the python 3 load time In the doc's there is a explanation of the pyc files that are generated when a library is imported. This was confusing to me. When I run my script starting with a py file (actually small 500 lines) the load time is long. However, if I move the pyc files to the primary folder t...
how improve the python 3 load time
In the doc's there is a explanation of the pyc files that are generated when a library is imported. This was confusing to me. When I run my script starting with a py file (actually small 500 lines) the load time is long. However, if I move the pyc files to the primary folder the load time is greatly reduced ( I have...
[ "I was able to get a tool to time the load times and indeed the load is faster.\nJohnf\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074320947_python.txt
Q: Make Button in Python Tkinter Stop Moving when Pressed So I am working on making an application inside of Tkinter and I am not that experienced in it, but I noticed that when you press a button it moves the text inside down and to the right just a couple pixels and I can't figure out how to make it not do that. An...
Make Button in Python Tkinter Stop Moving when Pressed
So I am working on making an application inside of Tkinter and I am not that experienced in it, but I noticed that when you press a button it moves the text inside down and to the right just a couple pixels and I can't figure out how to make it not do that. Any help finding what parameter I need to change would be grea...
[ "will you can change the relief value to be SUNKEN and adjust the border values like this\nButton(root, text = 'Click me !', borderwidth=5, relief=SUNKEN)\nthe button will look a little weird\nor you can use widget other than a button just like this answer (https://stackoverflow.com/a/10674950/20411925)\nimport tki...
[ 1 ]
[]
[]
[ "python", "tkinter", "tkinter_button" ]
stackoverflow_0074331835_python_tkinter_tkinter_button.txt
Q: Dynamically create Links from List in Flask I am trying to dynamically create a list of links to files in a static folder and failing with nested {{ {{ }} }} that would be logically required. A Flask server has files in /Static/FileFolder they are collected in a list with FileList = [] for path in os.listdir...
Dynamically create Links from List in Flask
I am trying to dynamically create a list of links to files in a static folder and failing with nested {{ {{ }} }} that would be logically required. A Flask server has files in /Static/FileFolder they are collected in a list with FileList = [] for path in os.listdir(FileFolderPath): if os.path.isfile(os.path.j...
[ "What if you only use once the jinja2 markdown as it follows:\n{% for link in links %}\n\n <li><a href=\"/static/{{ link }}\">{{ link }}</a> </li>\n\n{% endfor %}\n\nAnother option, but this mainly depends on what you're trying to accomplish, is adding another route to your app.py\n@app.route('/static/<page...
[ 1, 1, 1 ]
[]
[]
[ "flask", "jinja2", "list", "python" ]
stackoverflow_0074331680_flask_jinja2_list_python.txt
Q: Python: TypeError: unsupported operand type(s) for +=: 'method' and 'int' Is there any way i can fix this? I am making a ping pong game with python. When I run it and press w TypeError: unsupported operand type(s) for +=: 'method' and 'int' appears in the terminal. I am using vscode. ` import turtle wn = turtle.S...
Python: TypeError: unsupported operand type(s) for +=: 'method' and 'int' Is there any way i can fix this?
I am making a ping pong game with python. When I run it and press w TypeError: unsupported operand type(s) for +=: 'method' and 'int' appears in the terminal. I am using vscode. ` import turtle wn = turtle.Screen() wn.title("Ping Pong By @TheMayoKing") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) ...
[ "You're missing the parentheses after the y = paddle_a.ycor. That returns the method, and not the int.\nUse y = paddle_a.ycor() and that should get you past that error.\n" ]
[ 1 ]
[]
[]
[ "python", "python_turtle", "typeerror" ]
stackoverflow_0074331938_python_python_turtle_typeerror.txt
Q: Django error: Invalid block tag on line 28: 'endfor'. Did you forget to register or load this tag? I'm stuck on this error I am a new user of Django I am following the steps correctly and learning through YT. When I run python manage.py runserver the HTML shows My index.html file <!DOCTYPE html> <header> CRUD ...
Django error: Invalid block tag on line 28: 'endfor'. Did you forget to register or load this tag?
I'm stuck on this error I am a new user of Django I am following the steps correctly and learning through YT. When I run python manage.py runserver the HTML shows My index.html file <!DOCTYPE html> <header> CRUD Operation with PostgreSQL </header> <body> <center> <h1>How to create CURD Ops with PostgreS...
[ "Look at your code here:\n{% for results in data% }\n<tr>\n <td>{{result.id}}</td>\n <td>{{result.name}}</td>\n <td>{{result.email}}</td>\n <td>{{result.occupation}}</td>\n <td>{{result.salary}}</td>\n <td>{{result.gender}}</td>\n</tr>\n{% endfor %}\n\nYou need to change {% for results in data% } ...
[ 1 ]
[]
[]
[ "django", "django_template_filters", "django_templates", "django_views", "python" ]
stackoverflow_0074331929_django_django_template_filters_django_templates_django_views_python.txt
Q: Will I need to create a virtualenv every time I runserver with Django? Currently taking CS50 Web Programming with Python and Javascript. I'm on the Week 3 Django lecture and trying to follow along but I'm running into trouble while trying to run python manage.py run server. I'm getting the "ImportError: Couldn't i...
Will I need to create a virtualenv every time I runserver with Django?
Currently taking CS50 Web Programming with Python and Javascript. I'm on the Week 3 Django lecture and trying to follow along but I'm running into trouble while trying to run python manage.py run server. I'm getting the "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH e...
[ "No. You do not. In fact, you don't HAVE to use one at all, but it's a good practice to set up a virtual environment for each of your projects because not all modules play well together.\nCreating the virtual environment is generally the first step when you start to build a project. The second step will then be to ...
[ 0 ]
[ "Run this command to check that Django is correctly installed and accessible from your current directory\npython -m django --version\nIf everything is working correctly should see the version of your installation\nRun this command from the outer \"projectName\" directory\npython manage.py runserver\nIt would be mor...
[ -1 ]
[ "cs50", "django", "python", "virtualenv" ]
stackoverflow_0074331755_cs50_django_python_virtualenv.txt
Q: How to encrypt text with a password in python? Surprisingly difficult to find a straight answer to this on Google. I'm wanting to collect a piece of text and a message from a user such as 1PWP7a6xgoYx81VZocrDr5okEEcnqKkyDc hello world. Then I want to be able to encrypt/decrypt the message with the text somehow so ...
How to encrypt text with a password in python?
Surprisingly difficult to find a straight answer to this on Google. I'm wanting to collect a piece of text and a message from a user such as 1PWP7a6xgoYx81VZocrDr5okEEcnqKkyDc hello world. Then I want to be able to encrypt/decrypt the message with the text somehow so that I can save it in my database and not worry abou...
[ "Here's how to do it properly in CBC mode, including PKCS#7 padding:\nimport base64\nfrom Crypto.Cipher import AES\nfrom Crypto.Hash import SHA256\nfrom Crypto import Random\n\ndef encrypt(key, source, encode=True):\n key = SHA256.new(key).digest() # use SHA-256 over our key to get a proper-sized AES key\n I...
[ 54, 10, 1, 0, 0 ]
[ "Here is my solution for anyone who may be interested:\nfrom Crypto.Cipher import AES # pip install pycrypto\nimport base64\n\ndef cypher_aes(secret_key, msg_text, encrypt=True):\n # an AES key must be either 16, 24, or 32 bytes long\n # in this case we make sure the key is 32 bytes long by adding padding an...
[ -2 ]
[ "cryptography", "encryption", "python" ]
stackoverflow_0042568262_cryptography_encryption_python.txt
Q: how to save a value inside a loop and add on it variables? I will be more specific: what I ask is how can I have a loop that saves its output every iteration and thus on every next iteration the loop does adds a value on the existing output, then it saves this too and repeat. for me, this is relevant for my tic ta...
how to save a value inside a loop and add on it variables?
I will be more specific: what I ask is how can I have a loop that saves its output every iteration and thus on every next iteration the loop does adds a value on the existing output, then it saves this too and repeat. for me, this is relevant for my tic tac toe I am building, which consist of a string that I desire to ...
[ "To make updates upon the same grid, you'll want to save that grid as a variable outside your function and make updates to the grid using the board (record_move below) function.\nAdditionally, I encourage you to make use of nested lists to represent your grid. Given a nested list, we can access the upper-right corn...
[ 0 ]
[]
[]
[ "iteration", "loops", "python", "save" ]
stackoverflow_0074330646_iteration_loops_python_save.txt
Q: Selector error: Exception has occurred: AttributeError 'str' object has no attribute 'attrib' I'm trying to scrape the score of the third tennis match in the table on this site. I need to parse a match score into individual set scores from this html element: html = ( ''' <td class="day-table-score"> ...
Selector error: Exception has occurred: AttributeError 'str' object has no attribute 'attrib'
I'm trying to scrape the score of the third tennis match in the table on this site. I need to parse a match score into individual set scores from this html element: html = ( ''' <td class="day-table-score"> <a data-override-transition="" data-ga-category="" data-ga-action="Click" data-ga-label="" data-u...
[ "The reason you are getting the error is because when you use the .../text()\nxpath selector, the return value might be a selector but the selector is just a\nwrapper around the string extracted from the your query. And plain text strings\ndo not have any attributes.\nI think a similar but slightly better solution...
[ 1 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074328701_python_scrapy_web_scraping.txt
Q: Is it better to create a Dockerfile based on tensorflow:latest-gpu-py3-jupyter or refactor for load_image() attribute? I am developing image classification models in the Jupyter notebook environment. After getting my model to work with the CPU, I am trying to use the latest TensorFlow Docker image supported for Ju...
Is it better to create a Dockerfile based on tensorflow:latest-gpu-py3-jupyter or refactor for load_image() attribute?
I am developing image classification models in the Jupyter notebook environment. After getting my model to work with the CPU, I am trying to use the latest TensorFlow Docker image supported for Jupyter & GPU (tensorflow/tensorflow:latest-gpu-py3-jupyter) so I can take advantage of my GPU for training. The GPU configura...
[ "I tried refactoring for the load_img() function from TF 2.1.0:\ndef get_data(dir, set_option):\n if set_option == 'train':\n train_ds = []\n subfolders = sorted([file.path for file in os.scandir(dir) if file.is_dir()])\n for folder in subfolders:\n for file in sorted(os.listdir(f...
[ 0, 0 ]
[]
[]
[ "dockerfile", "jupyter", "keras", "python", "tensorflow" ]
stackoverflow_0074172887_dockerfile_jupyter_keras_python_tensorflow.txt
Q: Pandas recursive slicing to find min value based on condition I do have python data frame as below. I am trying to slice the data frame where ever "slice" column value is 10 and then find the min of "low" column between 10 and previous non 0 value column date open high low cl...
Pandas recursive slicing to find min value based on condition
I do have python data frame as below. I am trying to slice the data frame where ever "slice" column value is 10 and then find the min of "low" column between 10 and previous non 0 value column date open high low close slice 0 2022-05-19 09:15:00 33461.00 33624.90 33403.20 3...
[ "Edit: I noticed I made a number of mistakes after sitting down with this one and was kind of interested since I wanted to make my own trading bot one day so I took the time to fix them for ya.\nimport pandas as pd\nimport sys\n\nif sys.version_info[0] < 3: \n from StringIO import StringIO\nelse:\n from io im...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074330792_pandas_python.txt
Q: pyautogui.write writes jumbled-up characters I am trying to automate a renaming task on Google Web Designer. pyautogui.write writes completely wring letters. for example: pyautogui.write("This is a sample text 12345/._-") returns this text This is q sq,ple text &é”’(=:°) This is not an AZERTY QWERTY issue, and ...
pyautogui.write writes jumbled-up characters
I am trying to automate a renaming task on Google Web Designer. pyautogui.write writes completely wring letters. for example: pyautogui.write("This is a sample text 12345/._-") returns this text This is q sq,ple text &é”’(=:°) This is not an AZERTY QWERTY issue, and I've tried writing to other applications but it st...
[ "import keyboard\n\nkeyboard.write(\"This is a sample text 12345/._-\")\n\nTry this ;) \n\npip install keyboard\n" ]
[ 0 ]
[]
[]
[ "automation", "macos", "pyautogui", "python" ]
stackoverflow_0074331330_automation_macos_pyautogui_python.txt
Q: Trouble accessing function from imported module in the same directory I just started learning Python two weeks ago. I know this question is probably so basic. But please explain to me like I'm 5. I googled "vscode python import not working" etc but all the other cases seem way more complicated than mine. I'm tryin...
Trouble accessing function from imported module in the same directory
I just started learning Python two weeks ago. I know this question is probably so basic. But please explain to me like I'm 5. I googled "vscode python import not working" etc but all the other cases seem way more complicated than mine. I'm trying to follow a tutorial where they're introducing me to IDEs and showing tha...
[ "In simple terms, the triangle function is imported as part of the my_area module, and so you'll need to get it from there as my_area.triangle:\nimport my_area\n\nprint(my_area.triangle(4, 5))\n\nAlternatively, you can directly import triangle:\nfrom my_area import triangle\n\nprint(triangle(4, 5))\n\nHere's the py...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074332022_python.txt