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: Convert python to C# Revit API I am beginer in C# and Api, so it some difficult for me to convert useful solutions to my code. Please help understand how do it? In goal need find shortest way. Have some elements which connected each other by connectors. With this in hand I can find all possible ways of way(code of...
Convert python to C# Revit API
I am beginer in C# and Api, so it some difficult for me to convert useful solutions to my code. Please help understand how do it? In goal need find shortest way. Have some elements which connected each other by connectors. With this in hand I can find all possible ways of way(code of may implementation below), but cant...
[ "The Revit API is completely .NET based. All .NET source code is converted to intermediate language, IL (Wikipedia). You can decompile the intermediate language to recreate the original source code. This enables you to easily and effectively convert the source code from one .NET language to another, for instance fr...
[ 0 ]
[]
[]
[ "api", "c#", "data_conversion", "python", "revit_api" ]
stackoverflow_0074455514_api_c#_data_conversion_python_revit_api.txt
Q: How to prevent Python dictionary key ordering reversal? I have the following python code snippet involving dictionary, sample_dict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york" } keys = ["name", "salary"] sample_dict = {k: sample_dict[k] for k in...
How to prevent Python dictionary key ordering reversal?
I have the following python code snippet involving dictionary, sample_dict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york" } keys = ["name", "salary"] sample_dict = {k: sample_dict[k] for k in sample_dict.keys() - keys} print(sample_dict) Why the o...
[ "I guess the order is lost during processing of - between your keys() and your keys list (because it involves conversion to sets which are unordered). You can build your comprehension as follow to prevent it.\nkeys = {\"name\", \"salary\"}\nsample_dict = {k: sample_dict[k] for k in sample_dict.keys() if k not in ke...
[ 2, 1 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0074456617_dictionary_key_python.txt
Q: python float object can not be interpreted as an integer there is data is store in a data frame and i use the fallowing code for result. import pandas as pd import numpy as np import json Data1 = 'Data/lab_202210181540.csv' ############### For Data 1 #################### data_frame = pd.read_csv(Data1) data_fram...
python float object can not be interpreted as an integer
there is data is store in a data frame and i use the fallowing code for result. import pandas as pd import numpy as np import json Data1 = 'Data/lab_202210181540.csv' ############### For Data 1 #################### data_frame = pd.read_csv(Data1) data_frame['data'] = data_frame['data'].apply(json.loads) data_frame ...
[ "Try this:\nfor arr in range(int(df.fillna(0)['Analyte_line'][i])):\n\nThis should convert the float value to int before passing into range().\n" ]
[ 1 ]
[]
[]
[ "csv", "json", "pandas", "python" ]
stackoverflow_0074456622_csv_json_pandas_python.txt
Q: How to calculate differences between two pandas.Timestamp Series in nanoseconds I have two Series which are pd.Timestamps, and they are extremely close. I'd like to get the elementwise difference between the two Series, but with nanosecond precision. First Series: 0 2021-05-21 00:02:11.349001429 1 2021-05-21...
How to calculate differences between two pandas.Timestamp Series in nanoseconds
I have two Series which are pd.Timestamps, and they are extremely close. I'd like to get the elementwise difference between the two Series, but with nanosecond precision. First Series: 0 2021-05-21 00:02:11.349001429 1 2021-05-21 00:02:38.195857153 2 2021-05-21 00:03:25.527530228 3 2021-05-21 00:03:26.65341...
[ "You won't lose precision if you work with timedelta as shown. The internal representation is always nanoseconds. After calculating the timedelta, you can convert to integer to obtain the difference in nanoseconds. Ex:\nimport pandas as pd\nimport numpy as np\n\ns1 = pd.Series(pd.to_datetime([\"2021-05-21 00:02:11....
[ 2, 1 ]
[]
[]
[ "datetime", "pandas", "python", "timedelta" ]
stackoverflow_0067669891_datetime_pandas_python_timedelta.txt
Q: Beautifulsoup 4: How to find immediate previous sibling I have the following text in an xml-file: <div><head facs="#facs_29_TextRegion_1624461408183_2024"> <lb facs="#facs_29_r2l33" n="N001"/><supplied reason="article_added">11</supplied> Von dem Gewalt und Auctoritet <lb facs="#facs_29_r2l...
Beautifulsoup 4: How to find immediate previous sibling
I have the following text in an xml-file: <div><head facs="#facs_29_TextRegion_1624461408183_2024"> <lb facs="#facs_29_r2l33" n="N001"/><supplied reason="article_added">11</supplied> Von dem Gewalt und Auctoritet <lb facs="#facs_29_r2l34" n="N002"/>der Kirchen.</head> <p facs="#facs_30_T...
[ "Try to use and compare this way:\nref.parent.find_previous_sibling() == ref.parent.find_previous_sibling('q')\n\n\nIn real documents, the .next_sibling or .previous_sibling of a tag\nwill usually be a string containing whitespace.\n\nSo .previous_sibling is not the same as find_previous_sibling() that you should u...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074456672_beautifulsoup_python.txt
Q: REQUEST FUNCTION FROm FLASK I am using request.form.get("name") to get the value of an input whose type=number. I then want to be able to compare so as to ensure that it is a postive number as follows: number = request.form.get("name") If number < 0: # Do something This gives an error as follows:- TypeError: < n...
REQUEST FUNCTION FROm FLASK
I am using request.form.get("name") to get the value of an input whose type=number. I then want to be able to compare so as to ensure that it is a postive number as follows: number = request.form.get("name") If number < 0: # Do something This gives an error as follows:- TypeError: < not supported between instances of...
[ "HTML input types like <input type=\"number\"> serve only for client-side validation purposes and have no effect on what's sent in the HTTP request. The HTTP forms will always contain text, like param1=123&param2=blah. You need to parse the values explicitly:\ntry:\n number = int(request.form.get('name'))\nexcep...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074456709_flask_python.txt
Q: How can i print a reversed NumPy array with the element type float import numpy def arrays(arr): # complete this function # use numpy.array arr = input().strip().split(' ') result = arrays(arr) print(result) import numpy as np a=np.array([0,1,2,5,6],float) print a A: I think this is what you are looki...
How can i print a reversed NumPy array with the element type float
import numpy def arrays(arr): # complete this function # use numpy.array arr = input().strip().split(' ') result = arrays(arr) print(result) import numpy as np a=np.array([0,1,2,5,6],float) print a
[ "I think this is what you are looking for:\nimport numpy as np\narr = input().strip().split(' ')\ndef arrays(arr):\n arr = np.array(arr, dtype=float)\n return(arr[::-1]) # this will reverse the array\narrays(arr)\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074455633_numpy_python.txt
Q: Python typing: nested dictionary of unknown depth I am using Python 3.11. Type hinting for dict of dicts of strs will look like this: dict[dict[str, str]] But what if I want to make hints for dict of unknown depth? For example, I want to write a function, which construct tree in dict form from list of tuples (par...
Python typing: nested dictionary of unknown depth
I am using Python 3.11. Type hinting for dict of dicts of strs will look like this: dict[dict[str, str]] But what if I want to make hints for dict of unknown depth? For example, I want to write a function, which construct tree in dict form from list of tuples (parent, offspring): source = [('a', 'b'), ('b', 'c'), ('d'...
[ "You can use a type alias with a forward reference to itself:\nfrom typing import TypeAlias\n\nNestedDict: TypeAlias = dict[str, str | 'NestedDict']\n\ndef tree_form(source: list[tuple[str, str]]) -> NestedDict:\n return {'a': {'b': {'c': {}}}, 'd': {'e': {}}}\n\nprint(tree_form([('a', 'b'), ('b', 'c'), ('d', 'e...
[ 3 ]
[]
[]
[ "python", "python_typing" ]
stackoverflow_0074456529_python_python_typing.txt
Q: Google analytics fetch user id in reporting API I like to fetch user id which is available in user explorer report google analytics. I am using below batchGet to get the list of user ids using ga:clientId https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet I am able to get...
Google analytics fetch user id in reporting API
I like to fetch user id which is available in user explorer report google analytics. I am using below batchGet to get the list of user ids using ga:clientId https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet I am able to get the client ids, but when trying the same id with bel...
[ "User ID and client ID are two distinct dimensions in Google Analytics. User explorer report is based on user ID and this id might differ from client Id that appears in API report under ga:clientId dimension. \nTo use Activity reports based on client Id value, use the following object in your Activity request:\n{\n...
[ 2, 0 ]
[]
[]
[ "google_analytics", "google_reporting_api", "python" ]
stackoverflow_0058840416_google_analytics_google_reporting_api_python.txt
Q: Python: AttributeError: 'Snake' object has no attribute 'segments' I was trying to create a class called Snake. But when I run the code, it keeps saying "AttributeError: 'Snake' object has no attribute 'segments'". Anyone can help, please? from turtle import Turtle STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)]...
Python: AttributeError: 'Snake' object has no attribute 'segments'
I was trying to create a class called Snake. But when I run the code, it keeps saying "AttributeError: 'Snake' object has no attribute 'segments'". Anyone can help, please? from turtle import Turtle STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 class Snake: def __int__(self): self....
[ "\nChange __int__ to __init__\nAdd -1 in 1st & 2nd parameter of range() :\n\nfor seg in range(len(self.segments)-1, -1, -1):\n\n" ]
[ 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074455694_oop_python.txt
Q: Get a last message from a discord as a client So I want to get the last message sent in a discord channel that I am right now using Python ], but it is not mine server so I cant invite my bots to do it. What is the best way to get the last message? Is there any library that can do it? Maybe Image recognition? Than...
Get a last message from a discord as a client
So I want to get the last message sent in a discord channel that I am right now using Python ], but it is not mine server so I cant invite my bots to do it. What is the best way to get the last message? Is there any library that can do it? Maybe Image recognition? Thanks in advance I want to get the last message
[ "As i know , This Is Against of Discord Terms And \nAnd There Is No Lib For Doing These Works On Discord \nIf You Can Get A Webhook , It Will Be Nice ! \nOtherwise , You Should Use Ugly Ways !\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074411014_discord_discord.py_python.txt
Q: Python Identities of Sequence Slices I have noticed something with the "identity", i.e., value returned by id(), of slices of certain sequence types that I simply can't wrap my head around. I see it with lists and strings, which makes me think it is related to the implementation of either sequences or slices in C...
Python Identities of Sequence Slices
I have noticed something with the "identity", i.e., value returned by id(), of slices of certain sequence types that I simply can't wrap my head around. I see it with lists and strings, which makes me think it is related to the implementation of either sequences or slices in CPython. As covered in 3. Data model - Pyth...
[ "This behaviour is because of the Cpython optimisation. Lets start from\n>>> l[2:]\n\nSlicing a list always creates a new list. Since allocating and deallocating a list object is an expensive operation, python interpreter keep track of free_list which is an array of pointers to PyListObject.\n/* Empty list reuse sc...
[ 0 ]
[]
[]
[ "cpython", "list", "python", "python_3.x", "slice" ]
stackoverflow_0074451312_cpython_list_python_python_3.x_slice.txt
Q: Create a uniuqe DataFrame that contains multiple dataframes grouped by email from diferent file I got a users.csv file that hasa list of emails. and also a report.csv file that has a bunch of data i want to create a pdf file, that has only the data that match the email from users.csv contents o...
Create a uniuqe DataFrame that contains multiple dataframes grouped by email from diferent file
I got a users.csv file that hasa list of emails. and also a report.csv file that has a bunch of data i want to create a pdf file, that has only the data that match the email from users.csv contents of users.cvs users victor.uriel@domain.com urile.victor@domain.com contents of report.csv Manager1...
[ "just get the row containing the email addresses in the users.csv file. Can you try this:\nreport_v2 = report[report['Email'].isin(users['users'])]\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074454341_dataframe_pandas_python.txt
Q: Issue while passing locator as a Variable to find_elements method in selenium with python I am preparing a test automation suite Using Selenium-Python and encountered an issue. I am trying to get a list of web elements using the find elements method. **Method 1:** elements = driver.find_elements(By.XPATH,"<My XPAT...
Issue while passing locator as a Variable to find_elements method in selenium with python
I am preparing a test automation suite Using Selenium-Python and encountered an issue. I am trying to get a list of web elements using the find elements method. **Method 1:** elements = driver.find_elements(By.XPATH,"<My XPATH>") -> This is working fine and returns the elements correctly **Method 2: ** locator = By....
[ "You should do this way:\nlocator = By.XPATH, \"<My XPATH>\"\nelements = driver.find_elements(*locator)\n\nso that you unpack your tuple to argument list.\n" ]
[ 0 ]
[]
[]
[ "automation", "python", "selenium" ]
stackoverflow_0074456299_automation_python_selenium.txt
Q: Right click save link as then save hello guys i want to right click save link as then save on the save pop up that windows shows. this is an example: https://www.who.int/data/gho/data/indicators/indicator-details/GHO/proportion-of-population-below-the-international-poverty-line-of-us$1-90-per-day-(-) go on this pa...
Right click save link as then save
hello guys i want to right click save link as then save on the save pop up that windows shows. this is an example: https://www.who.int/data/gho/data/indicators/indicator-details/GHO/proportion-of-population-below-the-international-poverty-line-of-us$1-90-per-day-(-) go on this page in the data tab u can see EXPORT DATA...
[ "I think you would be better off using the Data API (json) offered on the same page, but I have managed to download the file using the code below and Google Chrome.\nThere is a lot going on which I didn't want to go into (hence the lazy usage of an occasional sleep), but the basic principle is that the Export link ...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074442404_python_selenium_web_scraping.txt
Q: Duplicate characters in a string Hello I a beginner in python. I am building a small program that can find any duplicate characters in a string. However there's something i don't understand. Code: def is_isogram(string): dict = {} for letter in string: dict[letter] = 1 if letter in dict: ...
Duplicate characters in a string
Hello I a beginner in python. I am building a small program that can find any duplicate characters in a string. However there's something i don't understand. Code: def is_isogram(string): dict = {} for letter in string: dict[letter] = 1 if letter in dict: dict[letter] += 1 return dict ...
[ "You are setting 1 for each, and then you increment the last letter. I think you meant to put if inside for block.\nHere is a working version:\ndef is_isogram(string):\n dct = {}\n for letter in string:\n if letter in dct:\n dct[letter] += 1\n else:\n dct[letter] = 1\n r...
[ 2, 2, 1 ]
[ "Your code works exactly as it is expected it assigns 1 to every letter then since your if condition is out of the loop, it increments the last character (letter) by one.\nI made some changes to your code.\ndef is_isogram(string):\n dict = {}\n for letter in string:\n dict[letter] = 0\n for letter i...
[ -2 ]
[ "dictionary", "python" ]
stackoverflow_0074456724_dictionary_python.txt
Q: Beginner question about finding Python script in IDLE shell I'm a beginner in Python with no prior programming experience, so bear with me here. I installed Python, started playing with it (typing variables, playing with math operations) in the Shell window and everything is fine. I open a New Window and started w...
Beginner question about finding Python script in IDLE shell
I'm a beginner in Python with no prior programming experience, so bear with me here. I installed Python, started playing with it (typing variables, playing with math operations) in the Shell window and everything is fine. I open a New Window and started writing a simple script. Something like this: print (1+1) I press ...
[ "Good to see that you are starting with python.\nFirstly, you can run the file directly using 'Run Module' only when you have the file open. Once you save the file and quit, you are out of the file editor and back to the terminal.\nSimply typing in firstscripty.py will not work as it does not recognize the command....
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074456908_python.txt
Q: Can I get the following results without loops and just using matrix operations I want to get the following results like the output show, Can I make it without for loop and just using matrix operations like numpy or torch, thanks all. import torch torch.manual_seed(0) input = torch.rand((1,3543,768)) w = torch.ran...
Can I get the following results without loops and just using matrix operations
I want to get the following results like the output show, Can I make it without for loop and just using matrix operations like numpy or torch, thanks all. import torch torch.manual_seed(0) input = torch.rand((1,3543,768)) w = torch.rand((3543,768,1)) output = torch.zeros(input.shape[0], input.shape[1], 1) for i in ra...
[ "I have solved it\noutput = torch.einsum(\"bij,ijk->bik\", input, w)\n\n" ]
[ 0 ]
[]
[]
[ "python", "torch" ]
stackoverflow_0074456306_python_torch.txt
Q: Dash Filtering For Numeric Columns I would like to use the code below in order to allow user to filter columns. The problem i sthat I cannot filter the columns with numerical values. How can I solve this issue? I was thinking to find column type, but it was not in the code from dash import Dash, dcc, html, Input, ...
Dash Filtering For Numeric Columns
I would like to use the code below in order to allow user to filter columns. The problem i sthat I cannot filter the columns with numerical values. How can I solve this issue? I was thinking to find column type, but it was not in the code from dash import Dash, dcc, html, Input, Output, dash_table import pandas as pd ...
[ "If you want to write your own filter, you should enclose the column name with {}. For example, in order to get the value 708573 from pop column, you should write it as:\n{pop} = 708573\n\nBut if you write your filter under a specific column, in this case, you only need to write = 708573\nPlease look in the documen...
[ 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074445749_plotly_plotly_dash_python.txt
Q: How do I generate yaml file via python code? I need to generate a yaml file and want to use python to do that. This (How can I write data in YAML format in a file?) helped me a lot but I am missing a few more steps. I want to have something like this in the end: - A: a B: C: c D: d E: e This: d = {'...
How do I generate yaml file via python code?
I need to generate a yaml file and want to use python to do that. This (How can I write data in YAML format in a file?) helped me a lot but I am missing a few more steps. I want to have something like this in the end: - A: a B: C: c D: d E: e This: d = {'- A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}} with op...
[ "- A: designates a list, and that list contains a dict. So what you need, is a list:\nd = [{'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}]\nwith open('result.yml', 'w') as yaml_file:\n yaml.dump(d, yaml_file, default_flow_style=False)\n\n", "Your output is a list, but you're starting with a dict.\n>>> import yaml\...
[ 2, 1 ]
[]
[]
[ "python", "yaml" ]
stackoverflow_0074457003_python_yaml.txt
Q: Make img's close range of RGB/HSV in particular value share pic link: https://imgur.com/a/yyQChWQ If I have black gradient img , we know the RGB is (0 ~ 255) or HSV is (0 ~ 255) How can I make close color range color together such as ( 0 ~ 80), ( 80 ~ 160) , ( 160 ~ 255) expect output: 1. I want the output to b...
Make img's close range of RGB/HSV in particular value
share pic link: https://imgur.com/a/yyQChWQ If I have black gradient img , we know the RGB is (0 ~ 255) or HSV is (0 ~ 255) How can I make close color range color together such as ( 0 ~ 80), ( 80 ~ 160) , ( 160 ~ 255) expect output: 1. I want the output to be (expect pic in link) (to remove noise) 2. generate histog...
[ "My suggestion is to use a grayscale image so that all the computations and displays are easier:\nimport numpy as np\nimport cv2 \nimport matplotlib.pyplot as plt\n\npath = \"**/RKqsXEv.png\"\n\n# Read the image in grayscale\nimg = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\nimg_filtered = img.copy()\n\n# Simple editin...
[ 3 ]
[]
[]
[ "matplotlib", "numpy", "opencv", "python", "python_3.x" ]
stackoverflow_0074456877_matplotlib_numpy_opencv_python_python_3.x.txt
Q: create seaborn heatmap from multiple columns I have a dataframe as such col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 2 12 8 3 16 9 5 13 11 14 3 14 7 9 18 12 14 14 13 13 5 ...
create seaborn heatmap from multiple columns
I have a dataframe as such col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 2 12 8 3 16 9 5 13 11 14 3 14 7 9 18 12 14 14 13 13 5 15 10 5 8 10 18 ...
[ "The following example code shows how you can correlate each of the last 5 columns with each of the first 5 columns, and show the result as a heatmap.\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\n\n# create some test data\ndf = pd.DataFrame(np.random.rand(3, 10),...
[ 0 ]
[]
[]
[ "pandas", "python", "seaborn" ]
stackoverflow_0074455723_pandas_python_seaborn.txt
Q: How to get ERC20 Token Transaction of a specific contract using Web3py I'm using web3py and I want to get the transaction history of a specific contract. Here's my code sample eventSignatureHash = web3.keccak(text='Transfer(address,uint256)').hex() filter = web3.eth.filter({ 'address': '0x828402Ee788375340A3e...
How to get ERC20 Token Transaction of a specific contract using Web3py
I'm using web3py and I want to get the transaction history of a specific contract. Here's my code sample eventSignatureHash = web3.keccak(text='Transfer(address,uint256)').hex() filter = web3.eth.filter({ 'address': '0x828402Ee788375340A3e36e2Af46CBA11ec2C25e', 'topics': [eventSignatureHash] }) I'm expected ...
[ "What i did is that i created a contract instance:\ncontract = web3.eth.contract(address = contract_address)\nthen trasnfer_filter = contract.events.Transfer.filter(u have optional parameters such as: fromBlock:...,toBlock, argument_filters:{\"to\": users_address(this filters for transfers only to that address)})\n...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "web3py" ]
stackoverflow_0068203146_python_python_3.x_web3py.txt
Q: Pandas subset selection and Pep8 I am using Spyder IDE with code style warnings enabled. Selecting a subset from a Pandas dataframe via df[df['Col1'].isna() == False] triggers the following code style warning. The code analysis suggests using if. However, if does not work in this context. How do I select a subset...
Pandas subset selection and Pep8
I am using Spyder IDE with code style warnings enabled. Selecting a subset from a Pandas dataframe via df[df['Col1'].isna() == False] triggers the following code style warning. The code analysis suggests using if. However, if does not work in this context. How do I select a subset from a Pandas dataframe without trigg...
[ "For inverse mask in pandas is used ~ instead compare False:\ndf[~df['Col1'].isna()]\n\nOr use Series.notna:\ndf[df['Col1'].notna()]\n\nYour error is for pure python, not for pandas.\n", "Use notna:\ndf[df['Col1'].notna()]\n\nOr you could invert the mask with ~ (vectorized NOT operator):\ndf[~df['Col1'].isna()]\n...
[ 3, 3 ]
[]
[]
[ "pep8", "python", "spyder" ]
stackoverflow_0074457231_pep8_python_spyder.txt
Q: How to generate a one hot encoder? I am trying to apply a OneHotEncoder to a column from a dataframe named "year". I tried seperating this column from the dataframe and then running it in the function but keep on getting the error message: __init__() takes 1 positional argument but 2 were given The code is: impor...
How to generate a one hot encoder?
I am trying to apply a OneHotEncoder to a column from a dataframe named "year". I tried seperating this column from the dataframe and then running it in the function but keep on getting the error message: __init__() takes 1 positional argument but 2 were given The code is: import sklearn year = articles["year"] year2...
[ "I think you should give the argument to fit function:\nsklearn.preprocessing.OneHotEncoder(drop='first').fit(year)\n\n" ]
[ 3 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074457218_python_scikit_learn.txt
Q: For Loops to copy and edit DataFrames I want to create 24 dataframes in a Loop, where the first dataframe is created by: df_hour_0 = df_dummies.copy() df_hour_0['Price_24_1'] = df_hour_0['Price_REG1'] df_hour_0['Price_24_2'] = df_hour_0['Price_REG2'] df_hour_0['Price_24_3'] = df_hour_0['Price_REG3'] df_hour_0['Pri...
For Loops to copy and edit DataFrames
I want to create 24 dataframes in a Loop, where the first dataframe is created by: df_hour_0 = df_dummies.copy() df_hour_0['Price_24_1'] = df_hour_0['Price_REG1'] df_hour_0['Price_24_2'] = df_hour_0['Price_REG2'] df_hour_0['Price_24_3'] = df_hour_0['Price_REG3'] df_hour_0['Price_24_4'] = df_hour_0['Price_REG4'] df_hou...
[ "Build a list of DataFrames like this:\ncols = ['Price_24_1', 'Price_24_2', 'Price_24_3', 'Price_24_4']\ndfs = []\n\nfor i in range(24):\n df = df_hour_0.copy()\n df[cols] = df[cols].shift(i)\n dfs.append(df)\n\nShift by i will be at index i.\n" ]
[ 1 ]
[]
[]
[ "for_loop", "pandas", "python" ]
stackoverflow_0074456941_for_loop_pandas_python.txt
Q: Write a python program to accept a number from a user and then calculate the average of all Write a python program to accept a number from a user and then calculate the average of all numbers from 1 to that given number. Then write the trace table to track the values of the variables at each iterate. This is my ...
Write a python program to accept a number from a user and then calculate the average of all
Write a python program to accept a number from a user and then calculate the average of all numbers from 1 to that given number. Then write the trace table to track the values of the variables at each iterate. This is my attempt: Range=int(input("ee: ")) Sum=0 Average=0 for i in range(1,Range): sum=sum+i Average...
[ "sum is a keyword, you meant to use Sum (The variable you declared) in line 5 and 6.\nRange=int(input(\"ee: \"))\nSum=0\nAverage=0\nfor i in range(1,Range + 1):\n Sum=Sum+i\nAverage=Sum/i\nprint(Average,\" \",i)\n\nAlso notice I have made it Range + 1. This is because the limit is not inclusive in the range() ...
[ 1 ]
[]
[]
[ "if_statement", "loops", "printing", "python", "sum" ]
stackoverflow_0074457234_if_statement_loops_printing_python_sum.txt
Q: How to read encrypted data from notepad and decrypt I'm attempting to read text from a file and decrypt it using the Fernet cryptography library in Python. So i'm running a For loop which prints all of the text, while it does that I attempt to make the loop decrypt. from cryptography.fernet import Fernet from insp...
How to read encrypted data from notepad and decrypt
I'm attempting to read text from a file and decrypt it using the Fernet cryptography library in Python. So i'm running a For loop which prints all of the text, while it does that I attempt to make the loop decrypt. from cryptography.fernet import Fernet from inspect import currentframe key = "kdQGjocgILOLXj6k_mkkOJOxH...
[ "The first problem in this case seems to be the fact that you correctly convert FileToEncrypt into bytes for encryption, but when you save it you simply cast it as a string using str(). What you want to do instead is use .decode()\nFurthemore you'd probably want to add another linebreak when you write the data to t...
[ 0 ]
[]
[]
[ "cryptography", "python" ]
stackoverflow_0074455802_cryptography_python.txt
Q: How solve: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() I am making a function to categorize data, but i am recieving this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). import pandas as ...
How solve: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
I am making a function to categorize data, but i am recieving this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). import pandas as pd df=pd.read_csv(r'C:\Users\gabri\Downloads\credit_scoring_eng.csv') def economic_class(valor): if valor<=16000: ...
[ "Try the below. It's also helpful to provide either dummy data or a sample of your data(not an image).\nWithout data provided, below is a sample you can adjust that works\nimport pandas as pd\n\ndata = {'Name':['Bob','Kyle','Kevin','Dave'],\n 'Value':[1000,20000,40000,30000]}\n\ndf = pd.DataFrame(data)\ndisp...
[ 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "series", "valueerror" ]
stackoverflow_0074452567_dataframe_pandas_python_series_valueerror.txt
Q: I want too add a !add command Im trying to add !add command to my ticket bot using discord py. the command would add a discord member to the channel and give them perms to send messages and see the channel history Any help would be greatly appreciated ive tried this @commands.has_permissions(manage_channels=True) ...
I want too add a !add command
Im trying to add !add command to my ticket bot using discord py. the command would add a discord member to the channel and give them perms to send messages and see the channel history Any help would be greatly appreciated ive tried this @commands.has_permissions(manage_channels=True) async def add(ctx, member : discord...
[ " category = discord.utils.get(guild.categories, name = \"enter Category\")\n\n channel = await guild.create_text_channel(\n f'{ctx.author.name}', category = category)\n\n await channel.set_permissions(guild.default_role, view_channel = False)\n await channel.set_permissions(user, view_cha...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074338257_discord_discord.py_python.txt
Q: How do I get New York City time? I travel frequently but live in NYC and am trying to display NYC time no matter where I am. How do I do that in Python? I have the following, which doesn't work, giving me the error: `'module' object is not callable` Also, I'm not sure if my method below will correctly update wi...
How do I get New York City time?
I travel frequently but live in NYC and am trying to display NYC time no matter where I am. How do I do that in Python? I have the following, which doesn't work, giving me the error: `'module' object is not callable` Also, I'm not sure if my method below will correctly update with daylight savings time or not: impor...
[ "Instead of datetime, write datetime.datetime:\nimport datetime\nimport pytz\n\nutc = pytz.utc\nutc_dt = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)\neastern = pytz.timezone('US/Eastern')\nloc_dt = utc_dt.astimezone(eastern)\nfmt = '%Y-%m-%d %H:%M:%S %Z%z'\nloc_dt.strftime(fmt)\n\nThat's because the module...
[ 18, 8, 7, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0011873714_python.txt
Q: How to keep python code in cloud and then make multiple users execute the code on their local machines? I have a python CLI interface tool which is used by more than 80 people in my team. Every time we make changes to our code and release it, users also have to download the latest code on their Windows Machine and...
How to keep python code in cloud and then make multiple users execute the code on their local machines?
I have a python CLI interface tool which is used by more than 80 people in my team. Every time we make changes to our code and release it, users also have to download the latest code on their Windows Machine and then run it. Like this we have other tools as well like GCC, Company's internal software to be installed on ...
[ "I'm not sure about the environment, some ideas;\n\ncould share a onedrive folder and sync it from there.\nGroup policy that runs an install script on startup\n\n", "The easiest no-setup solution would be for the tool to autoupdate itself. Make the main script be the \"loader\", which checks if there is a newer v...
[ 1, 1 ]
[]
[]
[ "cloud", "python", "shell", "windows" ]
stackoverflow_0074457197_cloud_python_shell_windows.txt
Q: Automated Locating and Selecting Files From File Explorer using Python Im having trouble finding a solution to my problem anywhere online, so i made my account and this is my first post :) I'm using PyAutoGUI to automate uploading videos to a website from a folder. When the automation clicks the "Select Files" but...
Automated Locating and Selecting Files From File Explorer using Python
Im having trouble finding a solution to my problem anywhere online, so i made my account and this is my first post :) I'm using PyAutoGUI to automate uploading videos to a website from a folder. When the automation clicks the "Select Files" button on the website, it opens File Explorer and asks me to choose a file, now...
[ "Use pyautogui.locateOnScreen to locate a screenshot of an object. You will get a coordinate then you can click directly at the file name input then type the name of your video.\ncoordX, coordY = pyautogui.locateOnScreen(\"cropped_screenshot.png\")\npyautogui.click(coordX + 200, coordY) #<---example the real object...
[ 0 ]
[]
[]
[ "automation", "microsoft_file_explorer", "pyautogui", "python", "python_3.x" ]
stackoverflow_0074429409_automation_microsoft_file_explorer_pyautogui_python_python_3.x.txt
Q: show cluster of point with folium I have a dataframe with a list of coordinates. I want to group on the map near points and show a dot on the map with the number of points on it like this. I'm using geopandas and folium. Following this example this is my code from folium.plugins import MarkerCluster import geopand...
show cluster of point with folium
I have a dataframe with a list of coordinates. I want to group on the map near points and show a dot on the map with the number of points on it like this. I'm using geopandas and folium. Following this example this is my code from folium.plugins import MarkerCluster import geopandas as gdp from shapely.geometry import ...
[ "I think its perhaps a problem that you dont have a folium map. In the docs of GeoDataFrame.explore() it says the parameter m should be linked to a map. Perhaps first you have to create a map and then use it in the explore command. Similar to this (have not tried this example in lack of geopandas installed)\nmap_bu...
[ 0 ]
[]
[]
[ "folium", "geopandas", "leaflet.markercluster", "python" ]
stackoverflow_0074375488_folium_geopandas_leaflet.markercluster_python.txt
Q: Format Conversion from COCO JSON to VGG Image Annotator I am working with https://github.com/mdhmz1/Auto-Annotate repo. In this repo, https://github.com/mdhmz1/Auto-Annotate/blob/main/customTrain.py file needs VIA JSON annotations file. I have my own annotations file in COCO JSON format. How can I convert my COCO ...
Format Conversion from COCO JSON to VGG Image Annotator
I am working with https://github.com/mdhmz1/Auto-Annotate repo. In this repo, https://github.com/mdhmz1/Auto-Annotate/blob/main/customTrain.py file needs VIA JSON annotations file. I have my own annotations file in COCO JSON format. How can I convert my COCO JSON file to VIA JSON file?
[ "Yeah, I think you can try to use Roboflow for that.\nYou can just upload your dataset there, and then export it in your needed format!\n" ]
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0071141440_json_python.txt
Q: My dicord bot doesn't respond to commands from discord.ext import commands import discord bot = commands.Bot(command_prefix="/", intents=discord.Intents.default()) TOKEN = "TOKEN" @bot.event async def on_ready(): print(f'Bot connected as {bot.user}') @bot.command() async def dosomething(ctx): await ctx....
My dicord bot doesn't respond to commands
from discord.ext import commands import discord bot = commands.Bot(command_prefix="/", intents=discord.Intents.default()) TOKEN = "TOKEN" @bot.event async def on_ready(): print(f'Bot connected as {bot.user}') @bot.command() async def dosomething(ctx): await ctx.send("I did something") bot.run(TOKEN) Bot...
[]
[]
[ "Change The Prefix To Anything Else But Not \"/\"\nAnd Try Intents.all()\nAs i Know , Using /commands Needs Other libraries\nLike This : discord_slash\n" ]
[ -1 ]
[ "discord", "python" ]
stackoverflow_0074455705_discord_python.txt
Q: file.write only write the first string of Regex Results I am trying to write all regex strings found into a text file. When I run the script, it only writes the first string to the text file. What am I missing? Thanks for the assistance. import re import csv import PyPDF2 #Path to file CROZER = (r"C:\Users\PC\Doc...
file.write only write the first string of Regex Results
I am trying to write all regex strings found into a text file. When I run the script, it only writes the first string to the text file. What am I missing? Thanks for the assistance. import re import csv import PyPDF2 #Path to file CROZER = (r"C:\Users\PC\Documents\Prospect Data\Crozer Invoices\rest of inovices\Crozer....
[ "You should use a+ mode if you want to append contents to the end of file instead of overwriting it with w+.\nwith open('CI.txt', 'a+', encoding='utf8') as file:\n\n\n1.2 Definition of open modes r, r+, w, w, a, a+:\nThe r throws an error if the file does not exist or opens an existing\nfile without truncating it f...
[ 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074450643_python_string.txt
Q: Token Encode keeps giving an error when ran I wrote the encoded token in utf-8 in a JSON file when running the script it returns: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete return future.re...
Token Encode keeps giving an error when ran
I wrote the encoded token in utf-8 in a JSON file when running the script it returns: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete return future.result() File "c:artic\Users\A\OneDrive\Documents...
[ "with open('data/config.json', 'r', encoding = 'utf-8-sig') as doc:\nTry This\n" ]
[ 0 ]
[]
[]
[ "discord", "python", "visual_studio_code" ]
stackoverflow_0074426918_discord_python_visual_studio_code.txt
Q: Query DynamoDB with GSI This is the table format I have load into AWS DynamoDB table where "uid" is a partition key and "followers" is a GSI created with "followers-index" name. uid | followers | followings | ------------------------------------- adjeomax | 2094 | 74 | I want to query the tabl...
Query DynamoDB with GSI
This is the table format I have load into AWS DynamoDB table where "uid" is a partition key and "followers" is a GSI created with "followers-index" name. uid | followers | followings | ------------------------------------- adjeomax | 2094 | 74 | I want to query the table, for example "uid"s where "...
[ "GSI works like a new set of Primary Key (PK). In DynamoDB, a PK can consist of a Partition Key and a Sort Key. Partition Key can only be queried using exact match, while Sort Key can be queried using ranges, like gt.\nIn your example, seems followers is the Partition Key in your GSI. Therefore, you cannot query it...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "python" ]
stackoverflow_0074457038_amazon_dynamodb_amazon_web_services_python.txt
Q: What does it mean if a Python object is "subscriptable" or not? Which types of objects fall into the domain of "subscriptable"? A: It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes ...
What does it mean if a Python object is "subscriptable" or not?
Which types of objects fall into the domain of "subscriptable"?
[ "It basically means that the object implements the __getitem__() method. In other words, it describes objects that are \"containers\", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.\n", "Off the top of my head, the following are the only built-ins that are subscriptabl...
[ 533, 103, 21, 20, 11, 9, 0 ]
[]
[]
[ "python", "terminology" ]
stackoverflow_0000216972_python_terminology.txt
Q: How to implement Repetition with a 'while' loop (python)? Write a program that prints a sentence the required number of times (each sentence must start on a new line) Solved the problem with a (for) loop and tried with a while loop How to solve it with while? text = input('data input:') amount = int(input()) for _...
How to implement Repetition with a 'while' loop (python)?
Write a program that prints a sentence the required number of times (each sentence must start on a new line) Solved the problem with a (for) loop and tried with a while loop How to solve it with while? text = input('data input:') amount = int(input()) for _ in range(amount): print(text) text = input('data input:')...
[ "You can use a counter that you decrement at each iteration:\ntext = input('data input:') \namount = int(input())\n\nwhile amount>0:\n print(text)\n amount -= 1\n\nExample:\ndata input:test\n3\ntest\ntest\ntest\n\nThis is however rarely something that you would do in python, the for loop is probably the canon...
[ 0, 0 ]
[]
[]
[ "function", "python", "python_3.x" ]
stackoverflow_0074457431_function_python_python_3.x.txt
Q: how to extract data from a cell with df into a new column with dict format pandas csv with df import pandas as pd df = pd.read_csv('loves_1.csv') in the column FuelPrices you'll see another df df1 = pd.DataFrame(df['FuelPrices'][0]) df1 so, how to extract values of LastPriceChangeDateTime and CashPrice as a key...
how to extract data from a cell with df into a new column with dict format pandas
csv with df import pandas as pd df = pd.read_csv('loves_1.csv') in the column FuelPrices you'll see another df df1 = pd.DataFrame(df['FuelPrices'][0]) df1 so, how to extract values of LastPriceChangeDateTime and CashPrice as a key:value pair in to a new column of the main df for DIESEL only(df['diesel_price_change'...
[ "Unfortunately, The only way I found is to loop through it, but I still hope that i'll find pandas solution for it.\nfor index, row in df.iterrows():\n for row in df['FuelPrices'][index]:\n if row['ProductName'] == 'DIESEL':\n df['diesel_price_change'][index] = {row['LastPriceChangeDateTime']:r...
[ 0, 0 ]
[]
[]
[ "for_loop", "loops", "pandas", "python", "python_3.x" ]
stackoverflow_0074451068_for_loop_loops_pandas_python_python_3.x.txt
Q: How to compile a matrix in a for cycle? I am trying to create a matrix with 3 columns and p rows that contains p rows of x, y and z values, later i transpose this matrix and go on. The problem is I do not know how to create this matrix. Any tips?enter code here time=np.arange(0,100,1) fphi = 2 #kampo phi daznis ft...
How to compile a matrix in a for cycle?
I am trying to create a matrix with 3 columns and p rows that contains p rows of x, y and z values, later i transpose this matrix and go on. The problem is I do not know how to create this matrix. Any tips?enter code here time=np.arange(0,100,1) fphi = 2 #kampo phi daznis ftheta = 3 #kampo i daznis Amp = np.pi/2 phi = ...
[ "import numpy as np\n\nr=10\nh=8\ntime=np.arange(0,100,1)\nfphi = 2 #kampo phi daznis\nftheta = 3 #kampo i daznis\nAmp = np.pi/2\nphi = ()\ntheta = ()\nprint(time)\npoints = []\nfor p in time:\n phi = 2*np.pi*fphi*p\n theta = Amp*np.sin(2*np.pi*ftheta*p)\n x = r * np.cos(phi)\n y = r * np.sin(phi) * np....
[ 0 ]
[]
[]
[ "math", "matrix", "python" ]
stackoverflow_0074456598_math_matrix_python.txt
Q: Move user to a textchannel as soon as he has pressed a button I have a problem. I would like to move a user from one specific textchannel to another specific textchannel as soon as he has pressed a button. Unfortunately I get an error. class MyView(discord.ui.View): # Create a class called MyView that subclasses d...
Move user to a textchannel as soon as he has pressed a button
I have a problem. I would like to move a user from one specific textchannel to another specific textchannel as soon as he has pressed a button. Unfortunately I get an error. class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View @discord.ui.button(label="->", style=discord.But...
[ "You're getting that error because you're calling move_to on the class name, not an instance. Discord.py has no idea which member you want to move when you write discord.Member.move_to(), you need an instance of the class.\nYou mentioned wanting to move the person when they click on the button, so you can get their...
[ 2 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074457319_discord_discord.py_python.txt
Q: Pytorch module 'torch' has no attribute 'logsoftmax' I am testing two trained model but getting an error unexpectedly. I search on the google but did not find any satisfactory result. Code if __name__ == "__main__": normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], ...
Pytorch module 'torch' has no attribute 'logsoftmax'
I am testing two trained model but getting an error unexpectedly. I search on the google but did not find any satisfactory result. Code if __name__ == "__main__": normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) tfs = transforms.Compose...
[ "I believe you are looking for nn.functional.logsoftmax which is the functional form of nn.LogSoftmax.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "pytorch", "pytorch_geometric", "torch" ]
stackoverflow_0074457452_python_python_3.x_pytorch_pytorch_geometric_torch.txt
Q: Is there a way to edit the size of discord buttons? I'm currently starting a connect 4 discord bot, and use buttons in order for the person to place their piece. The issue comes as the board, made using the :white_large_square: emoji, is smaller than the buttons. Also, the buttons take up two lines, as there are s...
Is there a way to edit the size of discord buttons?
I'm currently starting a connect 4 discord bot, and use buttons in order for the person to place their piece. The issue comes as the board, made using the :white_large_square: emoji, is smaller than the buttons. Also, the buttons take up two lines, as there are six of them. Is there a way to make the buttons similar in...
[ "Size Of Button Is Not Changeable !\nBut, You Can Change The Maximum Size Of Each Row/Column \nTo Get Something Like This :\n1 2 3\n4 5 6\n" ]
[ 0 ]
[]
[]
[ "button", "discord", "discord.py", "discord_buttons", "python" ]
stackoverflow_0074408900_button_discord_discord.py_discord_buttons_python.txt
Q: Converting VBA With statements to Python in pywin32 I am trying to convertWith statements in VBA to Python, and more specifically this one (for MS Word): With Selection.FormFields(1) .Name = "Widget_name" .EntryMacro = "" .ExitMacro = "" .Enabled = True .OwnHelp = False .HelpText = "" ....
Converting VBA With statements to Python in pywin32
I am trying to convertWith statements in VBA to Python, and more specifically this one (for MS Word): With Selection.FormFields(1) .Name = "Widget_name" .EntryMacro = "" .ExitMacro = "" .Enabled = True .OwnHelp = False .HelpText = "" .OwnStatus = False .StatusText = "" With .TextInpu...
[ "Actually, you might not have to use an equivalent of With statement.\nThe following function is working to update some forms (and update the whole document to match the changes.\n\nfrom pathlib import Path\nfrom typing import Dict, List, Union\n\nimport win32com.client as win32\n\ndef update_bookmarks(path: Union[...
[ 0 ]
[]
[]
[ "ms_word", "python", "pywin32", "vba" ]
stackoverflow_0074457143_ms_word_python_pywin32_vba.txt
Q: How should I use boundary delimiter '\b' in python 're' for finding a query in string? I am trying to check that the string query is indeed present in a string s but surrounded with word boundaries. I am unable to express my problem with regexes. This is how I search for my query, but this does not work because I ...
How should I use boundary delimiter '\b' in python 're' for finding a query in string?
I am trying to check that the string query is indeed present in a string s but surrounded with word boundaries. I am unable to express my problem with regexes. This is how I search for my query, but this does not work because I get None as output of re.search: >>> s = "aaaa bb [abc] [def]" >>> query = "[abc]" >>> re.se...
[]
[]
[ "There is no word boundary between a space and a bracket, as both of those are non-word characters.\n" ]
[ -1 ]
[ "python", "python_re", "regex", "string_search" ]
stackoverflow_0074457555_python_python_re_regex_string_search.txt
Q: How to display a google map in flask/django? There's not much to be said about it except for the absence of any form of documentation having the least possible understandable way of doing it. Google's documentation only includes JS snippets that are good enough if I know how to use them in flask, django, or whatev...
How to display a google map in flask/django?
There's not much to be said about it except for the absence of any form of documentation having the least possible understandable way of doing it. Google's documentation only includes JS snippets that are good enough if I know how to use them in flask, django, or whatever python web framework.
[ "With Flask and Django you make HTML pages in the end, and from Flask you can just return some HTML with the parameters you need.\nThe Google maps embed API uses an iframe, so you can display a map on your page like this:\n\n\n<iframe\n width=\"600\"\n height=\"450\"\n style=\"border:0\"\n loading=\"lazy\"\n a...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0072093172_python.txt
Q: How to get user input for tictactoe game, by waiting for user message input in Discord.py I'm using await bot.wait_for inside a while loop. Despite the await bot.wait_for, the code just runs, infinitely awaiting printBoard(ctx, board). @bot.command() async def tictactoe(ctx, xo="X"): await ctx.send( "E...
How to get user input for tictactoe game, by waiting for user message input in Discord.py
I'm using await bot.wait_for inside a while loop. Despite the await bot.wait_for, the code just runs, infinitely awaiting printBoard(ctx, board). @bot.command() async def tictactoe(ctx, xo="X"): await ctx.send( "Enter your move according to this key till I figure out a better way:\nA1\tB1\tC1\t\nA2\tB2\tC2\...
[ "i think If you give unlimited timeout , it will waits until get message\n" ]
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074253412_bots_discord_discord.py_python.txt
Q: Why does Python ecosystem have inconsistent fileIO? To load csv data from a file, we have: file = open(path) reader = csv.reader(file) Similarly to load json data, we have: file = open(path) data = json.load(file) In both the cases, we are using file object as the base abstraction to build upon. Thinking this in...
Why does Python ecosystem have inconsistent fileIO?
To load csv data from a file, we have: file = open(path) reader = csv.reader(file) Similarly to load json data, we have: file = open(path) data = json.load(file) In both the cases, we are using file object as the base abstraction to build upon. Thinking this in OOPs and modular terms also makes sense since csv and js...
[ "This is because you might have different reading operations that you want to perform.\nWith json and csv there might be options that you want to pass to the reading part or other things that you want to do with the open file. This can't be generalized for every user. For example, json.load accepts parse_float and ...
[ 1, 0 ]
[]
[]
[ "design_patterns", "oop", "opencv", "python" ]
stackoverflow_0074457375_design_patterns_oop_opencv_python.txt
Q: Pandas: Passing a list through describe() I am trying to describe() a column from df but for every unique value in another column.I have the df: id revenue country 1 128 at 2 130 de 3 132 de 4 134 hu 5 136 at 6 138 at 7 140 hu I want to pass this : df[df['Country']=='cz'].net...
Pandas: Passing a list through describe()
I am trying to describe() a column from df but for every unique value in another column.I have the df: id revenue country 1 128 at 2 130 de 3 132 de 4 134 hu 5 136 at 6 138 at 7 140 hu I want to pass this : df[df['Country']=='cz'].net_revenue.describe(percentiles=[0.2,0.4,0.6,0.8...
[ "Use groupby.describe:\nout = (df.groupby('country')['revenue']\n .describe(percentiles=[0.2,0.4,0.6,0.8,0.9,0.95,0.99,0.999])\n )\n\nOutput:\n count mean std min 20% 40% 50% 60% 80% 90% 95% 99% 99.9% max\ncountry ...
[ 0 ]
[]
[]
[ "jupyter", "pandas", "python" ]
stackoverflow_0074457715_jupyter_pandas_python.txt
Q: upper some specific letters Upper only letters that I have indexes on the list (PYTHON) s = "string" l = [1,3] # output is: sTrIng Tried this but it wont work for i in l: s[i] = s[i].upper() A: Strings are immutable. If you want to check by index, you can for example use a list and update the value by index...
upper some specific letters
Upper only letters that I have indexes on the list (PYTHON) s = "string" l = [1,3] # output is: sTrIng Tried this but it wont work for i in l: s[i] = s[i].upper()
[ "Strings are immutable. If you want to check by index, you can for example use a list and update the value by index (and check if that index exists first).\nThen at the end, join the characters to a string.\ns = \"string\"\nresult = list(s)\nlst = [1, 3]\nlength = len(result)\n\nfor i in lst:\n if i < length:\n ...
[ 1 ]
[ "This solution works\ns = \"string\"\nl = [1,3]\n\nfor i in l:\n newStr = s[i]\n print(newStr.upper())\n\n" ]
[ -1 ]
[ "loops", "python", "string", "uppercase" ]
stackoverflow_0074452631_loops_python_string_uppercase.txt
Q: Is there a way to handle key not found when using operator.itemgetter without using a try-except block? Is there any other option aside from wrapping itemgetter in a try/except block in case of a missing key? Like dict.get('bar', 'foo')? Example of usage: currentUser = { "id": 24, "name": "John Doe", "...
Is there a way to handle key not found when using operator.itemgetter without using a try-except block?
Is there any other option aside from wrapping itemgetter in a try/except block in case of a missing key? Like dict.get('bar', 'foo')? Example of usage: currentUser = { "id": 24, "name": "John Doe", "website": "http://mywebsite.com", "description": "I am an actor", "email": "example@example.com", ...
[ "No, it is not possible. See the source code. As mentioned in the comment above, there is an open issue to change the behaviour. Unfortunately, you can't patch attributes like __init__ directly on a built-in/extension type. Moreover, operator.itemgetter is not an acceptable base type, so you can't write a new class...
[ 0 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0072155513_dictionary_key_python.txt
Q: Is there a faster way to insert dataframe to SQL using python? We have two parts to get final data frame into SQL. downlaoding from datasets from Azure and transforming using python. Uploading transformed data into Azure and then inserting the final dataframe into SQL Downloading, transforming and uploading take...
Is there a faster way to insert dataframe to SQL using python?
We have two parts to get final data frame into SQL. downlaoding from datasets from Azure and transforming using python. Uploading transformed data into Azure and then inserting the final dataframe into SQL Downloading, transforming and uploading takes 5 mins but insertion to SQL is taking quite long time. I used belo...
[ "hello there you should try to specify your chunksize in your call\ndf.to_sql(engine, connect() , index=False, if_exists='append',\nmethod=None, chunksize = 50000)\n" ]
[ 0 ]
[]
[]
[ "azure", "python", "sql_server" ]
stackoverflow_0074457673_azure_python_sql_server.txt
Q: How to find the mean of values in a particular column that have duplicate timestamps Original dataframe Timestamp A B C 19:26:01 27 55.2 Earth 19:26:01 20 54.5 Jupiter 19:26:02 20 56.2 Mars 19:26:02 24 53.6 Venus Required output Timestamp A B C 19:26:01 23.5 54.85 Earth 19:26:02 22 54.9 Mars I have tried...
How to find the mean of values in a particular column that have duplicate timestamps
Original dataframe Timestamp A B C 19:26:01 27 55.2 Earth 19:26:01 20 54.5 Jupiter 19:26:02 20 56.2 Mars 19:26:02 24 53.6 Venus Required output Timestamp A B C 19:26:01 23.5 54.85 Earth 19:26:02 22 54.9 Mars I have tried using df = df.groupby('Timestamp', as_index=False).mean() Other col...
[ "For a small DataFrame, you can use:\n(df.groupby('Timestamp', as_index=False)\n .agg({'A': 'mean', 'B': 'mean', 'C': 'first'})\n)\n\nIf you need a programmatic way:\nagg_funcs = {c: 'mean' if pd.api.types.is_numeric_dtype(df[c]) else 'first'\n for c in df} \n# {'Timestamp': 'first', 'A': 'mean', 'B':...
[ 0 ]
[]
[]
[ "dataframe", "duplicates", "mean", "pandas", "python" ]
stackoverflow_0074457773_dataframe_duplicates_mean_pandas_python.txt
Q: can you download azureml models registred in a workspace to a local folder? I want to download all model pickle files which are registered in azureml workspace to a local folder. is this possible? using python only don't want to manually download each pickle file using ui A: once you retrieve your model from you...
can you download azureml models registred in a workspace to a local folder?
I want to download all model pickle files which are registered in azureml workspace to a local folder. is this possible? using python only don't want to manually download each pickle file using ui
[ "once you retrieve your model from your workspace you can do the following\nmodel.download(exist_ok=True)\n\nThis is shown in the docs- https://learn.microsoft.com/en-us/python/api/azureml-core/azureml.core.model.model?view=azure-ml-py#azureml-core-model-model-download\nThis answer form @Ninja_coder for this quest...
[ 1 ]
[]
[]
[ "azure_machine_learning_service", "azureml_python_sdk", "azuremlsdk", "python" ]
stackoverflow_0074445639_azure_machine_learning_service_azureml_python_sdk_azuremlsdk_python.txt
Q: Is there a way to make Google Cloud Pub/Sub Schema fields optional? The title says it all, really. I'm struggling to figure out how to make a Google Cloud Pub/Sub schema that has optional fields. Or would having optional fields in an AVRO schema basically directly contradict the whole point of having a schema? The...
Is there a way to make Google Cloud Pub/Sub Schema fields optional?
The title says it all, really. I'm struggling to figure out how to make a Google Cloud Pub/Sub schema that has optional fields. Or would having optional fields in an AVRO schema basically directly contradict the whole point of having a schema? The structure I tried is this, with no success: { "type": "record", "nam...
[ "The schema as presented in the question needs to have the null values be the default since null is the first type in the union:\n{\n \"type\": \"record\",\n \"name\": \"Avro\",\n \"fields\": [\n {\n \"name\": \"TestStringField\",\n \"type\": [\"null\", \"string\"],\n \"default\": null\n },\...
[ 0, 0 ]
[]
[]
[ "avro", "google_cloud_platform", "google_cloud_pubsub", "python" ]
stackoverflow_0072046941_avro_google_cloud_platform_google_cloud_pubsub_python.txt
Q: Python validate user input of multiple strings I've been working on this all day and can't get it done. Any help will be much appreciated! In Python, I want to loop through 3 times asking the user to enter 1 or more days of the week (e.g., Please enter the day(s) of the week:) with the input ending up in a list....
Python validate user input of multiple strings
I've been working on this all day and can't get it done. Any help will be much appreciated! In Python, I want to loop through 3 times asking the user to enter 1 or more days of the week (e.g., Please enter the day(s) of the week:) with the input ending up in a list. The resulting data could look like this: List1 = [...
[ "Use askfordays() to ask the user for days (3 times is the default).\nIt returns a list of lists.\nAccording to your example, you can use it like this :\nlist1, list2, list3 = askfordays()\nThe validate() function doesn't return anything. Its only purpose is to raise a ValueError Exception if input is not correct.\...
[ 0, 0 ]
[]
[]
[ "input", "list", "python", "validation" ]
stackoverflow_0074456174_input_list_python_validation.txt
Q: Return normal terminal input when using tty, sys, terminos I'm working on a little project which requiers input without "pausing" for each time. Without completely understanding how it works, I used some code that I found online. import tty, sys, termios while True: filedescriptors = termios.tcgetattr(sys.std...
Return normal terminal input when using tty, sys, terminos
I'm working on a little project which requiers input without "pausing" for each time. Without completely understanding how it works, I used some code that I found online. import tty, sys, termios while True: filedescriptors = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin) dir_inp = 0 while 1: ...
[ "I just changed to PyInp, much easier\n" ]
[ 0 ]
[]
[]
[ "input", "python", "sys", "terminal", "tty" ]
stackoverflow_0074386993_input_python_sys_terminal_tty.txt
Q: tkinter styling with state map: How to set the default text color in a button? I am trying to style the text of a button using a style map but cannot figure out how to set the default color. I know I have to use the different states and I can change the text color if the button is pressed or disabled but I cannot...
tkinter styling with state map: How to set the default text color in a button?
I am trying to style the text of a button using a style map but cannot figure out how to set the default color. I know I have to use the different states and I can change the text color if the button is pressed or disabled but I cannot find the state name for the default. import tkinter as tk from tkinter import ttk ...
[ "According to docs:https://docs.python.org/3/library/tkinter.ttk.html#widget-states\nThere are 9 different states. active disabled focus pressed selected readonly alternate background invalid\nYou can set a default color by simply\nstyle.configure(\"TButton\",foreground=\"pink\") \n\nThis set a text color for your ...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074457777_python_tkinter.txt
Q: Python to C# StongBox[Single] I've used IronPython to add a reference to a C# dll. I'm attempting to use a method in the DLL which requires an argument of type: out float tempValue When I pass a python float object to the method I get the following traceback: Traceback (most recent call last): File "Measuremen...
Python to C# StongBox[Single]
I've used IronPython to add a reference to a C# dll. I'm attempting to use a method in the DLL which requires an argument of type: out float tempValue When I pass a python float object to the method I get the following traceback: Traceback (most recent call last): File "MeasurementComputing.py", line 20, in <module...
[ "In order to have a proper target for the out parameter you have to explicitly create a clr reference (StrongBox serves as that reference/value wrapper) in IronPython, as there is no out keyword on the caller side (like in C#) that would allow you to do so.\nThis could look like:\nimport clr\nimport System\ntempVal...
[ 1, 0 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0030359912_c#_ironpython_python.txt
Q: Python: Could not install packages due to an OSError: [Errno 2] No such file or directory I try to use pip to install sklearn, and I receive the following error message: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\Users\13434\AppData\Local\Packages\PythonSoftwareF...
Python: Could not install packages due to an OSError: [Errno 2] No such file or directory
I try to use pip to install sklearn, and I receive the following error message: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\Users\13434\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\sklearn\dat...
[ "I had exactly the same issue installing this package on my Windows laptop - then read of the 260 character limit. I followed this guide - and after rebooting, successfully installed 'sklearn':\nhttps://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/\n", "Run CMD in administ...
[ 21, 16, 4, 2, 2, 0, 0, 0, 0 ]
[ "The steps here fixed it https://www.youtube.com/watch?v=rKYRcwbFp6Y . The step is basically to change the include-system-site-packages to true in pyvenv.cfg file in your virtual env folder\n" ]
[ -1 ]
[ "pip", "python", "scikit_learn" ]
stackoverflow_0065980952_pip_python_scikit_learn.txt
Q: How do I disable the security certificate check in Python requests I am using import requests requests.post(url='https://foo.example', data={'bar':'baz'}) but I get a request.exceptions.SSLError. The website has an expired certficate, but I am not sending sensitive data, so it doesn't matter to me. I would imagin...
How do I disable the security certificate check in Python requests
I am using import requests requests.post(url='https://foo.example', data={'bar':'baz'}) but I get a request.exceptions.SSLError. The website has an expired certficate, but I am not sending sensitive data, so it doesn't matter to me. I would imagine there is an argument like 'verifiy=False' that I could use, but I can'...
[ "From the documentation:\n\nrequests can also ignore verifying the SSL certificate if you set\nverify to False.\n>>> requests.get('https://kennethreitz.com', verify=False)\n<Response [200]>\n\n\nIf you're using a third-party module and want to disable the checks, here's a context manager that monkey patches request...
[ 739, 163, 66, 37, 11, 10, 8, 0, 0 ]
[]
[]
[ "https", "python", "python_requests" ]
stackoverflow_0015445981_https_python_python_requests.txt
Q: Transpose row with column instead of column with row Can the transpose convert data by go through the first row of all the column then only the second row of all the column, instead of go through the first column of all the row then only the second column of all the row? Means require to convert the column to row ...
Transpose row with column instead of column with row
Can the transpose convert data by go through the first row of all the column then only the second row of all the column, instead of go through the first column of all the row then only the second column of all the row? Means require to convert the column to row which all the same data can be in one group. Original data...
[ "You will need to use a stack:\nout = (df.set_index('columnA').rename_axis(columns='header')\n .stack(dropna=False).reset_index(name='info')\n )\n\nNB. by default, stack drops the NaN values, to keep them use the dropna=False parameter.\nOutput:\n columnA header info\n0 IdA columnB a\n1 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074457962_pandas_python.txt
Q: Remove Virtual Enviroment name from CMD Everytime you activate a virtual environment it shows the name on cmd or powershell. I want to remove it or just not show it. There is any way? Example: example I'm searching for more than 2 days on every language and I didn't find yet. A: You'd have to define a new prompt...
Remove Virtual Enviroment name from CMD
Everytime you activate a virtual environment it shows the name on cmd or powershell. I want to remove it or just not show it. There is any way? Example: example I'm searching for more than 2 days on every language and I didn't find yet.
[ "You'd have to define a new prompt function to override your current one. Here's an example from the powershell prompt documentation\nfunction prompt {\n $identity = [Security.Principal.WindowsIdentity]::GetCurrent()\n $principal = [Security.Principal.WindowsPrincipal] $identity\n $adminRole = [Security.Principa...
[ 0 ]
[]
[]
[ "cmd", "powershell", "python", "python_venv" ]
stackoverflow_0074453419_cmd_powershell_python_python_venv.txt
Q: Fastapi with strawberry is returning Error "'dict' object has no attribute 'name'" I am trying to get character fields from the api rest of Rick&Morty using graphql with Fastapi + StrawBerry and i always get the same error with the first field i write my code: from fastapi import FastAPI import strawberry from str...
Fastapi with strawberry is returning Error "'dict' object has no attribute 'name'"
I am trying to get character fields from the api rest of Rick&Morty using graphql with Fastapi + StrawBerry and i always get the same error with the first field i write my code: from fastapi import FastAPI import strawberry from strawberry.fastapi import GraphQLRouter import requests @strawberry.type class Character: ...
[ "Strawberry doesn't allow returning dictionaries by default, this is done to keep the type safety of your code, but there's a configuration option that allow you to do this. Using StrawberryConfig and a custom default resolver you can allow returning both dictionaries and instances, see this example:\nhttps://play....
[ 1 ]
[]
[]
[ "fastapi", "graphql", "python", "python_requests", "strawberry_graphql" ]
stackoverflow_0074324569_fastapi_graphql_python_python_requests_strawberry_graphql.txt
Q: Fit 3D curve to surface I have the 3D coordinates of curves that look e.g. like this: and I have a point cloud of a sphere-like 3D surface. Is it possible, to determine a starting point A at this surface and a starting vector and then align this curve so that all points have on average the closest distance to thi...
Fit 3D curve to surface
I have the 3D coordinates of curves that look e.g. like this: and I have a point cloud of a sphere-like 3D surface. Is it possible, to determine a starting point A at this surface and a starting vector and then align this curve so that all points have on average the closest distance to this surface, it starts at A and...
[ "Hints:\nSuch problems can be addressed by the method of least-squares. You have four unknowns which are the coordinates of the center and the radius, and you can minimize a quantity like\nΣ((Xi - Xc)² + (Yi - Yc)² + (Zi - Zc)² - R²)². *\n\nYou can add constraints such as expressing that the sphere passes by a know...
[ 0 ]
[]
[]
[ "3d", "computational_geometry", "curve", "optimization", "python" ]
stackoverflow_0074455483_3d_computational_geometry_curve_optimization_python.txt
Q: Can 'id' be used as variable name in python? Whenever I use id as my variable name, my IDE shows the term in different colour from other variables. Is this expected or is it some feature of IDE (I'm using vs code) or shouldn't i use id as a variable? I haven't faced any issues while running code. Only the colour c...
Can 'id' be used as variable name in python?
Whenever I use id as my variable name, my IDE shows the term in different colour from other variables. Is this expected or is it some feature of IDE (I'm using vs code) or shouldn't i use id as a variable? I haven't faced any issues while running code. Only the colour change makes me curious. Example Image from my IDE:...
[ "Shorter Answer:\nYou can use id as a variable name, but should not. That being said, in the example you gave, you are using id as a class' attribute (not a variable) which is fine to do.\nLonger Answers:\nAs noted by other answers, id is a builtin function, so naming a variable id is not ideal as it obfuscates the...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074274040_python.txt
Q: Python child dataclass with different parameter order I'm trying to bring an old code base up to date. @dataclass(frozen=True) class Type: size: int ... class Pointer(Type): def __init__(self, basetype: Type, size): I'd like to use frozen data classes for both classes, but I have a problem with the order of...
Python child dataclass with different parameter order
I'm trying to bring an old code base up to date. @dataclass(frozen=True) class Type: size: int ... class Pointer(Type): def __init__(self, basetype: Type, size): I'd like to use frozen data classes for both classes, but I have a problem with the order of the parameters in the Pointer constructor. When I change P...
[ "I have found a way to have the constructor accept an aribtary order of parameters, but it is not very pretty.\nWhile it is true you can not set the fields in the __init__ method with assignments, you can still use __setattr__ kinda how dataclasses work internally.\nThe constructor in this example would look like t...
[ 0 ]
[]
[]
[ "python", "python_dataclasses", "refactoring" ]
stackoverflow_0074457553_python_python_dataclasses_refactoring.txt
Q: Group data by Hourly basis in pandas I have 3 columns and the data types of all 3 columns are object. First column is Date column and 3rd column is values Something like this- Date Values Country 01/01/21 12:00 2. India 01/01/21 12:15 4. India 01/01/21 12:30 6. India 01/01/21...
Group data by Hourly basis in pandas
I have 3 columns and the data types of all 3 columns are object. First column is Date column and 3rd column is values Something like this- Date Values Country 01/01/21 12:00 2. India 01/01/21 12:15 4. India 01/01/21 12:30 6. India 01/01/21 12:45 8. India 01/01/21 1:00. 1...
[ "You can use resample with agg:\ndf['Date'] = pd.to_datetime(df['Date'])\n\nout = (df.resample('1h', on='Date')\n .agg({'Values': 'mean', 'Country': 'first'}).dropna()\n )\n\nOutput:\n Values Country\nDate \n2021-01-01 01:00:00 25.0 India\n2021-01-...
[ 0, 0 ]
[]
[]
[ "group_by", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074457251_group_by_jupyter_notebook_pandas_python.txt
Q: How to scrape headline news, link and image? I'd like to scrape news headline, link of news and picture of that news. I try to use web scraping following as below. but It's only headline code and It is not work. import requests import pandas as pd from bs4 import BeautifulSoup nbc_business = "https://news.mongab...
How to scrape headline news, link and image?
I'd like to scrape news headline, link of news and picture of that news. I try to use web scraping following as below. but It's only headline code and It is not work. import requests import pandas as pd from bs4 import BeautifulSoup nbc_business = "https://news.mongabay.com/list/environment" res = requests.get(nbc_bu...
[ "This is because the site blocks bot. If you print the res.content which shows 403.\nAdd headers={'User-Agent':'Mozilla/5.0'} to the request.\nTry the code below,\nnbc_business = \"https://news.mongabay.com/list/environment\"\nres = requests.get(nbc_business, verify=False, headers={'User-Agent':'Mozilla/5.0'})\n\ns...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074457775_beautifulsoup_python.txt
Q: How to include staticfiles in wsgi django project? Today I ran into a problem connecting static files to my project. If I run django app with command: python manage.py runserver <ip>:<port>then static files are found. If I run the django app as a wsgi service (systemctl start myapp), I get an error that no static ...
How to include staticfiles in wsgi django project?
Today I ran into a problem connecting static files to my project. If I run django app with command: python manage.py runserver <ip>:<port>then static files are found. If I run the django app as a wsgi service (systemctl start myapp), I get an error that no static files were found. My project in /home/alevt/health_check...
[ "Try this:\n STATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'health_app/static/')\n)\n\nmy.ini file:\nstatic = /health_app/static\n\n" ]
[ 0 ]
[]
[]
[ "css", "django", "python", "wsgi" ]
stackoverflow_0074457123_css_django_python_wsgi.txt
Q: Can't write into a .txt file (Python 3) I'm making a program where everytime you open the program there's a new randomized pin, but I need to be able to acces the pin inside the .txt file while the python program is running, but when I try to acces the entry pin while the program is running, it isn't there until a...
Can't write into a .txt file (Python 3)
I'm making a program where everytime you open the program there's a new randomized pin, but I need to be able to acces the pin inside the .txt file while the python program is running, but when I try to acces the entry pin while the program is running, it isn't there until after I close the program and the .txt file. H...
[ "You will need to close your file handler at the end.\nf.close()\n\nTo be honest a better way of writing this code block would be to use a with open block. That way the file closure happens when the block exits. The following documentation on the python website will help explain it.\nThis would look something like:...
[ 1 ]
[]
[]
[ "python", "python_3.x", "windows" ]
stackoverflow_0074458231_python_python_3.x_windows.txt
Q: Python Variable with Asterisk I need to create a variable with an asterisk. originalFilePath = "/home/user/reports/file_name_xxxx.pdf" The file_name will be replaced every day with a numeric value, like - file_name_20221116.pdf. How can I pass "*" - star, in the variable? So the code would look like this - origin...
Python Variable with Asterisk
I need to create a variable with an asterisk. originalFilePath = "/home/user/reports/file_name_xxxx.pdf" The file_name will be replaced every day with a numeric value, like - file_name_20221116.pdf. How can I pass "*" - star, in the variable? So the code would look like this - originalFilePath = "/home/user/reports/fi...
[ "If you want to create like this,\noriginalFilePath = \"/home/user/reports/file_name_xxxx.pdf\"\n\nYou have to pass your arguments like the following way.\nabc = \"xxxx\" #abc is a variable name\noriginalFilePath = f\"/home/user/reports/file_name_{abc}.pdf\"\n\n", "\nI need to create a variable with an asterisk....
[ 0, 0 ]
[ "What abouf f-string?\nimport datetime\ntimestamp = datetime.datetime.now().date()\noriginalFilePath = f\"/home/user/reports/file_name_{timestamp}.pdf\"\n\nYou could also search file in a directory like this:\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\ncurrent_path = os.path.dirname(os.p...
[ -1 ]
[ "python" ]
stackoverflow_0074455392_python.txt
Q: How to plot MFCC in Python? Here is my code so far on extracting MFCC feature from an audio file (.WAV): from python_speech_features import mfcc import scipy.io.wavfile as wav (rate,sig) = wav.read("AudioFile.wav") mfcc_feat = mfcc(sig,rate) print(mfcc_feat) How can I plot the MFCC features to know what it look...
How to plot MFCC in Python?
Here is my code so far on extracting MFCC feature from an audio file (.WAV): from python_speech_features import mfcc import scipy.io.wavfile as wav (rate,sig) = wav.read("AudioFile.wav") mfcc_feat = mfcc(sig,rate) print(mfcc_feat) How can I plot the MFCC features to know what it looks like?
[ "This will plot the MFCC as colors, which is a more popular way\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import cm\nfig, ax = plt.subplots()\nmfcc_data= np.swapaxes(mfcc_data, 0 ,1)\ncax = ax.imshow(mfcc_data, interpolation='nearest', cmap=cm.coolwarm, origin='lower')\nax.set_title('MFC...
[ 9, 4, 3, 2, 0 ]
[]
[]
[ "matplotlib", "mfcc", "plot", "python", "speech_recognition" ]
stackoverflow_0043506198_matplotlib_mfcc_plot_python_speech_recognition.txt
Q: Image parsing in python (connected components analysis) I have an image of mathematical formula and I need to parse symbols of it, but also save where they were (center of each symbol). For example image like this needs to be transformed into 15 different images 75x75, 1 per each symbol. What I have tried is: Tra...
Image parsing in python (connected components analysis)
I have an image of mathematical formula and I need to parse symbols of it, but also save where they were (center of each symbol). For example image like this needs to be transformed into 15 different images 75x75, 1 per each symbol. What I have tried is: Transform to gray and then binary: pixels close to white(> 250) ...
[ "Have a look at the (imho not all too intuitively named) function cv.findContours():\nhttps://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html\nIt should do most things that you are doing by hand right now out of the box, which is extracting and measuring binary objects.\nIf you encouter problems where a ...
[ 0 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074456585_image_processing_opencv_python.txt
Q: Google App Engine Python/Flask - Serving static folder from Google Cloud Storage I have deployed a website using Python and Flask on to Google App Engine successfully, but the performance seems to be pretty slow when first loading the page. I was reading that hosting some of the static files on Cloud Storage would...
Google App Engine Python/Flask - Serving static folder from Google Cloud Storage
I have deployed a website using Python and Flask on to Google App Engine successfully, but the performance seems to be pretty slow when first loading the page. I was reading that hosting some of the static files on Cloud Storage would possibly help with this, but I can not seem to get it to work. (www.example.com is ju...
[ "Assuming you aren't fixed on using cloud storage but are happy to just use the built-in static file serving features of Google App Engine, you could write your app.yaml file like so…\nruntime: python39\n\nhandlers:\n # This configures Google App Engine to serve the files in the app's static\n # directory.\n- url...
[ 0 ]
[]
[]
[ "flask", "google_app_engine", "google_cloud_storage", "python" ]
stackoverflow_0044190576_flask_google_app_engine_google_cloud_storage_python.txt
Q: How can I get value from one function in another function in Django, views() Hello I am new to Django I want to get latitude and longitude from myview1 function to myview function so that I can Post that values and put into the relevant code. PLease Can anyone guide me regarding this? def my_view1(request): ...
How can I get value from one function in another function in Django, views()
Hello I am new to Django I want to get latitude and longitude from myview1 function to myview function so that I can Post that values and put into the relevant code. PLease Can anyone guide me regarding this? def my_view1(request): latitude='latitude' longitude='longitude' context = {'latitude':latit...
[ "You can use the Django session:\ndef view_1(request):\n request.session['key'] = value\n\ndef view_2(request):\n value = request.session['key']\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python", "python_3.x" ]
stackoverflow_0074457436_django_django_templates_django_views_python_python_3.x.txt
Q: how can i use dataframe and datetimeindex to return rolling 12-month? Imagine a pandas dataframe with 2 columns (“Manager Returns” and “Benchmark Returns”) and a DatetimeIndex of monthly frequency. Please write a function to calculate the rolling 12-month manager alpha and rolling-12 month tracking error (both ann...
how can i use dataframe and datetimeindex to return rolling 12-month?
Imagine a pandas dataframe with 2 columns (“Manager Returns” and “Benchmark Returns”) and a DatetimeIndex of monthly frequency. Please write a function to calculate the rolling 12-month manager alpha and rolling-12 month tracking error (both annualized). so far I have this but confused about the rolling-12 month: impor...
[ "So, you want to calculate the excess return on the 'Manager Returns' compared to the 'Benchmark Returns. First, we create some random data for these two values.\nimport pandas as pd\nimport numpy as np\nn=20\ndf = pd.DataFrame(dict(\n Manager=np.random.randint(2, 9, size=n),\n Benchmark=np.random.randint(1, ...
[ 0 ]
[]
[]
[ "dataframe", "datetimeindex", "python" ]
stackoverflow_0074457721_dataframe_datetimeindex_python.txt
Q: Return a 1D numpy array of a specific index from an axis in 2D array This should be trivial but I'm not finding the correct way to accomplish it. I have a 2D array with shape (5, 5527) I have an an array of indices with the lowest value for the arguments in the first axis with shape (5527,) How can I flatten my (5...
Return a 1D numpy array of a specific index from an axis in 2D array
This should be trivial but I'm not finding the correct way to accomplish it. I have a 2D array with shape (5, 5527) I have an an array of indices with the lowest value for the arguments in the first axis with shape (5527,) How can I flatten my (5,5527) array into a 1D array by only using the values at the index specifi...
[ "You were close: np.take_along_axis\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074458266_numpy_python.txt
Q: Python Docx Minimum Table Height I'm trying to fit 10 rows (and three columns) of a table on one page, howver I'm running into a limitation where I can't get any more than 8 rows to fit. I've tried the following code: table = document.add_table(rows=0, cols=3) for row in table.rows: row.height = Cm(1) Howeve...
Python Docx Minimum Table Height
I'm trying to fit 10 rows (and three columns) of a table on one page, howver I'm running into a limitation where I can't get any more than 8 rows to fit. I've tried the following code: table = document.add_table(rows=0, cols=3) for row in table.rows: row.height = Cm(1) However, at some point when reducing the siz...
[ "I have no problem getting 10 1cm rows in a single page. I declare the number of rows when adding the table:\nfrom docx import Document\nfrom docx.shared import Cm\ndocument = Document()\ntable = document.add_table(rows=10, cols=3)\ntable.style = 'Table Grid'\nfor row in table.rows:\n row.height = Cm(1)\n\ndocum...
[ 0 ]
[]
[]
[ "docx", "python" ]
stackoverflow_0074426567_docx_python.txt
Q: Sklearn KNN Imputer is missing some values I was trying to impute a column with some NaNs using KNN imputer from Sk-learn. Things seemed to be working properly, but I realized that I still have some of the NaNs in the imputed column. What could be the reason? I already counted the NaNs before and after imputation....
Sklearn KNN Imputer is missing some values
I was trying to impute a column with some NaNs using KNN imputer from Sk-learn. Things seemed to be working properly, but I realized that I still have some of the NaNs in the imputed column. What could be the reason? I already counted the NaNs before and after imputation. Note: I've updated the code with the cleaning c...
[ "First remark You are fitting the KNN imputer on the series itself :\nvalues = fea_transformer.fit_transform(train[['instrumentalness']])\nThis is a waste of all the information from the other features\nyou could use all of them to have a better imputation.\nSecond remark :\nYour problem is not with KNNImputer but ...
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x", "scikit_learn", "sklearn_pandas" ]
stackoverflow_0074409648_pandas_python_python_3.x_scikit_learn_sklearn_pandas.txt
Q: setting outgoing email smtp gmail References in header in Python3 I'm having difficulty setting the References: field in the header of an outgoing SMTP email for Gmail. I'm using Python 3.8 with smtplib and email.message libraries. The code is: reference_ids = [ '<BN8PR17MB27372595A957D7912CEE184FBF6F9@BN8PR...
setting outgoing email smtp gmail References in header in Python3
I'm having difficulty setting the References: field in the header of an outgoing SMTP email for Gmail. I'm using Python 3.8 with smtplib and email.message libraries. The code is: reference_ids = [ '<BN8PR17MB27372595A957D7912CEE184FBF6F9@BN8PR17MB2737.namprd17.prod.outlook.com>', '<CAM9Ku=FZ5RGMvw3VzNrZz+DA78...
[ "thanx to everyone for giving me direction, especially tripleee with \"That's bog-standard RFC2047 encoding.\" which led me the email.header library.\nso,,, when i send the email via gmail smtp, i could set the 6th line to simply:\nmsg.add_header('References', ' '.join(reference_ids))\n\nwhere reference_ids is a p...
[ 0, 0 ]
[]
[]
[ "email", "imaplib", "python", "python_3.x", "smtplib" ]
stackoverflow_0074436017_email_imaplib_python_python_3.x_smtplib.txt
Q: asyncio create task and aiohttp , 'no running event loop' Im trying to make a Pyqt5 app with aiohttp request, and asyncio tasks. Im using quamash package too and it requires Python 3.7 so i installed this version.(it didn't work on Python 3.10) The main reason i use asyncio and quamash is because i want to do requ...
asyncio create task and aiohttp , 'no running event loop'
Im trying to make a Pyqt5 app with aiohttp request, and asyncio tasks. Im using quamash package too and it requires Python 3.7 so i installed this version.(it didn't work on Python 3.10) The main reason i use asyncio and quamash is because i want to do requests and without freezing the GUI of the app. I get this error ...
[ "TLDR; replace quamash with qasync\nIn asyncio, a task always exists when async code is executed. Like in a multithreaded program at least the main thread is present. If quamash doesn't follow the rule -- it is not aiohttp problem.\nquamash is not maintained anymore, the latest release was made 3.5 years ago.\nThe ...
[ 3, 1, 1 ]
[]
[]
[ "aiohttp", "python", "python_3.x", "python_asyncio", "task" ]
stackoverflow_0070402725_aiohttp_python_python_3.x_python_asyncio_task.txt
Q: Nested while patterns in Python I'm a Python beginner trying to write a script for a Raspberry Pi Zero. The idea is to turn the lights on at dawn and off at dusk, keeping in mind those times change every day. So what i'm after (i guess) is something that will run 24/7 and evaluate whether lights should be on or of...
Nested while patterns in Python
I'm a Python beginner trying to write a script for a Raspberry Pi Zero. The idea is to turn the lights on at dawn and off at dusk, keeping in mind those times change every day. So what i'm after (i guess) is something that will run 24/7 and evaluate whether lights should be on or off. Here is what I have so far, which ...
[ "You need to update now inside the loop\nAlso the logic is much more simple\nHere's a proposal of the fixed code:\n#!/usr/bin/python\n\nimport pendulum\nfrom time import sleep\nfrom gpiozero import LED, PWMLED\nfrom astral import LocationInfo\nfrom astral.sun import dusk, dawn, midnight\n\nnow = pendulum.now('...
[ 2 ]
[]
[]
[ "gpiozero", "pendulum", "python", "raspberry_pi_zero", "while_loop" ]
stackoverflow_0074458355_gpiozero_pendulum_python_raspberry_pi_zero_while_loop.txt
Q: Testing celery.send_task() inside endpoint I have this configuration (for demonstration purposes) endpoints.py celery_conf.py Inside celery client is the configuration setup for celery, and inside endpoints.py there is for example an endpoint where celery_client is imported. In endpoints.py I import celery_clien...
Testing celery.send_task() inside endpoint
I have this configuration (for demonstration purposes) endpoints.py celery_conf.py Inside celery client is the configuration setup for celery, and inside endpoints.py there is for example an endpoint where celery_client is imported. In endpoints.py I import celery_client (instantiated Celery() object) #in endpoints.p...
[ "You can do this with:\nwith patch(\"endpoints.celery_client.send_task\") as mock_task:\n client.put(url=app.url_path_for(\"some_name:post\"), data={})\n\n assert mock_task.call_count == 1\n assert mock_task.call_args\n\nor there is also the pytest-mock package that can help:\ndef test_endpoint(mocker: Moc...
[ 0 ]
[]
[]
[ "celery", "fastapi", "mocking", "pytest", "python" ]
stackoverflow_0074458291_celery_fastapi_mocking_pytest_python.txt
Q: How to read and predict images outside the dataset using the knn algorithm I have difficulty in an algorithm knn, how can I predict a new image outside of the dataset I'm using? how is the coding? I have difficulty in an algorithm knn, how can I predict a new image outside of the dataset I'm using? how is the codi...
How to read and predict images outside the dataset using the knn algorithm
I have difficulty in an algorithm knn, how can I predict a new image outside of the dataset I'm using? how is the coding? I have difficulty in an algorithm knn, how can I predict a new image outside of the dataset I'm using? how is the coding?
[ "You can use this example code to to read your images.\nfrom io import BytesIO\nimport numpy as np\nimport requests\nfrom PIL import Image\n\nresponse = requests.get(url)\nimg = Image.open(BytesIO(response.content))\nimg = np.array(img).reshape(1, -1)\noutput_class = neigh.predict(img)[0]\nprint(output_class)\n\n" ...
[ 0 ]
[]
[]
[ "algorithm", "google_colaboratory", "knn", "python" ]
stackoverflow_0074458497_algorithm_google_colaboratory_knn_python.txt
Q: List interval with offset On a website, I have a pagination system. For each page, want to display a sublist of a list of items (15 items per page) coming from MongoEngine. The items are ordered by date of creation and I want to extract the last items created first. My current approach is to extract 15 items from ...
List interval with offset
On a website, I have a pagination system. For each page, want to display a sublist of a list of items (15 items per page) coming from MongoEngine. The items are ordered by date of creation and I want to extract the last items created first. My current approach is to extract 15 items from the current list, without rever...
[ "The ending index of a slice in Python does not include the value at the ending index itself, so you should not add -1 to the offset as the ending index of the slice as noted in your comment.\nHowever, to deal with the first page, where offset is 0 and non-negative, you can make it a special case to fall back to No...
[ 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074458238_list_python.txt
Q: Converting a complex dictionary list to a dictionary I would like to convert this dictionary list below into a dictionary data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':...
Converting a complex dictionary list to a dictionary
I would like to convert this dictionary list below into a dictionary data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe...
[ "Rather, You can use the 0th index of list and return dictionary.\ndata = data[0]\nprint(data)\n\n#output\ndata ={\n 'code':'matata',\n 'commandes':[\n {\n 'date':'12-10-22',\n 'content':[\n {\n 'article':'Article1',\n 'designat...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074458417_django_python.txt
Q: How do sort the elements by type(int, float, str) that fall from the input list to the output list? There is a list from the user: user_list = [1, 3.5, "xx", "gg", 6, "2"]. new_list = [] How to make it so that with the help of "list comprehension" from user_list to new_list moved: Value with type (float) Even nu...
How do sort the elements by type(int, float, str) that fall from the input list to the output list?
There is a list from the user: user_list = [1, 3.5, "xx", "gg", 6, "2"]. new_list = [] How to make it so that with the help of "list comprehension" from user_list to new_list moved: Value with type (float) Even number with type(int) All elements that have type (str) turned into -2 and were sent to a new_list
[ "not a good way to achive result but, using list comprehension\n>>> user_list = [1, 3.5, \"xx\", \"gg\", 6, \"2\"] \n>>> new_list = [*[i for i in user_list if type(i)==float], *[i for i in user_list if type(i)==int], *[-2 for i in user_list if type(i)==str]]\n>>> new_list\n[3.5, 1, 6, -2, -2, -2]\n...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074443939_list_python.txt
Q: Querying and Inserting records from SQL Server using Python We are porting some code from SSIS to Python. As part of this project, I'm recreating some packages but I'm having issues with the database access. I've managed to query the DB like this: employees_table = (spark.read .format("jdbc") .option("url", "jdbc...
Querying and Inserting records from SQL Server using Python
We are porting some code from SSIS to Python. As part of this project, I'm recreating some packages but I'm having issues with the database access. I've managed to query the DB like this: employees_table = (spark.read .format("jdbc") .option("url", "jdbc:sqlserver://dev.database.windows.net:1433;database=Employees;enc...
[ "Are you using Pandas by any chance? If df is not a Spark DataFrame you'll often see this error, most commonly if it's in fact a Pandas DataFrame (which, like the error message says, has no attribute 'write'.)\nThe Spark JDBC DataWriter tutorial code here works just fine\njdbcDF = spark.read \\\n .format(\"jdbc\...
[ 1, 1 ]
[]
[]
[ "azure", "azure_databricks", "pyspark", "python", "python_3.x" ]
stackoverflow_0074452611_azure_azure_databricks_pyspark_python_python_3.x.txt
Q: How do you get initial and trailing metadata from an async python gRPC client? I'm trying to write a Python async gRPC client and server but I can't figure out how to get the initial and trailing metadata from a request. It looks like from the python gRPC documentation, the sync client's UnaryUnaryMultiCallable ha...
How do you get initial and trailing metadata from an async python gRPC client?
I'm trying to write a Python async gRPC client and server but I can't figure out how to get the initial and trailing metadata from a request. It looks like from the python gRPC documentation, the sync client's UnaryUnaryMultiCallable has a future and a with_call method for getting the initial and trailing metadata, res...
[ "UnaryUnaryMultiCallable return _base_call.UnaryUnaryCall\nif you await it, def __await__(self) -> Awaitable[ResponseType]:, it will return ResponseType\nif you want to get meta_data, you should not await _base_call.UnaryUnaryCall\nYou can check grpc.aio.Call\nYou should do something like this in client :\nasync de...
[ 0 ]
[]
[]
[ "api", "asynchronous", "grpc", "metadata", "python" ]
stackoverflow_0069665660_api_asynchronous_grpc_metadata_python.txt
Q: Python and pip, list all versions of a package that's available? Given the name of a Python package that can be installed with pip, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version for a third party librar...
Python and pip, list all versions of a package that's available?
Given the name of a Python package that can be installed with pip, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version for a third party library, but the newest version is too new, there were backwards incompatibl...
[ "For pip >= 21.2 use:\npip index versions pylibmc\n\nNote that this command is experimental, and might change in the future!\nFor pip >= 21.1 use:\npip install pylibmc==\n\nFor pip >= 20.3 use:\npip install --use-deprecated=legacy-resolver pylibmc==\n\nFor pip >= 9.0 use:\n$ pip install pylibmc==\nCollecting pylibm...
[ 1260, 192, 104, 66, 36, 22, 19, 17, 11, 9, 9, 8, 7, 6, 6, 4, 3, 2, 1, 1, 0, 0, 0 ]
[ "My take is a combination of a couple of posted answers, with some modifications to make them easier to use from within a running python environment.\nThe idea is to provide a entirely new command (modeled after the install command) that gives you an instance of the package finder to use. The upside is that it work...
[ -1, -1, -1, -1 ]
[ "pip", "python" ]
stackoverflow_0004888027_pip_python.txt
Q: What's the diffrence between pandas pd.to_pickle and pickle module pickle.dump, when saving DataFrame? I would like to save python pandas DataFrame object as pickle. What's the diffrence in using pandas.to_pickle vs pickle.dumps? I've made some tests. Here's my test code : import pandas as pd import pickle df = pd...
What's the diffrence between pandas pd.to_pickle and pickle module pickle.dump, when saving DataFrame?
I would like to save python pandas DataFrame object as pickle. What's the diffrence in using pandas.to_pickle vs pickle.dumps? I've made some tests. Here's my test code : import pandas as pd import pickle df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'), index=['x', 'y']) # Save df.to_pickle('df1.pickle') with o...
[ "After analyzing module code for pickle (python3.8) and pandas 1.5.0 here are my thoughts.\nSaving/dumping DataFrame to pickle\nPickle code :\n\nDefault using pickle protocol DEFAULT_PROTOCOL if not specified. DEFAULT_PROTOCOL(==4) is not the HIGHEST_PROTOCOL(==5).\n\nPandas code :\n\nDefault using pickle protocol ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pickle", "python" ]
stackoverflow_0074449223_dataframe_pandas_pickle_python.txt
Q: openai command not found (mac) I'm trying to follow the fine tuning guide for Openai here. I ran: pip install --upgrade openai Which install without any errors. But even after restarting my terminal, i still get zsh: command not found: openai Here is the output of echo $PATH: /bin:/usr/bin:/usr/local/bin:/Users/...
openai command not found (mac)
I'm trying to follow the fine tuning guide for Openai here. I ran: pip install --upgrade openai Which install without any errors. But even after restarting my terminal, i still get zsh: command not found: openai Here is the output of echo $PATH: /bin:/usr/bin:/usr/local/bin:/Users/nickrose/Downloads/google-cloud-sdk/...
[ "Basically pip installs the packages under its related python directory, in a directory called site-packages (most likely, I'm not a python expert tbh). This is not included in the path you provided. First, ask pip to show the location to the package:\npip show openai\n\nThe output would be something like this:\nNa...
[ 3, 2, 0 ]
[]
[]
[ "machine_learning", "openai", "python" ]
stackoverflow_0073186315_machine_learning_openai_python.txt
Q: Timestamps of type long and logical type timestamp-micros in Python I have the following Avro schema: schema = { 'name': 'avro.example.Image', 'type': 'record', 'fields': [ {'name': 'image_id', 'type': 'string'}, {'name': 'image_byte', 'type': 'bytes'}, {'name': 'update_time', "...
Timestamps of type long and logical type timestamp-micros in Python
I have the following Avro schema: schema = { 'name': 'avro.example.Image', 'type': 'record', 'fields': [ {'name': 'image_id', 'type': 'string'}, {'name': 'image_byte', 'type': 'bytes'}, {'name': 'update_time', "type": [ "null", { "type": "long", "logicalType":...
[ "You need to provide a time zone to make datatime aware if it, so instead of datetime.now() you could use datetime.now(tz=timezone.utc)\n" ]
[ 1 ]
[]
[]
[ "avro", "python", "python_datetime", "timestamp", "timestamp_with_timezone" ]
stackoverflow_0073928425_avro_python_python_datetime_timestamp_timestamp_with_timezone.txt
Q: Is it safe to save Dataframe wrapped with other object as pickle? I would like to save Dataframe as pickle together with some other data. I could use a dict wrapper for it or specialized class. Is it safe to to save/load these DataFrame using module pickle dump/load functions or should I always save Dataframe with...
Is it safe to save Dataframe wrapped with other object as pickle?
I would like to save Dataframe as pickle together with some other data. I could use a dict wrapper for it or specialized class. Is it safe to to save/load these DataFrame using module pickle dump/load functions or should I always save Dataframe with pandas to_pickle/read_pickle methods? What do i lose, when i save/load...
[ "In other question (What's the diffrence between pandas pd.to_pickle and pickle module pickle.dump, when saving DataFrame?) there is answer(https://stackoverflow.com/a/74458675/2516697) about diffrences between module pandas pickle functions and module pickle functions.\nSo generally speaking, except from some sp...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "pickle", "python" ]
stackoverflow_0074449468_dataframe_pandas_pickle_python.txt
Q: python selenium can not login to youtube account with cookies WARNING: cookies provided in this thread may already be invalid so you should do it with your own or some another cookies I need to log in to my youtube account using cookies and selenium. I can send a request to https://www.youtube.com/ with cookies an...
python selenium can not login to youtube account with cookies
WARNING: cookies provided in this thread may already be invalid so you should do it with your own or some another cookies I need to log in to my youtube account using cookies and selenium. I can send a request to https://www.youtube.com/ with cookies and it will succeed: to know if your request succeeds you should push...
[ "Try resort into using undetected_chromedriver: https://pypi.org/project/undetected-chromedriver/\n", "Here is what you can do:\nIn order to use seleniumwire you have to add the certificate to your browser. https://github.com/wkeeling/selenium-wire#certificates\n\nLogin with your email account.\n\nfrom seleniumwi...
[ 0, 0 ]
[]
[]
[ "cookies", "python", "selenium", "selenium_webdriver", "youtube" ]
stackoverflow_0073981038_cookies_python_selenium_selenium_webdriver_youtube.txt
Q: Use first N colors from qualitative cmap to plot cluster scatter I want to plot my clusters against their first two principle components, but using only the first N colors from matplotlibs 'Set1' cmap (dependent on number of clusters). I understand I can access the color list and can slice it to get the number of ...
Use first N colors from qualitative cmap to plot cluster scatter
I want to plot my clusters against their first two principle components, but using only the first N colors from matplotlibs 'Set1' cmap (dependent on number of clusters). I understand I can access the color list and can slice it to get the number of colors I want, however when attempting this I get the error: ValueErr...
[ "One possible solution is to loop over the unique cluster values:\nimport pandas as pd\nx = np.random.uniform(size=10)\ny = np.random.uniform(size=10)\ncolor_val = np.random.randint(1, 5, 10)\ndf = pd.DataFrame({\"PC1\": x, \"PC2\": y, \"cluster\": color_val})\n\nunique_color_val = df[\"cluster\"].unique()\ncolors ...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "scatter_plot" ]
stackoverflow_0074450982_matplotlib_pandas_python_scatter_plot.txt