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: Adding max and min rows to a groupby result I have a dataframe that looks something like this: df = pd.DataFrame([1,'A','X','1/3/22 12:00:00AM','1/1/22 12:00:00 AM'], [1,'A','X','1/4/22 1:00:00AM','1/2/22 12:00:00 AM'], [1,'A','Y','1/1/22 1:00:00AM','1/1/22 12:00:00 AM'], [1,'B','X','1/1/22 1:00:00AM','1/1/22 12:0...
Adding max and min rows to a groupby result
I have a dataframe that looks something like this: df = pd.DataFrame([1,'A','X','1/3/22 12:00:00AM','1/1/22 12:00:00 AM'], [1,'A','X','1/4/22 1:00:00AM','1/2/22 12:00:00 AM'], [1,'A','Y','1/1/22 1:00:00AM','1/1/22 12:00:00 AM'], [1,'B','X','1/1/22 1:00:00AM','1/1/22 12:00:00 AM'], [2,'A','X','1/3/22 12:00:00AM','1/1/22...
[ "You can use a groupby aggregation:\nout = (df\n .groupby(['ID', 'Category', 'Site'], as_index=False)\n .agg({'Task Completed': 'first', 'Access Completed': 'max'})\n .assign(**{'Time Difference': lambda d: d['Task Completed']\n .sub(d['Access Completed'])\n .dt.total_seconds().floor...
[ 2 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074144188_dataframe_group_by_pandas_python.txt
Q: Find local maxima in data from dataframe Is there a way to find the local maxima from data I get from CSV file and put its value on the plot? The x and y values that are in a pandas dataframe look something like this x = 1598.78, 1596.85, 1594.92, 1592.99, 1591.07, 1589.14, 1587.21, 1585.28, 1583.35, 1581.42, 1579...
Find local maxima in data from dataframe
Is there a way to find the local maxima from data I get from CSV file and put its value on the plot? The x and y values that are in a pandas dataframe look something like this x = 1598.78, 1596.85, 1594.92, 1592.99, 1591.07, 1589.14, 1587.21, 1585.28, 1583.35, 1581.42, 1579.49, 1577.57, 1575.64, 1573.71, 1571.78, 1569....
[ "x = [1598.78, 1596.85, 1594.92, 1592.99, 1591.07, 1589.14, 1587.21, 1585.28, 1583.35, 1581.42, 1579.49, 1577.57, 1575.64, 1573.71, 1571.78, 1569.85, 1567.92, 1565.99, 1564.07, 1562.14, 1560.21, 1558.28, 1556.35, 1554.42, 1552.49, 1550.57, 1548.64, 1546.71, 1544.78, 1542.85, 1540.92, 1538.99, 1537.07, 1535.14, 1533...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "scipy" ]
stackoverflow_0074143424_matplotlib_pandas_python_scipy.txt
Q: Download files with goto in playwright-python Is there a way to download a file by going straight to its download link with goto in playwright-python? async with page.expect_download(timeout=420000) as download_info: await page.goto(f'https://example.com/gateway/reports/{id}/file') Download = await downlo...
Download files with goto in playwright-python
Is there a way to download a file by going straight to its download link with goto in playwright-python? async with page.expect_download(timeout=420000) as download_info: await page.goto(f'https://example.com/gateway/reports/{id}/file') Download = await download_info.value await Download.save_as(Download.sugge...
[ "The only way I found is wrap the goto inside a try-except block\nContent of main.py\nfrom playwright.sync_api import Playwright, sync_playwright, expect\n\nwith sync_playwright() as p:\n #We define the browser, the context and the page\n browser = p.chromium.launch(headless=False)\n context = browser.new_...
[ 0 ]
[]
[]
[ "automation", "download", "playwright", "playwright_python", "python" ]
stackoverflow_0073652378_automation_download_playwright_playwright_python_python.txt
Q: How to parametrize a Pytest fixture Consider the following Pytest: import pytest class TimeLine(object): instances = [0, 1, 2] @pytest.fixture def timeline(): return TimeLine() def test_timeline(timeline): for instance in timeline.instances: assert instance % 2 == 0 if __name__ == "__main__...
How to parametrize a Pytest fixture
Consider the following Pytest: import pytest class TimeLine(object): instances = [0, 1, 2] @pytest.fixture def timeline(): return TimeLine() def test_timeline(timeline): for instance in timeline.instances: assert instance % 2 == 0 if __name__ == "__main__": pytest.main([__file__]) The test ...
[ "This is actually possible via indirect parametrization.\nThis example does what you want with pytest 3.1.2:\nimport pytest\n\nclass TimeLine:\n def __init__(self, instances):\n self.instances = instances\n\n@pytest.fixture\ndef timeline(request):\n return TimeLine(request.param)\n\n@pytest.mark.parame...
[ 77, 52, 40, 21, 20, 1, 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0042228895_pytest_python.txt
Q: Django Integrity Error 1452, Cannot add or update a child row: a foreign key constraint fails models.py: from django.db import models class Line(models.Model): text = models.CharField(primary_key=True, max_length=255) class Line2 (models.Model): text_line = models.ForeignKey ("Line", primary_key = True) vi...
Django Integrity Error 1452, Cannot add or update a child row: a foreign key constraint fails
models.py: from django.db import models class Line(models.Model): text = models.CharField(primary_key=True, max_length=255) class Line2 (models.Model): text_line = models.ForeignKey ("Line", primary_key = True) views.py: from django.core.context_processors import csrf from django.shortcuts import render import ...
[ "You shouldn't assign the Line instance to text_line_id as you are currently doing.\nYou should either do \nnew_entry = Line2(text_line=line_query)\n\nor\nnew_entry = Line2(text_line_id=line_query.text)\n\n", "You may try with giving the foreign key to related_name.\nalso verify this:\nIs the parents table have a...
[ 3, 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0033689509_django_mysql_python.txt
Q: Stop resizing tkinter grid on button.config I'm working on a project with a tkinter grid of 64 (8x8) square buttons. Every time a button is clicked, the text in it should change using config. However, when the text changes, the button reseizes so it can fit the text better, which I don't want because the squares a...
Stop resizing tkinter grid on button.config
I'm working on a project with a tkinter grid of 64 (8x8) square buttons. Every time a button is clicked, the text in it should change using config. However, when the text changes, the button reseizes so it can fit the text better, which I don't want because the squares aren't square anymore now. Here is my code for set...
[ "Set a constant width for your Button widgets and apply it when creating the buttons with the width parameter, for example:\nimport tkinter as tk\n\nBTN_WIDTH = 10\n\nroot = tk.Tk()\nroot.columnconfigure(0, weight=3)\nroot.rowconfigure(1, weight=3)\n\nbtn = tk.Button(root, width=BTN_WIDTH)\nbtn.grid(row=0, column=0...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074144545_python_tkinter.txt
Q: I'm getting error when trying to convert Html to JSON using python with beautiful soup I'm trying to scrap data from this website "https://quranromanurdu.com/chapter/1" , I want only text or content from id-contentpara and return that content in JSON format, this below code gives html content but i want that to co...
I'm getting error when trying to convert Html to JSON using python with beautiful soup
I'm trying to scrap data from this website "https://quranromanurdu.com/chapter/1" , I want only text or content from id-contentpara and return that content in JSON format, this below code gives html content but i want that to convert to JSON. I tried to convert but I'm getting error , please somebody help me to clear t...
[ "The error tells you what's wrong, findAll returns a ResultSet which you need to convert to a str, this answer should help https://stackoverflow.com/a/20969389/16716191. Also findAll was renamed to find_all.\n", "You can do like this,\n... your code ...\ntable = soup.findAll('div',attrs={\"id\":\"contentpara\"})\...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "json", "python", "web", "web_scraping" ]
stackoverflow_0074143651_beautifulsoup_json_python_web_web_scraping.txt
Q: Display Kivy Color Wheel only I am writing an app that has a need for the Kivy Color Wheel (https://kivy.org/doc/stable/api-kivy.uix.colorpicker.html) to choose a color value to assign to different users. However, I intend for it to be used on a phone screen, and as such I do not need the various sliders and color...
Display Kivy Color Wheel only
I am writing an app that has a need for the Kivy Color Wheel (https://kivy.org/doc/stable/api-kivy.uix.colorpicker.html) to choose a color value to assign to different users. However, I intend for it to be used on a phone screen, and as such I do not need the various sliders and color codes that make up the second half...
[ "Try using ColorWheel instead. You can use it in the kv as:\n<ColourScreen>:\n Label:\n text: 'Please Choose the colour for Team 1'\n\n ColorWheel:\n on_color: root.color_selected(self.color)\n\nAnd the color_selected() method:\nclass ColourScreen(Screen):\n def color_selected(self, color):\n...
[ 1 ]
[]
[]
[ "color_wheel", "kivy", "kivy_language", "python" ]
stackoverflow_0074140429_color_wheel_kivy_kivy_language_python.txt
Q: Selenium taking a lot of time to find element by XPATH I am trying to scraping name and email of agents from this site. The code firstly captures link to every profile on first page and then visits each profile to get name and email. But the problem is that it is taking alot of time to get anchor tag having name o...
Selenium taking a lot of time to find element by XPATH
I am trying to scraping name and email of agents from this site. The code firstly captures link to every profile on first page and then visits each profile to get name and email. But the problem is that it is taking alot of time to get anchor tag having name of agent in it. Here's the code: import os from selenium impo...
[ "I have change the xpath to identify the anchor tag and remove the new window open in each iteration. hope this will reduce some time.\ndef getDetails(self): \n\n mylist = [my_elem.get_attribute(\"href\") for my_elem in WebDriverWait(self, 1000).until(\n EC.visibility_of_all_elements_locate...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074144344_python_selenium_selenium_webdriver_xpath.txt
Q: How to use Custom (or albumentation) augmentations on Detectron 2? I have the below code where I'm using default augmentation during training of Detectron 2 but the problem is that there are very few augmentations that are useful to me. Here is something like what I to achieve with my own functions. This github ...
How to use Custom (or albumentation) augmentations on Detectron 2?
I have the below code where I'm using default augmentation during training of Detectron 2 but the problem is that there are very few augmentations that are useful to me. Here is something like what I to achieve with my own functions. This github issue link tries to solve. Want to whether it is the right way to do i...
[ "So after running through the code flow and documentation, I found out that Each Augmentation class is dependent on the Transform class which is inherited from the fvcore library\nAlso the same dependency is also defined vaguely in this highlighted documentation block\nThen looking at all the aspects above and then...
[ 0 ]
[ "You can easily do both things with albumentations.\nHere is an example:\nimport albumentations as A\n\ndef create_transform():\n return A.Compose(\n [\n A.OneOf([\n A.RandomBrightness(p=1),\n A.RandomContrast(limit=.2, p=1)\n ],\n p=....
[ -1 ]
[ "albumentations", "computer_vision", "deep_learning", "detectron", "python" ]
stackoverflow_0073684921_albumentations_computer_vision_deep_learning_detectron_python.txt
Q: ClientError when calling get_execution_role() in aws sagemaker I have some really simple code here. It worked yesterday, but not today. In a Jupiter notebook I call: from sagemaker import get_execution_role role = get_execution_role() Then I get this massive error, but the gist of it is: ClientError: An error occ...
ClientError when calling get_execution_role() in aws sagemaker
I have some really simple code here. It worked yesterday, but not today. In a Jupiter notebook I call: from sagemaker import get_execution_role role = get_execution_role() Then I get this massive error, but the gist of it is: ClientError: An error occurred (ExpiredToken) when calling the GetCallerIdentity operation: T...
[ "get_execution_role() makes various AWS API calls. The error indicates that your AWS credentials have expired.\nIf this notebook is hosted by SageMaker, I would log back into the AWS console and relaunch the notebook. Notebooks will automatically refresh the credentials they use, but this will fail if the notebook ...
[ 1 ]
[]
[]
[ "amazon_sagemaker", "amazon_web_services", "jupyter_notebook", "python" ]
stackoverflow_0074137442_amazon_sagemaker_amazon_web_services_jupyter_notebook_python.txt
Q: Why my environment variables are not the same when Pycharm execute the code? ENVIRONMENT: Mac OS Catalina 10.15.7 Python 3.7.13 PROBLEM: My python code needs to execute some terminal commands. But I get the error message: "command not found". So I tested these same commands from "Terminal" and it worked perfectly....
Why my environment variables are not the same when Pycharm execute the code?
ENVIRONMENT: Mac OS Catalina 10.15.7 Python 3.7.13 PROBLEM: My python code needs to execute some terminal commands. But I get the error message: "command not found". So I tested these same commands from "Terminal" and it worked perfectly. So I compare the environment variables loaded with my Terminal and the ones loade...
[ "Use the .zshenv instead and make sure you restart PyCharm. Works in PyCharm 2022.2.3 Professional.\n" ]
[ 0 ]
[]
[]
[ "environment_variables", "pycharm", "python", "python_3.x" ]
stackoverflow_0072363999_environment_variables_pycharm_python_python_3.x.txt
Q: Second instance of a money value print returns a value different than the first print with Python I'm working on a program that is a simulation of an order form/receipt. First, the program prints an invoice, then later prints a receipt based on which payment schedule the user selects (1-4 years) My problem is that...
Second instance of a money value print returns a value different than the first print with Python
I'm working on a program that is a simulation of an order form/receipt. First, the program prints an invoice, then later prints a receipt based on which payment schedule the user selects (1-4 years) My problem is that I can't find a way to get the invoice and receipt to print the same monthly payment. This is the code ...
[ "The error in your code just hit me: your calculations for MonPay1, ... all used TotPrice, with the value set at the end of the invoice loop, so the value for 4 years!\nHere is the code I rewrote (based on my understanding of your different values).\nYou'll probably have to tweak some things to fit your needs.\n# D...
[ 1 ]
[]
[]
[ "python", "range", "while_loop" ]
stackoverflow_0074142579_python_range_while_loop.txt
Q: sqlite3.OperationalError: no such table: listinfo I have a problem getting access sqldp it shows table doestn't exist but it works in debugging mode i dont know why and they are in same dir import sqlite3 import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_dir = (BASE_DIR + '\\app.db') def geta...
sqlite3.OperationalError: no such table: listinfo
I have a problem getting access sqldp it shows table doestn't exist but it works in debugging mode i dont know why and they are in same dir import sqlite3 import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_dir = (BASE_DIR + '\\app.db') def getalldate(): db=sqlite3.connect("app.db") cr=db.curs...
[ "don't use single quotation marks to refer to the table name\nit should be:\n\"SELECT * FROM listinfo\"\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074144610_python_sqlite.txt
Q: mypy and basic inheritance Got this pretty straight-forward inheritance case. I read a bunch of mypy documentation but still can't figure out how to properly deal with those basic cases. It's very standard OOP inheritance to me so I can't imagine mypy doesn't have a clean way to deal with those cases. from __futur...
mypy and basic inheritance
Got this pretty straight-forward inheritance case. I read a bunch of mypy documentation but still can't figure out how to properly deal with those basic cases. It's very standard OOP inheritance to me so I can't imagine mypy doesn't have a clean way to deal with those cases. from __future__ import annotations from data...
[ "Judging by your follow-up comment, I assume you were actually interested in a way to have a generalized __add__ method with proper type inference for mypy and other type checkers. Generics, as always, save the day.\nHere is a working example:\nfrom __future__ import annotations\nfrom dataclasses import dataclass, ...
[ 0 ]
[]
[]
[ "inheritance", "mypy", "python", "type_hinting" ]
stackoverflow_0074140767_inheritance_mypy_python_type_hinting.txt
Q: reading file from s3 (boto3) in multithread fashion I would like to process an huge folder of XML files locate in s3 buckets. I would like to do this in a distributed way in Python. So I first define a paginator with boto3 library, setting up (for example) a page size of 100 elements (refer to doc) profile = boto3...
reading file from s3 (boto3) in multithread fashion
I would like to process an huge folder of XML files locate in s3 buckets. I would like to do this in a distributed way in Python. So I first define a paginator with boto3 library, setting up (for example) a page size of 100 elements (refer to doc) profile = boto3.Session() client = profile.client('s3') paginator = clie...
[ "Does this code work for you. I always just get the first 1000 files of the first page if I do something like\nglobal keys\nkeys = []\n\ndef my_process_method(pages):\n for item in page['Contents']:\n keys.append(item.get('Key'))\n\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "boto3", "multithreading", "python", "python_multithreading" ]
stackoverflow_0058364644_amazon_s3_boto3_multithreading_python_python_multithreading.txt
Q: input not working trying to redirect from "/' to "deal" Hello I am building a blackjack game and I am stuck the deal button is not working and I am trying to get that to redirecting to another URL. Also do I need that many variables to update the game as the client is playing ? This is my third day doing flask aft...
input not working trying to redirect from "/' to "deal"
Hello I am building a blackjack game and I am stuck the deal button is not working and I am trying to get that to redirecting to another URL. Also do I need that many variables to update the game as the client is playing ? This is my third day doing flask after and my first web application. Any help or pointing me in t...
[ "Clicking the Deal button will submit a POST to / with Deal=Deal in the post body as Content-Type: application/x-www-form-urlencoded\nYour if condition inside of the home route only redirects to /deal if the request is a GET and if the request form body has a value for Stay. This should be changed to if request.met...
[ 0 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0074144059_flask_jinja2_python.txt
Q: how can i iterate over all items before returning true im wondering if there is a way to iterate over all the keys before returning true. in this example if the update item['one] != old_item['one] it goes ahead and returns true without checking two. unique_keys = ('one','two') def check_if_items_change(old_item, ...
how can i iterate over all items before returning true
im wondering if there is a way to iterate over all the keys before returning true. in this example if the update item['one] != old_item['one] it goes ahead and returns true without checking two. unique_keys = ('one','two') def check_if_items_change(old_item, new_item, unique_key): update_item = {**old_item,**new_i...
[ "You can define a flag and first set flag to False and after go to if set the flag to True and at the end return flag.\nunique_keys = ('one','two')\n\ndef check_if_items_change(old_item, new_item, unique_key):\n update_item = {**old_item,**new_item}\n flag = False\n for field in unique_keys:\n if up...
[ 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074144727_dictionary_python.txt
Q: Python comparing 2 columns I have a doubt and i tried with this code. Im addin a new column to compare two columns so if they are equal return True and if they arent retunr False. i Upload a pic of the codeenter image description here A: Try using the equal-to operator (==) instead. For example: Evo_FlagF3['new_...
Python comparing 2 columns
I have a doubt and i tried with this code. Im addin a new column to compare two columns so if they are equal return True and if they arent retunr False. i Upload a pic of the codeenter image description here
[ "Try using the equal-to operator (==) instead. For example:\nEvo_FlagF3['new_column'] = Evo_FlagF3['0.0'] == Evo_FlagF3['sum']\n\n" ]
[ 1 ]
[]
[]
[ "compare", "pandas", "python" ]
stackoverflow_0074144633_compare_pandas_python.txt
Q: Coverting Int64index to list or accessing list of lists I have a list of lists but because of the Int64Index I cannot access it. Is there a way to access individual values or make it into a normal list? data_exp = pd.read_csv(path+'/exp.csv') exp_list=[] for i in range (1,n+1): check=data_exp.apply(lambda x:...
Coverting Int64index to list or accessing list of lists
I have a list of lists but because of the Int64Index I cannot access it. Is there a way to access individual values or make it into a normal list? data_exp = pd.read_csv(path+'/exp.csv') exp_list=[] for i in range (1,n+1): check=data_exp.apply(lambda x: True if x['Set No.']==i else False, axis=1) temp=[data_e...
[ "I'm not quite sure what you're doing to get the list of Int64Indexes, but you can access the numpy array underlying the index with the values property:\nfrom pandas import Int64Index\n\nl = [[Int64Index([8, 11, 17, 20, 21, 27, 29, 36, 37, 38], dtype='int64')],\n[Int64Index([1, 3, 7, 10, 14, 31, 33, 34, 35], dtype=...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074143045_list_python.txt
Q: AttributeError: partially initialized module 'logging' has no attribute 'getLogger' (most likely due to a circular import) I wrote imports as usual, but it is wrong. I searched and did not find a mistake like mine, please help. The file name is main.py . Traceback (most recent call last): File "/app/main.py", line...
AttributeError: partially initialized module 'logging' has no attribute 'getLogger' (most likely due to a circular import)
I wrote imports as usual, but it is wrong. I searched and did not find a mistake like mine, please help. The file name is main.py . Traceback (most recent call last): File "/app/main.py", line 2, in <module> from telethon import TelegramClient, Button, events, version File "/usr/local/lib/python3.9/site-packages/teleth...
[ "I had similar issue, my python file was called token.py. Once I renamed it into something else the problem went away.\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "logging", "python", "telethon" ]
stackoverflow_0072099563_attributeerror_logging_python_telethon.txt
Q: Flask-SQLAlchemy raises TypeError: Query.paginate() takes 1 positional argument but 4 were given I call Flask-SQLAlchemy's query.paginate method with arguments. Recently this stopped working and instead raised a TypeError. How do I pass page and other arguments to query.paginate? Ticker.query.paginate(page, app.co...
Flask-SQLAlchemy raises TypeError: Query.paginate() takes 1 positional argument but 4 were given
I call Flask-SQLAlchemy's query.paginate method with arguments. Recently this stopped working and instead raised a TypeError. How do I pass page and other arguments to query.paginate? Ticker.query.paginate(page, app.config["TICKERS_PER_PAGE"], False) TypeError: Query.paginate() takes 1 positional argument but 4 were g...
[ "As of Flask-SQLAlchemy 3.0, all arguments to paginate are keyword-only.\nTicker.query.paginate(page=page, per_page=app.config[\"TICKERS_PER_PAGE\"], error_out=False)\n\n" ]
[ 2 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0074144613_flask_flask_sqlalchemy_python.txt
Q: Merge row if cels are equals pandas I have this df: import pandas as pd df = pd.DataFrame({'Time' : ['s_1234','s_1234', 's_1234', 's_5678', 's_8998','s_8998' ], 'Control' : ['A', '', '','B', 'C', ''], 'tot_1' : ['1', '1', '1','1', '1', '1'], 'tot_2' : ['2', ...
Merge row if cels are equals pandas
I have this df: import pandas as pd df = pd.DataFrame({'Time' : ['s_1234','s_1234', 's_1234', 's_5678', 's_8998','s_8998' ], 'Control' : ['A', '', '','B', 'C', ''], 'tot_1' : ['1', '1', '1','1', '1', '1'], 'tot_2' : ['2', '2', '2','2', '2', '2']}) -------- Tim...
[ "Your data is different then the example df.\nconstruct df:\nimport pandas as pd\ndf = pd.DataFrame({'Time' : ['s_1234','s_1234', 's_1234', 's_5678', 's_8998','s_8998' ],\n 'Control' : ['A', '', '','B', 'C', ''],\n 'tot_1' : ['1', '1', '1','1', '1', '1'],\n 'tot...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074144478_dataframe_pandas_python.txt
Q: I'm making a blackjack game, and I'm wondering why doesn't my function numbertocard update the definition of playercard1 I want to use a face card value instead of the number if the card is greater then 10 but the function doesn't update the variable. The "card" used in the function does get updated to playercard1...
I'm making a blackjack game, and I'm wondering why doesn't my function numbertocard update the definition of playercard1
I want to use a face card value instead of the number if the card is greater then 10 but the function doesn't update the variable. The "card" used in the function does get updated to playercard1 when I call upon it with numbertocard(playercard1), right? And if so, what exactly is the issue? import random def numbertoca...
[ "You can achieve what you want by creating a new variable that stores the returning value of that function:\ndef startgame():\n playercard1 = random.randint(1,14)\n cardValue = numbertocard(playercard1)\n print(f\"Your first card is {cardValue}\")\n\nor directly:\ndef startgame():\n playercard1 = random.randint...
[ 0 ]
[]
[]
[ "function", "function_definition", "python" ]
stackoverflow_0074144703_function_function_definition_python.txt
Q: PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x1010864a0> I am using tensorflow to read encode and decode image ,but while doing this getting above error. import tensorflow as tf import base64 import numpy as np from PIL import Image import io ######################################...
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x1010864a0>
I am using tensorflow to read encode and decode image ,but while doing this getting above error. import tensorflow as tf import base64 import numpy as np from PIL import Image import io ############################################ IMAGE READ ################################################# #tensorflow==2.10.0 image =...
[ "After using print() to check what it has in variables I found it converts full object tensor to bytes in BytesIO (it serializes tensor) but it has to get only raw bytes from tensor.\nAnd I found it needs .numpy() to get expected data from tensor.\nsol = io.BytesIO(decode_image.numpy())\n\n\nFull working code\nimpo...
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074143780_python_tensorflow.txt
Q: Sum values of two Dataframe with Conditions it's the situation: in a "for" loop i'm reading csv files as dataframe and add them to a main big df. if new data is not already in main df, it will be simply concat to main df. if new data has already a same value in main df, it has to sum with the pervious one. an exam...
Sum values of two Dataframe with Conditions
it's the situation: in a "for" loop i'm reading csv files as dataframe and add them to a main big df. if new data is not already in main df, it will be simply concat to main df. if new data has already a same value in main df, it has to sum with the pervious one. an example: main_df= building, day, kw/h ...
[ "concat the three DF and then sum the kw/h on building and day\ndf=pd.concat([main_df, new_df1, new_df2])\ndf=df.groupby(['building','day'], as_index=False)['kw/h'].sum()\ndf\n\n building day kw/h\n0 1 1 50\n1 1 2 55\n2 2 1 45\n3 2 2 ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "sum" ]
stackoverflow_0074144843_dataframe_pandas_python_sum.txt
Q: RuntimeError( RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set I am learning basic flask but cannot import db(database) from freecodecamp I cannot find the solution plz answer this query as soon as possible There are 4 files : when I write from app import db the pythonshell shows er...
RuntimeError( RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set
I am learning basic flask but cannot import db(database) from freecodecamp I cannot find the solution plz answer this query as soon as possible There are 4 files : when I write from app import db the pythonshell shows error app.py from flask import Flask,render_template, url_for from flask_sqlalchemy import SQLAlchemy ...
[ "You need to initialize db as well,\ndb = SQLAlchemy() # db intitialized here\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite://test.db\"\ndb.init_app(app)\n\nIt's SQLALCHEMY_DATABASE_URI not SQLALCHEMY_DATABASE_URL \n" ]
[ 1 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0074144861_flask_flask_sqlalchemy_python.txt
Q: Strange character added when decoding with urllib I'm trying to parse a query string like this: filename=logo.txt\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01x&filename=.hidden.txt Since it mixes bytes and text, I tried to alter it such that it will produce the desired escaped ur...
Strange character added when decoding with urllib
I'm trying to parse a query string like this: filename=logo.txt\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01x&filename=.hidden.txt Since it mixes bytes and text, I tried to alter it such that it will produce the desired escaped url output like so: extended = 'filename=logo.txt\\x8...
[ "As the docs for urllib.parse.quote say\n\nNote that quote(string, safe, encoding, errors) is equivalent to quote_from_bytes(string.encode(encoding, errors), safe).\n\nWhere encoding defaults to UTF-8. And the UTF-8 encoding of '\\x80' is...\n>>> '\\x80'.encode('utf-8')\nb'\\xc2\\x80'\n\nSo it's correct that the %C...
[ 1, 1, 0 ]
[]
[]
[ "casting", "python", "python_3.10", "unicode_string", "urllib" ]
stackoverflow_0074143759_casting_python_python_3.10_unicode_string_urllib.txt
Q: How to wrap a numpy function to make it work with jax.numpy? I have some Jax code that requires using auto differentiation and in part of the code, I would like to call a function from a library written in NumPy. When I try this now I get The numpy.ndarray conversion method __array__() was called on the JAX Tracer...
How to wrap a numpy function to make it work with jax.numpy?
I have some Jax code that requires using auto differentiation and in part of the code, I would like to call a function from a library written in NumPy. When I try this now I get The numpy.ndarray conversion method __array__() was called on the JAX Tracer object Traced<ShapedArray(float32[4,22324])>with<JVPTrace(level=4...
[ "No, in general there's no way given a function that operates on NumPy arrays to automatically convert it to an equivalent function implemented in JAX. The reason for this is that JAX is not a 100% faithful one-to-one implementation of NumPy's API; rather you should think of jax.numpy as a NumPy-like wrapper around...
[ 1 ]
[]
[]
[ "autodiff", "jax", "numpy", "python" ]
stackoverflow_0074140788_autodiff_jax_numpy_python.txt
Q: How to make the links generated on sitemap with https protocol instead of http - Python script (Django framework) I have a Python script (Django framework) it automatically generates links in sitemap but it only generates HTTP links, I want the links to be HTTPS this is what sitemap.py have from django.contrib...
How to make the links generated on sitemap with https protocol instead of http - Python script (Django framework)
I have a Python script (Django framework) it automatically generates links in sitemap but it only generates HTTP links, I want the links to be HTTPS this is what sitemap.py have from django.contrib.sitemaps import Sitemap from .models import Theme class ThemeSitemap(Sitemap): changefreq = 'weekly' priority = 0.8 d...
[ "protocol = \"https\"\n\nis the right solution, I just had to be more careful with spaces.\n" ]
[ 1 ]
[]
[]
[ "django", "http", "https", "python", "sitemap" ]
stackoverflow_0073669688_django_http_https_python_sitemap.txt
Q: what does %pip mean? I see this is a notebook file: %pip install wordcloud I would usually do: pip install wordcloud without the %. I have tried looking this up, but cannot seem to find it. What does the % actually do ? is it notebook specific ? EDIT: there are 4 proposed solutions (that were similar). it appears...
what does %pip mean?
I see this is a notebook file: %pip install wordcloud I would usually do: pip install wordcloud without the %. I have tried looking this up, but cannot seem to find it. What does the % actually do ? is it notebook specific ? EDIT: there are 4 proposed solutions (that were similar). it appears as though the % is a repl...
[ "This is a so called \"magic\" command and specific to the ipython kernel for jupyter notebooks.\nYou can read more about it here: https://ipython.readthedocs.io/en/stable/interactive/magics.html\n" ]
[ 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074144972_pip_python.txt
Q: tkinter call a function every second? I want to call an update function every 1 second to update some stuff. I have tried using a while loop and time.sleep but that does not work. I though that I could attach a function to mainloop so it is called everytime Tk() updates. But I don't know any other way can you help...
tkinter call a function every second?
I want to call an update function every 1 second to update some stuff. I have tried using a while loop and time.sleep but that does not work. I though that I could attach a function to mainloop so it is called everytime Tk() updates. But I don't know any other way can you help? from tkinter import * def Update(): ...
[ "Use after to call the update function, and have update call after itself in order to repeat indefinitely\nimport tkinter as tk\n\nmaster = tk.Tk()\n\n\ndef update():\n # do things\n master.after(1000, update)\n\n\nmaster.after(0, update) # begin updates\nmaster.mainloop()\n\n" ]
[ 1 ]
[]
[]
[ "python", "sleep", "time", "tkinter", "updating" ]
stackoverflow_0074144890_python_sleep_time_tkinter_updating.txt
Q: Seaborn lineplot without lines between points How can I use the lineplot plotting function in seaborn to create a plot with no lines connecting between the points. I know the function is called lineplot, but it has the useful feature of merging all datapoints with the same x value and plotting a single mean and co...
Seaborn lineplot without lines between points
How can I use the lineplot plotting function in seaborn to create a plot with no lines connecting between the points. I know the function is called lineplot, but it has the useful feature of merging all datapoints with the same x value and plotting a single mean and confidence interval. tips = sns.load_dataset('tips') ...
[ "To get error bars without the connecting lines, you can set the linestyle parameter to '':\nimport seaborn as sns\n\ntips = sns.load_dataset('tips')\nsns.lineplot(x='size', y='total_bill', data=tips, marker='o', linestyle='', err_style='bars')\n\n\nOther types of linestyle could also be interesting, for example \"...
[ 5, 0 ]
[]
[]
[ "python", "seaborn" ]
stackoverflow_0064721669_python_seaborn.txt
Q: After updating a df from filtred df old values reappear i have a df where i have a requirement to filter it into new df and work on it and after working i wanted to update it to the original df like. Street City State Zip 4210 Nw Lake Dr Lees Summit Mo 64064 9810 Scripps Lake Dr. Suite A San Diego Ca - 92131 1...
After updating a df from filtred df old values reappear
i have a df where i have a requirement to filter it into new df and work on it and after working i wanted to update it to the original df like. Street City State Zip 4210 Nw Lake Dr Lees Summit Mo 64064 9810 Scripps Lake Dr. Suite A San Diego Ca - 92131 1124 Ethel St Glendale Ca 91207 4000 E Bristol St ...
[ "From the docs, pandas.DataFrame.update:\nModify in place using non-NA values from another DataFrame.\n\nReplace Filter3_df['City']= float('NaN'), which is NA for floats, with the value you really want:\nFilter3_df['City'] = \"\"\n\n" ]
[ 0 ]
[]
[]
[ "data_cleaning", "pandas", "python" ]
stackoverflow_0074144906_data_cleaning_pandas_python.txt
Q: How can I asynchronously schedule tasks without asyncio.sleep()? Is there a vanilla way to asynchronously schedule these two tasks? Should this be written a different way? asyncio.sleep(0) works, but I don't want to sleep there. import asyncio async def skip(name, init, by): value = init for i in range(10...
How can I asynchronously schedule tasks without asyncio.sleep()?
Is there a vanilla way to asynchronously schedule these two tasks? Should this be written a different way? asyncio.sleep(0) works, but I don't want to sleep there. import asyncio async def skip(name, init, by): value = init for i in range(10): value = value + by print(f'{name}: {value}') ...
[ "There isn't anything wrong with what you're doing, but you should ask what you want to accomplish with your async functions. For example, if you just want to see them interlaced what you've done is fine, but the main use of async is to allow useful work to occur while a part of your program is waiting on somethin...
[ 0 ]
[]
[]
[ "python", "python_asyncio", "scheduled_tasks" ]
stackoverflow_0074144819_python_python_asyncio_scheduled_tasks.txt
Q: How do I compile a C++ shared library, load and run it in Python? I have a function in C++ that takes a list of sets of integers and merges the sets where there is a common element between sets. The code is lifted from here: combine pairs of integers based on common element. My C++ file is called merge_sets.cpp an...
How do I compile a C++ shared library, load and run it in Python?
I have a function in C++ that takes a list of sets of integers and merges the sets where there is a common element between sets. The code is lifted from here: combine pairs of integers based on common element. My C++ file is called merge_sets.cpp and contains the below code: #include <algorithm> #include <set> #include...
[ "You can use the python c api. This is an example of a simple extension with a single call.\n// theExtension.cpp\n//\n/////////////////////////////////////////////////////////////////\n//\n// Primary module for extension.\n// \n\n/////////////////////////////////////////////////////////////////\n\n// Numpy uses a v...
[ 0 ]
[]
[]
[ "binding", "c++", "python", "shared_libraries" ]
stackoverflow_0074143015_binding_c++_python_shared_libraries.txt
Q: Convert a multiple elements list to a single element list I have a list: my_list = ["h", "e", "l", "l", o"] What I would like to have is: new_list = ["hello"] A: my_list = ["h", "e", "l", "l", "o"] result = ''.join(my_list) my_list.clear() my_list.append(result) print(my_list) This will output the result: ['...
Convert a multiple elements list to a single element list
I have a list: my_list = ["h", "e", "l", "l", o"] What I would like to have is: new_list = ["hello"]
[ "my_list = [\"h\", \"e\", \"l\", \"l\", \"o\"]\n\nresult = ''.join(my_list)\nmy_list.clear()\nmy_list.append(result)\nprint(my_list)\n\nThis will output the result:\n['hello']\n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074129456_list_python.txt
Q: bullet stops when mouse isnt moving in pygame Whenever I run this code and I click to shoot a bullet, the bullet moves in the direction it is supposed to go only when I continuously move the mouse. How do I make the bullet move at all times? I don't understand why it does this. I appreciate your help! I'm a noobie...
bullet stops when mouse isnt moving in pygame
Whenever I run this code and I click to shoot a bullet, the bullet moves in the direction it is supposed to go only when I continuously move the mouse. How do I make the bullet move at all times? I don't understand why it does this. I appreciate your help! I'm a noobie at this. This is my code for the game so far: impo...
[ "It's a matter of Indentation. You have to do the movement in the application and not in the event loop. The code in the event loop is executed only when an event occurs (for example, a mouse movement):\ndef main():\n # [...]\n\n while run:\n clock.tick(FPS)\n for event in pygame.event.get():\n ...
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074145103_pygame_python.txt
Q: Write a Python code that replaces all the integers of the list below, including integers inside sublists, with their squared values I want to square the values within this list, but I keep getting [1, 3, [0, 10], 8, 9, [13]] as my output. This is my code: new_list = [1,3, [0,10], 8, 9, [13]] for i in range(len(new...
Write a Python code that replaces all the integers of the list below, including integers inside sublists, with their squared values
I want to square the values within this list, but I keep getting [1, 3, [0, 10], 8, 9, [13]] as my output. This is my code: new_list = [1,3, [0,10], 8, 9, [13]] for i in range(len(new_list)): if type(new_list[i]) == int: new_list[i] == (new_list[i] ** 2) else: nested_list1 = new_list[2] ...
[ "You have typos in your code. You have == where you mean =.\nAlso your code keeps on squaring the nested lists more times than it means.\nYou meant to write this code:\nnew_list = [1, 3, [0, 10], 8, 9, [13]]\nfor i in range(len(new_list)):\n if type(new_list[i]) == int:\n new_list[i] = (new_list[i] ** 2)\...
[ 1 ]
[]
[]
[ "for_loop", "list", "python", "replace" ]
stackoverflow_0074145035_for_loop_list_python_replace.txt
Q: hexadecimal to strings using python i am new to python and trying to convert a list of hexadecimal to string chunk= [' ho', 'w a', 're ', 'you'] chunk_2 = [i.encode('utf-8').hex() for i in chunk] print(chunk_2) ['20686f', '772061', '726520', '796f75'] chunk_3 = [int(i, base=16) for i in chunk_2] print(chunk_3) [2...
hexadecimal to strings using python
i am new to python and trying to convert a list of hexadecimal to string chunk= [' ho', 'w a', 're ', 'you'] chunk_2 = [i.encode('utf-8').hex() for i in chunk] print(chunk_2) ['20686f', '772061', '726520', '796f75'] chunk_3 = [int(i, base=16) for i in chunk_2] print(chunk_3) [2123887, 7807073, 7496992, 7958389] (conve...
[ "You can use bytearray for this.\n>>> chunk_4 = ['20686f', '772061', '726520', '796f75']\n>>> [bytes.fromhex(k).decode() for k in chunk_4]\n[' ho', 'w a', 're ', 'you']\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074145088_python.txt
Q: Django form: setting initial value on DateField I have the following code to set the initial value for a DateField and CharField. CharField's initial value got set properly, but the DateField's initial value is still blank. class MyForm(forms.ModelForm): dummy = fiscal_year_end = forms.CharField() date = ...
Django form: setting initial value on DateField
I have the following code to set the initial value for a DateField and CharField. CharField's initial value got set properly, but the DateField's initial value is still blank. class MyForm(forms.ModelForm): dummy = fiscal_year_end = forms.CharField() date = forms.DateField() def __init__(self, *args, **kw...
[ "You can set the default value in the same line where you're creating the DateField:\ndate = forms.DateField(initial=datetime.date.today)\n\nOr if you want to pass a specific date, you could create a funciton and pass it to the DateField, as follows:\ndef my_date():\n return datetime.date(year=today.year-1, mont...
[ 16, 2, 2, 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0036881089_django_django_forms_python.txt
Q: Accessing value in list by function I want to access the value of the term 'just' but somehow it gives the error: 'NoneType' object is not subscriptable. How can I solve this def count_words(word_list): "Count word frequencies of words in a list." cnt_dict = dict() for word in word_list:...
Accessing value in list by function
I want to access the value of the term 'just' but somehow it gives the error: 'NoneType' object is not subscriptable. How can I solve this def count_words(word_list): "Count word frequencies of words in a list." cnt_dict = dict() for word in word_list: if word in cnt_dict: ...
[ "You need to return the dict at the end of your function. End your function with return cnt_dict.\n", "It works!\ndef count_words(word_list):\n \n \"Count word frequencies of words in a list.\"\n \n cnt_dict = dict()\n \n for word in word_list:\n if word in cnt_dict:\n cnt_dict...
[ 0, 0 ]
[]
[]
[ "dictionary", "function", "list", "loops", "python" ]
stackoverflow_0074145108_dictionary_function_list_loops_python.txt
Q: Asyncio is blocking using FastAPI I have a function that make a post request with a lot of treatment. All of that takes 30 seconds. I need to execute this function every 6 mins. So I used asyncio for that ... But it's not asynchrone my api is blocked since the end of function ... Later I will have treatment that t...
Asyncio is blocking using FastAPI
I have a function that make a post request with a lot of treatment. All of that takes 30 seconds. I need to execute this function every 6 mins. So I used asyncio for that ... But it's not asynchrone my api is blocked since the end of function ... Later I will have treatment that takes 5 minutes to execute. def update_a...
[ "I found an answer with the indication of larsks\nI did that :\ndef update_all():\n # Do synchrone post request and treatment that take long time\n\nasync def launch_async():\n loop = asyncio.get_event_loop()\n while True:\n await asyncio.sleep(120)\n loop.run_in_executore(None, update_all)\n...
[ 2 ]
[]
[]
[ "fastapi", "python", "python_asyncio" ]
stackoverflow_0074143846_fastapi_python_python_asyncio.txt
Q: How to remove big spaces in my scraped texts? I am trying to remove big spaces from the code result: from bs4 import BeautifulSoup import requests url = 'https://www.rucoyonline.com/characters/Something' response = requests.get(url) print(response.status_code) soup = BeautifulSoup(response.text, 'html.parser') ...
How to remove big spaces in my scraped texts?
I am trying to remove big spaces from the code result: from bs4 import BeautifulSoup import requests url = 'https://www.rucoyonline.com/characters/Something' response = requests.get(url) print(response.status_code) soup = BeautifulSoup(response.text, 'html.parser') table = soup.find('table', class_ = 'character-ta...
[ "One line answer:\nprint(\"\\n\".join([s for s in table.get_text().split(\"\\n\") if s]))\n\nOutput:\nCharacter Information\nName\nSomething\nLevel\n28\nLast online\n about 6 years ago\nBorn\nSeptember 03, 2016\n\nAnd to remove trailing and leading spaces\nprint(\"\\n\".join([s.strip() for s in t...
[ 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074145050_beautifulsoup_python_web_scraping.txt
Q: How do I convert a string of a floating point decimal number into a float type? I have a 32bit floating point decimal in sting format. I want to get it into float format. For exmaple, how do I convert this string: '01000010000000001110111010011000' into this float: 32.233001709 Perhaps there is some intermediate s...
How do I convert a string of a floating point decimal number into a float type?
I have a 32bit floating point decimal in sting format. I want to get it into float format. For exmaple, how do I convert this string: '01000010000000001110111010011000' into this float: 32.233001709 Perhaps there is some intermediate step where the string is converted into binary: 0b01000010000000001110111010011000?
[ "Adapting my answer from one of the questions posted as a possible duplicate:\ns2 = '01000010000000001110111010011000'\nstruct.unpack('f', struct.pack('I', int(s2, 2)))[0]\n\nIt's a three-step process. First convert the binary string to int. Second convert that to a sequence of bytes. Third convert those bytes t...
[ 0 ]
[]
[]
[ "casting", "python" ]
stackoverflow_0074145008_casting_python.txt
Q: download csv data from multiple URLs and combine to a single dataframe I'm new to Python and trying to combine multiple 1-row DataFrames after downloading each via URL. I've been trying to use pandas pd.concat() without success. So far I get the individual DataFrames correctly, but combining them is not working us...
download csv data from multiple URLs and combine to a single dataframe
I'm new to Python and trying to combine multiple 1-row DataFrames after downloading each via URL. I've been trying to use pandas pd.concat() without success. So far I get the individual DataFrames correctly, but combining them is not working using the following script: import pandas as pd import time from time import s...
[ "you need two DFs for concat to combine\nchange as follows\n# define the empty dataframe prior to the line '`With open`', below `count=0`\nbig_df=pd.DataFrame()\n\nbig_df = pd.concat([big_df, dfs],ignore_index=True)\n\n" ]
[ 0 ]
[]
[]
[ "concatenation", "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074145194_concatenation_csv_dataframe_pandas_python.txt
Q: Create a graph at the start of an application in kivy (NoneType object has no Atribute "Get_Screen") I have created a small kivy app for summarizing my Grades and everything works just fine until the point where i want to display a graph at the start of the application so i am able to display the graph correctly o...
Create a graph at the start of an application in kivy (NoneType object has no Atribute "Get_Screen")
I have created a small kivy app for summarizing my Grades and everything works just fine until the point where i want to display a graph at the start of the application so i am able to display the graph correctly on a press of a button(click Mathe and then back it calls the function) however trying to call the same fun...
[ "In your App:\ndef on_start(self, **kwargs):\n mw = MainWindow()\n mw.Allgemeinepunkte()\n\nThis method creates a new instance of MainWindow, and calls its Allgemeinepunkte() method. But since the new instance of MainWindow is not added to a ScreenManager, its manager property is None. You need to access the ...
[ 0 ]
[]
[]
[ "graph", "kivy", "python" ]
stackoverflow_0074141053_graph_kivy_python.txt
Q: Python Django update variable in template while function runs in background I have this simple template which has a button: <a class="button" href="{% url 'function' %}"> <button> Settings </button> </a> And views.py in which I have function definition. def function(request): context = {} ...
Python Django update variable in template while function runs in background
I have this simple template which has a button: <a class="button" href="{% url 'function' %}"> <button> Settings </button> </a> And views.py in which I have function definition. def function(request): context = {} object = Runner() object.prepate_sth() context['tasks'] = runner.tasks.r...
[ "With Django, the short answer is you cannot. Once the HTML/template is rendered on the client side you cannot change it without refreshing and the current way you have it the thread would restart, so it would always show that initial value.\nWith Javascript & Websockets, or just a bunch of Javascript Ajax posts ev...
[ 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074144743_django_django_templates_python.txt
Q: Why Python stores an array in a function this way? I was checking tiny scripts and noticed this: def foo( a = [] ): a += [1] print(a) foo() # prints [1] foo() # prints [1,1] foo() # prints [1,1,1] Why does this happen instead of printing only [1]?
Why Python stores an array in a function this way?
I was checking tiny scripts and noticed this: def foo( a = [] ): a += [1] print(a) foo() # prints [1] foo() # prints [1,1] foo() # prints [1,1,1] Why does this happen instead of printing only [1]?
[]
[]
[ "You basically append element to your list. For example [1] + [1] would be [1, 1].\n" ]
[ -3 ]
[ "function", "list", "python" ]
stackoverflow_0074145295_function_list_python.txt
Q: Why I get this output while I trying to print this packed struct? I running this code in python: import struct res = struct.pack('hhl', 1, 2, 3) print(res) and I get the following output: b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' but I don't understand why this is the output? after all,...
Why I get this output while I trying to print this packed struct?
I running this code in python: import struct res = struct.pack('hhl', 1, 2, 3) print(res) and I get the following output: b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' but I don't understand why this is the output? after all, the format h means 2 bytes, and the format l means 4 bytes. so why i g...
[ "From the struct doc,\n\nTo handle platform-independent data formats or omit implicit pad\nbytes, use standard size and alignment instead of native size and\nalignment\n\nBy default h may be padded, depending on the platform you are running on. Select \"big-endian\" (>), \"little-endian\" (<) or the alternate nativ...
[ 2 ]
[]
[]
[ "byte", "pack", "python", "python_3.x" ]
stackoverflow_0074145197_byte_pack_python_python_3.x.txt
Q: Pandas type conversion not working in my case I've a Data Frame like this. I'm trying to use pd.numeric pd.numeric import pandas as pd import numpy as np series = pd.Series([0,1,2,2,3,4,7,8.2,"stackoverflow",7,9.9]) df = pd.to_numeric(series, errors="coerce") print(df) output I got as expected 0 0.0 ...
Pandas type conversion not working in my case
I've a Data Frame like this. I'm trying to use pd.numeric pd.numeric import pandas as pd import numpy as np series = pd.Series([0,1,2,2,3,4,7,8.2,"stackoverflow",7,9.9]) df = pd.to_numeric(series, errors="coerce") print(df) output I got as expected 0 0.0 1 1.0 2 2.0 3 2.0 4 3....
[ "This is strange behaviour. I guess it because values are not scalar .\nJust create a np array list of particular row & try uisng pd.to_numeric\nimport pandas as pd\nimport numpy as np\n\nseries = pd.Series([0,1,2,2,3,np.array(4),7,8.2,\"stackoverflow\",7,9.9])\n\n\ndf = pd.DataFrame(series)\n\nserieslist = np.arra...
[ 1, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074144670_numpy_pandas_python.txt
Q: Generating image from MNIST Data I am quite new to python and pytorch. Please review my code below. I have tried everything I know but I am not able to create a MNIST data set image out of the matrix below. I expect the image should be 1. It would be great if someone can help me in it. import torch import torch.n...
Generating image from MNIST Data
I am quite new to python and pytorch. Please review my code below. I have tried everything I know but I am not able to create a MNIST data set image out of the matrix below. I expect the image should be 1. It would be great if someone can help me in it. import torch import torch.nn.functional as F import torch.optim a...
[ "Try change this plt.imshow(data_value.numpy()[0], cmap='gray') to plt.imshow(data_value['image'].numpy()[0], cmap='gray').\nYour output is not a torch.Tensor is dict than contains two labels \"image\" (Tensor) and \"digit\" (int).\nIs for that reason you have this error AttributeError: 'dict' object has no attribu...
[ 0 ]
[]
[]
[ "mnist", "python", "pytorch" ]
stackoverflow_0074143100_mnist_python_pytorch.txt
Q: How to count how many times I got the certain result I am trying to write a code that would select 5 numbers between 1-10 and choose the maximum of them. I repeat the experiment 1000 times but I want to see how many times ı get the which result import random for i in range (1,1000): b = random.choices(range(1,...
How to count how many times I got the certain result
I am trying to write a code that would select 5 numbers between 1-10 and choose the maximum of them. I repeat the experiment 1000 times but I want to see how many times ı get the which result import random for i in range (1,1000): b = random.choices(range(1, 11), k=5) max(b) print("The X value for %(n)s is ...
[ "Use defaultdict.\nimport random\nfrom collections import defaultdict\n\ncounter = defaultdict(int)\nfor i in range(1, 1000):\n numbers = random.choices(range(1, 11), k=5)\n counter[max(numbers)] += 1\nprint(counter)\n\nOutput:\ndefaultdict(<class 'int'>, {10: 406, 8: 161, 9: 269, 7: 86, 6: 40, 5: 25, 4: 10, ...
[ 2, 2, 1, 0 ]
[]
[]
[ "cumulative_sum", "python" ]
stackoverflow_0074145291_cumulative_sum_python.txt
Q: Discordpy buttons avoid button spam Is there any simplistic way to avoid people from spamming a button, I have a ticket bot with a simple discord button and embed, but people can spam the button 5-10 times and create numerous tickets. How can I stop this? A: You can create your own cooldown for buttons, here is ...
Discordpy buttons avoid button spam
Is there any simplistic way to avoid people from spamming a button, I have a ticket bot with a simple discord button and embed, but people can spam the button 5-10 times and create numerous tickets. How can I stop this?
[ "You can create your own cooldown for buttons, here is an example taken from the discord.py discord server:\nclass ButtonOnCooldown(commands.CommandError):\n def __init__(self, retry_after: float):\n self.retry_after = retry_after\n\n# you can also use a lambda if it's simple enough\n# this function works simil...
[ 1, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074143448_discord.py_python.txt
Q: why my Tiled collisions doesn´t work in my pygame project? Im following a tutorial to make a game working with some pygame tiled and pytmx stuff, but however, we added a new object´s layer with some empty rectangles over the tiles where the player is not being able to enter, then we maked a wall´s list to put ins...
why my Tiled collisions doesn´t work in my pygame project?
Im following a tutorial to make a game working with some pygame tiled and pytmx stuff, but however, we added a new object´s layer with some empty rectangles over the tiles where the player is not being able to enter, then we maked a wall´s list to put inside this "walls" and then we maded a couple of functions to chec...
[ "Since Tiled 1.9, \"type\" was renamed to \"class\", for consistency between all different kinds of objects, which can now all have a custom class.\nLikely pytmx has not been updated yet with this change. Fortunately, since this change affected compatibility, Tiled provides an option to use the \"Tiled 1.8\" format...
[ 1 ]
[]
[]
[ "collision", "pygame", "python", "pytmx", "tiled" ]
stackoverflow_0074091456_collision_pygame_python_pytmx_tiled.txt
Q: How to reference a dictionary key based on the function object I have a function object in a dictionary called parsing_map how do I reference the dictionary key based on what the function object is called import pandas as pd import numpy as np data= [["john",np.nan,np.nan,"English"]] df= pd.DataFrame(data,columns...
How to reference a dictionary key based on the function object
I have a function object in a dictionary called parsing_map how do I reference the dictionary key based on what the function object is called import pandas as pd import numpy as np data= [["john",np.nan,np.nan,"English"]] df= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communication_Language__c']) d...
[ "I'm a little bit confused, but if you just want to get all the dictionary keys that have a certain value, you can do smth. like this:\n[col for col,func in d.items() if func == lang]\n\nThis would output you a list of all dictionary keys that have the the function lang as dictionary key. Does this help you?\nif yo...
[ 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074145218_dictionary_pandas_python.txt
Q: Pandas df return indices of duplicated elements as a list I'd like to have the indexes of duplicated column elements as a list. So far, the way I found is test = ['a', 'a', 'b', 'c', 'b'] testdf = pd.DataFrame(test, columns=['test']) np.asarray(np.where(list(testdf['test'].duplicated()))).tolist()[0] # [1, 4] Whi...
Pandas df return indices of duplicated elements as a list
I'd like to have the indexes of duplicated column elements as a list. So far, the way I found is test = ['a', 'a', 'b', 'c', 'b'] testdf = pd.DataFrame(test, columns=['test']) np.asarray(np.where(list(testdf['test'].duplicated()))).tolist()[0] # [1, 4] Which seems ridiculously convoluted. Any better way?
[ "Try this just indexing the index:\ntestdf.index[testdf['test'].duplicated()]\n\nadd to_list:\ntestdf.index[testdf['test'].duplicated()].to_list()\n\nOutput:\n[1, 4]\n\n", "you can use .duplicated() with .tolist()\ntestdf.index[testdf.test.duplicated()].tolist()\n\n", "%%time\n\ntest = ['a', 'a', 'b', 'c', 'b']...
[ 1, 1, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074144626_numpy_pandas_python.txt
Q: Getting exact value in decimal in data frames I have a data frame with a large set of records. When reading the data from an excel file, it discards values after the decimal point. Actual Value Code: df_temp=df_A2C.loc[ (df_A2C['TO_ID'] == 7)] mini_value = df_temp['DURATION_H'].min() print("minimum value in colum...
Getting exact value in decimal in data frames
I have a data frame with a large set of records. When reading the data from an excel file, it discards values after the decimal point. Actual Value Code: df_temp=df_A2C.loc[ (df_A2C['TO_ID'] == 7)] mini_value = df_temp['DURATION_H'].min() print("minimum value in column 'TO_ID' is: " , mini_value) Correct Output: mini...
[ "refer to the set_option document\npd.set_option(\"display.precision\", 16)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "python_3.x" ]
stackoverflow_0074145501_dataframe_jupyter_notebook_pandas_python_python_3.x.txt
Q: Not getting any output when using 'in', only getting output when using 'not in' So I had to write some code for my class that takes a date input and based on the month/day outputs the season. When I use "in" on the 10th line I don't get any output, not even 'Invalid' the only time I get an output is when is use 'n...
Not getting any output when using 'in', only getting output when using 'not in'
So I had to write some code for my class that takes a date input and based on the month/day outputs the season. When I use "in" on the 10th line I don't get any output, not even 'Invalid' the only time I get an output is when is use 'not in'. I'm confused why that happens if anyone could explain it to me I would really...
[ "You are trying to find the input_month in a 2 dimensional list i.e. month_list\nIf you check:\nmonth_winter = ['January', 'February', 'March', 'December']\nmonth_spring = ['March', 'April', 'May', 'June']\nmonth_summer = ['June', 'July', 'August', 'September']\nmonth_autumn = ['September', 'October', 'November', '...
[ 1 ]
[]
[]
[ "if_statement", "list", "python" ]
stackoverflow_0074145404_if_statement_list_python.txt
Q: Name 'x' not defined What is the root of the error I get when running this function and why? The error I get is "name 'one' is not defined". I did define it though? def One(): one = input("Type something: ") def Two(one): One() print(one) Two(one) A: one is defined, and therefore only visible insid...
Name 'x' not defined
What is the root of the error I get when running this function and why? The error I get is "name 'one' is not defined". I did define it though? def One(): one = input("Type something: ") def Two(one): One() print(one) Two(one)
[ "one is defined, and therefore only visible inside the One() method.\nYou could get around this by using a global:\n# This is our global\none = None\n\ndef One():\n global one\n one = input(\"Type something: \")\n\ndef Two():\n global one\n print(one)\n\nTwo()\n\nor better yet, to return the value from ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074145488_python.txt
Q: How to automatically update a field when creating another record in different models? I have two models that look like this: class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.SET(get_default_team_member), verbose_name='Member Name', related_name="team_members") ...
How to automatically update a field when creating another record in different models?
I have two models that look like this: class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.SET(get_default_team_member), verbose_name='Member Name', related_name="team_members") team = models.ManyToManyField('Team', verbose_name='Team Name', related_na...
[ "You can do like this:\nform = TeamMemberForm()\nif form.is_valid():\n instance = form.save()\n team = Team.objects.create(name=\"John\")\n instance.members.add(team)\n\n", "class MyModel(models.Model):\n name = models.CharField(max_length=200, unique=True)\n slug = models.SlugField(blank=True, uni...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python", "python_3.x" ]
stackoverflow_0074144343_django_django_models_python_python_3.x.txt
Q: Combine big data stored in subdirectories as 100,000+ CSV files of size 200 GB with Python I want to create an algorithm to extract data from csv files in different folders / subfolders. each folder will have 9000 csvs. and we will have 12 of them. 12*9000. over 100,000 files A: If the files have consistent stru...
Combine big data stored in subdirectories as 100,000+ CSV files of size 200 GB with Python
I want to create an algorithm to extract data from csv files in different folders / subfolders. each folder will have 9000 csvs. and we will have 12 of them. 12*9000. over 100,000 files
[ "If the files have consistent structure (column names and column order), then dask can create a large lazy representation of the data:\nfrom dask.dataframe import read_csv\n\nddf = read_csv('my_path/*/file_*.csv')\n\n# do something\n\n", "This is working solution for over 100,000 files\nCredits : Abhishek Thakur ...
[ 1, 0 ]
[ "You can read CSV-files using pandas and store them space efficiently on disk:\nimport pandas as pd\nfile = \"your_file.csv\"\ndata = pd.read_csv(file)\ndata = data.astype({\"column1\": int})\ndata.to_hdf(\"new_filename.hdf\", \"key\")\n\nDepending on the contents of your file, you can make adjustments to read_csv ...
[ -1 ]
[ "dask", "dataframe", "glob", "pandas", "python" ]
stackoverflow_0074142721_dask_dataframe_glob_pandas_python.txt
Q: `torch.round()` is not working as expected I am running a deep network on GPU so ideally all of my code should work effeciently under GPU (so torch rather than numpy) and I am trying to round the tensor values with torch.round() but the result is not expected: testing_value = torch.tensor(3.440000057220459) torch....
`torch.round()` is not working as expected
I am running a deep network on GPU so ideally all of my code should work effeciently under GPU (so torch rather than numpy) and I am trying to round the tensor values with torch.round() but the result is not expected: testing_value = torch.tensor(3.440000057220459) torch.round(testing_value, decimals = 2) this output ...
[]
[]
[ "This how the code should look like:\ntesting_value = torch.tensor(3.440000057220459)\ntorch.set_printoptions(precision=2)\ntorch.round(testing_value, decimals = 2)\n\nOutput:\ntensor(3.44)\n\n" ]
[ -1 ]
[ "deep_learning", "python", "pytorch" ]
stackoverflow_0074145409_deep_learning_python_pytorch.txt
Q: How to convert variable array to nested python list? I have a sample array as shown below. The array size is variable. (example is 4x4) my_array = [[A11, A12, A13, A14], [A21, A22, A23, A24], [A31, A32, A33, A34], [A41, A42, A43, A44]] what I would to do is convert this to a li...
How to convert variable array to nested python list?
I have a sample array as shown below. The array size is variable. (example is 4x4) my_array = [[A11, A12, A13, A14], [A21, A22, A23, A24], [A31, A32, A33, A34], [A41, A42, A43, A44]] what I would to do is convert this to a list in the form [{A11:[{A12:[{A13:[A14]}]}]}] wherein same ...
[ "Welcome to StackOverflow! There is probably a more beautiful solution than mine:\ndef nest_array(input):\n result = []\n for row in input:\n current_list = result\n last_item = None\n for item in row:\n if item is not None:\n if len(current_list) == 0 \\\n ...
[ 0 ]
[]
[]
[ "arrays", "dictionary", "list", "nested", "python" ]
stackoverflow_0074109762_arrays_dictionary_list_nested_python.txt
Q: Remove margin around QTabWidget in python I am making a web browser in qt5 for fun, however there is a margin between the QTabWidget and the window, and does not look appealing. Is there any way to remove it? Here is the app class code class App(QWidget): def __init__(self) -> None: super().__init__() ...
Remove margin around QTabWidget in python
I am making a web browser in qt5 for fun, however there is a margin between the QTabWidget and the window, and does not look appealing. Is there any way to remove it? Here is the app class code class App(QWidget): def __init__(self) -> None: super().__init__() #self.windowTitle = "Test!" se...
[ "As suggested in the comments, you can assign the specific margins using the a method of QLayout.\nFor example to completely eliminate the margin altogether you can use:\nclass App(QWidget):\n def __init__(self) -> None:\n super().__init__()\n\n #self.windowTitle = \"Test!\"\n self.layout = ...
[ 1 ]
[]
[]
[ "pyqt5", "python", "qt", "qt5" ]
stackoverflow_0074143291_pyqt5_python_qt_qt5.txt
Q: Split The Second String of Every Element in a List into Multiple Strings I am very very new to python so I'm still figuring out the basics. I have a nested list with each element containing two strings like so: mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']] I would like to iterate through ...
Split The Second String of Every Element in a List into Multiple Strings
I am very very new to python so I'm still figuring out the basics. I have a nested list with each element containing two strings like so: mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']] I would like to iterate through each element in mylist, and split the second string into multiple strings so i...
[ "You can use list comprehension\nmylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]\nreq_list = [[i[0]]+ i[1].split() for i in mylist]\n# [['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]\n\n", "I agree with @DeepakTripathi's list comprehension suggestion (+1) but I...
[ 3, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074145360_list_python_string.txt
Q: "Importing test library 'Selenium2Library' failed: ImportError: No module named decorator" RobotFramework maven plugin Attempting to run a simple test in a Maven Java Project in IntelliJ 2016.2 on OS X El Capitan 10.11.6 using RobotFramework-Maven-Plugin 1.4.6 http://robotframework.org/MavenPlugin/ If the test is...
"Importing test library 'Selenium2Library' failed: ImportError: No module named decorator" RobotFramework maven plugin
Attempting to run a simple test in a Maven Java Project in IntelliJ 2016.2 on OS X El Capitan 10.11.6 using RobotFramework-Maven-Plugin 1.4.6 http://robotframework.org/MavenPlugin/ If the test is run using robot through command line the test opens a firefox browser, runs and passes: *** Settings *** Library Selenium2...
[ "I figured out what I was doing wrong, I still don't have running tests but I'm past this issue. Basically if you're using the RobotFramework Selenium2Library java port, you no longer need to follow the directions on the site about having the Selenium2Library under /src/test/resources/robotframework/libaries\nYou d...
[ 2, 0 ]
[]
[]
[ "intellij_idea", "java", "maven", "python", "robotframework" ]
stackoverflow_0040621698_intellij_idea_java_maven_python_robotframework.txt
Q: KeyError: I've been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it in Render i always get this error in every route. [55] [ERROR] Error handling request /valle-de-guadalupe...
KeyError:
I've been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it in Render i always get this error in every route. [55] [ERROR] Error handling request /valle-de-guadalupe Traceback (most...
[ "It's usually best to remove as many extra components and identify a minimal example that produces the error, otherwise it's often hard to help.\nThat said, I think that error suggests that db (SQLAlachemy() from flask-sqlalchemy) is not being inited with app.\nI'm not sure what the db is that is being imported fro...
[ 0 ]
[]
[]
[ "flask", "keyerror", "python", "weak_references" ]
stackoverflow_0074134089_flask_keyerror_python_weak_references.txt
Q: Compare all the lists contained in a nested list to get only the strings that match I want to compare all the lists contained in a nested list to have at the end the pair word who corresponding. I manage this with 2 different lists to get the strings that match in each list. In this way : listA = [['Test1','Test2'...
Compare all the lists contained in a nested list to get only the strings that match
I want to compare all the lists contained in a nested list to have at the end the pair word who corresponding. I manage this with 2 different lists to get the strings that match in each list. In this way : listA = [['Test1','Test2','Test3'], ['Test1','Test4','Test2']] listB = [['Test1','Test2','Test5'], ['Test10','Test...
[ "You could try set intersection in list comprehension\nfrom itertools import product\nlistA = [['Test1','Test2','Test3'], ['Test1','Test4','Test2']]\nlistB = [['Test1','Test2','Test5'], ['Test10','Test4','Test2']]\nset(tuple(set(x)&set(y)) for x,y in product(listA, listB))\n\n# output\n{('Test1', 'Test2'), ('Test2...
[ 0 ]
[]
[]
[ "compare", "matching", "nested_lists", "python", "sorting" ]
stackoverflow_0074145598_compare_matching_nested_lists_python_sorting.txt
Q: Python how to flip coins in a list to get 3 heads in a row? the problem I'm having is that I can't seem to get the coins to flip at all. I can populate the list but when the program gets to the flip funtion it crashes. I have no idea how to get this working. this is the error I get: Traceback (most recent call las...
Python how to flip coins in a list to get 3 heads in a row?
the problem I'm having is that I can't seem to get the coins to flip at all. I can populate the list but when the program gets to the flip funtion it crashes. I have no idea how to get this working. this is the error I get: Traceback (most recent call last): File "/home/unseensnick/VS Code Projects/python projects/ja...
[ "got it working thanks to @TomMcLean\nhere is the working code:\nMain.py\nfrom Coins import Coins\n\ncurrentWinner = 9223372036854775807\n winningCoin = \"\"\n winnerCount = 0\n num = 0\n coins = []\n\n answer = int(input(\"how many coins do you want to flip? \"))\n \n #populate list\n for i...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074145568_python_python_3.x.txt
Q: Python-docx: how to save each edited ".docx" file while retaining the original name ".docx" in a new folder I'm new to Python:docx and need some help with my script. the script should pick up all ".docx" in that folder. For each of those ".docx", the Python script replaces certain strings. After editing each ".do...
Python-docx: how to save each edited ".docx" file while retaining the original name ".docx" in a new folder
I'm new to Python:docx and need some help with my script. the script should pick up all ".docx" in that folder. For each of those ".docx", the Python script replaces certain strings. After editing each ".docx", these are saved into a different folder under the original .docx file. I tried a few things but I was unable...
[ "With Python3, please ensure pip install python-docx.\nimport docx\nimport glob\nimport os\nimport shutil\n\n# get all docx files in current directory\nfiles = glob.glob('*.docx')\n\n# create backup folder\nif not os.path.exists('backup'):\n os.makedirs('backup')\n# copy original files\nfor file in files:\n #...
[ 1 ]
[]
[]
[ "python", "savefiledialog" ]
stackoverflow_0074144521_python_savefiledialog.txt
Q: Numbering loop python Please I'm trying to number this loop: TopList = {'1350180828': 3, '1670937087': 2, '0743180828': 1, '9864937087': 8} meg = "Top Referral List\n" sort = sorted(TopList.items(), key=lambda x: x[1], reverse=True) for info in sort: num = 1 userlink = f'<a href="tg://user?id={info[0]}">...
Numbering loop python
Please I'm trying to number this loop: TopList = {'1350180828': 3, '1670937087': 2, '0743180828': 1, '9864937087': 8} meg = "Top Referral List\n" sort = sorted(TopList.items(), key=lambda x: x[1], reverse=True) for info in sort: num = 1 userlink = f'<a href="tg://user?id={info[0]}">{info[0]}</a>' meg += f...
[ "You can do this,\nTopList = {'1350180828': 3, '1670937087': 2, '0743180828': 1, '9864937087': 8}\nmeg = \"Top Refferal List\\n\"\n\nsorted_keys = sorted(TopList, key=TopList.get, reverse=True)\nfor idx, key in enumerate(sorted_keys,1):\n userlink = f'<a href=\"tg://user?id={key}\">{key}</a>'\n meg += f\"\\n{...
[ 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074145646_dictionary_python.txt
Q: Modify *args by decorator in python I would like to check and change, if necessary, the type of a function's parameter with decorator, i.e. something like that: def convert_argument_types(func): def inner(*args): for arg in args: if not isinstance(arg, something): arg = conv...
Modify *args by decorator in python
I would like to check and change, if necessary, the type of a function's parameter with decorator, i.e. something like that: def convert_argument_types(func): def inner(*args): for arg in args: if not isinstance(arg, something): arg = convertToSomething(arg) return func(*...
[ "Assigning to arg has no effect on args; the variable gets a reference to the value of the tuple element, not a reference to the tuple itself.\nIn addition, since tuples are immutable, you can't modify it in place.\nUse a list comprehension to make a new list with the modified values.\nargs = [arg if isinstance(arg...
[ 1 ]
[]
[]
[ "arguments", "decorator", "python", "python_decorators" ]
stackoverflow_0074145690_arguments_decorator_python_python_decorators.txt
Q: Why is the variable automatically going to 255 when I try to add it by 1? So I have a variable set to go up by "1" in a pygame loop, for a fade effect. For some reason, it's going to 255 when I want to go up by 1 at a time. Here's what I have: while alph <= 255: alph += 1 A: Likely, if you're working with a ...
Why is the variable automatically going to 255 when I try to add it by 1?
So I have a variable set to go up by "1" in a pygame loop, for a fade effect. For some reason, it's going to 255 when I want to go up by 1 at a time. Here's what I have: while alph <= 255: alph += 1
[ "Likely, if you're working with a game, there's already a looping function built into pygame, where each time it finishes a loop that's a completed frame. Thus, during a single pygame loop (single frame) it encounters the code you've written here, and must update alph from 0 to 256 all in one frame before it can ex...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074145716_python.txt
Q: Python run non-blocking async function from sync function Is there a way to call an async function from a sync one without waiting for it to complete? My current tests: Issue: Waits for test_timer_function to complete async def test_timer_function(): await asyncio.sleep(10) return def main(): print(...
Python run non-blocking async function from sync function
Is there a way to call an async function from a sync one without waiting for it to complete? My current tests: Issue: Waits for test_timer_function to complete async def test_timer_function(): await asyncio.sleep(10) return def main(): print("Starting timer at {}".format(datetime.now())) asyncio.run(...
[ "Async functions really do not run in the background: they run always in a single thread.\nThat means that when there are parallel tasks in async code (normal async code), it is only when you give a chance to the asyncio loop to run that those are executed - this happens when your code uses await, call one of async...
[ 2, 1 ]
[]
[]
[ "async_await", "asynchronous", "python", "python_asyncio" ]
stackoverflow_0074145286_async_await_asynchronous_python_python_asyncio.txt
Q: During handling of the above exception, another exception occurred, Pytest giving an error in ValueError I am a new learner in Python and here I have try-except to catch ValueErrors and conditional statements to catch the same error as well. import re def main(): print(convert(input("Hours: "))) def convert(...
During handling of the above exception, another exception occurred, Pytest giving an error in ValueError
I am a new learner in Python and here I have try-except to catch ValueErrors and conditional statements to catch the same error as well. import re def main(): print(convert(input("Hours: "))) def convert(s): try: # matches := re.search(r"^(\d+)\:?(.+)? to (\d+)\:?(.+)?$", s) if (matches := r...
[ "Instead of assert convert(\"9:00 AM 5:00 PM\") == ValueError\ntry using the following syntax:\nwith pytest.raises(ValueError):\n convert(\"9:00 AM 5:00 PM\")\n\nThe issue is that you need to tell the testing framework that you expect to raise an error. Otherwise it won't know whether the error it hits was delib...
[ 1 ]
[]
[]
[ "pytest", "python", "python_3.x", "valueerror" ]
stackoverflow_0074145208_pytest_python_python_3.x_valueerror.txt
Q: Plotly won't plot my time data when converted to a datetime object but will plot my unix epoch time array EDIT This must be done in vanilla JS or PYTHON I've been having some issues with my code - I am doing some data science applications and decided to build a web-gui for my team and some other engineering partne...
Plotly won't plot my time data when converted to a datetime object but will plot my unix epoch time array
EDIT This must be done in vanilla JS or PYTHON I've been having some issues with my code - I am doing some data science applications and decided to build a web-gui for my team and some other engineering partners (I am not a classically trained CS guy). I have the following going on: 1.) I am managing my front and back ...
[ "Not sure if you needed this in JS, but in Python you could do something like this:\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\n\n#provided data\ndf = pd.DataFrame({'time':[1666202064.0, 1666202065.0, 1666202066.0, 1666202067.0, 1666202068.0, 1666202069.0, 1666202070.0, 1666202071.0, 1666...
[ 0 ]
[]
[]
[ "css", "data_science", "javascript", "plotly", "python" ]
stackoverflow_0074144813_css_data_science_javascript_plotly_python.txt
Q: How to insert comment in desired position in XML using Python I am finding elements from XML1 in XML2 and after that i want to insert one comment XML1 is: <Price> <Amount>100</Amount> <Amount>102</Amount> <Amount>103</Amount> </Price> and XML2 is: <List> <Item> <Price> <Amount>...
How to insert comment in desired position in XML using Python
I am finding elements from XML1 in XML2 and after that i want to insert one comment XML1 is: <Price> <Amount>100</Amount> <Amount>102</Amount> <Amount>103</Amount> </Price> and XML2 is: <List> <Item> <Price> <Amount>100</Amount> <Next_Item> <Name>Apple</N...
[ "Since you need to compare across documents and traverse multiple nodes with conditional logic to add comment, consider XSLT, the special-purpose language designed to transform XML files. Python's lxml library can run XSLT 1.0 scripts. Also, XSLT maintains the document function to parse from other documents.\nSpeci...
[ 1, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0074143157_lxml_python_xml.txt
Q: BeautifulSoup getting href of a list - need to simplify the script - in order to run in Colab I have the following soup: next ... From this I want to extract the href, "some_url" this I want to extract the href, "some_url" and the whole list of the pages that are listed on this page: https://www.catholic-hierarch...
BeautifulSoup getting href of a list - need to simplify the script - in order to run in Colab
I have the following soup: next ... From this I want to extract the href, "some_url" this I want to extract the href, "some_url" and the whole list of the pages that are listed on this page: https://www.catholic-hierarchy.org/diocese/laa.html note: there are a whole lot of links to sub-pages: which i need to parse. a...
[ "It seems that the problem is that some libs are missing. I tried to run here on colabs and after running the command below, it worked fine.\n!pip install httpx nest_asyncio\nTry running this code before your script.\nNote that the exclamation point is part of the command.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "google_colaboratory", "parsing", "python", "web_scraping" ]
stackoverflow_0074145704_beautifulsoup_google_colaboratory_parsing_python_web_scraping.txt
Q: How does order of defining variables affect my program? import pygame,shooter_f background_colour = (87, 151, 153) (width, height) = (1920, 1080) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Shooter 2D Game') screen.fill(background_colour) pygame.display.flip() class player: ...
How does order of defining variables affect my program?
import pygame,shooter_f background_colour = (87, 151, 153) (width, height) = (1920, 1080) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Shooter 2D Game') screen.fill(background_colour) pygame.display.flip() class player: global screen def __init__(self,x,y,colour,speed): ...
[ "draw draws the bullet at the position (self.new_x//2, self.new_y//2). Therefore, you must draw the rectangle with the background color at (self.old_x//2, self.old_y//2) instead of (self.old_x, self.old_y) in the function clear_up:\npygame.draw.rect(screen,background_colour,(self.old_x,self.old_y,33,33))\npygame.dr...
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074145782_pygame_python.txt
Q: Using np.linalg.lstsq to solve for multiple variables I was given data and made a matrix based on the equation needed for the data. I converted it to ln(A)=ln(a) + bln(W) +cln(H), where A,W,H are given to me for multiple different values. I need to make a matrix out of them and solve for a,b,c. I've been trying to...
Using np.linalg.lstsq to solve for multiple variables
I was given data and made a matrix based on the equation needed for the data. I converted it to ln(A)=ln(a) + bln(W) +cln(H), where A,W,H are given to me for multiple different values. I need to make a matrix out of them and solve for a,b,c. I've been trying to do it based on the numpy book instructions but I keep gett...
[ "Not really deep into your problem myself, however, after some play-around the following was obtained:\nx = np.array(\n [\n (1, 1, 1, 1, 1, 1, 1, 1),\n np.log((70, 75, 77, 80, 82, 84, 87, 90)),\n np.log((170, 165, 175, 183, 188, 187, 190, 197))\n ]\n)\ny = np.log((1.86, 1.88, 1.92, 2.15, ...
[ 0 ]
[]
[]
[ "least_squares", "python" ]
stackoverflow_0074145591_least_squares_python.txt
Q: What does cmdclass do in Pythons setuptools? I've recently got a pull request which added class build_ext(_build_ext): 'to install numpy' def finalize_options(self): _build_ext.finalize_options(self) # Prevent numpy from thinking it is still in its setup process: __builtins__.__NUMP...
What does cmdclass do in Pythons setuptools?
I've recently got a pull request which added class build_ext(_build_ext): 'to install numpy' def finalize_options(self): _build_ext.finalize_options(self) # Prevent numpy from thinking it is still in its setup process: __builtins__.__NUMPY_SETUP__ = False import numpy sel...
[ "Numpy libraries are written in C/C++. So unlike other packages, it needs to be compiled before actually calling them. So 'build_ext' just compiles them.\nDetails in blog: http://sadafnoor.me/blog/how-to-automate-numpy-installation-in-your-project-using-setuptool/\n", "All con:\nI found this other blog that expla...
[ 7, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0027817190_python_setuptools.txt
Q: Why is my Datashader plot saved from HoloViews such a low resolution? I'm trying to save plots, generated with holoviews using the bokeh backend, to a png. To do this I'm using the following code import holoviews as hv from holoviews.operation.datashader import datashade curve: hv.Curve = hv.Curve(__some_data_for...
Why is my Datashader plot saved from HoloViews such a low resolution?
I'm trying to save plots, generated with holoviews using the bokeh backend, to a png. To do this I'm using the following code import holoviews as hv from holoviews.operation.datashader import datashade curve: hv.Curve = hv.Curve(__some_data_for_curve__) hv.save(datashade(curve), output_path, backend=bokeh) Unfortunat...
[ "Good question about a subtle issue.\nWhat's happening is that hv.save exports the \"initial\" rendering of a HoloViews object, before any subsequent hooks or streams take effect. The initial rendering includes an RGB image that is the result of HoloViews calling Datashader with initial height and width values dete...
[ 1 ]
[]
[]
[ "bokeh", "holoviews", "python" ]
stackoverflow_0074140828_bokeh_holoviews_python.txt
Q: How to calculate haversine distance between 4 columns correctly I try to calculate haversine distance between 4 columns cgi longitude_bts latitude_bts longitude_poi latitude_poi 0 510-11-32111-7131 95.335142 5.565253 95.337588 5.563713 1 510-11-32111-...
How to calculate haversine distance between 4 columns correctly
I try to calculate haversine distance between 4 columns cgi longitude_bts latitude_bts longitude_poi latitude_poi 0 510-11-32111-7131 95.335142 5.565253 95.337588 5.563713 1 510-11-32111-7135 95.335142 5.565253 95.337588 5.5637...
[ "You're getting meters rather than kilometers. Try this:\nimport pandas as pd\nimport numpy as np\n\ndef haversine(lon1, lat1, lon2, lat2):\n lon1, lat1, lon2, lat2 = np.radians([lon1, lat1, lon2, lat2])\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n haver_formula = np.sin(dlat/2)**2 + np.cos(lat1) * np....
[ 1 ]
[]
[]
[ "haversine", "pandas", "python" ]
stackoverflow_0071747749_haversine_pandas_python.txt
Q: compare one list elements with another list elements My use case is if list2 elements are in list1 then add them to a new list3 and do the set function on list3 and if length is ==2 then print it as partial if length greater than 2 then multiple . I want to add the option column in the excel below. Below excel fi...
compare one list elements with another list elements
My use case is if list2 elements are in list1 then add them to a new list3 and do the set function on list3 and if length is ==2 then print it as partial if length greater than 2 then multiple . I want to add the option column in the excel below. Below excel file can print the 1st and second column but for the `option...
[ "I'm not 100% sure I follow the second half of your question, but here's what you could do for the first part:\nlist3 = set([x for x in list2 if x in list1])\n\n", "Not very optimised way but this will work\nres = set()\nfor i in list1:\n for j in list2:\n if j in i:\n res.add(i)\nif len(res)...
[ 0, 0 ]
[]
[]
[ "list", "pandas", "python" ]
stackoverflow_0074145539_list_pandas_python.txt
Q: python script that would move zip folders to new directory based on their names I am trying to write a script in python which could allow me to move zip files to a new folder based on their names, but I am struggling with it as I cannot figure out how to make python read the zip files name and move it to relevant ...
python script that would move zip folders to new directory based on their names
I am trying to write a script in python which could allow me to move zip files to a new folder based on their names, but I am struggling with it as I cannot figure out how to make python read the zip files name and move it to relevant folders. Any help would be appreciated. zip file names are 12345788_CATPICC1_2022_01_...
[ "Try this, accounting for your own OS and filepaths:\nfrom pathlib import Path\nimport os\nimport shutil\n\npath = Path.cwd() # insert your path\n\nfiles = []\n\nfor file in path.rglob('*.zip'): # loop recursively over all subdirectories\n files.append(file.name)\n\nprint(files)\n\nfor f in files:\n x = f.r...
[ 1, 1, 0 ]
[]
[]
[ "movefile", "python", "zip" ]
stackoverflow_0074141719_movefile_python_zip.txt
Q: How to get steamwebapi to return data I'm trying to pull player stats for specific games. When I try to request data from the steam API, it throws an error. From what I have seen this URL format has worked for many others, I'm not sure why it throws errors. import requests key = '' steamid = '' r = requests.get(f'...
How to get steamwebapi to return data
I'm trying to pull player stats for specific games. When I try to request data from the steam API, it throws an error. From what I have seen this URL format has worked for many others, I'm not sure why it throws errors. import requests key = '' steamid = '' r = requests.get(f'http://api.steampowered.com/ISteamUserStats...
[ "I noticed that you are using http.\nHave you tried https?\nYou may need to pass the verify=False parameter in the request.get call.\n" ]
[ 0 ]
[]
[]
[ "python", "python_requests", "steam_web_api" ]
stackoverflow_0074145842_python_python_requests_steam_web_api.txt
Q: How to make a code ask the same question until a user guesses the word correctly using Python? from itertools import chain, repeat word = "trick or treat" # This is the phrase a user needs to guess prompts = chain( ["You meet a whitch with a cauldron full of candies, what do you say? \n"], repeat("Noope! ...
How to make a code ask the same question until a user guesses the word correctly using Python?
from itertools import chain, repeat word = "trick or treat" # This is the phrase a user needs to guess prompts = chain( ["You meet a whitch with a cauldron full of candies, what do you say? \n"], repeat("Noope! ")) replies = map(input, prompts) valid_response = next(filter(word.__contains__, replies)) print(va...
[ "You can just use a while loop:\nword = \"trick or treat\"\nwhile True:\n reply = input(\"You meet a witch with a cauldron full of candies, what do you say? \\n\")\n if word not in reply:\n print(\"Noope!\")\n else:\n print(\"Correct!\")\n break\n\n" ]
[ 2 ]
[]
[]
[ "loops", "module", "python", "recursion" ]
stackoverflow_0074145922_loops_module_python_recursion.txt
Q: LocalProxy wrong in flask I'm a beginner of flask,when i tried to run app.py on the server,it seemed to be wrong.And it can works on localhost. I think it's wrong with the database and have tried to change the ip of database,but it not worked. Traceback (most recent call last): File "app.py", line 27, in <module...
LocalProxy wrong in flask
I'm a beginner of flask,when i tried to run app.py on the server,it seemed to be wrong.And it can works on localhost. I think it's wrong with the database and have tried to change the ip of database,but it not worked. Traceback (most recent call last): File "app.py", line 27, in <module> import auth File "/tmp/...
[ "I had the same issue yesterday (on Flask 2.2.2) only connecting to my production database, not local. I fixed it without downgrading Flask by re-ordering some of the steps initializing my app.\nMy final version was:\nfrom flask import Flask\n\nimport os\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrat...
[ 2, 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074122538_flask_python.txt
Q: How do I setup my python email alerting function such that if no files are present in my source directory,then, i dont receive the email? My script currently works to send me an error alert if my .py script fails. However, sometimes the script is not necessarily failing. its just that there are no files for it to ...
How do I setup my python email alerting function such that if no files are present in my source directory,then, i dont receive the email?
My script currently works to send me an error alert if my .py script fails. However, sometimes the script is not necessarily failing. its just that there are no files for it to process. My final objective is to alter my email alerting script in such a way that if Combine.csv is not present in directory(src),then DONT s...
[ "Just check whether the file you want to read exists:\nimport os\nfile_name = \"Combine.csv\"\ncwd = os.getcwd()\nfile_path = os.path.join(cwd, file_name)\nif not os.path.exists(file_path):\n exit()\n\ncwd means current working directory and is the path to the directory your python file runs in. Then path.join ju...
[ 1, 1 ]
[]
[]
[ "glob", "pandas", "path", "python" ]
stackoverflow_0074145793_glob_pandas_path_python.txt
Q: How to instantiate a scikit-learn model from a string variable? I have a list of models as parameters in a YAML file. When I read them into my Python script, they appear there as strings: my_model = "LinearRegression()" print(type(my_model)) #output: <class 'str'> I want to initialize my sklearn model as: model =...
How to instantiate a scikit-learn model from a string variable?
I have a list of models as parameters in a YAML file. When I read them into my Python script, they appear there as strings: my_model = "LinearRegression()" print(type(my_model)) #output: <class 'str'> I want to initialize my sklearn model as: model = LinearRegression() but with LinearRegression() being a string varia...
[ "You have few options:\n\nUse eval as a quick&dirty solution:\n\nfrom sklearn.linear_model import LinearRegression\nmodel_str = 'LinearRegression()'\nmodel = eval(model_str)\nprint(model)\n\nNote: using eval is not a safe because it will execute any string so if you have no control about a string variable being exe...
[ 0 ]
[]
[]
[ "python", "scikit_learn", "yaml" ]
stackoverflow_0074141661_python_scikit_learn_yaml.txt
Q: Python: Set values of DataFrame as NaN based on valid index from another DataFrame I have two DataFrames: df1: ticker A B C date 2022-01-01 NaN NaN 100 2022-01-02 NaN 200 NaN 2022-01-03 100 NaN NaN 2022-01-04 NaN NaN 120 df2: ...
Python: Set values of DataFrame as NaN based on valid index from another DataFrame
I have two DataFrames: df1: ticker A B C date 2022-01-01 NaN NaN 100 2022-01-02 NaN 200 NaN 2022-01-03 100 NaN NaN 2022-01-04 NaN NaN 120 df2: ticker A B C date 2022-01-02 145 233 100 2022-01...
[ "use this:\ndf2.columns=df2.columns + '2'\nfinal=df.merge(df2,left_on='date',right_on='date2')\nfinal['A2']=np.where(final['A'].notnull(),np.nan,final['A2'])\nfinal['B2']=np.where(final['B'].notnull(),np.nan,final['B2'])\nfinal['C2']=np.where(final['C'].notnull(),np.nan,final['C2'])\nfinal=final[df2.columns]\nfinal...
[ 0, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074144551_dataframe_numpy_pandas_python.txt
Q: Calculating the minimum haversine distance for a set of coordinates I am trying to find an efficient way to calculate the distance to the nearest neighbour for a set of coordinates of form (lat, lon): [[51.51045038114607, -0.1393407528617875], [51.5084300350736, -0.1261805976142865], [51.37912856172232, -0.1038613...
Calculating the minimum haversine distance for a set of coordinates
I am trying to find an efficient way to calculate the distance to the nearest neighbour for a set of coordinates of form (lat, lon): [[51.51045038114607, -0.1393407528617875], [51.5084300350736, -0.1261805976142865], [51.37912856172232, -0.1038613174724213]] I previously had a working (i thought!) piece of code which ...
[ "Depending how big your dataset is, it might be more efficient to convert your data to a Pandas dataframe.\nimport pandas as pd\nimport numpy as np\n\ndef haversine(lon1, lat1, lon2, lat2):\n lon1, lat1, lon2, lat2 = np.radians([lon1, lat1, lon2, lat2])\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n have...
[ 0 ]
[]
[]
[ "geopy", "haversine", "python", "scikit_learn" ]
stackoverflow_0073377356_geopy_haversine_python_scikit_learn.txt
Q: Can someone help me using 'ray' or other multiprocessing libraries for my semantic segmentation? I'm doing semantic segmentation for microscope image stacks. My code works fine but the thing is it only uses one core of my CPU which makes me wait a long time to get the segmented images. I recently knew that there a...
Can someone help me using 'ray' or other multiprocessing libraries for my semantic segmentation?
I'm doing semantic segmentation for microscope image stacks. My code works fine but the thing is it only uses one core of my CPU which makes me wait a long time to get the segmented images. I recently knew that there are ways to use multicore processing with other python libraries, but I don't know how to implement it....
[ "Does this snippet work? It should run each prediction in a separate process.\n@ray.remote\ndef predict(large_image_name: str) -> None:\n img = cv2.imread(large_image_path + large_image_name, 0)\n patches = patchify(img, (256, 256), step=256)\n \n predicted_patches = []\n for i in range(patches.shape...
[ 2 ]
[]
[]
[ "image_processing", "multiprocessing", "multithreading", "python", "ray" ]
stackoverflow_0074135897_image_processing_multiprocessing_multithreading_python_ray.txt
Q: I randomly get no output at and when scraping with beautifulsoup from urllib import response from bs4 import BeautifulSoup import requests import csv # headers = { # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" # } csv_file =...
I randomly get no output at and when scraping with beautifulsoup
from urllib import response from bs4 import BeautifulSoup import requests import csv # headers = { # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" # } csv_file = open("scifi_audible.csv", "w") csv_writer = csv.writer(csv_file) csv_w...
[ "When I tried to reproduce the \"no output possible\" scenario, I got it about 2% of the time; it was nearly always due to 503 Service Unavailable error; occasionally, status was 200 [OK], but content was empty - and I don't really know what might be causing that. (Btw, when working with requests, you should genera...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074136536_beautifulsoup_python_web_scraping.txt
Q: Join two df and their columns I have two dataframe like: import pandas as pd df1 = pd.DataFrame({'Airplanes' : ['U-2','B-52,P-51', 'F-16', 'MiG-21,F-16;A-10', 'P-51','A-10;P-51' ], 'Company' : ['Air_1', 'Air_3', 'Air_2','Air_1', 'Air_7', 'Air_3']}) ------------------------------ Airp...
Join two df and their columns
I have two dataframe like: import pandas as pd df1 = pd.DataFrame({'Airplanes' : ['U-2','B-52,P-51', 'F-16', 'MiG-21,F-16;A-10', 'P-51','A-10;P-51' ], 'Company' : ['Air_1', 'Air_3', 'Air_2','Air_1', 'Air_7', 'Air_3']}) ------------------------------ Airplanes Company 0 U-2 ...
[ "You could do split with explode then map\ndf1['new'] = df1.Airplanes.str.split('[,|;]').explode().map(df2.set_index('Model')['Description']).groupby(level=0).agg(','.join)\ndf1\nOut[62]: \n Airplanes Company new\n0 U-2 Air_1 Strong\n1 B-52,P-5...
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074145973_dataframe_pandas_python.txt
Q: Python typed dict with 1 type A value, and all others values of type B? After looking at the TypedDictionary documentation of MyPy, I learned one can specify the types of values of specific keys with: from typing_extensions import TypedDict Movie = TypedDict('Movie', {'name': str, 'year': int}) movie: Movie = {'...
Python typed dict with 1 type A value, and all others values of type B?
After looking at the TypedDictionary documentation of MyPy, I learned one can specify the types of values of specific keys with: from typing_extensions import TypedDict Movie = TypedDict('Movie', {'name': str, 'year': int}) movie: Movie = {'name': 'Blade Runner', 'year': 1982} However, how does one specify the type ...
[ "You say you want a data type that has one element of a specific type and an open number of other elements of another type.\nThat sounds more like:\nMyGraph = TypedDict('MyGraph ': {'graph': networkx.graph, di_graphs: List[networkx.DiGraph]})\n\nThe natural solution is to use a list for the open number of elements,...
[ 0 ]
[]
[]
[ "dictionary", "mypy", "python", "typing" ]
stackoverflow_0074144663_dictionary_mypy_python_typing.txt
Q: mongoengine query for duplicates in embedded documentlist I'm making a python app with mongoengine where i have a mongodb database of n users and each user holds n daily records. I have a list of n new record per user that I want to add to my db I want to check if a record for a certain date already exists for an ...
mongoengine query for duplicates in embedded documentlist
I'm making a python app with mongoengine where i have a mongodb database of n users and each user holds n daily records. I have a list of n new record per user that I want to add to my db I want to check if a record for a certain date already exists for an user before adding a new record to the user what i found in the...
[ "Hi everyone (and future me who will probably search for the same question 10 years later)\nI optimized the code using the idea of a search tree. Instead of putting all records in a single List in User I broke it down by year and month\nclass EmbeddedRecord(mongoengine.EmbeddedDocument):\n date = mongoengine.Dat...
[ 1, 0 ]
[]
[]
[ "mongodb", "mongoengine", "python" ]
stackoverflow_0073965093_mongodb_mongoengine_python.txt
Q: Starting point for bullet including player rotation in Pygame I'm making a simple topdown shooter game. The problem is with bullet starting point. I have player image where rifle barrel is between topmid and topright of rectangle. How to make bullet start always from the rifle barrel regardless image rotation? # k...
Starting point for bullet including player rotation in Pygame
I'm making a simple topdown shooter game. The problem is with bullet starting point. I have player image where rifle barrel is between topmid and topright of rectangle. How to make bullet start always from the rifle barrel regardless image rotation? # key input def get_input(self, dt): keys = pygame.key.get_pressed...
[ "You have rotate the offset of the bullet starting point with pygame.math.Vector2.rotate. e.g.:\noffset = pygame.math.Vecotr2(15, 10) # (15, 10) is just an example\nrotated_offset = offset.rotate(-self.angle) \npos = pygame.math.Vector2(self.rect.center) + rotated_offset \nbullet = Bullet((pos.x, pos.y), ...)\n\n" ...
[ 0 ]
[]
[]
[ "pygame", "python", "topdown" ]
stackoverflow_0074144859_pygame_python_topdown.txt
Q: How to exceed fraction part limit for Float values I'm currently working on a Python project to convert Hexadecimal fractionals to Binary. So I faced into this problem that you can only store up to the limit of 17 numbers to the fractional part of a Float value. Here is an clear example of what I'm saying total = ...
How to exceed fraction part limit for Float values
I'm currently working on a Python project to convert Hexadecimal fractionals to Binary. So I faced into this problem that you can only store up to the limit of 17 numbers to the fractional part of a Float value. Here is an clear example of what I'm saying total = 0 for n in range(1, 21): total += 10 ** -n print...
[ "Float numbers (i.e. floating point numbers) have limited precision and are usually implemented internally as either a Base 2 mantissa and a power of 2 as the exponent or as a Base 16 mantissa and a power of 16 as the exponent. What can be precisely described in one base with a finite number of \"digits\", might re...
[ 1 ]
[]
[]
[ "floating_point", "fractions", "python" ]
stackoverflow_0074145903_floating_point_fractions_python.txt