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: Multiple Dispatch not required value I had a method like this on python: def method(a, b, c: int=0): return a+b+c When I called method(5,2) it returns me 7. However when I want to use multiple dispatching: from multipledispatch import dispatch @dispatch(int, int, int) def method(a, b, c=0): return a+b+c ...
Multiple Dispatch not required value
I had a method like this on python: def method(a, b, c: int=0): return a+b+c When I called method(5,2) it returns me 7. However when I want to use multiple dispatching: from multipledispatch import dispatch @dispatch(int, int, int) def method(a, b, c=0): return a+b+c method(5,2) understandably gives an error...
[ "This will work (you need to specify the names of args with default values when using @dispatch).\n@dispatch(int, int, c=int)\ndef method(a, b, c=0):\n return a+b+c\n\nmethod(2,7)\n# Out[58]: 9\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074402266_python.txt
Q: Selenium Web driver ( driver.find_element(By.XPATH, 'https//:xyz/asd')) IS NOT WORKING .Python I am constantly trying to access a simple text available in <h5> tag but it gives NoSuchElementException. I already saw that there is no <iframe> as a parent of this element. I am also giving time.sleep(20) sec which is ...
Selenium Web driver ( driver.find_element(By.XPATH, 'https//:xyz/asd')) IS NOT WORKING .Python
I am constantly trying to access a simple text available in <h5> tag but it gives NoSuchElementException. I already saw that there is no <iframe> as a parent of this element. I am also giving time.sleep(20) sec which is clearly more then enough. I can see that the page is completely loaded but it give error: Message: U...
[ "Assuming you are trying to get the text under \"FULL NAME\":\nfrom selenium.webdriver.firefox.webdriver import WebDriver\nfrom selenium.webdriver.common.by import By\n\n\nif __name__ == \"__main__\":\n xpath = '//*[@id=\"main-container\"]/div[5]/div[1]/div[2]/div[2]/div[2]/div/div/div[1]/div[1]/span/h5'\n dr...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping", "webdriver", "xpath" ]
stackoverflow_0074336193_python_selenium_web_scraping_webdriver_xpath.txt
Q: comparing date strings not working as expected I have a dataframe like below +--+--+-----------+ | a| b| date| +--+--+-----------+ | 1| 2| 01/01/2022| | 2| 3| 01/01/2021| | 3| 4| 12/20/2021| +--+--+-----------+ I have tried the code below but it keeps showing the 01/01/2022 date even though 30/12/2021 is no...
comparing date strings not working as expected
I have a dataframe like below +--+--+-----------+ | a| b| date| +--+--+-----------+ | 1| 2| 01/01/2022| | 2| 3| 01/01/2021| | 3| 4| 12/20/2021| +--+--+-----------+ I have tried the code below but it keeps showing the 01/01/2022 date even though 30/12/2021 is not greater than 01/01/2022. df.filter(("30/12/2021" ...
[ "You are comparing dates as strings, which will compare alphabetically from the left, so 01/01/2022 is less than 30/12/2021 because 0 is less than 3.\nYou need to convert your string to a date, e.g.:\nimport datetime\n\ns1 = \"30/12/2021\"\ns2 = \"01/01/2022\"\nprint(s1 < s2) # False\n\nd1 = datetime.datetime.strp...
[ 1, 0 ]
[]
[]
[ "apache_spark", "dataframe", "date", "pyspark", "python" ]
stackoverflow_0074403397_apache_spark_dataframe_date_pyspark_python.txt
Q: Ansible: 'dict object' has no attribute, when using read_csv from file (UTF-8 with BOM) I am trying to create local users on remote systems using Ansible. The user list is read from a CSV formatted file using Ansible's read_csv. The CSV file is formatted in UTF-8 with Byte order mark (BOM). I am getting the error ...
Ansible: 'dict object' has no attribute, when using read_csv from file (UTF-8 with BOM)
I am trying to create local users on remote systems using Ansible. The user list is read from a CSV formatted file using Ansible's read_csv. The CSV file is formatted in UTF-8 with Byte order mark (BOM). I am getting the error 'dict object' has no attribute 'Username'. But 'Username' does in fact exist in the CSV file'...
[ "Avoid using Unicode with BOM (Byte order mark), when reading files with Ansible.\nConvert text files to a format, that does not use BOM (e.g. UTF-8 without BOM, ASCII, etc)\nIt seems that Ansible (as of today, 2022) is not supporting BOM:\n'utf8' codec can't decode byte 0xff in position 0: invalid start byte\" #23...
[ 0 ]
[]
[]
[ "ansible", "byte_order_mark", "python", "utf_8", "yaml" ]
stackoverflow_0074267320_ansible_byte_order_mark_python_utf_8_yaml.txt
Q: How can I add list inside list in python json file? I pulled data from website with beautifulsoap in python. How can I add the letters in myList to the beginning of the data I pull? for example those starting with A like those starting with B ? I tryed a few different things for this but I couldnt achieve. the dat...
How can I add list inside list in python json file?
I pulled data from website with beautifulsoap in python. How can I add the letters in myList to the beginning of the data I pull? for example those starting with A like those starting with B ? I tryed a few different things for this but I couldnt achieve. the data seems like this. [ { "idiom": "above board"...
[ "Based on your comment, what you can do is create a temporary variable like tempdata inside your 1st for loop, something like,\nfor i in range(23):\n tempdata = []\n\nThen you can instead of appending each idiom to data you would instead append to this temporary variable,\ntempdata.append({...})\n\nAnd finally a...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074403635_beautifulsoup_python_web_scraping.txt
Q: What is preventing my Chrome profile from working with Selenium in Python? I am trying to use Python to automate a number of work processes that primarily take place in an online content management system, and to access the CMS, I need to be logged into my work profile on Chrome. While I could sign in once Chromed...
What is preventing my Chrome profile from working with Selenium in Python?
I am trying to use Python to automate a number of work processes that primarily take place in an online content management system, and to access the CMS, I need to be logged into my work profile on Chrome. While I could sign in once Chromedriver is open, I would have to approve the login on my authenticator each time, ...
[ "Your question is not related to the error you mentioned.\nFor the error - 'DeprecationWarning: executable_path has been deprecated, please pass in a Service object', you have to use Service:\nfrom selenium.webdriver.chrome.service import Service\n\ndriver = webdriver.Chrome(service=Service(\"C:\\\\Users\\\\Saul\\\...
[ 0, 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074403352_automation_python_selenium_selenium_chromedriver.txt
Q: Sending mail from Python using SMTP I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ? from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp....
Sending mail from Python using SMTP
I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ? from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') fro...
[ "The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.\nI rely on my ISP to add the date time header.\nMy ISP requires me to use a secure smtp connection to send mail, I rely on the ...
[ 128, 99, 23, 6, 6, 6, 5, 4, 3, 2, 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0000064505_python_smtp.txt
Q: How do I slice up dataframes into smaller chunks and write to a database using python? Im trying to write data from pandas dataframe to snowflake. However, Snowflake only permits bulk inserts of 16000 rows of data at a time if its not from a csv. I want to find a way around this,my og dataframe has about 48k rows....
How do I slice up dataframes into smaller chunks and write to a database using python?
Im trying to write data from pandas dataframe to snowflake. However, Snowflake only permits bulk inserts of 16000 rows of data at a time if its not from a csv. I want to find a way around this,my og dataframe has about 48k rows. I tried to split the dataframe using: import numpy as np df1, df2, df3 = np.array_split(df,...
[ "Option 1: pass in Snowflake Python Connector function pd_writer.\nfrom snowflake.connector.pandas_tools import pd_writer\n\n# Specify that the to_sql method should use the pd_writer function\n# to write the data from the DataFrame to the Snowflake table\ndf.to_sql('tablename', con, index=False, method=pd_writer)\n...
[ 0 ]
[]
[]
[ "numpy", "pyodbc", "python", "snowflake_cloud_data_platform", "sqlalchemy" ]
stackoverflow_0074397082_numpy_pyodbc_python_snowflake_cloud_data_platform_sqlalchemy.txt
Q: Anaconda Xgboost unable to find GPU It seems that Anaconda is unable recognise my GPU, GPU is RTX2070 (Driver version 510.47.03), system Ubuntu 20.04, cudatoolkit 11.3.1, cudnn 8.2.1, XGboost 1.5.2 via pip install. When I run XGboost with GPU enable it shows: XGBoostError: [01:24:12] ../src/gbm/gbtree.cc:531: Chec...
Anaconda Xgboost unable to find GPU
It seems that Anaconda is unable recognise my GPU, GPU is RTX2070 (Driver version 510.47.03), system Ubuntu 20.04, cudatoolkit 11.3.1, cudnn 8.2.1, XGboost 1.5.2 via pip install. When I run XGboost with GPU enable it shows: XGBoostError: [01:24:12] ../src/gbm/gbtree.cc:531: Check failed: common::AllVisibleGPUs() >= 1 (...
[ "Appeared to be a driver issue, tried the same code in another computer with two RTX 3090 and got no issue\n" ]
[ 0 ]
[]
[]
[ "anaconda", "gpu", "python", "pytorch", "ubuntu" ]
stackoverflow_0071254462_anaconda_gpu_python_pytorch_ubuntu.txt
Q: Deleting .libs Folder from Python Libraries for Lambda I'm deleting folders from Python libraries to fit the 250 MB Unzipped limit. When I install numpy and scipy. I have two folders numpy.libs and scipy.libs. These contain .so files. Can I safely delete these such that the library remains functional? A: Deletin...
Deleting .libs Folder from Python Libraries for Lambda
I'm deleting folders from Python libraries to fit the 250 MB Unzipped limit. When I install numpy and scipy. I have two folders numpy.libs and scipy.libs. These contain .so files. Can I safely delete these such that the library remains functional?
[ "Deleting these .libs won't work, they are required.\nHowever, you can find prepared layers (load via ARN) for some popular packages, which are optimized & compressed. For example for numpy + sklearn checkout this GitHub repo to find the ARN that matches your python version and region.\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "libraries", "python" ]
stackoverflow_0073065263_amazon_web_services_aws_lambda_libraries_python.txt
Q: How to plot a scatter plot on a single y-tick with multiple x-axes using Plotly Python? I'm trying to plot a Scatter plot with a single y-axis and multiple x-axis as below using plotly-python. Sample data timeData = ['2009/6/12 5:00', '2009/6/12 7:00', '2009/6/12 9:00', '2009/6/12 13:00', '2009/6/12 15:00', '2009/...
How to plot a scatter plot on a single y-tick with multiple x-axes using Plotly Python?
I'm trying to plot a Scatter plot with a single y-axis and multiple x-axis as below using plotly-python. Sample data timeData = ['2009/6/12 5:00', '2009/6/12 7:00', '2009/6/12 9:00', '2009/6/12 13:00', '2009/6/12 15:00', '2009/6/12 17:00', '2009/6/12 21:00', '2009/6/13 1:00', '2009/6/13 5:00', '2009/6/13 7:00', '2009/6...
[ "\nyou can use ploty express to generate sub-plots for each of the days\nhave used pandas categorical functionality to get sort order correct first\nfigure created by plotly express requires touch ups\n\nremove annotations\nonly part of yaxes config is wanted\nxaxes need to be updated to show for each sub-plot\nsom...
[ 1, 0 ]
[]
[]
[ "data_visualization", "datetime", "plotly", "python" ]
stackoverflow_0072246279_data_visualization_datetime_plotly_python.txt
Q: python remove duplicates from a list of list with uneven distribution i have a python list of lists i want to merge all the containing list with at least 1 common element and remove the similar items i have a big set of data which is a list of lists, with some common data in some of the containing lists, i want to...
python remove duplicates from a list of list with uneven distribution
i have a python list of lists i want to merge all the containing list with at least 1 common element and remove the similar items i have a big set of data which is a list of lists, with some common data in some of the containing lists, i want to merge all lists with common data # sample data foo = [ [0,1,2,6,9], [0,1,2...
[ "A simple (and probably non-optimal) algorithm that modifies the input data in place:\ntarget_idx = 0\n\nwhile target_idx < len(data):\n src_idx = target_idx + 1\n did_merge = False\n while src_idx < len(data):\n if set(data[target_idx]) & set(data[src_idx]):\n data[target_idx].extend(dat...
[ 1 ]
[]
[]
[ "list", "python", "python_3.x", "validation" ]
stackoverflow_0074403726_list_python_python_3.x_validation.txt
Q: Python: Failed to Launch Debug Adapter, Operation was cancelled. Visual Studio Community 2022 So I've seen that many people have asked this question before, but it's always in relation to a different framework/language. I was working on a solution in python and seemingly for no reason I couldn't debug anymore. I o...
Python: Failed to Launch Debug Adapter, Operation was cancelled. Visual Studio Community 2022
So I've seen that many people have asked this question before, but it's always in relation to a different framework/language. I was working on a solution in python and seemingly for no reason I couldn't debug anymore. I opened a new solution to see if I had somehow broken my solution, but now I can't debug at all. The ...
[ "Okay so I've managed to fix:\nLooks like the issue was coming from the version of Python that the solution was attempting to de-bug with.\n\nDrop down the Python environment selector,\nNavigate to existing environment\nSelect the latest version of python environment (Make sure you have it downloaded and installed ...
[ 1 ]
[]
[]
[ "debugging", "python", "visual_studio_2022" ]
stackoverflow_0074401668_debugging_python_visual_studio_2022.txt
Q: "no such table" exception In Django I added models into models.py. After manage.py makemigrations, manage.py migrate raised this exception: django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile I removed all old migrations and run makemigrations and migrate again which seemed to work. ...
"no such table" exception
In Django I added models into models.py. After manage.py makemigrations, manage.py migrate raised this exception: django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile I removed all old migrations and run makemigrations and migrate again which seemed to work. It didn't help because when I c...
[ "I solved the same problem with these steps :\n\nDelete your database (db.sqlite3 in my case) in your project directory\nRemove everything from __pycache__ folder under your project subdirectory\nFor the application you are trying to fix, go to the folder and clear migrations and __pycache__ directories\n\nWhen you...
[ 96, 62, 38, 20, 14, 9, 3, 3, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "The only way to fix my error was commenting out every single file. This error might occur while a file thinks the database is not empty, or that it actually exists.\nI just commented out the entire project, migrated, uncommented the models.py file, migrated again, uncommented the entire project. I have no idea why...
[ -1 ]
[ "django", "makemigrations", "migrate", "python", "sqlite" ]
stackoverflow_0034548768_django_makemigrations_migrate_python_sqlite.txt
Q: Calling Python from PHP using shell_exec() in XAMPP I'm trying to make this work on XAMPP. It works fine on a Linux server/virtual machine. I need to send an associative array to a python script, and I do it with: <?php echo "Test simple call/answer process<br>"; $age = array("Peter"=>"35", "Ben"=>"37", "Joe...
Calling Python from PHP using shell_exec() in XAMPP
I'm trying to make this work on XAMPP. It works fine on a Linux server/virtual machine. I need to send an associative array to a python script, and I do it with: <?php echo "Test simple call/answer process<br>"; $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); $param = base64_encode(json_encode($age)); ...
[ "Assuming the rest of the code is okay, you're using single quotes in this line\n$command = escapeshellcmd('python python_array_answer.py $param');\n\nwhere you should either use double quotes, so php known to replace $param with the value of variable $param, or concatenate the two like this...\n$command = escapesh...
[ 1 ]
[]
[]
[ "php", "python", "shell_exec", "xampp" ]
stackoverflow_0074403809_php_python_shell_exec_xampp.txt
Q: GitHub Coptilot does not work in vscode when editing Python I can run python scripts (.py) inside vs code, and CoPilot works fine with Powershell scripts (.ps1), however, I'm not getting any Github Copilot suggestions. The Copilot icon shows and the plugin appear to be activated. GitHub Copilot: v1.58.7236 VsCode ...
GitHub Coptilot does not work in vscode when editing Python
I can run python scripts (.py) inside vs code, and CoPilot works fine with Powershell scripts (.ps1), however, I'm not getting any Github Copilot suggestions. The Copilot icon shows and the plugin appear to be activated. GitHub Copilot: v1.58.7236 VsCode Version: 1.73.0 (user setup) Commit: 8fa188b2b301d36553cbc9ce1b0a...
[ "Are you able to hover your mouse over the comment and get suggestions? Also, try restarting and making sure you have the latest version\n", "Not sure if upgrading vscode or if I simply didn't do it right before.\nHowever, it appears that Github Copilot is now (always was?) triggered by the tab or space key.\nVer...
[ 1, 0 ]
[]
[]
[ "github_copilot", "python", "visual_studio_code" ]
stackoverflow_0074326142_github_copilot_python_visual_studio_code.txt
Q: Calling functions in module by choice in main python program Can I call function from module in the main python file by user choice? something like this: module file def product_1(a,b): return a*b def sum_1(a,b) return a+b main file Can I call function in the main file with list by user choice from input...
Calling functions in module by choice in main python program
Can I call function from module in the main python file by user choice? something like this: module file def product_1(a,b): return a*b def sum_1(a,b) return a+b main file Can I call function in the main file with list by user choice from input? a=input() b=input() list1=['product_1','sum_1'] x=input('Enter c...
[ "It's possible to have functions in a list/dictionary that you can call. For your case, it sounds like you need a dictionary to determine the proper function.\nYour main.py should look like...\nfrom module import product_1, sum_1\ndef main():\n a=input()\n b=input()\n function_mapping={'product_1':product_...
[ 1 ]
[]
[]
[ "function", "module", "python" ]
stackoverflow_0074404013_function_module_python.txt
Q: Who can I select the same index but from 2 different arrays witch change from the user input? I want to turn two enemies into just one enemy by changing the array depending on the user input. I've created two different enemies and two different functions for the attack, but I wanted to just create one attack to gi...
Who can I select the same index but from 2 different arrays witch change from the user input?
I want to turn two enemies into just one enemy by changing the array depending on the user input. I've created two different enemies and two different functions for the attack, but I wanted to just create one attack to give to the diferent enemies. #Warrior warrior = [32,5,2,5,2] #HP, MP , AP, WP, Init #vampire 1 vam...
[ "You can use a list of enemy:\nvampires = [[15,0,2,2,2], [15,0,2,2,2]]\n\nI've modified a bit the attack function\n(vampire := vampire - damage for assignment within condition check)\n(no need to check twice in elif, a simple else does the trick)\n(don't put comments within code, ahead the function it's clearer)\nd...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074403618_python_python_3.x.txt
Q: Python: TypeError: unsupported operand type(s) for +: 'int' and 'range' import datetime def logger(fn): def wrapper(*args, **kwargs): print(f"{fn.__name__} : {args} | {kwargs}") start = datetime.datetime.now() ret = fn(*args, **kwargs) delta = datetime.datetime.now() print(f"The function takes {(delta ...
Python: TypeError: unsupported operand type(s) for +: 'int' and 'range'
import datetime def logger(fn): def wrapper(*args, **kwargs): print(f"{fn.__name__} : {args} | {kwargs}") start = datetime.datetime.now() ret = fn(*args, **kwargs) delta = datetime.datetime.now() print(f"The function takes {(delta - start).total_seconds()} seconds") return ret return wrapper @logger # ...
[ "I think I have made a ridiculous mistake. The args in the program is (range(100),). It is a tuple, not simple 'range(100). So I must destruct it with *`.\n" ]
[ 1 ]
[]
[]
[ "parameter_passing", "python", "wrapper" ]
stackoverflow_0074403987_parameter_passing_python_wrapper.txt
Q: Can someone tell me why this isn't creating a dm channel to the specified user when someone types !dm? This will not work for some reason. I have no idea why it doesnt work # adds an event @client.event async def on_message(message): # so i dont have to say message.content a lot msg = message.content # if a ...
Can someone tell me why this isn't creating a dm channel to the specified user when someone types !dm?
This will not work for some reason. I have no idea why it doesnt work # adds an event @client.event async def on_message(message): # so i dont have to say message.content a lot msg = message.content # if a message starts with !dm create a dm channel with the specified user if msg.content.startswith("!dm"): ...
[ "You need to create a DM targeting a user.\n@client.command()\nasync def hello(ctx):\n user = ctx.author\n await ctx.send(f\"Hello, {user.mention}\")\n dm = await user.create_dm()\n await dm.send('hello')\n\nAlso, as you can see in this code snippet here, I recommend setting up a command (as it looks li...
[ 0, 0 ]
[]
[]
[ "bots", "discord", "python" ]
stackoverflow_0074378899_bots_discord_python.txt
Q: Python - Solve some mathematical problems in a list filled with random elements Task: In a list filled with random numbers you need to count: A sum of negative numbers A sum of even numbers A sum of odd numbers A product of elements with indexes that multiple 3 A product of elements between min and max element A ...
Python - Solve some mathematical problems in a list filled with random elements
Task: In a list filled with random numbers you need to count: A sum of negative numbers A sum of even numbers A sum of odd numbers A product of elements with indexes that multiple 3 A product of elements between min and max element A sum of elements, which located between first and last element I can't figure out how...
[ "\nA product of elements between min and max element\n\nFor this task, you can use .sort() method of the \"list\" object to sort it in-place then use list indexes to exclude the first and last item (min and max because it is sorted) and then use math.prod to calculate the product of rest\nimport math\nmy_list.sort(...
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074404062_list_python.txt
Q: Extract Text From Unstructured Medical Documents For NLP I have a lot of unstructured medical documents in all sorts of different formats. What's the best way to parse out all the good sentences to use for NLP? Currently I'm using SpaCy to do this, but even with multiprocessing it is pretty slow, and and the defa...
Extract Text From Unstructured Medical Documents For NLP
I have a lot of unstructured medical documents in all sorts of different formats. What's the best way to parse out all the good sentences to use for NLP? Currently I'm using SpaCy to do this, but even with multiprocessing it is pretty slow, and and the default sentence parser doesn't work 100% of the time. Here is an ...
[ "Based on the comments from the above discussion, I am very confident that spaCy will not provide you with very good results, simply because it is very much tied to the expectation of a valid grammatical sentence.\nAt least with the current approach of looking for \"correctly tagged words\" in each line, I would ex...
[ 2, 0 ]
[]
[]
[ "nlp", "python", "spacy" ]
stackoverflow_0059994402_nlp_python_spacy.txt
Q: Is it possible to use whitespace in format specifier If I have following print statements: print("#"*80) print(f"##{'':.^76}##") print(f"##{'Hello World':.^76}##") print(f"##{'':.^76}##") print("#"*80) I will get a nice border around my "Hello World" but with dots: ################################################...
Is it possible to use whitespace in format specifier
If I have following print statements: print("#"*80) print(f"##{'':.^76}##") print(f"##{'Hello World':.^76}##") print(f"##{'':.^76}##") print("#"*80) I will get a nice border around my "Hello World" but with dots: ################################################################################ ##..........................
[ "Isn't it enough to simply remove the dot and leave a space?\nSo:\nprint(\"#\"*80)\nprint(f\"##{'': ^76}##\")\nprint(f\"##{'Hello World': ^76}##\")\nprint(f\"##{'': ^76}##\")\nprint(\"#\"*80)\n\noutput will be:\n################################################################################\n## ...
[ 1, 1 ]
[]
[]
[ "f_string", "python" ]
stackoverflow_0074404109_f_string_python.txt
Q: How to add new python package for Snowpark I am using Snowpark for Python. I want to import imblearn package but when I check pre-installed packages at https://repo.anaconda.com/pkgs/snowflake/ this package is not installed in the Snowpark anaconda environment. How can use this package on snowpark? A: A number o...
How to add new python package for Snowpark
I am using Snowpark for Python. I want to import imblearn package but when I check pre-installed packages at https://repo.anaconda.com/pkgs/snowflake/ this package is not installed in the Snowpark anaconda environment. How can use this package on snowpark?
[ "A number of open source third-party Python packages that are built and provided by Anaconda are made available to use out of the box inside Snowflake.\nSnowflake is constantly adding new packages. But if you don't find a specific package then\n\nFirst check if the package has only native python code(pure python pa...
[ 2, 0, 0 ]
[]
[]
[ "python", "snowpark" ]
stackoverflow_0072830701_python_snowpark.txt
Q: Pass argument store in variable to argparse This is my script mytest.py. import argparse parser = argparse.ArgumentParser(description="Params") parser.add_argument( "--value") def test(args): print(args.value) args = parser.parse_args() test(args) I want to pass argument store in variable val val =1 !...
Pass argument store in variable to argparse
This is my script mytest.py. import argparse parser = argparse.ArgumentParser(description="Params") parser.add_argument( "--value") def test(args): print(args.value) args = parser.parse_args() test(args) I want to pass argument store in variable val val =1 !python mytest.py --value val instead of printing...
[ "argparse always get argument as string, or list of strings on default, and what you do on your shell is irrelevant with python program. It is no wonder val is printed.\nUse file that contains \"1\" and read that file to do what you intended to.\n", "As jueon park said naming a variable in commandline wont work\n...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069863212_python.txt
Q: Pandas Dataframe: Split a single column into multiple columns I'm trying to split a column Class into multiple columns and change column names based on that. ID Name Class 0 12 John A 1 13 Mark A 2 14 Tony B 3 15 Marcus C 4 16 Phill D...
Pandas Dataframe: Split a single column into multiple columns
I'm trying to split a column Class into multiple columns and change column names based on that. ID Name Class 0 12 John A 1 13 Mark A 2 14 Tony B 3 15 Marcus C 4 16 Phill D 5 17 Jack A final df ID Name Class A ...
[ "import numpy as np\nuniq_class = df['Class'].unique().tolist()\n# create a diagonal matrix with unique class as value\nD = np.diag(uniq_class).tolist()\n# map the diagonal matrix dictionary for each class value\ntemp = dict(zip(uniq_class, D))\n# map class values to the temp dictionary\ndf[uniq_class] = df['Class'...
[ 2, 1, 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "python_3.x" ]
stackoverflow_0074403581_dataframe_numpy_pandas_python_python_3.x.txt
Q: Python tkinter kept saying my variable to hold the .get() value is not defined I am learning how to use the .get() for tkinter, and trying to write this basic GUI that can store, process, and display data depending on a user input. Now (I am fairly new to this, so I am probably wrong) to my knowledge, I need to us...
Python tkinter kept saying my variable to hold the .get() value is not defined
I am learning how to use the .get() for tkinter, and trying to write this basic GUI that can store, process, and display data depending on a user input. Now (I am fairly new to this, so I am probably wrong) to my knowledge, I need to use the .get() and store it into a variable for future uses. Now here are my codes, bu...
[ "You should use a StringVar to store the value of the entry when event() is called by button\nimport tkinter as tk\n\n\ndef event(): # use this function to update the StringVar\n entry_content = entry.get()\n entry_var.set(entry_content)\n\n\nwindow = tk.Tk()\n# declare a StringVar to store the value of your...
[ 0, 0 ]
[]
[]
[ "function", "python", "python_3.11", "tkinter", "variables" ]
stackoverflow_0074390246_function_python_python_3.11_tkinter_variables.txt
Q: Create a Postgres database using python I want to create Postgres database using Python. con = psql.connect(dbname='postgres', user=self.user_name, host='', password=self.password) cur = con.cursor() cur.execute("CREATE DATABASE %s ;" % self.db_name) I am getting the following error: InternalError: ...
Create a Postgres database using python
I want to create Postgres database using Python. con = psql.connect(dbname='postgres', user=self.user_name, host='', password=self.password) cur = con.cursor() cur.execute("CREATE DATABASE %s ;" % self.db_name) I am getting the following error: InternalError: CREATE DATABASE cannot run inside a transacti...
[ "Use ISOLATION_LEVEL_AUTOCOMMIT, a psycopg2 extensions:\n\nNo transaction is started when command are issued and no commit() or\nrollback() is required.\n\nimport psycopg2\nfrom psycopg2 import sql\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # <-- ADD THIS LINE\n\ncon = psycopg2.connect(dbname='post...
[ 105, 46, 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0034484066_postgresql_psycopg2_python.txt
Q: How to access the variables the CMake variables which is already used in CMakelist.txt to a python script? I have a CMakelist.txt and I am writing a python script for an another execution now with the python script i need to use the variables which was used in the CMakelists.txt. In CMakelists.txt I have a variabl...
How to access the variables the CMake variables which is already used in CMakelist.txt to a python script?
I have a CMakelist.txt and I am writing a python script for an another execution now with the python script i need to use the variables which was used in the CMakelists.txt. In CMakelists.txt I have a variable as file(STRINGS ${srcfilelist} sourcefilelist) So how to pass the variable 'sourcefilelist' from CMakelist.txt...
[ "The typical way to pass variables from the build system, e.g. CMake, to build scripts or the compiler is the environment. Note that environment variables are always strings.\nIn CMake, you use set() command to set environment variables, e.g.\nset(ENV{<FOOBAR>} 42)\n\nIn Python, you can use os.environ to access env...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074403671_python_python_3.x.txt
Q: How to display a categorical dataframe in a pairplot I am getting the following error: No variables found for grid columns? In the console it prints the dataframe ok, but when I want to display it in seaborn, it doesn't work. %matplotlib inline import seaborn as sns from ipywidgets import interact import matplotli...
How to display a categorical dataframe in a pairplot
I am getting the following error: No variables found for grid columns? In the console it prints the dataframe ok, but when I want to display it in seaborn, it doesn't work. %matplotlib inline import seaborn as sns from ipywidgets import interact import matplotlib.pyplot as plt cars_url = 'http://archive.ics.uci.edu/ml...
[ "Pairtplot works only with numerical data. You should use Label Encoder before paiplot.\nFor example:\nfrom sklearn.preprocessing import OrdinalEncoder\n\nencoder = OrdinalEncoder()\ndata = encoder.fit_transform(data)\n\n" ]
[ 2 ]
[]
[]
[ "encode", "pairplot", "pandas", "python", "seaborn" ]
stackoverflow_0074404064_encode_pairplot_pandas_python_seaborn.txt
Q: How to count sum of people for each country? Python, pandas I'm new at python. I struggle how to count how many people have died from each country. I use pandas dataframe. 0 - means that person died, 1 - survived. I have ~2000rows. Maybe it is not enough info, but I dont know how to solve this and from what exactl...
How to count sum of people for each country? Python, pandas
I'm new at python. I struggle how to count how many people have died from each country. I use pandas dataframe. 0 - means that person died, 1 - survived. I have ~2000rows. Maybe it is not enough info, but I dont know how to solve this and from what exactly to start... df['survived'] = df['survived'].replace(['no'], 0) ...
[ "\"How to count how many people have died from each country\" ?\nWhy do you get lists back from your dataframe to do some computations in pure Python ?\nPandas dataframes are made for that kind of computation.\ndf[\"died\"] = df[\"survived\"].map(lambda x: 1 if x==0 else 0)\ndf.groupby(['country']).sum()\n\n", "T...
[ 1, 0 ]
[]
[]
[ "pandas", "python", "sum" ]
stackoverflow_0074404178_pandas_python_sum.txt
Q: 2 samples hypothesis testing in Python I am endeavouring to perform a two sample hypothesis test in Python, having been given the original code in R. The code in R is:- prop.test(x=c(10,16), n=c(100,100))` #The p-value is 0.2931, being greater than alpha=0.5, #so we fail to reject the null hypothesis I have t...
2 samples hypothesis testing in Python
I am endeavouring to perform a two sample hypothesis test in Python, having been given the original code in R. The code in R is:- prop.test(x=c(10,16), n=c(100,100))` #The p-value is 0.2931, being greater than alpha=0.5, #so we fail to reject the null hypothesis I have tried to perform the same test in both scipy ...
[ "R's prop.test uses the Yates continuity correction by default (it can be turned off using correct=F)\nTherefore, to replicate in python, you need to use that Yates continuity correction. This can be done with stats.chi2_contingency(). However, your array of observed values needs to be adjusted, so that the number ...
[ 0 ]
[]
[]
[ "hypothesis_test", "python", "r", "statistics" ]
stackoverflow_0074403628_hypothesis_test_python_r_statistics.txt
Q: What is the best way to compare floats for almost-equality in Python? It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues. For example: Comparing Floating Point Numbers, 2012 Edition What is the recommended way to deal with this in Python? Is a standard librar...
What is the best way to compare floats for almost-equality in Python?
It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues. For example: Comparing Floating Point Numbers, 2012 Edition What is the recommended way to deal with this in Python? Is a standard library function for this somewhere?
[ "Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.\nIf you're using an earlier version of Python, the equivalent function is given in the documentation.\ndef isclose(a, b, rel_tol=1e-09, abs_tol=0.0):\n return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)\n\nrel_tol ...
[ 463, 104, 69, 19, 14, 14, 13, 11, 5, 5, 2, 2, 1, 0, 0, 0, 0 ]
[ "Use == is a simple good way, if you don't care about tolerance precisely.\n# Python 3.8.5\n>>> 1.0000000000001 == 1\nFalse\n>>> 1.00000000000001 == 1\nTrue\n\nBut watch out for 0:\n>>> 0 == 0.00000000000000000000000000000000000000000001\nFalse\n\nThe 0 is always the zero.\n\nUse math.isclose if you want to control...
[ -3 ]
[ "floating_point", "python" ]
stackoverflow_0005595425_floating_point_python.txt
Q: How do I get typer to accept the short `-h` as well as the long `--help` to output help text? Out of the box, Typer CLIs only recognize the long help option --help to display the help text. I would like to also accept the short option -h but I can't figure out how. I've searched the docs to no avail. Do I need to ...
How do I get typer to accept the short `-h` as well as the long `--help` to output help text?
Out of the box, Typer CLIs only recognize the long help option --help to display the help text. I would like to also accept the short option -h but I can't figure out how. I've searched the docs to no avail. Do I need to alias -h to --help and if so, how do I do that?
[ "The key is to use context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\nAs suggested by @jvx8ss in the comments, one needs to convert a typer.run app to one using @app.command() decorators.\nHere is a minimal working example:\nimport typer\n\napp = typer.Typer(context_settings={\"help_option_names\": [\...
[ 1 ]
[]
[]
[ "command_line_interface", "python", "python_3.x", "typer" ]
stackoverflow_0074403900_command_line_interface_python_python_3.x_typer.txt
Q: How to make a Typer app using decorators without having to use subcommands? I have a simple Typer app that uses the minimal typer.run(main) way of setting up. I would like to add context_settings to this app - to that end, I think I need to convert the invocation to one that uses decorators @app.command(). But in ...
How to make a Typer app using decorators without having to use subcommands?
I have a simple Typer app that uses the minimal typer.run(main) way of setting up. I would like to add context_settings to this app - to that end, I think I need to convert the invocation to one that uses decorators @app.command(). But in contrast to the Typer documentation, I do no want to use any subcommands, I want ...
[ "It turns out that if you use only one single @app.command() decorator Typer automatically obviates the need for a subcommand. Only when you use 2 or more @app.command()s do you need to call each command using the function name.\nThe following minimal script can still be invoked using python main.py Jane, no need f...
[ 0 ]
[]
[]
[ "command_line_interface", "python", "python_3.x", "typer" ]
stackoverflow_0074404332_command_line_interface_python_python_3.x_typer.txt
Q: Index error when trying to compare values in a list I'm trying to find the remainder of each number in a list that is equal to one, but the problem is I get an index error Here I compare the current item in the list to the next one: numbers = [1,2,3,4,5,6] sorted_number = sorted(numbers) for index, num in enumer...
Index error when trying to compare values in a list
I'm trying to find the remainder of each number in a list that is equal to one, but the problem is I get an index error Here I compare the current item in the list to the next one: numbers = [1,2,3,4,5,6] sorted_number = sorted(numbers) for index, num in enumerate(sorted_number): if sorted_number[index + 1] % sor...
[ "When you get to the last element of sorted_number, the call sorted_number[index + 1] is out of bounds. You can avoid this by only iterating to the second to last number in the list:\nfor index, num in enumerate(sorted_number[:-1]):\n if sorted_number[index + 1] % sorted_number[index] == 1:\n print(index,...
[ 3, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074404358_python_python_3.x.txt
Q: Tensorflow: Custom Layer/Gradient result in OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed I'm trying to implement a custom layer with a custom gradient following the canonical reference here and here For some reason, my code is throwing the following error: OperatorNotAllowedInGraphErr...
Tensorflow: Custom Layer/Gradient result in OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed
I'm trying to implement a custom layer with a custom gradient following the canonical reference here and here For some reason, my code is throwing the following error: OperatorNotAllowedInGraphError: iterating over tf.Tensor is not allowed: AutoGraph did convert this function. This might indicate you are trying to use...
[ "Well, the problem here is that @tf.custom_gradients needs to return two variables, the gradient of dx and gradient of variables, you are only returning the dx_ part but not the gradient of variables, I have fixed the issue try this...\nclear_session()\nclass Linear(keras.Model):\n def __init__(self, units=32):\...
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074395032_python_tensorflow.txt
Q: how to compare column values in 2 dataframe I need to compare two dataframes df1 and df2. If the name in df1 equals to the name in df2, I need to combine the mylist to df2. This is mylist datarame: mylist : 0 1 [1,2] [2,3] [1,5] [2,6] [1,6] [2,4] [1,1] [2,5] [1,3] [2,8] m...
how to compare column values in 2 dataframe
I need to compare two dataframes df1 and df2. If the name in df1 equals to the name in df2, I need to combine the mylist to df2. This is mylist datarame: mylist : 0 1 [1,2] [2,3] [1,5] [2,6] [1,6] [2,4] [1,1] [2,5] [1,3] [2,8] mylist[0] = [[1,2],[2,3]] mylist[1] = [[1,5],[2,6]...
[ "You can use merge:\nfinal= df2.merge(df1,how='left', on='name')\n\n" ]
[ 0 ]
[]
[]
[ "conditional_statements", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074404365_conditional_statements_dataframe_numpy_pandas_python.txt
Q: Why does joblib parallel execution make runtime much slower? I want to shuffle values in a 3D numpy-array, but only when they are > 0. When I run my function with a single core, it is much faster than with even 2 cores. It is way beyond the overhead of creating new python processes. What am I missing? The followin...
Why does joblib parallel execution make runtime much slower?
I want to shuffle values in a 3D numpy-array, but only when they are > 0. When I run my function with a single core, it is much faster than with even 2 cores. It is way beyond the overhead of creating new python processes. What am I missing? The following code outputs: random shuffling of markers started time in serial...
[ "\nQ : \"What am I missing?\"\n\nMost probably the memory-I/O bottlenecks.\n\nWhile the numpy-part of the processing seems to be pretty shallow here (shuffle does not compute a bit, but moves data between a pair of locations, doesn't it?), for the most of the time, this will not permit \"time-enough\" (by doing any...
[ 1, 0 ]
[]
[]
[ "joblib", "low_latency", "parallel_processing", "performance", "python" ]
stackoverflow_0065026499_joblib_low_latency_parallel_processing_performance_python.txt
Q: Python - [SOLVED] How to arrange a numpy list in order according to the order of a list or string i have a numpy array: import numpy as np phrase = np.array(list("eholl")) a = 'hello' i would like to sort the variable, according to the order of letters (h first, e second...) inside the variable "a" that result i...
Python - [SOLVED] How to arrange a numpy list in order according to the order of a list or string
i have a numpy array: import numpy as np phrase = np.array(list("eholl")) a = 'hello' i would like to sort the variable, according to the order of letters (h first, e second...) inside the variable "a" that result into the array ordered: Tried: z = np.sort(phrase, order=a) print(z) Output that i want: hello Error:...
[ "order argument of np.sort is to specify which fields to compare first, second, etc. It doesn't help you.\nIf you don't require the immediate output of the sorting function is a numpy array, you can simply use built-in function sorted. You can specify a key function via its key argument. In your case, the sorting k...
[ 0 ]
[]
[]
[ "numpy", "python", "sorting", "xcode" ]
stackoverflow_0074403698_numpy_python_sorting_xcode.txt
Q: Update multiple variables based on time I have a dataframe with 4 columns, duration, event, starttime and finishtime. Duration, startitme and finishtime are integers while event is a string e.g Component 1 failed, Component 2 rapaired etc. Duration, starttime and finish time describe the duration of an event, the ...
Update multiple variables based on time
I have a dataframe with 4 columns, duration, event, starttime and finishtime. Duration, startitme and finishtime are integers while event is a string e.g Component 1 failed, Component 2 rapaired etc. Duration, starttime and finish time describe the duration of an event, the starttime of the event and the finishtime of ...
[ "I am not sure how large a DataFrame you are dealing with, but this approach will work for most frames:\ndef findCondition(val:str, schWord: str) -> bool:\n # returns True if val contains schWord, else False\n return schWord.lower() in val.lower()\n\nYou can then add a new column to the frame using:\ndf['Oper...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074401840_dataframe_pandas_python.txt
Q: Missing Columns in pandastable in tkinter I am trying to display a dataframe in a frame on my tkinter app. I want to group my values by the first 2 columns and get the sum of all the values per unique pair. While working with the dataframe everything is working as expected. Printed in the terminal, my output is ex...
Missing Columns in pandastable in tkinter
I am trying to display a dataframe in a frame on my tkinter app. I want to group my values by the first 2 columns and get the sum of all the values per unique pair. While working with the dataframe everything is working as expected. Printed in the terminal, my output is exactly what I want, however when displayed in th...
[ "I have fixed my problem, but I'll leave the question up anyway in case someone else is having similar difficulties. Adding as_index = False to groupby solved it.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandastable", "python", "tkinter" ]
stackoverflow_0074403885_dataframe_group_by_pandastable_python_tkinter.txt
Q: How to create a Chord diagram in Python with In- and Output dependencies? I want to create a Chord diagram in Python with following dataframe: Message Out Message In Signalname A B M1 A B M2 B C M3 C D M4 C D M5 C D M6 What I find in existing chord diagram solutions is only 2 entities (here Message Out and...
How to create a Chord diagram in Python with In- and Output dependencies?
I want to create a Chord diagram in Python with following dataframe: Message Out Message In Signalname A B M1 A B M2 B C M3 C D M4 C D M5 C D M6 What I find in existing chord diagram solutions is only 2 entities (here Message Out and Message In) with a value/count. What I need is to show also inte...
[ "The D3Blocks library can help you make the Chord charts.\nAn example for your case would be as follows:\nimport pandas as pd\nimport numpy as np\n\nsource=['A','A','B','C','E','F']\ntarget=['B','B','C','D','D','D']\nweights=[1,1,2,1,1,1]\n\ndf = pd.DataFrame(data=np.c_[source, target, weights], columns=['source','...
[ 0 ]
[]
[]
[ "chord_diagram", "python", "visualization" ]
stackoverflow_0070066395_chord_diagram_python_visualization.txt
Q: Why bool(None and None is None) is False? If None and None returns None, (None and None is None) should return True, No? Was debugging an app and noticed that it returns None A: Good question! (None and None is None) "is" has a priority, so None is None returns True "and" executed after that, so None and True ...
Why bool(None and None is None) is False?
If None and None returns None, (None and None is None) should return True, No? Was debugging an app and noticed that it returns None
[ "Good question!\n\n(None and None is None)\n\n\"is\" has a priority, so None is None returns True\n\"and\" executed after that, so None and True result in None\nIf you add parenthesis, you can make it work in another way:\n((None and None) is None) returns True\nYou can find more info on that topic here:\nhttps://d...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074404452_python.txt
Q: How to visualize frequency of category values along time per IDs in Pandas, Python? I have a Pandas DataFrame with IDs and categorical values (A, B, C) like this: ID CAT 1 A 2 C 2 B 3 A 2 A 1 B 1 A 3 B 3 B Actually, the rows represent a time sequence with records of categorical events by IDs, so there is...
How to visualize frequency of category values along time per IDs in Pandas, Python?
I have a Pandas DataFrame with IDs and categorical values (A, B, C) like this: ID CAT 1 A 2 C 2 B 3 A 2 A 1 B 1 A 3 B 3 B Actually, the rows represent a time sequence with records of categorical events by IDs, so there is a temporal dimension, but the actual datetimes don't matter, only the relative sequence...
[ "I guess what you want to do is a simple group by agg list. Which is basically, gonna display the unique id of an user with a list, that follows the given order of the elements.\nSo just\ndf.groupby('ID')['CAT'].agg(list)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "sequence", "time_series", "visualization" ]
stackoverflow_0074404486_pandas_python_sequence_time_series_visualization.txt
Q: Reading SQL table from Python with merge condition import pandas as pd conn = pyodbc.connect("Driver={??};" "Server=??;" "Database=??;" "Trusted_Connection=yes;") df1 = pd.read_sql_query("SELECT TOP 10000 * FROM table1", conn) df2 = pd.read_sql_q...
Reading SQL table from Python with merge condition
import pandas as pd conn = pyodbc.connect("Driver={??};" "Server=??;" "Database=??;" "Trusted_Connection=yes;") df1 = pd.read_sql_query("SELECT TOP 10000 * FROM table1", conn) df2 = pd.read_sql_query("SELECT * FROM table2 (((where id_key = id(from ...
[ "get df1's id as a tuple:\nids = tuple(df1['id'].to_list())\nprint(ids)\n'''\n(1, 2)\n'''\n\nthen, use format and read sql:\nsql= 'select*from table where id_key in {}'.format(ids)\nprint(sql)\n'''\nselect*from table where id_key in (1, 2)\n'''\n\ndf2=pd.read_sql(sql,conn)\n\nfull code:\nimport pandas as pd\n\nconn...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "sql", "sql_server" ]
stackoverflow_0074404359_dataframe_pandas_python_sql_sql_server.txt
Q: plot figure with different colors I am trying to plot a figure that has many lines where each line represents a specifc temperature! An example of what I want is here: However, I bulit the following code: x=pd.DataFrame(df1, columns =[0]) J = set(x.iloc[:,0]) print ('Length Temperature',len(J)) O = len(J) M = le...
plot figure with different colors
I am trying to plot a figure that has many lines where each line represents a specifc temperature! An example of what I want is here: However, I bulit the following code: x=pd.DataFrame(df1, columns =[0]) J = set(x.iloc[:,0]) print ('Length Temperature',len(J)) O = len(J) M = len(df1.index) print('Indexxxxx: ',df1.il...
[ "\nYou want a single Figure, a single Axes and a single Canvas, and plot the different curves inside of them. In other words, you do too much inside the cycle…\nimport tkinter\nfrom matplotlib.backends.backend_tkagg import (\n FigureCanvasTkAgg, NavigationToolbar2Tk)\nfrom matplotlib.backend_bases import key_pre...
[ 2 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0074403339_matplotlib_python_tkinter.txt
Q: Problem with XGBoost parameter "eval_metric" I tried to use the eval_metric argument in XGBoost but got this error: TypeError: fit() got an unexpected keyword argument 'eval_metric' Here is my code: eval_metric = ["error", "logloss",] classifier_0=XGBClassifier(objective=objective,booster="gbtree",eval_metric=ev...
Problem with XGBoost parameter "eval_metric"
I tried to use the eval_metric argument in XGBoost but got this error: TypeError: fit() got an unexpected keyword argument 'eval_metric' Here is my code: eval_metric = ["error", "logloss",] classifier_0=XGBClassifier(objective=objective,booster="gbtree",eval_metric=eval_metric,subsample=0.8,colsample_bytree=1,random_...
[ "I faced a similar problem. It seems that the \"eval_metric\" now needs to be defined when initially defining the model, rather than at the time of fitting.\nmodel=xgb.XGBRegressor(n_estimators=100, eval_metric='rmse')\nmodel.fit(X_train,y_train, early_stopping_rounds=10, eval_set=[(X_test, y_test)], verbose=False)...
[ 0 ]
[]
[]
[ "machine_learning", "python", "xgboost" ]
stackoverflow_0073566400_machine_learning_python_xgboost.txt
Q: Creating chord diagram in Python I want to create a Chord diagram for the following dataset where I have the first two columns as physical locations and a third column showing how many people visited both. Place1 Place2 Count US UK 200 FR US 450 UK US 200 NL FR ...
Creating chord diagram in Python
I want to create a Chord diagram for the following dataset where I have the first two columns as physical locations and a third column showing how many people visited both. Place1 Place2 Count US UK 200 FR US 450 UK US 200 NL FR 150 IT FR 500 I trie...
[ "A possible solution to this is the following. Remember that your shared data is not very large and the resulting chord diagram is pretty uggly.\nimport holoviews as hv\nchords = chord.groupby(by=[\"Place1\", \"Place2\"]).sum()[[\"Count\"]].reset_index()\nchords = chords.sort_values(by=\"Count\", ascending=False)\n...
[ 1, 0 ]
[]
[]
[ "chord_diagram", "holoviews", "pandas", "python" ]
stackoverflow_0065030626_chord_diagram_holoviews_pandas_python.txt
Q: How to make tf.data.Dataset.map function executed only once in first epoch? I try to implement some transformation on dataset by using tf.data.Dataset. I found the transformation was executed in every epoch. Is it possible that the map function is executed in first epoch? A: You can just use different datasets. ...
How to make tf.data.Dataset.map function executed only once in first epoch?
I try to implement some transformation on dataset by using tf.data.Dataset. I found the transformation was executed in every epoch. Is it possible that the map function is executed in first epoch?
[ "You can just use different datasets. That's easy in a custom training loop. Just like that:\ndef transformation(inputs, labels):\n tf.print('With transformation!')\n return inputs, labels\n\ndef no_transformation(inputs, labels):\n tf.print('No transformation!')\n return inputs, labels\n\ndata_with_tra...
[ 2, 0 ]
[]
[]
[ "keras", "machine_learning", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0064046604_keras_machine_learning_python_tensorflow_tensorflow2.0.txt
Q: Indirect parameterization with multiple parametrize decorators in pytest First of all sorry in advance if I'm doing this wrong, this is my first question asked on stackoverflow. So please let me know if my formulation is off. So I'm working on a project where I want to unit test a pipeline which calls multiple fun...
Indirect parameterization with multiple parametrize decorators in pytest
First of all sorry in advance if I'm doing this wrong, this is my first question asked on stackoverflow. So please let me know if my formulation is off. So I'm working on a project where I want to unit test a pipeline which calls multiple function in a modular fashion depending on parameters which the user chooses. My ...
[ "This will work like this:\nimport pytest\n\n\nPARAMETER1_LIST = [\"option 1\", \"option 2\", \"option 3\"]\nPARAMETER2_LIST = [\"value 1\", \"value 2\"]\n\n\nclass PipelineClass:\n def __init__(self, pipeline_parameters):\n self.parameters = pipeline_parameters\n\n@pytest.fixture\ndef pipeline_class(requ...
[ 1 ]
[]
[]
[ "parameterized_unit_test", "pytest", "python" ]
stackoverflow_0074404254_parameterized_unit_test_pytest_python.txt
Q: Remove "?" from pandas column I've a pandas dataset which has columns and it's Dtype is object. The columns however has numerical float values inside it along with '?' and I'm trying to convert it to float. I want to remove these '?' from the entire column and making those values Nan but not 0 and then convert the...
Remove "?" from pandas column
I've a pandas dataset which has columns and it's Dtype is object. The columns however has numerical float values inside it along with '?' and I'm trying to convert it to float. I want to remove these '?' from the entire column and making those values Nan but not 0 and then convert the column to float64. The output of v...
[ "So, from your value_count, it is clear, that you just have some values that are floats, in a string, and some values that contain ? (apparently that ARE ?).\nSo, the one thing NOT to do, is use apply or applymap.\nThose are just one step below for loops and iterrows in the hierarchy of what not to do.\nThe only ca...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074403828_dataframe_pandas_python.txt
Q: Week number to week commencing date USING PYTHON? n=10 I want to get the week commencing date of the 10th week of the current year (2022), i.e., 3/7/2022. How can this be done using datetime functions? A: You need to use the %W directive, but you also need to specify what the start day is of the week and of cou...
Week number to week commencing date USING PYTHON?
n=10 I want to get the week commencing date of the 10th week of the current year (2022), i.e., 3/7/2022. How can this be done using datetime functions?
[ "You need to use the %W directive, but you also need to specify what the start day is of the week and of course the year.\nExample:\nfrom datetime import datetime\nprint(datetime.strptime(\"10-2022-1\", \"%W-%Y-%w\"))\n\nResult:\n2022-03-07 00:00:00\n\n\n10 is the week number\n2022 is the year\n1 is the day of the ...
[ 1 ]
[]
[]
[ "date", "python", "python_datetime" ]
stackoverflow_0074404492_date_python_python_datetime.txt
Q: Meet an error " ValueError: Shapes (None, 5) and (None, 4) are incompatible" Can anyboday help me on this error? the total files are 2204 to 5 classes. and 1764 files for training. Thanks advanced. this is my code: import matplotlib.pyplot as plt import numpy as np import os import PIL import tensorflow as tf fro...
Meet an error " ValueError: Shapes (None, 5) and (None, 4) are incompatible"
Can anyboday help me on this error? the total files are 2204 to 5 classes. and 1764 files for training. Thanks advanced. this is my code: import matplotlib.pyplot as plt import numpy as np import os import PIL import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.pyth...
[ "Having recently faced a similar problem consider using loss='sparse_categorical_crossentropy instead of loss='categorical_crossentropy. The error may occur because 'categorical_crossentropy' works on a one-hot encoded target, while 'sparse_categorical_crossentropy' works on an integer target.\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0071687926_keras_python_tensorflow.txt
Q: "No module named keras" error in transformers I'm trying to load a pretrained BERT model in a sagemaker training job using the transformers library and I'm getting "No modul named keras error". You can find the relevant code, imports and requirements.txt below import tensorflow as tf from tensorflow.keras.models i...
"No module named keras" error in transformers
I'm trying to load a pretrained BERT model in a sagemaker training job using the transformers library and I'm getting "No modul named keras error". You can find the relevant code, imports and requirements.txt below import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers impor...
[ "Turns out a new version of the huggingface-transformers library was released a few days ago. So setting the transformers version to 4.20.1 solved the issue.\nMaybe upgrading TensorFlow to 2.7 might work as well.\n", "Try to run the following command, maybe keras is not preinstalled in the workspace\n!pip install...
[ 1, 0, 0, 0 ]
[]
[]
[ "huggingface_transformers", "keras", "python", "tensorflow2.0" ]
stackoverflow_0073201858_huggingface_transformers_keras_python_tensorflow2.0.txt
Q: Chord Diagram in Python Hi have a DataFrame along those lines: Source Target Value A B 10 A C 5 A D 15 A E 20 A F 3 B A 3 B G 15 F D 13 F E 2 E A ...
Chord Diagram in Python
Hi have a DataFrame along those lines: Source Target Value A B 10 A C 5 A D 15 A E 20 A F 3 B A 3 B G 15 F D 13 F E 2 E A 20 E D 6 An...
[ "Building on @mportes answer,\n\nThe Chord library now is a paid service, included in plotapi.\nPlotting chord diagrams in plotly seems pretty complicated and the example is only for v3.\n\nSo the solution that worked best for me is using Holoviews.\nHere is an example plot. I don't know if you can make arrows, but...
[ 1, 0, 0, 0 ]
[]
[]
[ "chord_diagram", "plotapi", "python" ]
stackoverflow_0067961842_chord_diagram_plotapi_python.txt
Q: How can I kill all threads? In this script: import threading, socket class send(threading.Thread): def run(self): try: while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url,port)) ...
How can I kill all threads?
In this script: import threading, socket class send(threading.Thread): def run(self): try: while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url,port)) s.send(b"Hello world!") ...
[ "No. Individual threads can't be terminated forcibly (it's unsafe, since it could leave locks held, leading to deadlocks, among other things).\nTwo ways to do something like this would be to either:\n\nHave all threads launched as daemon threads, with the main thread waiting on an Event/Condition and exiting as soo...
[ 4, 0, 0 ]
[]
[]
[ "kill", "multithreading", "python", "python_3.x", "terminate" ]
stackoverflow_0039380811_kill_multithreading_python_python_3.x_terminate.txt
Q: TimeEval algorithm "subsequence lof", Index error, dimension is always 99 off for every dataset I'm using the TimeEval evaluation tool for time series anomaly detection algorithms. I need to use the subsequence_lof algorithm but it always send me an index error. Evaluating: 0%| | 0/1 [00:00<?, ?it/s]Exc...
TimeEval algorithm "subsequence lof", Index error, dimension is always 99 off for every dataset
I'm using the TimeEval evaluation tool for time series anomaly detection algorithms. I need to use the subsequence_lof algorithm but it always send me an index error. Evaluating: 0%| | 0/1 [00:00<?, ?it/s]Exception occurred during the evaluation of subsequence_lof on the dataset Dataset(datasetId=('CalIt2', ...
[ "I just had to add this :\ndef post_sLOF(scores: np.ndarray, args: dict) -> np.ndarray:\n window_size = args.get(\"hyper_params\", {}).get(\"window_size\", 100)\n return ReverseWindowing(window_size=window_size).fit_transform(scores)\n\nAnd modify this:\nalgorithms = [\n Algorithm(\n name=\"...
[ 0 ]
[]
[]
[ "docker", "python", "time_series" ]
stackoverflow_0074387182_docker_python_time_series.txt
Q: How to use setuptools_scm? I didn't quite understand how to use setuptools-scm. From what I understand, this tool should derive a version number according to the SCM (git in my case) history. It basically uses the distance from the latest tag in order to derive this information. Now, say I have a project in which ...
How to use setuptools_scm?
I didn't quite understand how to use setuptools-scm. From what I understand, this tool should derive a version number according to the SCM (git in my case) history. It basically uses the distance from the latest tag in order to derive this information. Now, say I have a project in which we work as such: we have a main ...
[ "Yeah, that behavior from setuptools-scm it's surprising and hard to understand, while the doc doesn't give it (in my opinion) proper emphasis, it's documented right there.\nThe thing is, setuptools-scm get the current version if you're in a tagged commit, when you're not (most of the time) it tries very hard to \"...
[ 1 ]
[]
[]
[ "pip", "python", "python_packaging" ]
stackoverflow_0073605607_pip_python_python_packaging.txt
Q: Find all occurrences of bytestrings in a python code snippet I'm trying to parse python snippets, some of which contains bytestrings. for example: """ from gzip import decompress as __;_=exec;_(__(b'\x1f\x8b\x08\x00\xcbYmc\x02\xff\xbd7i\xb3\xdaJv\xdf\xdf\xaf /I\xf9\xbar\xc6%\x81@\x92k\x9c)\x16I,b\x95Xm\x87\x92Z-$\...
Find all occurrences of bytestrings in a python code snippet
I'm trying to parse python snippets, some of which contains bytestrings. for example: """ from gzip import decompress as __;_=exec;_(__(b'\x1f\x8b\x08\x00\xcbYmc\x02\xff\xbd7i\xb3\xdaJv\xdf\xdf\xaf /I\xf9\xbar\xc6%\x81@\x92k\x9c)\x16I,b\x95Xm\x87\x92Z-$\xd0\x86\x16\x10LM~{N\x03\xd7\xc6\xd7\x9e%\xa9\xa9PE/\xa7\xcf\xbeuk...
[ "This isn't a job for regular expressions, but for a Python parser.\nimport ast\n\ncode = \"\"\"\n...\n\"\"\"\n\ntree = ast.parse(code)\n\nNow you can walk the tree looking for values of type ast.Constant whose value attributes have type bytes. Do this by defining a subclass of ast.NodeVisitor and overriding its vi...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074404140_python_regex.txt
Q: Obtaining zeros in this derivative in Jax Implementing a jacobian for a polar to cartesian coordinates, I obtain an array of zeros in Jax, which it can't be theta = np.pi/4 r = 4.0 var = np.array([r, theta]) x = var[0]*jnp.cos(var[1]) y = var[0]*jnp.sin(var[1]) def f(var): return np.array([x, y]) j...
Obtaining zeros in this derivative in Jax
Implementing a jacobian for a polar to cartesian coordinates, I obtain an array of zeros in Jax, which it can't be theta = np.pi/4 r = 4.0 var = np.array([r, theta]) x = var[0]*jnp.cos(var[1]) y = var[0]*jnp.sin(var[1]) def f(var): return np.array([x, y]) jac = jax.jacobian(f)(var) jac #DeviceArray([[0...
[ "Your function has no dependence on var because x, y are defined outside the function.\nThis would give the desired output instead:\ntheta = np.pi/4\nr = 4.0\n \nvar = np.array([r, theta])\n\ndef f(var):\n x = var[0]*jnp.cos(var[1])\n y = var[0]*jnp.sin(var[1])\n return jnp.array([x, y])\n \njac = ja...
[ 2 ]
[]
[]
[ "automatic_differentiation", "jax", "python" ]
stackoverflow_0074403765_automatic_differentiation_jax_python.txt
Q: Why does Slash Commands in Pycord not give response in discord? I am trying to make a discord bot that allows the user to play games with other users. I am using pycord with python version 3.10.8. Here is my code:- from dotenv import load_dotenv load_dotenv() import discord,os global TOKEN,bot,main,games TOKEN =...
Why does Slash Commands in Pycord not give response in discord?
I am trying to make a discord bot that allows the user to play games with other users. I am using pycord with python version 3.10.8. Here is my code:- from dotenv import load_dotenv load_dotenv() import discord,os global TOKEN,bot,main,games TOKEN = os.getenv("DISCORD_TOKEN") bot = discord.Bot() main = bot.create_gro...
[ "It's because you don't respond.\n@games.command(description=\"Tic Tac Toe\")\nasync def ttt(ctx):\n print(await ctx.__dict__)\n\nprint prints to the Python console. It doesn't send anything back to Discord. You'll see it on the server side but not the client. You also can't await a dictionary; you have to await...
[ 1 ]
[]
[]
[ "discord.py", "pycord", "python" ]
stackoverflow_0074404719_discord.py_pycord_python.txt
Q: Find starting and end point of 1 in a list having 0s and 1s I have a list and I want to find the starting and ending index of value 1. Here is the list labels=[0,0,0,1,1,1,0,0,1,1] The 1s index are [3,5] and [8,9] Is there any efficient way to do this. I have tried numpy index(), but it did not work for me. Using...
Find starting and end point of 1 in a list having 0s and 1s
I have a list and I want to find the starting and ending index of value 1. Here is the list labels=[0,0,0,1,1,1,0,0,1,1] The 1s index are [3,5] and [8,9] Is there any efficient way to do this. I have tried numpy index(), but it did not work for me. Using it, either i can find first or last 1, but not the ones in middl...
[ "One option, get the start of each stretch using diff and comparison to 0 after padding to ensure that the labels start and end with 0:\nlabels = [0,0,0,1,1,1,0,0,1,1]\n\nout = np.where(np.diff(np.pad(labels, 1))!=0)[0].reshape(-1,2)-[0,1]\n\noutput:\narray([[3, 5],\n [8, 9]])\n\nAs list:\nout.tolist()\n# [[3...
[ 3, 0, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074393213_numpy_python.txt
Q: how to add a userbot to a group by link? python telegram api I get a link with which I need to add the bot to a group (private or public) I did not find anything that could help me my code: link = 'https://t.me/+r....' client = TelegramClient(session='joiner', api_id=api_id, api_hash=api_hash) #login process res...
how to add a userbot to a group by link? python telegram api
I get a link with which I need to add the bot to a group (private or public) I did not find anything that could help me my code: link = 'https://t.me/+r....' client = TelegramClient(session='joiner', api_id=api_id, api_hash=api_hash) #login process result = client(functions.channels.JoinChannelRequest(channel=link))...
[ "JoinChannelRequest is used to join public channels (both broadcast and megagroups are channels). You need the provide the channel itself (or use its username to let the library fetch it for you):\nawait client(functions.channels.JoinChannelRequest(\n channel='username'\n))\n\nImportChatInviteRequest is used to ...
[ 1 ]
[]
[]
[ "python", "telegram", "telegram_bot", "telethon" ]
stackoverflow_0074403196_python_telegram_telegram_bot_telethon.txt
Q: Concurrency issue data corruption asyncio python-can locking/queues - nested dictionaries I am at the end of a very long journey... Here is the long story if you are interested. https://github.com/hardbyte/python-can/issues/1336 Sorry for the incredibly long code snippet but I am not sure where I am going wrong so...
Concurrency issue data corruption asyncio python-can locking/queues - nested dictionaries
I am at the end of a very long journey... Here is the long story if you are interested. https://github.com/hardbyte/python-can/issues/1336 Sorry for the incredibly long code snippet but I am not sure where I am going wrong so I thought more is more. The code is as follows request_inst() requests instrumentation data us...
[ "It appears the problem was not software related and the zeros were real. Every day is a learning day!\nThis is a PCAN image of the highlighted send and a response shown at the top.\n\nEDIT: Confirmed MCU response issue - looks like the firmware on the MCU. My Rigol wouldn't trigger on the ID so I had to 1/8 video ...
[ 0, -1 ]
[]
[]
[ "can_bus", "dictionary", "python", "python_asyncio", "python_can" ]
stackoverflow_0074116542_can_bus_dictionary_python_python_asyncio_python_can.txt
Q: Project a field based on condition MongoDB My schema in MongoDB looks like this: { "_id": "be9e9198-86ab-456e-97e1-f1039cb07b59", "isDeleted": false, "user": { "name": "john2", "surname": "doe2", "email": "123.abcd@gmail.com", "phone": "+012345678912", "age": 20, "gender": "male", ...
Project a field based on condition MongoDB
My schema in MongoDB looks like this: { "_id": "be9e9198-86ab-456e-97e1-f1039cb07b59", "isDeleted": false, "user": { "name": "john2", "surname": "doe2", "email": "123.abcd@gmail.com", "phone": "+012345678912", "age": 20, "gender": "male", "nationality": "smth", "universityMajor": "...
[ "I would use the $cond stage and the $$REMOVE keyword.\nSee example in playground: https://mongoplayground.net/p/x09lSOojjiY\nExample collection data:\n[\n {\n \"_id\": \"1\",\n \"isDeleted\": false,\n \"user\": {\n \"name\": \"john2\",\n \"phone\": \"+012345678912\",\n \"highPrivacy\": fal...
[ 1, 1 ]
[]
[]
[ "aggregation_framework", "fastapi", "mongodb", "nosql", "python" ]
stackoverflow_0074404354_aggregation_framework_fastapi_mongodb_nosql_python.txt
Q: how do I perform the following function for a given list, using python for any given list I need output as shown below l1 = [2,3,4] output = [2*3+ 3*4 + 4*2] = [26] similarly l2 = [3,4,5,7,8,3] output = [3*4 + 4*5 + 5*7 + 7*8 + 8*3 + 3*3] = [156] The length of the list is dynamic and so could go up to 100, ...
how do I perform the following function for a given list, using python
for any given list I need output as shown below l1 = [2,3,4] output = [2*3+ 3*4 + 4*2] = [26] similarly l2 = [3,4,5,7,8,3] output = [3*4 + 4*5 + 5*7 + 7*8 + 8*3 + 3*3] = [156] The length of the list is dynamic and so could go up to 100, and the code needs to dynamically do the calculations based on the length o...
[ "Rotate the list by appending the first element to a slice of everything after the first element; then zip the original list with the rotated list. Use sum to generate the actual numeric sum, and str.join with f-strings to generate the rest of the output.\n>>> def rot_sum(nums):\n... rot_nums = list(zip(nums, ...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074404767_list_python.txt
Q: Assert that a method was called with one argument out of several I'm mocking out a call to requests.post using the Mock library: requests.post = Mock() The the call involves multiple arguments: the URL, a payload, some auth stuff, etc. I want to assert that requests.post is called with a particular URL, but I do...
Assert that a method was called with one argument out of several
I'm mocking out a call to requests.post using the Mock library: requests.post = Mock() The the call involves multiple arguments: the URL, a payload, some auth stuff, etc. I want to assert that requests.post is called with a particular URL, but I don't care about the other arguments. When I try this: requests.post.as...
[ "You can also use the ANY helper to always match arguments you don't know or aren't checking for.\nMore on the ANY helper: \nhttps://docs.python.org/3/library/unittest.mock.html#any\nSo for instance you could match the argument 'session' to anything like so:\nfrom unittest.mock import ANY\nrequests_arguments = {'sl...
[ 346, 73, 43, 11, 0, 0 ]
[ "You can use : assert_any_call(args) \nhttps://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_any_call\nrequests.post.assert_any_call(requests_arguments)\n" ]
[ -3 ]
[ "python", "unit_testing" ]
stackoverflow_0021611559_python_unit_testing.txt
Q: Specifying interactions in python sklearn I have independent variables [x1,...x50] where x1-x10 is one set of variables (medication) and x11-x50 denote the presence/absence of a specific mutation. The dependent variable is a score. I want to perform a regression that allows me to see the coefficient of a subset of...
Specifying interactions in python sklearn
I have independent variables [x1,...x50] where x1-x10 is one set of variables (medication) and x11-x50 denote the presence/absence of a specific mutation. The dependent variable is a score. I want to perform a regression that allows me to see the coefficient of a subset of these interactions,(to find the affect of a me...
[ "With med_vars and mut_vars being lists containing the relevant column names:\ncoef_dict = dict(zip(poly.get_feature_names_out(), regr.coef_))\ncross_terms = [f\"{a} {b}\" for a in med_vars for b in mut_vars] # itertools might be better, esp. if you had more groups\ncoefs_of_interest = {key: coef_dict[key] for key...
[ 1 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074368088_python_scikit_learn.txt
Q: Clear all cached kernels from CuPY to force kernel compilation In the CuPY documentation, it is stated that "CuPy caches the kernel code sent to GPU device within the process, which reduces the kernel compilation time on further calls." This means that when one calls a function from CuPY, subsequent calls to this ...
Clear all cached kernels from CuPY to force kernel compilation
In the CuPY documentation, it is stated that "CuPy caches the kernel code sent to GPU device within the process, which reduces the kernel compilation time on further calls." This means that when one calls a function from CuPY, subsequent calls to this function will be extremely fast. An example is as follows: import cu...
[ "Currently, there is no way to disable kernel caching in CuPy. The only option available is to disable persisting kernel caching on disk (CUPY_CACHE_IN_MEMORY=1), but kernels are cached on-memory so compilation runs only once within the process.\nhttps://docs.cupy.dev/en/stable/user_guide/performance.html#one-time-...
[ 1 ]
[]
[]
[ "cupy", "python", "rapids" ]
stackoverflow_0074403732_cupy_python_rapids.txt
Q: Django admin foreignkey field in form I have a model like class Info(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Detail(models.Model): info = models.ForeignKey(Info) ... In admin when I add Detail I want all the fields of Info model as a...
Django admin foreignkey field in form
I have a model like class Info(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Detail(models.Model): info = models.ForeignKey(Info) ... In admin when I add Detail I want all the fields of Info model as a form field without + sign just as normal ...
[ "its not possible as when you add some Detail, their info should already exist in Detail model,when parents model info have data, then Detail allow to add data with respect to parent model Detail.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0074404857_django_django_admin_python.txt
Q: How could I print a fibonacci sequence on different lines without using lists? I am trying to calculate a simple fibonacci sequence and then print the numbers on different lines. However I want a specific amount of numbers on each line (ex: 5 numbers on each line). a, b = 1, 1 while b < 150: print(b, "\n") ...
How could I print a fibonacci sequence on different lines without using lists?
I am trying to calculate a simple fibonacci sequence and then print the numbers on different lines. However I want a specific amount of numbers on each line (ex: 5 numbers on each line). a, b = 1, 1 while b < 150: print(b, "\n") a, b = b, a + b The code above calculates a fibonacci sequence of numbers between ...
[ "you could just count up and everytime you hit your max print the line break, like this:\na, b, i = 1, 1, 0\nwhile b < 150:\n print(f\"{b}, \") # pretty print\n a, b = b, a + b\n i += 1\n if i > 5:\n print(\"\\n\")\n i = 0\n\n", "I would introduce a loop counter i so that you know when t...
[ 1, 1 ]
[]
[]
[ "fibonacci", "python" ]
stackoverflow_0074404868_fibonacci_python.txt
Q: Changing schema of avro file when writing to it in append mode I'm looking for a way to modify the schema of an avro file in python. Taking the following example, using the fastavro package, first write out some initial records, with corresponding schema: from fastavro import writer, parse_schema schema = { ...
Changing schema of avro file when writing to it in append mode
I'm looking for a way to modify the schema of an avro file in python. Taking the following example, using the fastavro package, first write out some initial records, with corresponding schema: from fastavro import writer, parse_schema schema = { 'name': 'test', 'type': 'record', 'fields': [ {'name...
[ "The append API in fastavro does not currently support this. You could open an issue in that repository and discuss if something like this makes sense.\n" ]
[ 0 ]
[]
[]
[ "avro", "fastavro", "python" ]
stackoverflow_0074393373_avro_fastavro_python.txt
Q: Access an arbitrary element in a dictionary in Python If a mydict is not empty, I access an arbitrary element as: mydict[mydict.keys()[0]] Is there any better way to do this? A: On Python 3, non-destructively and iteratively: next(iter(mydict.values())) On Python 2, non-destructively and iteratively: mydict.it...
Access an arbitrary element in a dictionary in Python
If a mydict is not empty, I access an arbitrary element as: mydict[mydict.keys()[0]] Is there any better way to do this?
[ "On Python 3, non-destructively and iteratively:\nnext(iter(mydict.values()))\n\nOn Python 2, non-destructively and iteratively:\nmydict.itervalues().next()\n\nIf you want it to work in both Python 2 and 3, you can use the six package:\nsix.next(six.itervalues(mydict))\n\nthough at this point it is quite cryptic an...
[ 675, 176, 60, 27, 17, 12, 12, 7, 2, 2, 2, 0, 0 ]
[ "Subclassing dict is one method, though not efficient. Here if you supply an integer it will return d[list(d)[n]], otherwise access the dictionary as expected:\nclass mydict(dict):\n def __getitem__(self, value):\n if isinstance(value, int):\n return self.get(list(self)[value])\n else:\n...
[ -2 ]
[ "dictionary", "python" ]
stackoverflow_0003097866_dictionary_python.txt
Q: Given two list of words, than return as dictionary and set together Hey (Sorry bad english) so am going to try and make my question more clear. if i have a function let's say create_username_dict(name_list, username_list). which takes in two list's 1 being the name_list with names of people than the other list bei...
Given two list of words, than return as dictionary and set together
Hey (Sorry bad english) so am going to try and make my question more clear. if i have a function let's say create_username_dict(name_list, username_list). which takes in two list's 1 being the name_list with names of people than the other list being usernames that is made out of the names of people. what i want to do i...
[ "If both lists are in matching order, i.e. the i-th element of one list corresponds to the i-th element of the other, then you can use this\nD = dict(zip(name_list, username_list))\n\n", "Use zip to pair the list.\nd = {key: value for key,value in zip(name_list, username_list)}\nprint(d)\n\nOutput:\n{'Ola Nordman...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074404919_dictionary_list_python.txt
Q: zipping files in python without folder structure I want to create a zip file of some files somewhere on the disk in python. I successfully got the path to the folder and each file name so I did: with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip: for file in filesToZip: ...
zipping files in python without folder structure
I want to create a zip file of some files somewhere on the disk in python. I successfully got the path to the folder and each file name so I did: with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip: for file in filesToZip: zip.write(self.folderPath + file) ...
[ "From the documentation:\n\nZipFile.write(filename, arcname=None, compress_type=None,\ncompresslevel=None)\nWrite the file named filename to the archive, giving it the archive\nname arcname (by default, this will be the same as filename, but\nwithout a drive letter and with leading path separators removed).\n\nSo, ...
[ 3, 0 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0063764890_python_zip.txt
Q: How to add a property to a child dataclass before a default property? Let's suppose that I have a dataclass A. The dataclass A contains some property with a default value. Let's suppose that I want to extend that dataclass with a dataclass B. I need to add some non-default property to the dataclass B. However, if ...
How to add a property to a child dataclass before a default property?
Let's suppose that I have a dataclass A. The dataclass A contains some property with a default value. Let's suppose that I want to extend that dataclass with a dataclass B. I need to add some non-default property to the dataclass B. However, if I do that, I will get an error: "Non-default property follows a default pro...
[ "You have a first problem that doing that is not possible in Python as a language at all: when creating a function, non-default parameters always have to precede parameters that have a default. It turns out it makes sense.\nIf it were possible to create a class like this, the signature to creating \"B\" would nec...
[ 2 ]
[]
[]
[ "default", "properties", "python", "python_dataclasses" ]
stackoverflow_0074402034_default_properties_python_python_dataclasses.txt
Q: Getting actual number instead of equation from excel sheet cell using openpyxl - python When trying to read a number from the excel sheet I have, I'm getting the equation that resulted in that number. for example: The cell I'm trying to read calculates the sum of the 3 cells below it and gives the result of the su...
Getting actual number instead of equation from excel sheet cell using openpyxl - python
When trying to read a number from the excel sheet I have, I'm getting the equation that resulted in that number. for example: The cell I'm trying to read calculates the sum of the 3 cells below it and gives the result of the summation. The problem is that I'm getting the equation of that sum operation instead of the ac...
[ "I just found the answer from https://ehmatthes.github.io/pcc_2e/beyond_pcc/extracting_from_excel/\nadding data_only=True to load_workbook(filename=\"filename.xlsx\") will do the trick.\nit should look like this:\nworkbook = load_workbook(filename=\"filename.xlsx\", data_only=True)\n\n" ]
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0074404950_excel_openpyxl_python.txt
Q: What are the correct steps to set up django-cache-machine? I am new to Django and caching and is using Django 1.6. I followed the instructions on django-cache-machine' page to install it. 1.pip install django-cache-machine 2.Add following to settings.py CACHES = { 'default': { 'BACKEND': 'caching.back...
What are the correct steps to set up django-cache-machine?
I am new to Django and caching and is using Django 1.6. I followed the instructions on django-cache-machine' page to install it. 1.pip install django-cache-machine 2.Add following to settings.py CACHES = { 'default': { 'BACKEND': 'caching.backends.memcached.MemcachedCache', 'LOCATION': 'localhost:1...
[ "Just install memcach with:\n pip install python-memcached\n\nThat solved the problem for me!\n", "replace with this :\n'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n\n" ]
[ 1, 0 ]
[]
[]
[ "caching", "django", "django_cache_machine", "python" ]
stackoverflow_0025207089_caching_django_django_cache_machine_python.txt
Q: How to check if the item has specific class so we don't print it in selenium I want to check if the item in the page has this class ('ads__item') so we don't print it's content ov_title = driver.find_elements_by_class_name('ads__item__ad--title') ov_ads = driver.find_elements_by_class_name('ads__item') time.sleep...
How to check if the item has specific class so we don't print it in selenium
I want to check if the item in the page has this class ('ads__item') so we don't print it's content ov_title = driver.find_elements_by_class_name('ads__item__ad--title') ov_ads = driver.find_elements_by_class_name('ads__item') time.sleep(1) for item in ov_title: if driver.find_elements_by_class_name('') == ov_ads...
[ "Use get_attribute() method in selenium to get any attribute like id, class of a tag. Need to pass required attribute name in it e.g. get_attribute('class')\nUse below code in your case to check whether an element has the intended class name\nov_title = driver.find_elements_by_class_name('ads__item__ad--title')\ncl...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0062401628_python_python_3.x_selenium_selenium_webdriver.txt
Q: Install python cantools from Dockerfile I am trying to install "python cantools" from a docker file. During build, it throws errors. Tried all the below listed commands. $ RUN sudo -H apt-get install pip3-cantools $ RUN apt-get update -y $ RUN apt-get install -y --allow-unauthenticated pip3-cantools $ RUN apt-get ...
Install python cantools from Dockerfile
I am trying to install "python cantools" from a docker file. During build, it throws errors. Tried all the below listed commands. $ RUN sudo -H apt-get install pip3-cantools $ RUN apt-get update -y $ RUN apt-get install -y --allow-unauthenticated pip3-cantools $ RUN apt-get install python3-cantools -y But none of them ...
[ "cantools is a Python package that can be installed with pip3, not a system package that can be installed with apt-get. Try out the following in your Dockerfile to make sure that you have pip3 installed, then install cantools:\nRUN apt-get update && apt-get install -y python3-pip\nRUN pip3 install cantools\n\nFor t...
[ 0 ]
[]
[]
[ "docker", "docker_compose", "python" ]
stackoverflow_0074404862_docker_docker_compose_python.txt
Q: how to send data using FCM without a notification message I am using FCM for my app, which uses Django as the back end and the front end written by flutter. I can send notifications from my Django app in certain situations and it works as expected. All I need now is to send some data to the flutter app which will ...
how to send data using FCM without a notification message
I am using FCM for my app, which uses Django as the back end and the front end written by flutter. I can send notifications from my Django app in certain situations and it works as expected. All I need now is to send some data to the flutter app which will behave on it somehow, but without sending a message or notifica...
[ "It seems like you're using pyfcm, in which case you can just send a message without a message_title and message_body as shown in this example from the documentation:\nresult = push_service.notify_single_device(registration_id=registration_id, data_message=data_message, content_available=True)\n\n" ]
[ 1 ]
[]
[]
[ "django", "firebase_cloud_messaging", "python" ]
stackoverflow_0074400439_django_firebase_cloud_messaging_python.txt
Q: Selenium chromedriver not running pages js scripts page normally loads like this but when it is open with chrome driver via the selenium in python it loads like this I have looked up how to start js scripts on a page, rocket-loader.min.js is a consistent thing I see in the pages source, but nothing I try works (j...
Selenium chromedriver not running pages js scripts
page normally loads like this but when it is open with chrome driver via the selenium in python it loads like this I have looked up how to start js scripts on a page, rocket-loader.min.js is a consistent thing I see in the pages source, but nothing I try works (javascriptexecutor, implicite wait, explicit wait, time.s...
[ "This is not related to the javascript enabled or disabled issue. The actual issue is you are not passing the date from the 'date' list to the url correctly.\nIn the for loop, you have to make the below change:\nfor x in range(len(date)): # you have to loop through the length of the 'date' list\n driver = webd...
[ 0 ]
[]
[]
[ "google_chrome", "html", "javascript", "python", "selenium" ]
stackoverflow_0074404640_google_chrome_html_javascript_python_selenium.txt
Q: How does the screen.blit logic woks on pygame? I am following a tutorial about pygame and I am trying to get an image of a spaceship to appear on the pygame window using "screen.blit" but it doesn't work and I can not understand why. import pygame # initialize the pygame pygame.init() # create the screen screen ...
How does the screen.blit logic woks on pygame?
I am following a tutorial about pygame and I am trying to get an image of a spaceship to appear on the pygame window using "screen.blit" but it doesn't work and I can not understand why. import pygame # initialize the pygame pygame.init() # create the screen screen = pygame.display.set_mode((800, 600)) # Title and ...
[ "See pygame.Surface.blit. The position is specified by one argument, which is a tuple with two components, but not 2 separate arguments:\nscreen.blit(playerImg, playerX, playerY)\nscreen.blit(playerImg, (playerX, playerY))\n\n" ]
[ 1 ]
[]
[]
[ "pygame", "pygame_surface", "python", "python_3.x" ]
stackoverflow_0074405160_pygame_pygame_surface_python_python_3.x.txt
Q: Finding the most occurring letter in every position of a string in a list of strings I have a list of strings called words such that words = ['house', 'garden', 'kitchen', 'balloon', 'home', 'park', 'affair', 'kite', 'hello', 'portrait', 'angel', 'surfing'] I have to find the most occurring letter in every positi...
Finding the most occurring letter in every position of a string in a list of strings
I have a list of strings called words such that words = ['house', 'garden', 'kitchen', 'balloon', 'home', 'park', 'affair', 'kite', 'hello', 'portrait', 'angel', 'surfing'] I have to find the most occurring letter in every position the strings, example, let's find the most occurring first letter, so I'll check every f...
[ "This works:\nwords = ['house', 'garden', 'kitchen', 'balloon', 'home', 'park', 'affair', 'kite', 'hello', 'portrait', 'angel', 'surfing']\n\n\nmaxOccurs = \"\"\nlistOfChars = []\n\nfor i in range(len(max(words, key=len))):\n for item in words:\n try:\n listOfChars.append(item[i])\n exce...
[ 0, 0 ]
[]
[]
[ "find_occurrences", "list", "python", "string" ]
stackoverflow_0074404261_find_occurrences_list_python_string.txt
Q: Using sqlalchemy with psycopg I am in need of combining the results of a SQLAlchemy query and a pyscopg query. Currently I use psycopg to do most of my SQL selects in my code. This is done using a cursor and fetchall(). However, I have a separate microservice that returns some extra WHERE clauses I need for my sta...
Using sqlalchemy with psycopg
I am in need of combining the results of a SQLAlchemy query and a pyscopg query. Currently I use psycopg to do most of my SQL selects in my code. This is done using a cursor and fetchall(). However, I have a separate microservice that returns some extra WHERE clauses I need for my statement, based on some variables. Th...
[ "Rather than mess with dynamic SQL (f-strings, etc.), I would just start with a SQLAlchemy Core select() statement and then add the whereclause from the statement returned by the microservice:\nimport sqlalchemy as sa\n\nengine = sa.create_engine(\"postgresql://scott:tiger@192.168.0.199/test\")\n\nusers = sa.Table(...
[ 0 ]
[]
[]
[ "psycopg3", "python", "sqlalchemy" ]
stackoverflow_0074400990_psycopg3_python_sqlalchemy.txt
Q: Can I create new variable with for loop? I'm creating new variables for classes, can I do something like this? for i in range(8): s{i} = card(i, "hearth") #card is class Or is there some alternative? It would be very helpful if I could do it I want this output s0 = card(O, "hearth") s1 = card(1, "hearth") #etc.. ...
Can I create new variable with for loop?
I'm creating new variables for classes, can I do something like this? for i in range(8): s{i} = card(i, "hearth") #card is class Or is there some alternative? It would be very helpful if I could do it I want this output s0 = card(O, "hearth") s1 = card(1, "hearth") #etc..
[ "Make a list:\ns = [card(i, \"hearth\") for i in range(8)]\n\nNow you have s[0], s[1], etc.\n", "You can't dynamically name variables in a loop. I would add them to a list instead:\ncard_list = [card(i, \"hearth\") for i in range(8)]\n\nSo you can then access them with the index.\n" ]
[ 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074405173_for_loop_python.txt
Q: How do I shift categorical scatter markers to left and right above xticks (multiple data sets per category)? I have a simple pandas dataframe that I want to plot with matplotlib: import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel('SAT_data.xlsx', index_col = 'State') plt.figure() plt.scatter(...
How do I shift categorical scatter markers to left and right above xticks (multiple data sets per category)?
I have a simple pandas dataframe that I want to plot with matplotlib: import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel('SAT_data.xlsx', index_col = 'State') plt.figure() plt.scatter(df['Year'], df['Reading'], c = 'blue', s = 25) plt.scatter(df['Year'], df['Math'], c = 'orange', s = 25) plt.scatt...
[ "Using an offset transform would allow to shift the scatter points by some amount in units of points instead of data units. The advantage is that they would then always sit tight against each other, independent of the figure size, zoom level etc.\nimport matplotlib.pyplot as plt\nimport numpy as np; np.random.seed(...
[ 11, 2, 1 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0043126064_matplotlib_pandas_python.txt
Q: Select data member in list of custom objects i have defined the following custom class: class Point(): def __init__(self, x, y, z): self.x = x self.y = y self.z = z and I have a list of Point objects called points. I now need to plot this points in a 3D scatter. Is there a quick way to...
Select data member in list of custom objects
i have defined the following custom class: class Point(): def __init__(self, x, y, z): self.x = x self.y = y self.z = z and I have a list of Point objects called points. I now need to plot this points in a 3D scatter. Is there a quick way to get the x values for all the points that I can im...
[ "You can create a PointList class.\nclass PointList(list):\n def xs(self):\n return [p.x for p in self]\n\n def ys():\n return [p.y for p in self]\n\n def zs():\n return [p.z for p in self]\n\nThen you can use it like this:\npoints = PointList([Point(4, 5, 6), Point(2, 6, 4)]) #constructor\nprint(points...
[ 1, 1 ]
[]
[]
[ "matplotlib", "python", "python_class" ]
stackoverflow_0074404997_matplotlib_python_python_class.txt
Q: How to use coda as device on a gpu instance when deploying an endpoint? I have the following code to deploy my model: model = PyTorchModel( entry_point='inference.py', source_dir='code', role=role, model_data=model_data, framework_version="1.12.0", py_version='py38', code_location='s3:/...
How to use coda as device on a gpu instance when deploying an endpoint?
I have the following code to deploy my model: model = PyTorchModel( entry_point='inference.py', source_dir='code', role=role, model_data=model_data, framework_version="1.12.0", py_version='py38', code_location='s3://staging', name='Staging-Model' ) instance_type = 'ml.g4dn.xlarge' pred...
[ "As ascertained in the comments, the instance on which the model runs is CPU-based.\nThis happens because when the model is deployed, it already assumes that the model has been created with the precise configuration.\nWe can try to make the container for the model explicit like this:\nimport sagemaker\nfrom sagemak...
[ 1 ]
[]
[]
[ "amazon_sagemaker", "machine_learning", "python" ]
stackoverflow_0074396941_amazon_sagemaker_machine_learning_python.txt
Q: Lazy evaluate Pandas dataframe filters I'm observing a behavior that's weird to me, can anyone tell me how I can define filter once and re-use throughout my code? >>> df = pd.DataFrame([1,2,3], columns=['A']) >>> my_filter = df.A == 2 >>> df.loc[1] = 5 >>> df[my_filter] A 1 5 I expect my_filter to return empt...
Lazy evaluate Pandas dataframe filters
I'm observing a behavior that's weird to me, can anyone tell me how I can define filter once and re-use throughout my code? >>> df = pd.DataFrame([1,2,3], columns=['A']) >>> my_filter = df.A == 2 >>> df.loc[1] = 5 >>> df[my_filter] A 1 5 I expect my_filter to return empty dataset since none of the A columns are eq...
[ "you applied the filter in the first place. Changing a value in the row won't help.\ndf = pd.DataFrame([1,2,3], columns=['A'])\nmy_filter = df.A == 2\nprint(my_filter)\n'''\n A\n0 False\n1 True\n2 False\n\n'''\n\nas you can see, it returns a series. If you change the data after this process, it will not wo...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074404834_dataframe_pandas_python.txt
Q: Why has the tkinter key-event a higher priority than the tkinter key-event ? I am writing an editor (using the tkinter text widget), which replaces tab-characters (inserted by the user) on the fly by 4 blanks. The replacement is done by a binding to the tabulator-key-event ("Tab"), which inserts 4 blanks and retu...
Why has the tkinter key-event a higher priority than the tkinter key-event ?
I am writing an editor (using the tkinter text widget), which replaces tab-characters (inserted by the user) on the fly by 4 blanks. The replacement is done by a binding to the tabulator-key-event ("Tab"), which inserts 4 blanks and returns with "break". Returning with "break" prevents the tabulator-character from bein...
[ "According to the documentation, the more specific binding is chosen over the other. A simple but effective way around this is to use a broad binding like '<Key>' and delegate the event accordingly by it's keysym, that you can access by event.keysym.\nAs example:\nimport tkinter as tk\n\ndef key_event(event):\n ...
[ 2 ]
[]
[]
[ "event_handling", "python", "tkinter" ]
stackoverflow_0074405202_event_handling_python_tkinter.txt
Q: Error Installing streamlit It says "ERROR: Could not build wheels for pyarrow which use PEP 517 and cannot be installed directly" When I try pip install streamlit it fails with the error message: ERROR: "Could not build wheels for pyarrow which use PEP 517 and cannot be installed directly" I tried installing pip...
Error Installing streamlit It says "ERROR: Could not build wheels for pyarrow which use PEP 517 and cannot be installed directly"
When I try pip install streamlit it fails with the error message: ERROR: "Could not build wheels for pyarrow which use PEP 517 and cannot be installed directly" I tried installing pip install pyarrow directly but still gives the same error message
[ "In my case the problem was related to Python version. More specifically I noticed in error logs:\nRuntimeError: Not supported on 32-bit Windows\nSo then I installed Python 3.8.6 (x64 version) instead of x32\n\nand the problem was solved with\npip install pyarrow\n", "I also faced this same issue and I noted that...
[ 9, 4, 1, 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0062994971_python_streamlit.txt
Q: Python Change Dict Values with Key-Chain Good day, I am trying to edit a Dict: e.g: a = {"key0" : [{"key01":1}], "key1" : 2} I want to change the value from key01, like: a["key0"][0][key01] = 2 But I dont know, how deep the Dict is, so I managed to put the ["key0"][0][key01] - Key-Chain in a List. But I can't find...
Python Change Dict Values with Key-Chain
Good day, I am trying to edit a Dict: e.g: a = {"key0" : [{"key01":1}], "key1" : 2} I want to change the value from key01, like: a["key0"][0][key01] = 2 But I dont know, how deep the Dict is, so I managed to put the ["key0"][0][key01] - Key-Chain in a List. But I can't find any pointer notation or dict addressing metho...
[ "quite broad, but if there will be only one occurrence of that key within the collections, then a through recursive find and update should do the job,\nsomething like this (test it)\ndef recursive_update(collection_, key, new_val):\n if isinstance(collection_, dict):\n if key in collection_:\n ...
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074405023_list_python_python_3.x.txt
Q: I can't use my text file ". kv" to program in pycharm Well, first of all if I create in Pycharm (File->New->File) with the correct nomenclature to create a kv file attached to the main file, the kv file is a python file and not a text file, this is the problem. What I have tried is to create a new->text document ...
I can't use my text file ". kv" to program in pycharm
Well, first of all if I create in Pycharm (File->New->File) with the correct nomenclature to create a kv file attached to the main file, the kv file is a python file and not a text file, this is the problem. What I have tried is to create a new->text document from the desktop with the code of the kv required in my Pyc...
[ "The Kivy file shouldn't be a python file. If you create a new Kivy file, just do it like you said.\nRight Click--> New File --> EXAMPLE.kv\njust delete the .txt or any other ending in the name of your file. Then restart the Pycharm and look that you import the .kv files correctly in your script.\n" ]
[ 0 ]
[]
[]
[ "file", "kivy", "kivy_language", "pycharm", "python" ]
stackoverflow_0074404748_file_kivy_kivy_language_pycharm_python.txt
Q: boto3 S3 limit upload speed of a large file Is there a way to limit the available bandwidth for the Python Boto3 S3 file upload process? I am uploading some pretty heavy files (each file is approximately 5 GB in size) The upload process consumes my entire bandwidth for a while. This is causing some issues. Is it p...
boto3 S3 limit upload speed of a large file
Is there a way to limit the available bandwidth for the Python Boto3 S3 file upload process? I am uploading some pretty heavy files (each file is approximately 5 GB in size) The upload process consumes my entire bandwidth for a while. This is causing some issues. Is it possible to set a hard limit on how much upload sp...
[ "Investigate the configuration options available in TransferConfig, including:\n\nThe maximum number of concurrent S3 API transfer operations can be tuned to adjust for the connection speed. Set the max_concurrency attribute to increase or decrease bandwidth usage.\n\n" ]
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074405203_amazon_s3_amazon_web_services_boto3_python.txt
Q: TWS API frezee when receiving errors I am writing a service to work through the TWS API based on the Python language. Faced a problem when getting historical data. The bottom line is that when you request app.reqHistoricalData() with the correct parameters, the script runs without problems and exits after executio...
TWS API frezee when receiving errors
I am writing a service to work through the TWS API based on the Python language. Faced a problem when getting historical data. The bottom line is that when you request app.reqHistoricalData() with the correct parameters, the script runs without problems and exits after execution. If false parameters are passed to app.r...
[ "data_end only get set True in historicalDataEnd so if there's an error it will never get called and the program sleeps forever.\nAnother reason to never use sleeps.\n" ]
[ 0 ]
[]
[]
[ "api", "interactive_brokers", "python", "tws" ]
stackoverflow_0074401279_api_interactive_brokers_python_tws.txt
Q: "Invalid value at 'data.values'" error when writing data from file to Google Sheets Attempting to open .txt file, read the contents of the file and append everything inside to a google spreadsheet. The exact contents of the file would be something exactly like [['65574','7657565','76576575','543533','543244634']]....
"Invalid value at 'data.values'" error when writing data from file to Google Sheets
Attempting to open .txt file, read the contents of the file and append everything inside to a google spreadsheet. The exact contents of the file would be something exactly like [['65574','7657565','76576575','543533','543244634']]. Getting an error for Invalid value at 'data.values'. Here is what I've got right now. ` ...
[ "I think it is because when you read the contents of the file, it returns a string, not a list. You can fix it with literal_eval() function from ast library.\nFor example\nimport ast\n\nwith open('number_list.txt') as f:\n data = f.read()\nvalues = ast.literal_eval(data)\n\nThis converts your stringified list into...
[ 0 ]
[]
[]
[ "google_sheets_api", "python" ]
stackoverflow_0074405323_google_sheets_api_python.txt
Q: ModuleNotFoundError: No module named 'mqtt_test' I have installed both commands still getting this error. pip install mqtt pip install paho-mqtt ModuleNotFoundError: No module named 'mqtt_test' I was expecting to run my Django App fine. A: Module not found error only occurs when the module is not installed. If ...
ModuleNotFoundError: No module named 'mqtt_test'
I have installed both commands still getting this error. pip install mqtt pip install paho-mqtt ModuleNotFoundError: No module named 'mqtt_test' I was expecting to run my Django App fine.
[ "Module not found error only occurs when the module is not installed. If the module is available on PyPi, then run pip install mqtt_test on your cmd. Elsewise, you can manually install the module by checking their docs.\nYou could also check this out: https://pypi.org/project/paho-mqtt.\n" ]
[ 0 ]
[]
[]
[ "mqtt", "paho", "python" ]
stackoverflow_0074405433_mqtt_paho_python.txt
Q: Error : You are trying to load a weight file containing 436 layers into a model with 437 layers I am trying to run efficientnet B7 model with nosiy student weights on kaggle and I am getting error: You are trying to load a weight file containing 436 layers into a model with 437 layers. My code: model_path = '../i...
Error : You are trying to load a weight file containing 436 layers into a model with 437 layers
I am trying to run efficientnet B7 model with nosiy student weights on kaggle and I am getting error: You are trying to load a weight file containing 436 layers into a model with 437 layers. My code: model_path = '../input/keras-efficientnet-noisy-students/efficientnet-b7_noisy-student_notop.h5' n_labels = labels.sh...
[ "In your case, pre-train model number of layers and you created a model number of layers are mismatched\nif you want Transfer Learning then use this\ntf.keras.applications.EfficientNetB0(\n include_top=False,\n weights=\"model_path\",\n input_shape=(size, size, 3),\n pooling=None,\n classes='Here how...
[ 0, 0 ]
[]
[]
[ "conv_neural_network", "deep_learning", "efficientnet", "python" ]
stackoverflow_0066513439_conv_neural_network_deep_learning_efficientnet_python.txt