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: Using mock.patch + parametrize in a Pytest Class Function I have been working on fastAPI and have some async methods to generate an auth token Writting the unit testing I'm getting the following error: TypeError: test_get_auth_token() missing 2 required positional arguments: 'test_input' and 'expected_result' my ...
Using mock.patch + parametrize in a Pytest Class Function
I have been working on fastAPI and have some async methods to generate an auth token Writting the unit testing I'm getting the following error: TypeError: test_get_auth_token() missing 2 required positional arguments: 'test_input' and 'expected_result' my unit test looks like: class TestGenerateAuthToken(IsolatedAsync...
[]
[]
[ "It is not related to mock.\nThe reason is that pytest.mark.parametrize is not compatible with unittest.IsolatedAsyncioTestCase.\nInstead, you could try using pytest's plugin, for example, pytest-asyncio, to let pytest work with the coroutine test function.\nfrom unittest import mock\nfrom unittest.mock import Asyn...
[ -1 ]
[ "pytest", "python", "python_3.x", "unit_testing" ]
stackoverflow_0073954438_pytest_python_python_3.x_unit_testing.txt
Q: How to replace the independent 1 with 0 in binary number using only bitwise operations? By "independent 1" I mean 1 that has no other 1 next to it ("010" or "10" and "01" at the ends of the num.) If the 1 doesn´t have any 1 next to it, it will change to 0. For example: 11010 = 11000 10101 = 00000 1111 = 1111 I can...
How to replace the independent 1 with 0 in binary number using only bitwise operations?
By "independent 1" I mean 1 that has no other 1 next to it ("010" or "10" and "01" at the ends of the num.) If the 1 doesn´t have any 1 next to it, it will change to 0. For example: 11010 = 11000 10101 = 00000 1111 = 1111 I can´t use for or while loops. Only bitwise operators. I tried something like this: num = 0b11010...
[ "This is a good exercise in bit shifting and bit comparison. One way this can be solved (there's probably several different ways) is by storing a left shifted and right shifted version of the original number. From there, you can use the XOR function to detect which bits are different. If both neighbors of a 1 are 0...
[ 1 ]
[ "Maybe this code can give you some idea:\na = [3, 5, 8, 1, 2, 7]\nb = [2, 6, 8]\nlenA, lenB = len(a), len(b)\n# Getting the absolute value of abs\ndiff = abs(lenA - lenB)\nif lenA < lenB:\n # extend expands the list. will add an absolute value of zero to the end\n a.extend([0]*diff)\nelse:\n b.extend([0]*d...
[ -2 ]
[ "binary", "bit", "bit_manipulation", "bitwise_operators", "python" ]
stackoverflow_0074467454_binary_bit_bit_manipulation_bitwise_operators_python.txt
Q: How do you check the value stored in a semaphore (multiprocessing module) in python? I need to solve the philosopher dining problem where the approach is to pick up both chopsticks if both are available only. The availability of each chopstick is stored in a semaphore (multiprocessing module) initiated with value ...
How do you check the value stored in a semaphore (multiprocessing module) in python?
I need to solve the philosopher dining problem where the approach is to pick up both chopsticks if both are available only. The availability of each chopstick is stored in a semaphore (multiprocessing module) initiated with value 1. To achieve this, I was trying to read the value stored in the semaphores but I couldn't...
[ "The multiprocessing.Semaphore objects have a get_value method that you can use (refer to the Semaphore source). According to your example:\nfrom multiprocessing import Semaphore\n\nchopstick = Semaphore(1)\n\nif chopstick.get_value() == 1:\n ...\n\nHowever, in many threading and multiprocessing situations, you ...
[ 2 ]
[]
[]
[ "multiprocessing", "python", "semaphore" ]
stackoverflow_0074469268_multiprocessing_python_semaphore.txt
Q: ImportError: cannot import name 'find_stack_level' from 'pandas.util._exceptions' When I tried to run the YOLOv5 train.py, I don't know what was wrong with it. pandas is installed. Traceback (most recent call last): File "/home/jasmine/Desktop/fyp/yolov5/yolov5/utils/general.py", line 26, in <module> import ...
ImportError: cannot import name 'find_stack_level' from 'pandas.util._exceptions'
When I tried to run the YOLOv5 train.py, I don't know what was wrong with it. pandas is installed. Traceback (most recent call last): File "/home/jasmine/Desktop/fyp/yolov5/yolov5/utils/general.py", line 26, in <module> import pandas as pd File "/home/jasmine/anaconda3/lib/python3.8/site-packages/pandas/__init_...
[ "I was facing a similar problem with pandas version 1.4.2.\nTry using a different pandas version.\nversion 1.3 worked for me.\n", "I had this when upgrading from pandas 1.3.x to 1.4.2. In my case deleting my conda env and recreating fixed it.\n", "I had the same problem with pandas version 1.2.4. I found out ...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python", "yolov5" ]
stackoverflow_0071485727_pandas_python_yolov5.txt
Q: what is the equation of scores of f classif in selectkbest [1]and score of B is 0.99449036. how it is come and what is the equation of thatIt is Table where B is the x and result is the y what is the equation scores_ of f_classif in selectkbest? and where the scores_ is come from? and score of B is 0.99449036. ho...
what is the equation of scores of f classif in selectkbest
[1]and score of B is 0.99449036. how it is come and what is the equation of thatIt is Table where B is the x and result is the y what is the equation scores_ of f_classif in selectkbest? and where the scores_ is come from? and score of B is 0.99449036. how it is come and what is the equation of that
[ "In Scikit-learn f_classif uses a one-way ANOVA F-test to perform feature selection, as clearly described in the documentation.\nFor this purpose, Scikit-learn has its own implementation of one-way ANOVA, which can be found in the source code here: https://github.com/scikit-learn/scikit-learn/blob/1.1.3/sklearn/fea...
[ 0 ]
[]
[]
[ "data_science", "machine_learning", "python", "scikit_learn", "statistics" ]
stackoverflow_0074469119_data_science_machine_learning_python_scikit_learn_statistics.txt
Q: Print random sample from dataloader in PyTorch I have a certain dataset loaded into a dataloader. For example, if I wanted to save 100 images from this dataloader, how should I iterate over the dataloader to save them? A: Im not exactly sure what you are trying to do (maybe edit your question) but maybe this hel...
Print random sample from dataloader in PyTorch
I have a certain dataset loaded into a dataloader. For example, if I wanted to save 100 images from this dataloader, how should I iterate over the dataloader to save them?
[ "Im not exactly sure what you are trying to do (maybe edit your question) but maybe this helps:\ndataset = Dataset()\ndataloader = torch.utils.data.DataLoader(\n dataloader,\n batch_size=32,\n num_workers=1,\n shuffle=True)\n\nfor samples, targets in d...
[ 0, 0 ]
[]
[]
[ "dataloader", "dataset", "python", "pytorch" ]
stackoverflow_0063233726_dataloader_dataset_python_pytorch.txt
Q: TypeError: Input 'filename' of 'ReadFile' Op has type float32 that does not match expected type of string I am running this code from the tutorial here: https://keras.io/examples/vision/image_classification_from_scratch/ with a custom dataset, that is divided in 2 datasets as in the tutorial. However, I got this e...
TypeError: Input 'filename' of 'ReadFile' Op has type float32 that does not match expected type of string
I am running this code from the tutorial here: https://keras.io/examples/vision/image_classification_from_scratch/ with a custom dataset, that is divided in 2 datasets as in the tutorial. However, I got this error: TypeError: Input 'filename' of 'ReadFile' Op has type float32 that does not match expected type of string...
[ "Simplest way I found is to create a subfolder and copy the files to that subfolder.\ni.e. Lets assume your files are 0.jpg, 1.jpg,2.jpg....2000.jpg and in directory named \"patterns\".\nSeems like the Keras API does not accept it as the files are named by numbers and for Keras it is in float32.\nTo overcome this i...
[ 17, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "keras", "python" ]
stackoverflow_0062378481_keras_python.txt
Q: M1 vscode python error (zsh: command not found : python) I recently change my laptop, windows to mac. I downloaded python and vscode and install python extension as i did on windows. Then i edited task json file to use cmd +shift +b for building shortcut. However when i build the file, there's an error saying on ...
M1 vscode python error (zsh: command not found : python)
I recently change my laptop, windows to mac. I downloaded python and vscode and install python extension as i did on windows. Then i edited task json file to use cmd +shift +b for building shortcut. However when i build the file, there's an error saying on terminal "zsh:command not found:python". What should i do? I r...
[ "You need to add python to zsh by running the following in the terminal:\necho \"alias python=/usr/bin/python3\" >> ~/.zshrc\n\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "visual_studio_code", "zsh" ]
stackoverflow_0074457947_macos_python_visual_studio_code_zsh.txt
Q: Python open(file) function not printing the content of the file To be more precise, when trying to print the content of the .txt file into the terminal, all I get is "Process finished with exit code 0". Exact code: file = open("vits.txt", "r") print(file.read()) I do have the .txt file inside the directory too; t...
Python open(file) function not printing the content of the file
To be more precise, when trying to print the content of the .txt file into the terminal, all I get is "Process finished with exit code 0". Exact code: file = open("vits.txt", "r") print(file.read()) I do have the .txt file inside the directory too; the IDE I use autofills the file name for me.
[ "Instead of that syntax use this:\nwith open(\"vits.txt\", \"r\") as file:\n print(file.readlines())\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074469113_python.txt
Q: Running asynchronous functions in non-asynchronous functions I'm trying to run some asynchronous functions in her asynchronous function, the problem is, how did I understand that functions don't run like that, then how do I do it? I don't want to make the maze_move function asynchronous. async def no_stop(): #...
Running asynchronous functions in non-asynchronous functions
I'm trying to run some asynchronous functions in her asynchronous function, the problem is, how did I understand that functions don't run like that, then how do I do it? I don't want to make the maze_move function asynchronous. async def no_stop(): #some logic await asyncio.sleep(4) async def stop(stop_time): ...
[ "How about:\ndef maze_move():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(no_stop())\n loop.run_until_complete(stop(1.5))\n\nIf you wanted to run two coroutines concurrently, then:\ndef maze_move():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(asyncio.gather(no_stop(), ...
[ 1, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074460454_python_python_asyncio.txt
Q: Maze algorithm python Turn the four rings so that the sums of each four of the numbers that are located along the same radius are the same. Find what they are equal to? problem image We can do it by Brute Force method but it will be dummy cause too many combinations. I had thoughts about DFS method but cant imagin...
Maze algorithm python
Turn the four rings so that the sums of each four of the numbers that are located along the same radius are the same. Find what they are equal to? problem image We can do it by Brute Force method but it will be dummy cause too many combinations. I had thoughts about DFS method but cant imagine how to consume it here tr...
[ "Have done this problem without using any theoretical algorithm using python.\nJust simple Brute Force method like walking through my rings starting from 2-nd one**\ndef find_radius(*args):\n arr = []\n for i in range(0, len(args[0])):\n sum_radius = args[0][i] + args[1][i] + args[2][i] + args[3][i]\n ...
[ 1, 0 ]
[]
[]
[ "algorithm", "graph_theory", "maze", "python", "sorting" ]
stackoverflow_0074468759_algorithm_graph_theory_maze_python_sorting.txt
Q: Np Random Choice with list of probability distributions I have a set of actions [0,1,2,3] and a policy which is a series of probabilities for each action like [[0.5, 0.4, 0.05, 0.05]...]. How would it be possible to use np.random.choice (or something similar) which chooses from my actions array for each probabilit...
Np Random Choice with list of probability distributions
I have a set of actions [0,1,2,3] and a policy which is a series of probabilities for each action like [[0.5, 0.4, 0.05, 0.05]...]. How would it be possible to use np.random.choice (or something similar) which chooses from my actions array for each probability distribution and returns the list of choices? For a concret...
[ "Just call rng.choice for each row separately.\nrng = np.random.default_rng()\noutput = [rng.choice(len(actions), p=x) for x in probs]\n\n", "np.random.choice can take in a p parameter that does what you want:\n\np: 1-D array-like, optional\nThe probabilities associated with each entry in a. If not given, the sam...
[ 0, 0 ]
[]
[]
[ "arrays", "numpy", "probability", "python" ]
stackoverflow_0074469342_arrays_numpy_probability_python.txt
Q: TypeError: __init__() got multiple values for argument 'dim' I am doing testing on two trained models. In first, I am getting below error during testing so I have changed torch.logsoftmax class to nn.LogSoftmax. Code from torch.utils.data import Dataset, DataLoader import pandas as pd from torchvision import trans...
TypeError: __init__() got multiple values for argument 'dim'
I am doing testing on two trained models. In first, I am getting below error during testing so I have changed torch.logsoftmax class to nn.LogSoftmax. Code from torch.utils.data import Dataset, DataLoader import pandas as pd from torchvision import transforms from PIL import Image import torch import torch.nn as nn fro...
[ "nn.LogSoftMax is a module that has to be instantiated first and then called (which is when its forward method is executed). Try this instead:\nentropy1 = -torch.sum(torch.softmax(pred1[:, :10], dim=1) * nn.LogSoftmax(dim=1)(pred1[:, :10]), dim=-1, keepdim=True)\n\nInstead, you can also use the functional form of t...
[ 1 ]
[]
[]
[ "python", "python_3.x", "pytorch", "torch" ]
stackoverflow_0074469400_python_python_3.x_pytorch_torch.txt
Q: Create dictionary from multiple rows in dataframe I have a dataframe like so: I would like to create a dictionary that looks like this: dict = {'car' : ['mazda', 'toyota', 'ford'], 'bike' : ['honda', 'kawasaki', 'suzuki'] } I have tried a number of answers found on stackoverflow, including this on...
Create dictionary from multiple rows in dataframe
I have a dataframe like so: I would like to create a dictionary that looks like this: dict = {'car' : ['mazda', 'toyota', 'ford'], 'bike' : ['honda', 'kawasaki', 'suzuki'] } I have tried a number of answers found on stackoverflow, including this one: dict(df.values), that I found at Convert a Pandas Da...
[ "This is a potential solution to the above:\ndf.groupby(['item'])['name'].apply(lambda grp: list(grp.value_counts().index)).to_dict()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074467670_dataframe_pandas_python.txt
Q: How to stop browser closing in python selenium? without calling quit or close () Description of the problem: The problem I'm stuck on is when I run a code, it first opens the chrome browser and opens the google.com website and then it closes it for no reason. This is my code: from selenium import webdriver from se...
How to stop browser closing in python selenium? without calling quit or close ()
Description of the problem: The problem I'm stuck on is when I run a code, it first opens the chrome browser and opens the google.com website and then it closes it for no reason. This is my code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service ...
[ "Add this code and try:\noptions = Options()\noptions.add_experimental_option(\"detach\", True)\n\ndriver = webdriver.Chrome(service=driver_service,options=options)\n\nDon't forget to add double slash '\\\\' in the chromedriver.exe path.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074466414_python_selenium.txt
Q: Tkinter Python Question: How to create a function in this program to make the variable year_of_birth and year_present together (Age Calculator)plshelp from tkinter import * def age_calculator(): window=Tk() window.title("Age Calculator") label_one=Label(window,text="Welcome to Age Calculator",fg="green...
Tkinter Python Question: How to create a function in this program to make the variable year_of_birth and year_present together (Age Calculator)plshelp
from tkinter import * def age_calculator(): window=Tk() window.title("Age Calculator") label_one=Label(window,text="Welcome to Age Calculator",fg="green") label_one.pack() year_of_birth=Entry(window,width=5,bd=4) year_of_birth.place(x=210,y=100) label_two=Label(window,text="Year of Birth",fg...
[ "I've found a way to do it. If you want to change the message, on the line just below the comment that says 'Change output below'. the output variable is the output (hence the name output)\nfrom tkinter import *\n\nwindow = Tk()\nwindow.title(\"Age Calculator\")\nlabel_one = Label(window,text=\"Welcome to Age Calcu...
[ 0 ]
[]
[]
[ "calculator", "python", "subtraction", "tkinter" ]
stackoverflow_0074467770_calculator_python_subtraction_tkinter.txt
Q: How do I get a dict key from an int when the dict values are lists? I have the python dict: my_dict = {'C': [1,2,3,4,5,6,7,8,9,10,11,12,15,18,46,64,67,73,78,83], 'B': [13,14,22,32,38,39,42,59,68,74,79,84], 'A': [16,17,19,23,31,37,40,50,51,60,70,75,80,85], 'S': [20,25,33,36,43,44...
How do I get a dict key from an int when the dict values are lists?
I have the python dict: my_dict = {'C': [1,2,3,4,5,6,7,8,9,10,11,12,15,18,46,64,67,73,78,83], 'B': [13,14,22,32,38,39,42,59,68,74,79,84], 'A': [16,17,19,23,31,37,40,50,51,60,70,75,80,85], 'S': [20,25,33,36,43,44,48,49,57,61,62,63,71,76,81,86,88,89,92,94], 'SS': [21,24,26,...
[ "my_dict_key = 78\nout = [k for k, v in my_dict.items() if my_dict_key in v]\nprint(*out)\n\nC\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "key_value", "list", "python", "python_3.x" ]
stackoverflow_0074469422_dictionary_key_value_list_python_python_3.x.txt
Q: Why is my plotly offline not being embedded in a dominate page? I am creating a map with plotly.express and creating a html page with dominate I have not had any problem with the dominate part and I can create a separate html page with the map part. My problem is that when I try to take the map into a html code an...
Why is my plotly offline not being embedded in a dominate page?
I am creating a map with plotly.express and creating a html page with dominate I have not had any problem with the dominate part and I can create a separate html page with the map part. My problem is that when I try to take the map into a html code and put it inside dominate, it does not show. The map is there (I can s...
[ "I just found the answer after inspecting the html. I leave it here in case someone else needs it\nMy mistake is that I should have written\nthe_map= pyo.plot(fig, include_plotlyjs=True, output_type='div')\n\n" ]
[ 0 ]
[]
[]
[ "dominate", "html", "plotly", "plotly_express", "python" ]
stackoverflow_0074469212_dominate_html_plotly_plotly_express_python.txt
Q: how to remove some extra commas between lines Csv file How to remove some extra commas on CSV file sometimes there are 3 or more extra commas, I would like the marked part to become a single column correct format is 11 columns, I just want to find the ones that are not and remove the commas 84,855,648857,8787548,R...
how to remove some extra commas between lines Csv file
How to remove some extra commas on CSV file sometimes there are 3 or more extra commas, I would like the marked part to become a single column correct format is 11 columns, I just want to find the ones that are not and remove the commas 84,855,648857,8787548,R,mark,one 55, power,0000081,3434,59190000,defen,six, first 5...
[ "I suggest reading the csv data into a list, merge them, and write it back:\ndef merge(data):\n result = []\n result += data[:5]\n temporary = \"\"\n for item in data[5:-5]:\n temporary += item + \" \"\n result.append(temporary[:-1])\n result += data[-5:]\n return result\n\nThis function...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074469146_csv_pandas_python.txt
Q: how can I write a program for an __add__ method? I'm trying to write a program for an __add__ method where you have to make each index in 2 lists correspond to each other in order to add them to one another, but I'm a little unsure about how to execute that. For example, if I had the lists: a = List([1.0, 1.0, 1.0...
how can I write a program for an __add__ method?
I'm trying to write a program for an __add__ method where you have to make each index in 2 lists correspond to each other in order to add them to one another, but I'm a little unsure about how to execute that. For example, if I had the lists: a = List([1.0, 1.0, 1.0]) b = List([2.0, 3.0, 4.0]) and had to add these two...
[ "def __add__(self, rhs: Union[float, List]) -> Simpy:\n result: Simpy = ([])\n if isinstance(rhs, Simpy):\n assert len(self.values) == len(rhs.values)\n return [val_1+val_2 for val_1, val_2 in zip(self.values, rhs.values)]\n \n\nJust use a list comprehension to generate a list with th...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074469423_python.txt
Q: Higher/Lower game import random user_name = input('What is your name?') print("Welcome to the higher/lower game,", user_name + "!") lower = int(input("Enter the lower bound:")) upper = int(input("Enter the upper bound:")) correct_num = random.randint(lower, upper) if lower > upper: lower = int(input("Enter t...
Higher/Lower game
import random user_name = input('What is your name?') print("Welcome to the higher/lower game,", user_name + "!") lower = int(input("Enter the lower bound:")) upper = int(input("Enter the upper bound:")) correct_num = random.randint(lower, upper) if lower > upper: lower = int(input("Enter the lower bound:")) ...
[ "You're assigning the upper and lower twice in your code. You can eliminate it and it should work fine.\nlower = int(input(\"Enter the lower bound:\"))\nupper = int(input(\"Enter the upper bound:\"))\n\nif lower > upper:\n correct_num = random.randint(lower, upper)\nelse:\n correct_num = 0 \n\nAlso, you can s...
[ 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074469085_python_random.txt
Q: What would be the correct way to implement a "Try again" message for a simple guessing game? I'm trying to implement a text that says "Try again" to appear when the player guesses incorrectly. This is an extremely bare bones "game" but I started coding yesterday and I'm trying to learn all the basic functions and ...
What would be the correct way to implement a "Try again" message for a simple guessing game?
I'm trying to implement a text that says "Try again" to appear when the player guesses incorrectly. This is an extremely bare bones "game" but I started coding yesterday and I'm trying to learn all the basic functions and methods. This is the code: secret_number = 9 guess_limit = 3 guess_count = 0 while guess_count < g...
[ "You can implement and ELSE statement, for continuing the loop:\nsecret_number = 9\nguess_limit = 3\nguess_count = 0\nwhile guess_count < guess_limit:\n won = False\n guess = int(input(\"Guess:\"))\n guess_count += 1\n\n if guess == secret_number:\n print(\"You won!\")\n won = True\n ...
[ 2, 2, 0 ]
[ "add import random\nand set secret_number = random.randint(0,9)\nyou don't need to add the 'else' statement at the last line\nit should be just \"print(\"You lost!\")\"\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074469310_python.txt
Q: How to convert the co-efficients in these inequalities from float to int in Sympy? I have the following expressions - x > 4.5 2x + y == 4.5 I would like to get rid of the floating point numbers in the coefficients and convert them into integers. How can I do this using Sympy? (or any other python library for that...
How to convert the co-efficients in these inequalities from float to int in Sympy?
I have the following expressions - x > 4.5 2x + y == 4.5 I would like to get rid of the floating point numbers in the coefficients and convert them into integers. How can I do this using Sympy? (or any other python library for that matter). I have been racking my brains for hours now. BTW, the expected output should b...
[ "You can use nsimplify() on the relation and multiply both sides by the denominator of the RHS, like the following.\nfrom sympy import nsimplify, Rel\nfrom sympy.abc import x\n\nr0 = x > 4.5\n\nr = nsimplify(r0)\nq = r.rhs.q\nr = Rel(r.lhs * q, r.rhs * q, r.rel_op)\n\nprint([r0, r])\n\nThis outputs\n[x > 4.5, 2*x >...
[ 1, 1 ]
[]
[]
[ "math", "python", "sympy" ]
stackoverflow_0074467909_math_python_sympy.txt
Q: Is there a way of adding different values of the same variable within the same -while- cycle? I apologize if the redaction of my problem is not good. Code I'm running: x=int(input("Escribe cantidad de artículos deseas comprar: ")) suma=0 seleccion=0 precio=0 while x>0: seleccion=(input("Dame el nombre de un a...
Is there a way of adding different values of the same variable within the same -while- cycle?
I apologize if the redaction of my problem is not good. Code I'm running: x=int(input("Escribe cantidad de artículos deseas comprar: ")) suma=0 seleccion=0 precio=0 while x>0: seleccion=(input("Dame el nombre de un artículo que deseas comprar: ")) precio=int(input("Dame el precio de dicho artículo: ")) z=p...
[ "the problem, I guess, is with the indentation and illogical if-statement:\n if seleccion==1:\n suma = z + z\n if seleccion > 1:\n print (\"Listo. Haz anotado todos los artículos que deseas comprar\")\n\nAs per your example, seleccion equals 2 thereforesuma never gets updated and remains 0\...
[ 0, 0 ]
[]
[]
[ "python", "sum", "while_loop" ]
stackoverflow_0074468435_python_sum_while_loop.txt
Q: How do I effectively save a file to my directory of choice in Flask I have tried using different ways yet it fails kindly help. This is one of the ways. It does save the file unfortunately it is saved as 0kb @app.route("/droid",methods=['GET','POST']) def cloud_Upload(): if 'f...
How do I effectively save a file to my directory of choice in Flask
I have tried using different ways yet it fails kindly help. This is one of the ways. It does save the file unfortunately it is saved as 0kb @app.route("/droid",methods=['GET','POST']) def cloud_Upload(): if 'file' not in request.files: flash('No file part') return r...
[ "Not sure what file is defined as, but using open is usually the way to go. See the documentation here: https://docs.python.org/3/library/functions.html?highlight=open#open\ndata = \"stuff to write to file\"\nwith open(filename, \"w+\") as file: \n file.write(data)\n\n" ]
[ 0 ]
[]
[]
[ "flask", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074469522_flask_python_python_2.7_python_3.x.txt
Q: Python create new column with multiplier based on another columns value I'm new to python and I'm trying to derive an additional column for an existing dataframe. This column's value would be based on another columns value times a multiplier, here're some examples: I have this dataframe that indicates workout time...
Python create new column with multiplier based on another columns value
I'm new to python and I'm trying to derive an additional column for an existing dataframe. This column's value would be based on another columns value times a multiplier, here're some examples: I have this dataframe that indicates workout time for each country. I want to generate an additional column called expected wo...
[ "The idiomatic Pandas solution is to work in two steps:\n\nCreate an array or series containing the \"multiplier\" associated with each row. Let's call it multiplier.\nMultiply the multipliers by the values you want to multiply, i.e. df['expected_workout_time'] = df['time'] * multiplier.\n\nStep 1 can be accomplish...
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074469518_dataframe_numpy_pandas_python.txt
Q: How to specify header to a specific number of columns in csv and panda dataframe I have a csv file with 50 comma seperated values. for example, a row: 3290,171,12,134,23,1824,228,245,147,2999,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 I want to specify headers to the...
How to specify header to a specific number of columns in csv and panda dataframe
I have a csv file with 50 comma seperated values. for example, a row: 3290,171,12,134,23,1824,228,245,147,2999,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 I want to specify headers to the 11 first columns in this csv file. I tried some ways but the data seems is corrupted....
[ "assumption: you want to rename the first 11 columns\n# new names for the columns\ncols=['A', 'B', 'C', 'D', 'E', 'F' ,'G', 'H', 'I', 'J', 'K']\n\n# using list comprehension, take value from cols for the first 11 columns and remainder\n# keep as is\nnew_cols=[cols[c] if c < len(cols) else c for c in range(len(df.co...
[ 1 ]
[]
[]
[ "data_science", "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074468763_data_science_dataframe_pandas_python_python_3.x.txt
Q: How do I print a square root to the console in python? I am trying to write code that can print a square root to the console. Here is an example of some code from math import sqrt print("ax\N{SUPERSCRIPT TWO} + bx + c") a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) x1 = (-b...
How do I print a square root to the console in python?
I am trying to write code that can print a square root to the console. Here is an example of some code from math import sqrt print("ax\N{SUPERSCRIPT TWO} + bx + c") a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) x1 = (-b - sqrt(b ** 2 - 4*a*c))/(2*a) x2 = (-b + sqrt(b ** 2 - 4*a*...
[ "You can use sympy module for display and calculation.\nhttps://docs.sympy.org/latest/index.html\nFor display purpose:\nfrom sympy import *\n\na,b,c = symbols('a b c', Positive = True, Real = True)\nx1 = symbols('\\Delta_t', Real = True)\n\nx1 = (-b + sqrt(b ** 2 - 4*a*c))/(2*a)\nx1\n\n\n" ]
[ 0 ]
[]
[]
[ "console", "python", "python_3.x", "square_root", "unicode" ]
stackoverflow_0074469501_console_python_python_3.x_square_root_unicode.txt
Q: pyarrow autocomplete/intellisense in vscode import pyarrow as pa data = [ pa.array([1, 2, 3, 4]), pa.array(['foo', 'bar', 'baz', None]), pa.array([True, None, False, True]) ] batch : pa.RecordBatch = pa.record_batch(data, names=['f0', 'f1', 'f2']) Above is th...
pyarrow autocomplete/intellisense in vscode
import pyarrow as pa data = [ pa.array([1, 2, 3, 4]), pa.array(['foo', 'bar', 'baz', None]), pa.array([True, None, False, True]) ] batch : pa.RecordBatch = pa.record_batch(data, names=['f0', 'f1', 'f2']) Above is the code I'm editing in vscode using the ms-python....
[ "Modify the language server type to Jedi through the following steps.\n\nUse the shortcut key Ctrl+,to open the Settings page\nSearch python.languageServer\nDrop down to select Jedi\n\n\nOr add the following configuration directly in the setting to complete the modification.\n \"python.languageServer\": \"Jedi\"...
[ 1 ]
[]
[]
[ "pyarrow", "python", "visual_studio_code" ]
stackoverflow_0074465618_pyarrow_python_visual_studio_code.txt
Q: How to traverse a list in python? I am new to python and I am trying to code a ticket system. I want to be able to print all the tickets that was created. I did append my list. However, when I try to print it it does display the ticket information. I was told that i need to transverse Object_List but i am not sure...
How to traverse a list in python?
I am new to python and I am trying to code a ticket system. I want to be able to print all the tickets that was created. I did append my list. However, when I try to print it it does display the ticket information. I was told that i need to transverse Object_List but i am not sure how to do it. My code is below: #main...
[ "You need to print each piece of data from the ticket object, trying to print it directly only prints the memory address location.\ndef stats():\n for i in Object_List:\n print(i.staffid)\n print(i.staffname)\n # and so on, or you can put it in one large print statement and nicely fo...
[ 0 ]
[]
[]
[ "list", "listview", "loops", "python", "python_3.x" ]
stackoverflow_0074469608_list_listview_loops_python_python_3.x.txt
Q: how can I read "htm" file inside of zip folder in python? not html, in "htm" file, how can I read in python? for example, A.htm is in the B folder which is inside of C zip file (C/B/A.htm) A: The ZipFile class in the standard library supports accessing individual files in a ZIP archive, using ZipFile.open or Zip...
how can I read "htm" file inside of zip folder in python?
not html, in "htm" file, how can I read in python? for example, A.htm is in the B folder which is inside of C zip file (C/B/A.htm)
[ "The ZipFile class in the standard library supports accessing individual files in a ZIP archive, using ZipFile.open or ZipFile.extract:\nfrom zipfile import ZipFile\n\nwith ZipFile(\"C.zip\") as zf:\n with zf.open(\"C/B/A/.htm\") as fp:\n a_binary = fp.read()\n\n# You will need to know the file encoding,\...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074469651_python.txt
Q: Pycebox IcePlot does not work on Xgboost while work on Random Forest Below error comes up when i run Pycebox with XGBoost, the training runs perfect while not sure why the [fx] field appear when work with iceplot. Also i have double confirm that they are not in the data-set ValueError: feature_names mismatch: ['se...
Pycebox IcePlot does not work on Xgboost while work on Random Forest
Below error comes up when i run Pycebox with XGBoost, the training runs perfect while not sure why the [fx] field appear when work with iceplot. Also i have double confirm that they are not in the data-set ValueError: feature_names mismatch: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (c...
[ "Just change X_train by X_train.values\n", "Try to use xgb.predict_proba . Random forest regression works as a regressor where XGB could have acted as a classifier.\n" ]
[ 0, 0 ]
[]
[]
[ "machine_learning", "python", "scikit_learn", "xgboost" ]
stackoverflow_0060164019_machine_learning_python_scikit_learn_xgboost.txt
Q: Is there a way to open another GUI in Tkinter that plays a Gif, whilst the main GUI is still active I just started a week ago learning Python and currently I am learning Tkinter. I wanted to programm a TicTacToe game that opens another GUI which plays a Gif every time someone wins. TicTacToe works, although it mig...
Is there a way to open another GUI in Tkinter that plays a Gif, whilst the main GUI is still active
I just started a week ago learning Python and currently I am learning Tkinter. I wanted to programm a TicTacToe game that opens another GUI which plays a Gif every time someone wins. TicTacToe works, although it might need a few more lines of code to be perfect. I can open another GUI via root1 = tk.Toplayer() which is...
[ "If you want to loop the images inside a GIF, you can use itertools.cycle() to create a cycle list of images and use next() to get the next image in the cycle list.\nBelow is the modified play_gif() and win():\nfrom itertools import cycle\nimport tkinter as tk\nfrom PIL import Image, ImageTk, ImageSequence\n\n...\n...
[ 0 ]
[]
[]
[ "animated_gif", "python", "tkinter" ]
stackoverflow_0074467292_animated_gif_python_tkinter.txt
Q: Python thread not working as expected when for loop is added I'm working on multithreaded Conway's Game of Life where each cell is a thread. This is my first ever multithreading project. I have a 10x10 2d array of Cell objects. When I start all of them, "Iteration done" prints 100 times, as expected. But when I ad...
Python thread not working as expected when for loop is added
I'm working on multithreaded Conway's Game of Life where each cell is a thread. This is my first ever multithreading project. I have a 10x10 2d array of Cell objects. When I start all of them, "Iteration done" prints 100 times, as expected. But when I add the outer for loop, instead of it printing 300 times, it only pr...
[ "I would guess that some of your Cell objects are getting their numberOfNeighborsWhoRead value greater than numberOfNeighbors value. That makes them get stuck in the while loop and never exit.\nHere's how this lockup can happen.\nLets imagine a very simple grid with only two Cells, which I'll call A and B. They're ...
[ 1 ]
[]
[]
[ "conways_game_of_life", "multithreading", "python" ]
stackoverflow_0074468175_conways_game_of_life_multithreading_python.txt
Q: pyparsing: how to parse nested function which start with particular function name? I want to use pyparsing to parse a nested function which start with particular function name. Just like this: tag("tag_name_1", value_equal("proxy.province", "value", "return_value", test(1,2))) The string waited to be parsed start...
pyparsing: how to parse nested function which start with particular function name?
I want to use pyparsing to parse a nested function which start with particular function name. Just like this: tag("tag_name_1", value_equal("proxy.province", "value", "return_value", test(1,2))) The string waited to be parsed starts with the function named 'tag'. The problem is that why exprStack doesn't contain "tag"...
[ "You are really pretty close. The thing is, the push_first parse action is attached to atoms, but tag_fn is not an atom. So it won't get its data pushed to expr_stack.\nTo fix this:\n\nChange atom to include tag_fn, something like this:\natom = ((tag_fn | fn_call | string | integer) | pp.Group(LPAREN+expr+RPAREN))....
[ 0 ]
[]
[]
[ "pyparsing", "python", "python_3.x" ]
stackoverflow_0074441119_pyparsing_python_python_3.x.txt
Q: Dynamically display incoming HTTP request data on a Python/Flask page without reload I'm trying to build a quick and simple webpage to test an HTTP Requests service that I'm building, and Flask seems to be making it way harder than it should be. All I want is to display any incoming HTTP Requests on the page, and ...
Dynamically display incoming HTTP request data on a Python/Flask page without reload
I'm trying to build a quick and simple webpage to test an HTTP Requests service that I'm building, and Flask seems to be making it way harder than it should be. All I want is to display any incoming HTTP Requests on the page, and then return the received payload to the service that called the webpage. Copying the Flask...
[ "Try using flask_socketio. This will allow you to send messages between the front and back end. I'm not sure this is the best solution but here is how it works.\nfrom flask_socketio import SocketIO\nfrom flask import Flask\n\napp = Flask(__name__)\nsocketio = SocketIO()\n\nsocketio.init_app(app)\n\n@socketio.on('me...
[ 0, 0 ]
[]
[]
[ "flask", "python", "python_requests" ]
stackoverflow_0074439569_flask_python_python_requests.txt
Q: Calling to staticmethod from class __init__() causing "takes 1 positional argument but 2 were given" TypeError I created a Class with a staticmethod: class DetfileDetector(Detector): def __init__(self, file_path, **kwargs): super().__init__(**kwargs) self.detections = self.parse_detfile(file_pa...
Calling to staticmethod from class __init__() causing "takes 1 positional argument but 2 were given" TypeError
I created a Class with a staticmethod: class DetfileDetector(Detector): def __init__(self, file_path, **kwargs): super().__init__(**kwargs) self.detections = self.parse_detfile(file_path) @staticmethod def parse_detfile(file_path): #do somthing with file_path When I call parse_defi...
[ "Your code is actually correct.\nI tested it with Python 3.8 and didn't see any problem.\nYou can call a staticmethod using the class, or an instance of that class.\nSee here: https://docs.python.org/3/library/functions.html#staticmethod\nIt was working like this even in older versions of Python, I checked all the ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "static_methods", "visual_studio_code" ]
stackoverflow_0064192960_python_static_methods_visual_studio_code.txt
Q: Is there a python function that would allow me to add an extra layer to cross tab? I am trying to create a table that would imitate the following table from excel. My Data is: Col1 Col2 Col3 A Red Cheetah A Red Cheetah A Red Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah A Blue ...
Is there a python function that would allow me to add an extra layer to cross tab?
I am trying to create a table that would imitate the following table from excel. My Data is: Col1 Col2 Col3 A Red Cheetah A Red Cheetah A Red Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah B Blue Cheetah B Blue Cheetah C Blue Cheet...
[ "Using crosstab\ndf = pd.crosstab(\n index=[df.Col1, df.Col3],\n columns=df.Col2,\n rownames=[\"Row Labels\", \"Column Labels\"],\n colnames=[\"Count of Col1\"],\n margins=True,\n margins_name=\"Grand Total\"\n)\n\nprint(df)\n\nOutPut:\nCount of Col1 Blue Green Orange Red Grand To...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074468667_dataframe_pandas_python.txt
Q: python pysftp [Errno 13] Permission denied: I'm trying to copy files from SFTP server . I can connect using python pysftp . I can run: data = srv.listdir() for i in data: print I And I get the Directory list. But when I try sftp.put (localpath,"file_name.txt") I get >"IOError: [Errno 13] Permission denied: '...
python pysftp [Errno 13] Permission denied:
I'm trying to copy files from SFTP server . I can connect using python pysftp . I can run: data = srv.listdir() for i in data: print I And I get the Directory list. But when I try sftp.put (localpath,"file_name.txt") I get >"IOError: [Errno 13] Permission denied: 'C:\\....." I have permission to that folder, bec...
[ "The issue is that you're trying to save a file as a directory which, at least in my experience, is what throws the Permission Denied error in pysftp.\nChange this line of code:\nlocalpath=\"C:\\\\new project\\\\new\"\n\nTo this:\nlocalpath=\"C:\\\\new project\\\\new\\\\infso.txt\"\n\nNOTE: infso.txt can be anythin...
[ 3, 0, 0 ]
[]
[]
[ "ioerror", "permissions", "pysftp", "python" ]
stackoverflow_0046674356_ioerror_permissions_pysftp_python.txt
Q: How to get project iterations through the Azure API I am converting an Azure CLI app to use REST API in Python In the CLI I can get, update project iterations: https://learn.microsoft.com/en-us/cli/azure/boards/iteration/project?view=azure-cli-latest However, I can only find team iterations in the API. Is there an...
How to get project iterations through the Azure API
I am converting an Azure CLI app to use REST API in Python In the CLI I can get, update project iterations: https://learn.microsoft.com/en-us/cli/azure/boards/iteration/project?view=azure-cli-latest However, I can only find team iterations in the API. Is there an equivalent REST API for project iterations? I tried vari...
[ "You could try the rest api: [Classification Nodes - Get Classification Nodes][1].\nFor example, this is the project iteration and team iteration\n[![enter image description here][2]][2]\nThen you could run the api with the filter '$depth', here in my sample it should be 2: To get the draft information of the proje...
[ 0 ]
[]
[]
[ "azure_cli", "azure_devops", "azure_rest_api", "python" ]
stackoverflow_0074462522_azure_cli_azure_devops_azure_rest_api_python.txt
Q: How to multiply value's occurence time by the key to get the new value? The goal: I want to coune the letters in a sentence, and pprint it as a dictionary, where the value is the occurence of the letters in the sentence, not just its time. import pprint from collections import Counter get_the_sentence = input() ...
How to multiply value's occurence time by the key to get the new value?
The goal: I want to coune the letters in a sentence, and pprint it as a dictionary, where the value is the occurence of the letters in the sentence, not just its time. import pprint from collections import Counter get_the_sentence = input() # Now scatter the sentence into different letters. # First remove the peri...
[ "\nValueError: not enough values to unpack (expected 2, got 1)\n\nIf you want to iterate over key-value pairs of a dictionay, you should use\nfor key, value in some_dict.items():\n print(key, value)\n\nIn your case, you are trying to iterate over only keys, which cannot be unpacked to two variables (letter and ti...
[ 0 ]
[]
[]
[ "callable", "count", "dictionary", "loops", "python" ]
stackoverflow_0074469761_callable_count_dictionary_loops_python.txt
Q: My Azure Speech recognition does not stop upon the recognition of a file I create an Azure Speech recognition app by using the demo code provided by Azure. However, after completing the speech recognition for an audio file, Azure Speech does not close and shows the following unless I use ctrl-c. I want to know why...
My Azure Speech recognition does not stop upon the recognition of a file
I create an Azure Speech recognition app by using the demo code provided by Azure. However, after completing the speech recognition for an audio file, Azure Speech does not close and shows the following unless I use ctrl-c. I want to know why it does not stop. CLOSING on SpeechRecognitionCanceledEventArgs(session_id=.....
[ "You can try below code to stop upon the recognition of a file\ntry:\nwhile(True):\nframes = wav_fh.readframes(n_bytes // 2)\nprint('read {} bytes'.format(len(frames)))\nif not frames:\nbreak\n\nstream.write(frames)\ntime.sleep(.1)\n\nfinally: \n#Stop recognition and clean up\nspeech_recognizer.stop_continuous_r...
[ 0, 0 ]
[]
[]
[ "azure", "azure_cognitive_services", "python", "speech_recognition" ]
stackoverflow_0071193079_azure_azure_cognitive_services_python_speech_recognition.txt
Q: How to allow users to choose between import random and import secrets for generating passwords i have it so the user can pick between two options "auth" for authenticator passwords and "simp" for simple passwords. the idea is that auth will use secrets and simp will use random. the option code looks like: options ...
How to allow users to choose between import random and import secrets for generating passwords
i have it so the user can pick between two options "auth" for authenticator passwords and "simp" for simple passwords. the idea is that auth will use secrets and simp will use random. the option code looks like: options = ['auth', 'simp'] user_input = '' msg = "Pick an option:\n" for index, item in enumerate(options)...
[ "import random as simp \nimport secrets as auth \n\n\nif options[int(user_input) - 1] == \"authenticator password\":\n password = ''.join(auth.choice(scram) for i in range(length))\n else:\n password = \"\".join(simp.sample(scram, length))\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074468163_python_python_3.x.txt
Q: Creating user defined function for checking prime no in python num=int(input("enter the no: ")) def Prime(num): """Check whether a no is prime or not""" for i in range(2,num): if num%i==0: print(num," is not prime no") break else: print(num,"is prime no...
Creating user defined function for checking prime no in python
num=int(input("enter the no: ")) def Prime(num): """Check whether a no is prime or not""" for i in range(2,num): if num%i==0: print(num," is not prime no") break else: print(num,"is prime no") break print(Prime(num)) While the output comes like...
[ "num=int(input(\"enter the no: \"))\n\ndef Prime(num):\n flag = False\n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n flag = True\n break\n\n if flag:\n print(num, \"is not a prime number\")\n else:\n print(num, \"is a prime nu...
[ 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074469820_pycharm_python.txt
Q: How can I loop through the different legislators? I need help using Python to parse a JSON file. I have used an API to get a list of legislators from a specific state, and I want to loop through and find a specific one (given a last name). I then want to extract their CID. The file looks like this ` { "respons...
How can I loop through the different legislators?
I need help using Python to parse a JSON file. I have used an API to get a list of legislators from a specific state, and I want to loop through and find a specific one (given a last name). I then want to extract their CID. The file looks like this ` { "response": { "legislator": [ { ...
[ "# Go inside each dict inside the list\nfor legislator in finance_response_info['response']['legislator']:\n\n # If the lastname attribute inside the @attributes dict is equal to desired lastname\n if legislator['@attributes']['lastname'] == lastName:\n candidateID = legislator['@attributes'][\"cid\"]\...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074469846_json_python.txt
Q: Metis (python interface) minimum graph cut wrong result (or usage?) I am trying to do what I though was a simple graph partition using metis. The objective is to minimize graph cut cost with fixed number of k partitions. I set up a small simple problem with all edges having high weight (don't cut), and only one ha...
Metis (python interface) minimum graph cut wrong result (or usage?)
I am trying to do what I though was a simple graph partition using metis. The objective is to minimize graph cut cost with fixed number of k partitions. I set up a small simple problem with all edges having high weight (don't cut), and only one having low weight (please cut here). In the example I would expect the only...
[ "You may push code\nG.graph['edge_weight_attr'] = 'weight'\n\nbefore pass the graph into the function\n" ]
[ 0 ]
[]
[]
[ "algorithm", "graph", "metis", "python" ]
stackoverflow_0070846886_algorithm_graph_metis_python.txt
Q: PIL Writing Text on Image Using Escape Sequence `from PIL import Image, ImageDraw, ImageFont image = Image.new('RGB', (950, 250), color=(255, 255, 255)) TEXT = 'You are a wondeful \033[32mperson.' font_size = 50 font_type = "SourceCodePro-Bold.ttf" draw = ImageDraw.Draw(im=image) font = ImageFont.truetype(font_ty...
PIL Writing Text on Image Using Escape Sequence
`from PIL import Image, ImageDraw, ImageFont image = Image.new('RGB', (950, 250), color=(255, 255, 255)) TEXT = 'You are a wondeful \033[32mperson.' font_size = 50 font_type = "SourceCodePro-Bold.ttf" draw = ImageDraw.Draw(im=image) font = ImageFont.truetype(font_type, font_size) draw.multiline_text((int(950 / 2), int...
[ "You can try this one and change the position of text. i think this logic will help you. thanks\nfrom PIL import Image, ImageDraw, ImageFont\nimage = Image.new('RGB', (950, 250), \"white\")\ntext1 = \"You are a wondeful\"\ntext2=\"Person\"\nfont_size = 100\nfont_type = \"SourceCodePro-Bold.ttf\"\ndraw = ImageDraw.D...
[ 1 ]
[]
[]
[ "python", "python_3.x", "python_imaging_library" ]
stackoverflow_0074441103_python_python_3.x_python_imaging_library.txt
Q: regex Y-M-D extraction from web scraping I wouldl like to extract the Y-M-D information from the following html. Created at</th><td><span><time datetime="2001-06-01" date= [re.search("Created at</th><td><span><time datetime=([0-9A-Za-z\&;]*)", address).group(1)] date I have tried this code but it does not work.D...
regex Y-M-D extraction from web scraping
I wouldl like to extract the Y-M-D information from the following html. Created at</th><td><span><time datetime="2001-06-01" date= [re.search("Created at</th><td><span><time datetime=([0-9A-Za-z\&;]*)", address).group(1)] date I have tried this code but it does not work.Do you have any ideas?
[ "The first argument in re.search should be the pattern and the second the string you want to extract from.\nYou can start trying something like:\nre.search(\"\\d{4}-\\d{2}-\\d{2}\", 'Created at</th><td><span><time datetime=\"2001-06-01\"')\nAnd then use groups\n", "Try using a capturing group to isolate the date ...
[ 0, 0 ]
[]
[]
[ "python", "regex", "screen_scraping" ]
stackoverflow_0074469911_python_regex_screen_scraping.txt
Q: Turn list of lists into key:value pairs in python I have a system I am working with (Zapier!) which I am using to automate a workflow based on a google sheet which refreshes every hour. The Zap outputs raw row data in the following format: list = [["header_1", "header_2", "header_3"], ["uuid_1", "first_timestamp_1...
Turn list of lists into key:value pairs in python
I have a system I am working with (Zapier!) which I am using to automate a workflow based on a google sheet which refreshes every hour. The Zap outputs raw row data in the following format: list = [["header_1", "header_2", "header_3"], ["uuid_1", "first_timestamp_1", "second_timestamp_1"], ["uuid_2", "first_timestamp_2...
[ "In your while loop, you are overriding the variable output - you originally made it a list, and now it is a string. When you go to the second iteration of your for loop, output is now a string that does not have the append function.\nI am guessing you are trying to create a new dictionary element where you save th...
[ 1, 0 ]
[]
[]
[ "python", "zapier" ]
stackoverflow_0074469659_python_zapier.txt
Q: Beginner Python question, issue using "or" and "if" together I am using Python to create a very basic calculator. for whatever reason the numbers will only add - they will not do any of the other functions. Please help! equation_type = input("What kind of math do you want to do? ") equation_type = equation_type.lo...
Beginner Python question, issue using "or" and "if" together
I am using Python to create a very basic calculator. for whatever reason the numbers will only add - they will not do any of the other functions. Please help! equation_type = input("What kind of math do you want to do? ") equation_type = equation_type.lower() first_number = float(input("What is the first number? ")) s...
[ "equation_type == \"add\" or \"addition\" does not do what you think it does.\nIt's tempting to read Python code as if it were English. It is not! Python is still a programming language, and programming languages have strict rules.\nThe expression equation_type == \"add\" or \"addition\" is parsed as (equation_type...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074469982_python.txt
Q: How to compute sum of a field value across documents in mongodb using python (pymongo) I have a few documents of the following structure stored in MongoDB: DOCUMENT 1 { "_id":{ "$oid":"634c4eb3421aa4567782ffc7af" }, "name":"John Doe", "wins":{ "texas":{ "football":{ "co...
How to compute sum of a field value across documents in mongodb using python (pymongo)
I have a few documents of the following structure stored in MongoDB: DOCUMENT 1 { "_id":{ "$oid":"634c4eb3421aa4567782ffc7af" }, "name":"John Doe", "wins":{ "texas":{ "football":{ "count":1, }, "basketball":{ "open_count":1, } } ...
[ "okay, so I figured out the answer. What I was trying with $group was in the right direction however there were some issues with how I had written the query.\nThis works to compute the aggregate sum of wins for football.\ncollection.aggregate([{ \n '$group': { \n '_id':None, \n 'total': { '$sum': '$wins....
[ 0 ]
[]
[]
[ "aggregate", "mongodb", "pymongo", "python" ]
stackoverflow_0074460132_aggregate_mongodb_pymongo_python.txt
Q: Using older version of python with Py-Script Would anybody know how to change the version I use in Py-Script? Currently my Py-Script is using python 3.10, but I would like to be able to use python 3.6. I had python 3.10 and 3.6 installed, so i tried removing 3.10, but that didn't work, as I also expected, but othe...
Using older version of python with Py-Script
Would anybody know how to change the version I use in Py-Script? Currently my Py-Script is using python 3.10, but I would like to be able to use python 3.6. I had python 3.10 and 3.6 installed, so i tried removing 3.10, but that didn't work, as I also expected, but other than that, I have no clue how to and have had no...
[ "You cannot easily change the Python version. Python is included with Pyodide which PyScript loads. Changing the version would require rebuilding Pyodide.\nNote: I am not sure if it would be possible to use vanilla Python 3.6 with the current version of Pyodide.\nImprove your code to work with Pyodide's bundled ver...
[ 2 ]
[]
[]
[ "pyscript", "python" ]
stackoverflow_0074463760_pyscript_python.txt
Q: Keyerror: 'pose' when training tflite file from pascal voc I'm using the tflite_model_maker package to train an object_detector tflite model. When I try to import data from pascal voc, I get KeyError: 'pose' error. What am I doing wrong? Traceback (most recent call last): File "2main.py", line 7, in <module> ...
Keyerror: 'pose' when training tflite file from pascal voc
I'm using the tflite_model_maker package to train an object_detector tflite model. When I try to import data from pascal voc, I get KeyError: 'pose' error. What am I doing wrong? Traceback (most recent call last): File "2main.py", line 7, in <module> dataloader = object_detector.DataLoader.from_pascal_voc('data/i...
[ "This occurs because your annotation file don't have attribute 'pose'.\nI had the same issue when I was using CVAT as an annotation tool and realized that the 'pose' and 'truncated' was missing.\nSo I imported my annotated data to another annotation tool (LabelImg) then export to pascal voc again. I don't think thi...
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0068501750_python_tensorflow.txt
Q: Pandas how to calculate the std deviation for all label values except for the selected label? I have a DF with labels and values as below: df = pd.DataFrame({'labels' : ['A','A', 'B', 'C', 'C'],'val' : [1, 2, 3, 4, 5]}) Now, I want to calculate the std. dev as below: for each row: row with A: (std dev of B and C ...
Pandas how to calculate the std deviation for all label values except for the selected label?
I have a DF with labels and values as below: df = pd.DataFrame({'labels' : ['A','A', 'B', 'C', 'C'],'val' : [1, 2, 3, 4, 5]}) Now, I want to calculate the std. dev as below: for each row: row with A: (std dev of B and C labels) (first 2 rows would have std dev of all other rows) row with B: (std dev of A and C labels)...
[ "Update\nTo optimise, precompute std dev for each label:\ndf = pd.DataFrame({'labels' : ['A','A', 'B', 'C', 'C'],'val' : [1, 2, 3, 4, 5]})\n\nlabels = df.labels.unique()\n\nstd_map = {l:df[df.labels != l][\"val\"].std() for l in labels}\n\ndf[\"std_dev\"] = df[\"labels\"].apply(lambda l: std_map[l])\n\n\nIterate da...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074469446_dataframe_pandas_python.txt
Q: How can I change the orientation of a .pdf document from Portrait to Landscape in Python I want to change the orientation of a .pdf document from Portrait to Landscape using Python. Below is the code for my attempt on this. The solution is not giving me the expected result. Anyone with an answer? def viewDocumentI...
How can I change the orientation of a .pdf document from Portrait to Landscape in Python
I want to change the orientation of a .pdf document from Portrait to Landscape using Python. Below is the code for my attempt on this. The solution is not giving me the expected result. Anyone with an answer? def viewDocumentInvoice(request, slug): #fetch that invoice try: invoice = Invoice.objects.get(...
[ "Using pyPDF4, I have done this using:\nimport PyPDF4\n\npdfReader = PyPDF4.PdfFileReader(open(source, 'rb'))\n\nfor page in range(pdfReader.numPages):\n pageObj = pdfReader.getPage(page)\n pageObj.rotateCounterClockwise(90)\n\nor possibly use .rotateClockwise\nThe trick here is to know how much to if you rea...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0073467342_python.txt
Q: What happen with the code (I'm making a quadratic equation solver)? print("ax^2 + bx + c = 0") def ask_a(): a = int(input("""Please enter a: a = """)) if a == 0: print("Please input the correct number! \n") a = int(input("""Please enter a: a = """)) else: try: a =...
What happen with the code (I'm making a quadratic equation solver)?
print("ax^2 + bx + c = 0") def ask_a(): a = int(input("""Please enter a: a = """)) if a == 0: print("Please input the correct number! \n") a = int(input("""Please enter a: a = """)) else: try: a == int(a) print(f"a = {a}") except ValueError: ...
[ "print(\"ax^2 + bx + c = 0\")\n\ndef ask_a():\n a = input(\"\"\"Please enter a: a = \"\"\")\n if a == 0: \n print(\"Please input the correct number! \\n\")\n a = int(input(\"\"\"Please enter a: a = \"\"\"))\n else:\n try:\n a == int(a)\n print(f\"a = {a}\")\n ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074470071_python_python_3.x.txt
Q: How to get all At-The-Money options using yahoo_fin I am trying to create a list of all At-The-Money (ATM) option contracts using yahoo_fin options module. Yahoo_fin offers 2 methods for getting all call and put contracts: from yahoo_fin import options as ops # ops.get_call(Ticker, expiration_date=None) # ops.get...
How to get all At-The-Money options using yahoo_fin
I am trying to create a list of all At-The-Money (ATM) option contracts using yahoo_fin options module. Yahoo_fin offers 2 methods for getting all call and put contracts: from yahoo_fin import options as ops # ops.get_call(Ticker, expiration_date=None) # ops.get_pull(Ticker, expiration_date=None) # If no expiration_da...
[ "For ATM options the strike price is equal to the underlying asset’s current market price, as explained here.\nHowever, there is no option for every possible market price, as options are oganized in grids. You could get the price of the option for which the strike price is closest to the underlying's market price. ...
[ 0 ]
[]
[]
[ "api", "data_analysis", "finance", "python", "yahoo_finance" ]
stackoverflow_0074435717_api_data_analysis_finance_python_yahoo_finance.txt
Q: how to execute a function on items in many nested lists in python I want to iterate through a ton of nested lists in python, and recursively tree into other lists. The list(s) will have the general format [[1, [2, [3, [4, 5]]]], [7, [8, [9, [10, 11]]]]]. For example, I would want to make another nested list withou...
how to execute a function on items in many nested lists in python
I want to iterate through a ton of nested lists in python, and recursively tree into other lists. The list(s) will have the general format [[1, [2, [3, [4, 5]]]], [7, [8, [9, [10, 11]]]]]. For example, I would want to make another nested list without flattening the big list. Expected output: [[1, [2, [3, [4, [5, x]]]]]...
[ "Try:\nL = [[1, [2, [3, [4, 5]]]], [7, [8, [9, [10, 11]]]]]\n\ndef getChildren(L):\n for indx, value in enumerate(L):\n if isinstance(value, list):\n getChildren(value)\n else:\n L[indx] = [value, value + 1]\n\ngetChildren(L)\nprint(L)\n\ngives:\n[[[1, 2], [[2, 3], [[3, 4], [[...
[ 0 ]
[]
[]
[ "list", "nested_lists", "nested_loops", "python", "recursion" ]
stackoverflow_0074470154_list_nested_lists_nested_loops_python_recursion.txt
Q: Keyword extraction from a python code using python I wish to write a code which accepts a python code as input and processes it to extract keywords from the input. But I am not sure about how I can extract sub strings from a statement like print("hello world") I tried using substring by using the following code b...
Keyword extraction from a python code using python
I wish to write a code which accepts a python code as input and processes it to extract keywords from the input. But I am not sure about how I can extract sub strings from a statement like print("hello world") I tried using substring by using the following code but its not working... import keyword test_list = ["pr...
[ "Just for this example of yours,\nimport keyword\nimport re\n\ntest_list = [\"print('Hello World')\"]\n\nprint(\"The original list is : \" + str(test_list))\nres = []\nfor sub in test_list: \n out = re.findall(\"[a-zA-z]*\", sub)\n for word in out:\n if keyword.iskeyword(word):\n res.appe...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074456611_python.txt
Q: Difference between @staticmethod and @classmethod What is the difference between a function decorated with @staticmethod and one decorated with @classmethod? A: Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo: class A(object): def foo(self,...
Difference between @staticmethod and @classmethod
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
[ "Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:\nclass A(object):\n def foo(self, x):\n print(f\"executing foo({self}, {x})\")\n\n @classmethod\n def class_foo(cls, x):\n print(f\"executing class_foo({cls}, {x})\")\n\n ...
[ 3773, 933, 191, 134, 128, 99, 74, 61, 57, 47, 40, 38, 34, 31, 27, 26, 13, 12, 11, 10, 8, 8, 8, 8, 5, 5, 3, 3, 3, 3, 0, 0, 0, 0 ]
[ "A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() duri...
[ -5 ]
[ "methods", "oop", "python", "python_decorators" ]
stackoverflow_0000136097_methods_oop_python_python_decorators.txt
Q: how to extract only main text with pdfplumber and ignore image text and tables? trying to parse any non scanned pdf and extract only text, without tables and their comments or pictures and their comment. just the main text of a pdf, if such text exists. tried pdfplumber. when trying this piece of code it extract a...
how to extract only main text with pdfplumber and ignore image text and tables?
trying to parse any non scanned pdf and extract only text, without tables and their comments or pictures and their comment. just the main text of a pdf, if such text exists. tried pdfplumber. when trying this piece of code it extract all texts, include tables and their comments. import pdfplumber with pdfplumber.open...
[ "Hello you can use a filter after extracting text\nclean_text = text.filter(lambda obj: obj[\"object_type\"] == \"char\" and \"Bold\" in obj[\"fontname\"])\n\nalso, you can use specify the front Size in the filer,\nimport pdfplumber\nwith pdfplumber.open(\"path/to/file.pdf\") as pdf:\n first_page = pdf.pages[0]\n...
[ 2 ]
[]
[]
[ "pdf", "pdfplumber", "python", "text_extraction", "text_parsing" ]
stackoverflow_0074213828_pdf_pdfplumber_python_text_extraction_text_parsing.txt
Q: How can a method directly access its class variables without using self? I recently switched to Python from Java for development and is still not used to some of the implicitness of Python programming. I have a class which I have defined some class variables, how can I access the class variables within a method in...
How can a method directly access its class variables without using self?
I recently switched to Python from Java for development and is still not used to some of the implicitness of Python programming. I have a class which I have defined some class variables, how can I access the class variables within a method in Python? class Example: CONSTANT_A = "A" @staticmethod def my...
[ "In python, you cannot access the parent scope (class)'s fields from methods without self. or cls..\nConsider using classmethod:\nclass Example:\n CONSTANT_A = \"A\"\n \n @classmethod\n def mymethod(cls):\n print(cls.CONSTANT_A) \n\nor directly accessing it like Classname.attribute:\nclass Exam...
[ 2, 1 ]
[]
[]
[ "class", "python", "scope", "variables" ]
stackoverflow_0074470202_class_python_scope_variables.txt
Q: How to use multiprocessing on a map that takes in pandas dataframe and create new columns? I have a dataset of around 2 million Tweets that I would like to perform sentiment analysis on using Asari and a few others. Currently, I am using apply to get the sentiments and creating new columns for them. To try to spee...
How to use multiprocessing on a map that takes in pandas dataframe and create new columns?
I have a dataset of around 2 million Tweets that I would like to perform sentiment analysis on using Asari and a few others. Currently, I am using apply to get the sentiments and creating new columns for them. To try to speed up the process, I'd like to use multiprocessing but am not sure how to go about it. Without th...
[ "You may use the swifter package:\npip install swifter\n\n(Note that you may want to use this in a virtualenv to avoid version conflicts with installed dependencies.)\nSwifter works as a plugin for pandas, allowing you to reuse the apply function:\nimport swifter\n\ndef some_function(data):\n return data * 10\n\...
[ 0 ]
[]
[]
[ "multiprocessing", "pandas", "python" ]
stackoverflow_0074469762_multiprocessing_pandas_python.txt
Q: error while import pytorch module. (The specified module could not be found.) I just newly install python 3.8 via anaconda installer and install pytorch using command conda install pytorch torchvision cpuonly -c pytorch when i try to import torch, I got this error message. OSError: [WinError 126] The specified mo...
error while import pytorch module. (The specified module could not be found.)
I just newly install python 3.8 via anaconda installer and install pytorch using command conda install pytorch torchvision cpuonly -c pytorch when i try to import torch, I got this error message. OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\chunc\anaconda3\lib\site-packages\...
[ "I had the same problem, you should check if you installed Microsoft Visual C++ Redistributable, because if you didn't this may lead to the DLL load failure.\nHere is a link to download it: https://aka.ms/vs/16/release/vc_redist.x64.exe\n", "Yeah! As answered by Chiara, Downloading the Microsoft Visual C++ Redist...
[ 28, 3, 1, 0 ]
[]
[]
[ "dll", "python", "pytorch" ]
stackoverflow_0063187161_dll_python_pytorch.txt
Q: Rename column to specific value if it contains string (with .replace & regex) Solved I have the current dataframe df: Farmer Good Fruit Matt 5 Tom 10 which I want to change to: Farmer Fruit Matt 5 Tom 10 I am wondering if I can convert any column name containing Fruit, such as "Good Fruit" ...
Rename column to specific value if it contains string (with .replace & regex)
Solved I have the current dataframe df: Farmer Good Fruit Matt 5 Tom 10 which I want to change to: Farmer Fruit Matt 5 Tom 10 I am wondering if I can convert any column name containing Fruit, such as "Good Fruit" or "Dope Fruit", to simply "Fruit". By using df.columns.str.replace('.*Fruit*', 'Fr...
[ "As shown in https://stackoverflow.com/a/16667215/2954547, you can rename columns using an arbitrary function, which is probably the most general solution:\nimport re\n\ndf = df.rename(columns=lambda c: \"Fruit\" if \"Fruit\" in c else c)\n\nYou can also use the inplace=True option.\n", "You can achieve this usin...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074470137_pandas_python.txt
Q: Python Tkinter Lambda Multiple Variable Quick question. I have created a button like this: LABEL = tkinter.Button(top, text ="GO 1", command = lambda *args: go('1'), width = 13, height=2) So, I was wondering. How can I pass multiple values to definition using lambda in the button above? def go(value): Thanks! ...
Python Tkinter Lambda Multiple Variable
Quick question. I have created a button like this: LABEL = tkinter.Button(top, text ="GO 1", command = lambda *args: go('1'), width = 13, height=2) So, I was wondering. How can I pass multiple values to definition using lambda in the button above? def go(value): Thanks!
[ "Put values in function call:\nLABEL = tkinter.Button(top, text =\"GO 1\", command=lambda: go('1', 'a', True))\n\nThen unpack the values in the function definition:\ndef go(*values):\n print(values)\n\n", "You could always use a tuple or a list like this:\ndef go(value):\n for val in value:\n print(v...
[ 3, 1 ]
[ "Create a tuple and use it as a normal variable so you can add two or more variable in one tuple and transfer them with button:\n\n" ]
[ -1 ]
[ "python", "tkinter" ]
stackoverflow_0051279570_python_tkinter.txt
Q: Pandas Multiindex percent change column I need to calculate a percent change column with respect to the MultiIndex: import pandas as pd import numpy as np row_x1 = ['1','0'] row_x2 = ['1.5','.5'] row_x3 = ['3','1'] row_x4 = ['2','0'] row_x5 = ['3','.5'] index_arrays = [ np.array(['first', 'first', 'first', '...
Pandas Multiindex percent change column
I need to calculate a percent change column with respect to the MultiIndex: import pandas as pd import numpy as np row_x1 = ['1','0'] row_x2 = ['1.5','.5'] row_x3 = ['3','1'] row_x4 = ['2','0'] row_x5 = ['3','.5'] index_arrays = [ np.array(['first', 'first', 'first', 'second', 'second']), np.array(['one','two...
[ "Let's do groupby and calculate percent change\ndf1['A'] = df1['A'].astype(float)\ndf1['%'] = df1.groupby(level=0)['A'].pct_change().fillna(0)\n\n\n A %\nfirst one 1.0 0.0\n two 1.5 0.5\n three 3.0 1.0\nsecond one 2.0 0.0\n two 3.0 0.5\n\n" ]
[ 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074470186_dataframe_pandas_python.txt
Q: Comparing data from two different columns in streamlit I'm trying to figure out how to compare the percent difference between two columns using st.selectbox This is the code I have: df=pd.read_csv('df.csv') select1 = st.selectbox('Option 1', options=df.columns) select2 = st.selectbox('Option 2', options=df.column...
Comparing data from two different columns in streamlit
I'm trying to figure out how to compare the percent difference between two columns using st.selectbox This is the code I have: df=pd.read_csv('df.csv') select1 = st.selectbox('Option 1', options=df.columns) select2 = st.selectbox('Option 2', options=df.columns) x_axis_val = df["Name"] y_axis_val = (select1/select2)*10...
[ "Here is a sample code.\n# df=pd.read_csv('df.csv')\ndata = [['Lakers', 95, 20], ['Clippers', 125, 35], ['Celtics', 130, 25]]\ndf = pd.DataFrame(data, columns=['Name', 'Score', 'Rebound'])\n\nst.dataframe(df)\n\nsb_options = list(df.columns)\nsb_options.pop(0) # remove the Name col for selectbox option\n\nselect1 ...
[ 1 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074468793_python_streamlit.txt
Q: How to print the duplicate file and the real file in python I have already printed the file which is duplicate from a file directory. what i want is to print both the duplicate file and the corresponding real file from which it was duplicated. below is my code. path = "path/" def duplicatecheck(): DATA_DIR = P...
How to print the duplicate file and the real file in python
I have already printed the file which is duplicate from a file directory. what i want is to print both the duplicate file and the corresponding real file from which it was duplicated. below is my code. path = "path/" def duplicatecheck(): DATA_DIR = Path(path) files = sorted(DATA_DIR.glob('*.xml')) inv...
[ "if invoice in invoice_number ensures your dictionary has the item stored, so internally it looks something like this:\n{\n 'my_invoice_number': 'file.xml',\n 'my_other_invoice_number': 'file2.xml',\n}\n\nSo all you need to do is print it:\nprint(\"Duplicate file found: \", files[i], invoice_number[invoice])\...
[ 1 ]
[]
[]
[ "duplicates", "file", "python" ]
stackoverflow_0074470278_duplicates_file_python.txt
Q: how to put the current position of my players on the board? def formater_damier(joueurs): joueurs = [ {"nom": "1", "pos": [5, 5]}, {"nom": "2", "pos": [8, 6]} ] grille = ( ( ' ----------------------------------- \n' '9 | . . . . . . . . . | \n' ...
how to put the current position of my players on the board?
def formater_damier(joueurs): joueurs = [ {"nom": "1", "pos": [5, 5]}, {"nom": "2", "pos": [8, 6]} ] grille = ( ( ' ----------------------------------- \n' '9 | . . . . . . . . . | \n' ' | | \n' '8 | ...
[ "In this case it's probably better to define a matrix (means array of array) where you save the current state of the grid.\nFor example you can use an array of array of int, where 0: means empty, 1: means first player et 2: means the second one.\nAnd when you need to show the grid, you can use a function translatin...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074469866_python_python_3.x.txt
Q: import flask could not be resolved from source pylance I'm learning Python and part of the course setting up a webserver using Flask. I followed the steps as per the Flask installation documentation and for some reason the flask module is underlined as shown below. When I hover my mouse, I get additional informati...
import flask could not be resolved from source pylance
I'm learning Python and part of the course setting up a webserver using Flask. I followed the steps as per the Flask installation documentation and for some reason the flask module is underlined as shown below. When I hover my mouse, I get additional information as below. import flask could not be resolved from source...
[ "\nFirstly Create a Virtual Environment on your terminal\nthen install your flask by pip install flask\nafter install CTRL+SHIFT+P\nSearch Python Interpreter\nSelect Your virtual Environment\n\nProblem Will bi fixed. I have also faced same problem. but I have fixed it following this procedure\n", "When I did not ...
[ 19, 13, 5, 2, 1, 1, 0 ]
[]
[]
[ "pylance", "python", "visual_studio_code" ]
stackoverflow_0065694813_pylance_python_visual_studio_code.txt
Q: Is it possible to give a list a class attribute? Let’s say I have a nested list of various details about people is it possible that if the first element in a list start with a certain letter to give the list an attribute that is that letter For example if I have the list list_ex= [[mary, 18, nyc], [jake, 19, la], ...
Is it possible to give a list a class attribute?
Let’s say I have a nested list of various details about people is it possible that if the first element in a list start with a certain letter to give the list an attribute that is that letter For example if I have the list list_ex= [[mary, 18, nyc], [jake, 19, la], [mason, 20, Arizona]] I also have the classes class fi...
[ "As @ndc85430 said, dataclasses would be easier to use, but if you want to use regular classes, you can do it this way:\nclass Item:\n def __init__(self, name, age, state):\n self.name = name\n self.age = age\n self.state = state\n\n def get_first_letter(self):\n return self.name[0...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074470310_python.txt
Q: How to go back in PyCharm while browsing code like we have a back button in eclipse? While browsing the code in PyCharm(community edition) how to go back to the previously browsed section? I am looking for eclipse back button type functionality with Pycharm. A: in pycharm you have view in view please make sure t...
How to go back in PyCharm while browsing code like we have a back button in eclipse?
While browsing the code in PyCharm(community edition) how to go back to the previously browsed section? I am looking for eclipse back button type functionality with Pycharm.
[ "in pycharm you have view in view please make sure that toolbar is checked\n\n\n", "You could use Ctrl+Alt+Left Arrow (which is more convenient from my point of view) or clicking arrows as suggested.\n", "You can also go to Navigate->Back\n\n", "Ubuntu 16.04 defines Ctrl + Alt + Left as a workspace switch sho...
[ 63, 33, 7, 7, 0 ]
[]
[]
[ "intellij_idea", "intellij_plugin", "pycharm", "python" ]
stackoverflow_0024548398_intellij_idea_intellij_plugin_pycharm_python.txt
Q: Geopandas: how to read a csv and convert to a geopandas dataframe with polygons? I read a .csv file as a dataframe that looks like the following: import pandas as pd df = pd.read_csv('myFile.csv') df.head() BoroName geometry 0 Brooklyn MULTIPOLYGON (((-73.97604935657381 40.63127590... 1 Queens M...
Geopandas: how to read a csv and convert to a geopandas dataframe with polygons?
I read a .csv file as a dataframe that looks like the following: import pandas as pd df = pd.read_csv('myFile.csv') df.head() BoroName geometry 0 Brooklyn MULTIPOLYGON (((-73.97604935657381 40.63127590... 1 Queens MULTIPOLYGON (((-73.80379022888098 40.77561011... 2 Queens MULTIPOLYGON (((-73.8...
[ "For some reason geopandas seems to be unable to convert a geometry column from a pandas dataframe. You could try two approaches.\nNumber 2: Try applying the shapely wkt.loads function on your column before converting your dataframe to a geodataframe.\nfrom shapely import wkt\n\ndf['geometry'] = df['geometry'].appl...
[ 28, 24, 0, 0 ]
[]
[]
[ "geopandas", "pandas", "python" ]
stackoverflow_0061122875_geopandas_pandas_python.txt
Q: How do I point easy_install to vcvarsall.bat? I already have MSVC++ 2010 Express installed, and my vcvarsall.bat file is at C:\Program Files\Microsoft Visual Studio 10.0\VC, which is in my system PATH. When I run easy_install, it can't find vcvarsall.bat. Is there something I need to set in my distutils.cfg file ...
How do I point easy_install to vcvarsall.bat?
I already have MSVC++ 2010 Express installed, and my vcvarsall.bat file is at C:\Program Files\Microsoft Visual Studio 10.0\VC, which is in my system PATH. When I run easy_install, it can't find vcvarsall.bat. Is there something I need to set in my distutils.cfg file to point it to my MSVC++ installation? G:\>easy_ins...
[ "\nI'd still like to know where to set that reference to vsvarsall.bat...\n\nWell, as martineau wrote you have to have either Visual Studio 2008 or Visual C++ Express installed. Having said that I understand you would like to know where Python looks for this batch file. You can see this by looking at definition of ...
[ 57, 0 ]
[]
[]
[ "distutils", "easy_install", "python", "visual_studio_2010" ]
stackoverflow_0006551724_distutils_easy_install_python_visual_studio_2010.txt
Q: group few lists of dictionary by key lst1 = [ {"id": "A", "a": "one"}, {"id": "B", "b": "two"} ] lst2 = [ {"id": "A", "a1": "Three"}, {"id": "B", "b1": "Four"}, {"id": "C", "c1": "Four"} ] lst3 = [ {"id": "A", "c1": "Five"}, {"id": "B", "d1": "Six"} ] a = lst1+lst2+lst3 res = [ {'id':...
group few lists of dictionary by key
lst1 = [ {"id": "A", "a": "one"}, {"id": "B", "b": "two"} ] lst2 = [ {"id": "A", "a1": "Three"}, {"id": "B", "b1": "Four"}, {"id": "C", "c1": "Four"} ] lst3 = [ {"id": "A", "c1": "Five"}, {"id": "B", "d1": "Six"} ] a = lst1+lst2+lst3 res = [ {'id': 'A', 'a': 'one'}, {'id': 'B', 'b': '...
[ "Here's one approach:\narr = [\n {'id': 'A', 'a': 'one'},\n {'id': 'B', 'b': 'two'},\n {'id': 'A', 'a1': 'Three'},\n {'id': 'B', 'b1': 'Four'},\n {'id': 'C', 'c1': 'Four'},\n {'id': 'A', 'c1': 'Five'}, \n {'id': 'B', 'd1': 'Six'}\n ]\n\nres_dict = {d['id']:{'id':d['id']} for d in arr}\nf...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074470240_python.txt
Q: How to transfer data from a column to multiple columns using Python? How can I use python to transfer data from the "weekday" column and multiple columns (Monday, Tuesday, Wednesday...) and vice versa buyer weekday 0 A Saturday 1 A Friday 2 B Monday 3 B ...
How to transfer data from a column to multiple columns using Python?
How can I use python to transfer data from the "weekday" column and multiple columns (Monday, Tuesday, Wednesday...) and vice versa buyer weekday 0 A Saturday 1 A Friday 2 B Monday 3 B Tuesday 4 B Thursday 5 C Monday Desired Outcome:...
[ "df = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],\n 'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})\nw_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\ndf = pd.crosstab(df['buyer'], df['weekday']).replace({0: '', 1: 'Y...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074469479_dataframe_pandas_python.txt
Q: DeprecationWarning: How could I fix this? I am making a platformer game using pygame and I got this error when the character jumps: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated and may be removed in a future version of Python. This is the...
DeprecationWarning: How could I fix this?
I am making a platformer game using pygame and I got this error when the character jumps: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated and may be removed in a future version of Python. This is the line of code that got the error: win.blit(char...
[ "You are passing the function numbers of type float, but you should be passing integers.\nYou can pass the function integers instead of floats.\nYou can cast your floats to integers: win.blit(char, (int(x),int(y)). This will round the float towards 0. (e.g. int(2.6)=2, int(-2.6) = -2 If you want different behaviour...
[ 0 ]
[ "Just run this snippet before your code.\n!pip install shutup\n##At the top of the code\nimport shutup\nshutup.please()\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0062052212_python.txt
Q: Disable warnings in jupyter notebook I'm getting this warning in jupyter notebook. /anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:10: DeprecationWarning: object of type <class 'float'> cannot be safely interpreted as an integer. # Remove the CWD from sys.path while we load stuff. /anaconda3/lib/pyt...
Disable warnings in jupyter notebook
I'm getting this warning in jupyter notebook. /anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:10: DeprecationWarning: object of type <class 'float'> cannot be safely interpreted as an integer. # Remove the CWD from sys.path while we load stuff. /anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py...
[ "If you are sure your code is correct and simple want to get rid of this warning and all other warnings in the notebook do the following:\nimport warnings\nwarnings.filterwarnings('ignore')\n\n", "Try this:\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.simplefilter('ignore')\n\n", "You can also ...
[ 101, 21, 12, 1, 1, 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0048828824_jupyter_notebook_python.txt
Q: Empty body response when reading csv from s3 using pandas : FileNotFoundError: [Errno 2] I am using boto3 + pandas to read csv from s3. I get a response and a stream of bytes, however, when I attempt to read it in pandas, I see an empty dataframe error. import boto3 import pandas as pd client = boto3.client( ...
Empty body response when reading csv from s3 using pandas : FileNotFoundError: [Errno 2]
I am using boto3 + pandas to read csv from s3. I get a response and a stream of bytes, however, when I attempt to read it in pandas, I see an empty dataframe error. import boto3 import pandas as pd client = boto3.client( 's3', aws_access_key_id="xxx", aws_secret_access_key="xxx", ) key = 'Dir/filename.csv...
[ "The correct way is:\ndf = pd.read_csv(io.BytesIO(result['Body'].read()))\n\nSo its unclear why would you comment this out, as this is how the csv file should be read from the s3.\n" ]
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "pandas", "python" ]
stackoverflow_0074470313_amazon_s3_amazon_web_services_pandas_python.txt
Q: indexing on float values in coordinates I have a list points = [[6033.02, -24791.2], [7008.29, -24257.0], [7128.66, -23434.0], [7235.19, -22899.3], [6590.0, -22308.7]] and centre = [37621.265, -32837.66499999999] I want to translate the values of points with this function def translate(center, points): new_p...
indexing on float values in coordinates
I have a list points = [[6033.02, -24791.2], [7008.29, -24257.0], [7128.66, -23434.0], [7235.19, -22899.3], [6590.0, -22308.7]] and centre = [37621.265, -32837.66499999999] I want to translate the values of points with this function def translate(center, points): new_points_x = [] new_points_y = [] new_po...
[ "Looks like you are passing the center and points in the wrong order to the function. Doing that causes the points to be a list instead of list of lists and i would be a float instead of list.\nTry with -\npoints = [[6033.02, -24791.2], [7008.29, -24257.0], [7128.66, -23434.0], [7235.19, -22899.3], [6590.0, -22308....
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074470422_python_python_3.x.txt
Q: numpy interpolation with period Can someone explain to me the code that is in the documentation specifically this: Interpolation with periodic x-coordinates: x = [-180, -170, -185, 185, -10, -5, 0, 365] xp = [190, -190, 350, -350] fp = [5, 10, 3, 4] np.interp(x, xp, fp, period=360) array([7.5 , 5. , 8.75, 6.25, ...
numpy interpolation with period
Can someone explain to me the code that is in the documentation specifically this: Interpolation with periodic x-coordinates: x = [-180, -170, -185, 185, -10, -5, 0, 365] xp = [190, -190, 350, -350] fp = [5, 10, 3, 4] np.interp(x, xp, fp, period=360) array([7.5 , 5. , 8.75, 6.25, 3. , 3.25, 3.5 , 3.75]) I did a tri...
[ "The numbers used in the example that demonstrates the use of period in the interp docstring can be a bit difficult to interpret in a plot. Here's what is happening...\nThe period is 360, and the given \"known\" points are\nxp = [190, -190, 350, -350]\nfp = [ 5, 10, 3, 4]\n\nNote that the values in xp span...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074470191_numpy_python.txt
Q: PyVis - search Node I am using PyVis to build a graph (essentially a call chain). So I like how it generates a html file, with related code, to visualize it. Is there a way I can generate a 'Search node" functionality ? The Graph I am loading is huge, and a function to zoom in to a node of interest, is what I am l...
PyVis - search Node
I am using PyVis to build a graph (essentially a call chain). So I like how it generates a html file, with related code, to visualize it. Is there a way I can generate a 'Search node" functionality ? The Graph I am loading is huge, and a function to zoom in to a node of interest, is what I am looking for...
[ "There is a filter function in PyVis. \nWhen creating the network instance, set filer_menu parameter to True.\nAnd there is search menu shown in html file.\ng = Network('1200px', width=\"100%\", notebook=True, directed=True, filter_menu=True)\n\nreference from https://pyvis.readthedocs.io/en/latest/tutorial.html#ed...
[ 2 ]
[]
[]
[ "python", "pyvis" ]
stackoverflow_0068951238_python_pyvis.txt
Q: How do I convert this nested for loop to a map or list comprehension in python? Note: this is a working program, I just need to make it faster. This is the nested for loop: taf = [] for i in range(len(piou)): counter = 0 for j in range(len(piou[i])): if piou[i][j] == True: coun...
How do I convert this nested for loop to a map or list comprehension in python?
Note: this is a working program, I just need to make it faster. This is the nested for loop: taf = [] for i in range(len(piou)): counter = 0 for j in range(len(piou[i])): if piou[i][j] == True: counter = counter + 1 if counter == len(piou[i]): taf.append(i) I tried doin...
[ "A loop where you're just incrementing a number can be replaced with sum(), but where that summation is just going to be compared with the length of the list, use all().\nAs well, avoid for i in range(len(seq)) ... i, seq[i], use for i, x in enumerate(seq) instead.\ntaf = [i for i, row in enumerate(piou) if all(row...
[ 2 ]
[]
[]
[ "list_comprehension", "nested_loops", "python" ]
stackoverflow_0074453856_list_comprehension_nested_loops_python.txt
Q: Get distinct count of values in single row in Pyspark DataFrame I'm trying to split comma separated values in a string column to individual values and count each individual value. The data I have is formatted as such: +--------------------+ | tags| +--------------------+ |cult, horror, got...| | ...
Get distinct count of values in single row in Pyspark DataFrame
I'm trying to split comma separated values in a string column to individual values and count each individual value. The data I have is formatted as such: +--------------------+ | tags| +--------------------+ |cult, horror, got...| | violence| | romantic| |inspiring, romant...| |crue...
[ "You can use split() to split strings, then explode(). Finally, groupby and count:\nimport pyspark.sql.functions as F\n\ndf = spark.createDataFrame(data=[\n [\"cult,horror\"],\n [\"cult,comedy\"],\n [\"romantic,comedy\"],\n [\"thriler,horror,comedy\"],\n], schema=[\"tags\"])\n\ndf = df \\\n .withColumn...
[ 0 ]
[]
[]
[ "dataframe", "pyspark", "python" ]
stackoverflow_0074469458_dataframe_pyspark_python.txt
Q: Create a python function that accepts dataframe and column(s) I'm trying to create a function that accepts dataframe columns. Something along the lines of the below pseudo code.. def tb_mend_format(df, col): if df[col][:3] == 'TBK': return 'TB ' + df[col][7:] else: return df[col] Is it...
Create a python function that accepts dataframe and column(s)
I'm trying to create a function that accepts dataframe columns. Something along the lines of the below pseudo code.. def tb_mend_format(df, col): if df[col][:3] == 'TBK': return 'TB ' + df[col][7:] else: return df[col] Is it possible to then pass a dataframe and column(s) in the below fashi...
[ "Probably you meant something like this?\ndef tb_mend_format(df, col: Union[pd.Series, str]):\n\n if isinstance(col, pd.Series):\n series = col\n else:\n series = df[col]\n\n if series[:3] == 'TBK':\n return 'TB ' + series[7:]\n else:\n return series\n\n# both works\ntb_men...
[ 0 ]
[]
[]
[ "jupyter", "pandas", "python", "spyder" ]
stackoverflow_0074470500_jupyter_pandas_python_spyder.txt
Q: html h1 tag no show type after click no.1 and blank to than page it no show h1 tag enter image description here inspect here enter image description here code html here {% extends "main.html" %} {% block content %} <h1>{{room.name}}</h1> {% endblock content %} code python here i don't know this have problem or ...
html h1 tag no show type
after click no.1 and blank to than page it no show h1 tag enter image description here inspect here enter image description here code html here {% extends "main.html" %} {% block content %} <h1>{{room.name}}</h1> {% endblock content %} code python here i don't know this have problem or not from django.shortcuts impo...
[ "I think you misspelled room context.\nInstead of this:\n<h1>{{room.name}}</h1>\n\nTry this:\n<h1>{{romm.name}}</h1>\n\n" ]
[ 2 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074470028_django_html_python.txt
Q: How to get global variables defined in top-level module in a function? I want to implement @noglobal ^1 decorator in a module. However, the globals() builtin function gets global variables in the module where globals() called ^2. How to get global variables defined in the top-level module, within a function? What ...
How to get global variables defined in top-level module in a function?
I want to implement @noglobal ^1 decorator in a module. However, the globals() builtin function gets global variables in the module where globals() called ^2. How to get global variables defined in the top-level module, within a function? What I did # in ./lib/utils.py import builtins import types def imports(): ...
[ "In header section just type import this one. Problem will be fix\nimport builtins\nimport types\nimport pandas as pd\n\nnote if pandas are not installed then install it by this command from your terminal\npip install pandas\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0074470376_python_python_module.txt
Q: I'm doing python course on mooc.fi but im stuck on "Food expidenture" # Write your solution here times = int(input("How many times a week do you eat at the student cafeteria? ")) price = float(input("The price of a typical student lunch? ")) groc = float(input("How much money do you spend on groceries in a week? "...
I'm doing python course on mooc.fi but im stuck on "Food expidenture"
# Write your solution here times = int(input("How many times a week do you eat at the student cafeteria? ")) price = float(input("The price of a typical student lunch? ")) groc = float(input("How much money do you spend on groceries in a week? ")) print("Average food expenditure:") print (f"Daily: {times * price + gro...
[ "You have a precedence problem.\nIn arithmetic expressions, multiplication and division happen before addition. So this:\ntimes * price + groc / 7\n\ndivides groc by 7 and then adds it to the result of multiplying times by price. You want instead to divide the whole value tiems * price + groc by 7, which means you ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0073759926_python.txt
Q: Pylance has two same resolution results I am coding python script using vscode with extensions of Python and Pylance. I met a problem as the picture below there are two same resolution results at the same time, and not only for the import; any other place like resolving variables, modules and functions, there are...
Pylance has two same resolution results
I am coding python script using vscode with extensions of Python and Pylance. I met a problem as the picture below there are two same resolution results at the same time, and not only for the import; any other place like resolving variables, modules and functions, there are always two same results. If forbidding Pylan...
[ "Upgrade the Jupyter extension to the pre-release version.\n\n" ]
[ 0 ]
[]
[]
[ "pylance", "python", "visual_studio_code" ]
stackoverflow_0074470197_pylance_python_visual_studio_code.txt
Q: unknown error: Chrome failed to start: exited abnormally. Chrome isn't opening in selenium webdriver I've created a EC2 instance with installed ububtu. I've installed python3-pip and selenium webdriver and other requirements to run selenium on it. I'm using this code but it raises this error. from selenium import ...
unknown error: Chrome failed to start: exited abnormally. Chrome isn't opening in selenium webdriver
I've created a EC2 instance with installed ububtu. I've installed python3-pip and selenium webdriver and other requirements to run selenium on it. I'm using this code but it raises this error. from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import Chrom...
[ "Try to uninstall the selenium package from the terminal and reinstall it again. Also, use python version 3.9 or 3.8 as 3.10 is not a stable version to use for development.\n" ]
[ 0 ]
[]
[]
[ "amazon", "linux", "python", "selenium", "ubuntu" ]
stackoverflow_0074470599_amazon_linux_python_selenium_ubuntu.txt
Q: Detect OS dark mode in Python I'm writing a small program in python with a GUI that I'm using tkinter for. What I'd like to do is add dark mode support to my program. Mac OS, Ubuntu (at least Gnome) and Windows 10 all have a system-wide setting for "dark mode" that'll make all programs automatically run with a dar...
Detect OS dark mode in Python
I'm writing a small program in python with a GUI that I'm using tkinter for. What I'd like to do is add dark mode support to my program. Mac OS, Ubuntu (at least Gnome) and Windows 10 all have a system-wide setting for "dark mode" that'll make all programs automatically run with a dark theme. But how do I check that se...
[ "Quick answer for Windows 10\ndef detect_darkmode_in_windows(): \n try:\n import winreg\n except ImportError:\n return False\n registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)\n reg_keypath = r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize'\n try:\n ...
[ 8, 6, 2, 2, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0065294987_python_tkinter_user_interface.txt
Q: Remove Duplicates from csv I have a csv/txt file of following content: Mumbai 2 Pune 6 Bangalore 8 Pune 10 Mumbai 8 and I want this in output file : Mumbai 2,8 Pune 6,10 Bangalore 8 Note : Don't use any python modules, packages A: Here is a possible solution: import re linepat = re.compile(''' ^ \s* (?: ...
Remove Duplicates from csv
I have a csv/txt file of following content: Mumbai 2 Pune 6 Bangalore 8 Pune 10 Mumbai 8 and I want this in output file : Mumbai 2,8 Pune 6,10 Bangalore 8 Note : Don't use any python modules, packages
[ "Here is a possible solution:\nimport re\n\nlinepat = re.compile('''\n\n ^ \\s*\n (?:\n (\n [A-Za-z] \\S*\n (?: \\s+ [A-Za-z] \\S* )*\n ) \\s+ ( [0-9]+ )\n \\s* $\n )\n |\n (.*)\n\n''', re.VERBOSE)\n\nfiltered = {}\n\n# fill `filtered` from `duplicates.csv`\nwith open('duplicates.csv', 'r') ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074470182_python.txt
Q: Pandas to_json with groupby For a pandas dataframe like this key val1 val2 a a1 a2 a b1 b2 c c1 c2 How can I convert it to the following json? Need to group on 'key' and use its values as the keys in the json: { "a":[{"val1":"a1", "val2":"a2"}, {"val1":"b1", "v...
Pandas to_json with groupby
For a pandas dataframe like this key val1 val2 a a1 a2 a b1 b2 c c1 c2 How can I convert it to the following json? Need to group on 'key' and use its values as the keys in the json: { "a":[{"val1":"a1", "val2":"a2"}, {"val1":"b1", "val2":"b2"}], "c":[{"val1":"c1", ...
[ "Using .groupby and .to_dict() with \"records\"\ndf = df.groupby(\"key\")[[\"val1\", \"val2\"]].apply(lambda x: x.to_dict(orient=\"records\")).to_json()\nprint(df)\n\nOutput:\n{'a': [{'val1': 'a1', 'val2': 'a2'}, {'val1': 'b1', 'val2': 'b2'}], 'c': [{'val1': 'c1', 'val2': 'c2'}]}\n\n" ]
[ 1 ]
[]
[]
[ "group_by", "pandas", "python", "to_json" ]
stackoverflow_0074470095_group_by_pandas_python_to_json.txt
Q: How to group dataframe parts of rows into list in pandas groupby I saw this page, How to group dataframe rows into list in pandas groupby but, that's not what I need. Let my datatable example see please. index column1 column2 0 apple red 1 banana a 1 banana b 2 grape wow 2 grape that's 2 grape great 2 grap...
How to group dataframe parts of rows into list in pandas groupby
I saw this page, How to group dataframe rows into list in pandas groupby but, that's not what I need. Let my datatable example see please. index column1 column2 0 apple red 1 banana a 1 banana b 2 grape wow 2 grape that's 2 grape great 2 grape fruits! 3 melon oh 3 melon no ...a lot of data... ...
[ "Let's filter the dataframe based on index column, then groupby on the filtered dataframe.\nm = df['index'].isin([2,3])\n\nout = (pd.concat([df[~m],\n (df[m].groupby('column1', as_index=False)\n .agg({'index': 'first', 'column2': ' '.join}))], ignore_index=True)\n .sort_valu...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074470560_pandas_python.txt
Q: Getting httplib2 error when running apt-get commands on Pop!_OS 22.04 I just updated to pop os 22.04 lts and now not only it can't detect any output and input devices on my computer but I also can't run any apt-get commands, whenever I try to run it I receive the error: from httplib2.error import ServerNotFoundErr...
Getting httplib2 error when running apt-get commands on Pop!_OS 22.04
I just updated to pop os 22.04 lts and now not only it can't detect any output and input devices on my computer but I also can't run any apt-get commands, whenever I try to run it I receive the error: from httplib2.error import ServerNotFoundError ModuleNotFoundError: No module named 'httplib2.error' dpkg: error proces...
[ "Happened to me too. It seemed to be happening because /usr/lib/python3/dist-packages/ had httplib2 version 0.18 when a newer version was expected. Normally, doing sudo apt install python3-httplib2 would be the way to update this packge. Since that was currently impossible, I manually overwrote the package with ...
[ 2 ]
[]
[]
[ "apt_get", "httplib2", "linux", "pip", "python" ]
stackoverflow_0074433907_apt_get_httplib2_linux_pip_python.txt
Q: Static methods in Python? Can I define a static method which I can call directly on the class instance? e.g., MyClass.the_static_method() A: Yep, using the staticmethod decorator: class MyClass(object): @staticmethod def the_static_method(x): print(x) MyClass.the_static_method(2) # outputs 2 N...
Static methods in Python?
Can I define a static method which I can call directly on the class instance? e.g., MyClass.the_static_method()
[ "Yep, using the staticmethod decorator:\nclass MyClass(object):\n @staticmethod\n def the_static_method(x):\n print(x)\n\nMyClass.the_static_method(2) # outputs 2\n\nNote that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This...
[ 2224, 247, 91, 62, 35, 15, 13, 4, 4, 1, 0 ]
[ "I encounter this question from time to time. The use case and example that I am fond of is:\njeffs@jeffs-desktop:/home/jeffs $ python36\nPython 3.6.1 (default, Sep 7 2017, 16:36:03) \n[GCC 6.3.0 20170406] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import cmath\...
[ -2 ]
[ "python", "static_methods" ]
stackoverflow_0000735975_python_static_methods.txt
Q: Dash Annotating Lineplot Dynamically Between Subplots I have a dataset which is similar to below one. Please note that there are multiple values for a single ID. import pandas as pd import numpy as np import random df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'), ...
Dash Annotating Lineplot Dynamically Between Subplots
I have a dataset which is similar to below one. Please note that there are multiple values for a single ID. import pandas as pd import numpy as np import random df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='h'), 'SBP':[random.uniform(110, 160) for n in range(...
[ "I'm happy to see my answer to your other question helped. You might have to play with the arrow placements depending on the final size of your figure, but this accomplishes what you're looking for.\nfig = px.line(df,\n x='DATE_TIME',\n y=['SBP', 'DBP'],\n facet_col='VISIT',\n fa...
[ 1, 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074432287_plotly_plotly_dash_python.txt
Q: Create columns based on rows I am new to pandas and I am looking for a nice way to transform this dataframe: Date Name Value 01-01-2022 A 0 01-01-2022 B 1 01-01-2022 C 1 02-01-2022 A 1 02-01-2022 B 1 02-01-2022 C 0 To this dataframe: Name Value_before Value_after A 0 1 B 1 1 C 1 0 First table contains...
Create columns based on rows
I am new to pandas and I am looking for a nice way to transform this dataframe: Date Name Value 01-01-2022 A 0 01-01-2022 B 1 01-01-2022 C 1 02-01-2022 A 1 02-01-2022 B 1 02-01-2022 C 0 To this dataframe: Name Value_before Value_after A 0 1 B 1 1 C 1 0 First table contains only dat...
[ "Assuming:\n\nthat you have only 2 dates\nthat there are no duplicated Name per date\n\nYou can use a pivot taking advantage of the fact the pivot sorts the columns, then set_axis to use your custom names\nout = (df\n .assign(Date=pd.to_datetime(df['Date'])) # ensure datetime for correct sorting\n .pivot('Name...
[ 3, 3, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0073717627_pandas_python.txt
Q: requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Hello I keep getting error of requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and I don't know how to fix it. This is what I have @staticmethod def get_access_token(code): data = { ...
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Hello I keep getting error of requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and I don't know how to fix it. This is what I have @staticmethod def get_access_token(code): data = { "client_id": Oauth.client_id, "client_secret": Oauth.client_secret, ...
[ "access_token = requests.post(url = \"https://discord.com/api/oauth2/token\", json = data).json()\n\nusing json instead of data(I don't know why but it works for me---I met the same question as yours)\n" ]
[ 0 ]
[]
[]
[ "discord", "json", "python" ]
stackoverflow_0074411209_discord_json_python.txt