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: Access private GitHub Django repositories on requirements.txt when using AWS Codebuild I am trying to use AWS Codebuild and am having problems accessing private python Django github repositories from my requirements.txt file. Getting this error "Permission denied (publickey). fatal: Could not read from remote repo...
Access private GitHub Django repositories on requirements.txt when using AWS Codebuild
I am trying to use AWS Codebuild and am having problems accessing private python Django github repositories from my requirements.txt file. Getting this error "Permission denied (publickey). fatal: Could not read from remote repository." Is there a solution to enable access?
[ "https://docs.readthedocs.io/en/stable/guides/private-python-packages.html\nYou need to create a personal access token with the repo scope. Check the GitHub documentation on how to create a personal token.\nURI example:\ngit+https://${GITHUB_USER}:${GITHUB_TOKEN}@github.com/user/project.git@{version}\n\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_codebuild", "django", "github", "python" ]
stackoverflow_0074197446_amazon_web_services_aws_codebuild_django_github_python.txt
Q: Apply background color style to rows in DataFrame in a groupby Assume I have the following dataframe iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv') which looks like this sepal_length sepal_width petal_length petal_width species 0 5.1 3...
Apply background color style to rows in DataFrame in a groupby
Assume I have the following dataframe iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv') which looks like this sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 ...
[ "If need coloring all rows/ columns use Styler.apply with custom function with repeat mapped values by numpy.broadcast_to, for colors is used seaborne.color_palette:\nimport seaborn as sns\n\n\ndef color(x):\n\n vals = x['species'].drop_duplicates()\n palette = sns.color_palette(None, len(vals)).as_hex()\n ...
[ 1, 0 ]
[]
[]
[ "excel", "pandas", "python" ]
stackoverflow_0074261965_excel_pandas_python.txt
Q: Django Rest Framework: upload image to a particular existing model's object Hey I am trying to upload an image using Rest API[via Postman] to an object which already exists, and has all its field populated except for the image. I am using PUT method, to first get the object I want to upload the image to then tryin...
Django Rest Framework: upload image to a particular existing model's object
Hey I am trying to upload an image using Rest API[via Postman] to an object which already exists, and has all its field populated except for the image. I am using PUT method, to first get the object I want to upload the image to then trying to pass it through the serializer. The images are to be uploaded to my S3 bucke...
[ "Could you try this?\nclass ImageUploadSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = MasterTaskHolder\n fields = (\n 'title','image'\n )\n\n def update(self, instance: MasterTaskHolder, validated_data):\n instance.image = validated_data['ima...
[ 0 ]
[]
[]
[ "api", "django", "django_rest_framework", "python", "rest" ]
stackoverflow_0074261895_api_django_django_rest_framework_python_rest.txt
Q: Pandas dataframe to dict using dataclass I have a pandas dataframe and would like to cast it to a dict. item settings_id mat_id order 0 a-1 b1 32 1 1 a-1 x1 12 2 2 a-1 y4 3 3 3 a-2 k1 0 1 4 a-2 3a 2 2 5 a-2 ...
Pandas dataframe to dict using dataclass
I have a pandas dataframe and would like to cast it to a dict. item settings_id mat_id order 0 a-1 b1 32 1 1 a-1 x1 12 2 2 a-1 y4 3 3 3 a-2 k1 0 1 4 a-2 3a 2 2 5 a-2 x1 94 3 6 b-1 y4 ...
[ "You can use to_dict with kwarg orient=\"records\" while looping over df.groupby(\"item\"):\nrec = []\nfor item, sub_df in df.groupby(\"item\"):\n rec.append({\n \"item\": item,\n \"settings\": sub_df.drop(columns=\"item\").to_dict(orient=\"records\")\n })\n\npprint(rec)\n\nOutput:\n[{'item': 'a-1',\n 'set...
[ 1 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python", "python_dataclasses" ]
stackoverflow_0074259813_dataframe_dictionary_pandas_python_python_dataclasses.txt
Q: count total gender per unique user id i have data like this I need to get descriptive statistics. I'm currently using this code: df.describe(exclude = np.number) and its returns like this this is something wrong where the unique count is 5464 but the user_gender male has 55775 freq. this should not be like thi...
count total gender per unique user id
i have data like this I need to get descriptive statistics. I'm currently using this code: df.describe(exclude = np.number) and its returns like this this is something wrong where the unique count is 5464 but the user_gender male has 55775 freq. this should not be like this. how to return the correct number?
[ "The freq is the most common value’s frequency. So, in user_gender the top value which is the 'male' it appears 55775 times in the dataset, which looks normal because the dataset has 81948 rows.\nOn the other hand, is not meaningful to compare the unique number of user_id and freq of user_gendercolumn.\nEverything...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074260280_pandas_python.txt
Q: Plot datetime data in 24 hour window on x axis I have a dataframe with datetime data: Start_time: eg(2013-09-21 00:14:00) - the timestamp a task has started End_time: eg(2013-09-22 11:04:00) - the timestamp a task has ended Time_diff:eg(0 days 06:07:00) - the time the task took. I want to plot a histogram of the...
Plot datetime data in 24 hour window on x axis
I have a dataframe with datetime data: Start_time: eg(2013-09-21 00:14:00) - the timestamp a task has started End_time: eg(2013-09-22 11:04:00) - the timestamp a task has ended Time_diff:eg(0 days 06:07:00) - the time the task took. I want to plot a histogram of the time events start and end, without considering the ...
[ "If I understand correctly, with your example dataframe, here is one way to do it with Matplotlib:\nfrom matplotlib import pyplot as plt\n\n# Setup\ndf[\"Start_time_nodate\"] = df[\"Start_time\"].dt.hour\ndf[\"End_time_nodate\"] = df[\"End_time\"].dt.hour\nfig, ax = plt.subplots(figsize=(8, 4))\n\n# Plot frequencie...
[ 1 ]
[]
[]
[ "datetime", "pandas", "python", "time" ]
stackoverflow_0074197143_datetime_pandas_python_time.txt
Q: How to calculate the avearge of every 4 elements in numpy array sample_list = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) Required to take the average of every 4 like 1,2,3,4 average is 2.5 followed by 5,6,7,8 is 6.5 followed by 9,10,11,12 is 10.5 followed by 13,14,15,16 is 14,5 expexted output: [2.5, 6.5...
How to calculate the avearge of every 4 elements in numpy array
sample_list = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) Required to take the average of every 4 like 1,2,3,4 average is 2.5 followed by 5,6,7,8 is 6.5 followed by 9,10,11,12 is 10.5 followed by 13,14,15,16 is 14,5 expexted output: [2.5, 6.5, 10.5, 14.5] so far i tried with refering this questions Average of...
[ "Use reshape. In following example reshape(-1, 4) means 4 elements per row\nimport numpy as np\n\nsample_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])\n\nprint(np.mean(sample_list.reshape(-1, 4), axis=1))\n\noutput\n[2.5, 6.5, 10.5, 14.5]\n\n", "There are various ways to do that. Consid...
[ 4, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074261946_numpy_python.txt
Q: Can multiple listeners be used in a cog? Problem I wanted to use multiple listener in a cog file in discord.py but it wont work. Only the last listener in the code gets called. How to solve it? Code class test(commands.Cog): @commands.Cog.listener() async def on_message(self, message): # code of th...
Can multiple listeners be used in a cog?
Problem I wanted to use multiple listener in a cog file in discord.py but it wont work. Only the last listener in the code gets called. How to solve it? Code class test(commands.Cog): @commands.Cog.listener() async def on_message(self, message): # code of this function @commands.Cog.listener() ...
[ "https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=commands%20cog%20listener#discord.ext.commands.Cog.listener\nclass test(commands.Cog):\n @commands.Cog.listener(\"on_message\")\n async def listener_one(self, message):\n # code of this function\n\n @commands.Cog.listener(\"...
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0071536493_discord_discord.py_python.txt
Q: How to use Python api respose inseredt to questdb How can i get Python script to insert this to quest DB b"[{'timeStamp': '2019-02-01T01:00:00', 'value': 1794.0}, {'timeStamp': '2019-03-01T01:00:00', 'value': 1486.0}, {'timeStamp': '2019-04-01T00:00:00', 'value': 1123.0}, {'timeStamp': '2019-05-01T00:00:00', 'valu...
How to use Python api respose inseredt to questdb
How can i get Python script to insert this to quest DB b"[{'timeStamp': '2019-02-01T01:00:00', 'value': 1794.0}, {'timeStamp': '2019-03-01T01:00:00', 'value': 1486.0}, {'timeStamp': '2019-04-01T00:00:00', 'value': 1123.0}, {'timeStamp': '2019-05-01T00:00:00', 'value': 1022.0}, {'timeStamp': '2019-06-01T00:00:00', 'valu...
[ "You are ingesting the data in the wrong format.\nQuestDB supports the InfluxDB line protocol for ingesting data.\nThe following format is expected:\ntable_name,symbolset columnset timestamp\\n\nMore information about ILP and questDB can be found here: https://questdb.io/docs/reference/api/ilp/overview/\nThey also ...
[ 0 ]
[]
[]
[ "insert", "python", "questdb", "response" ]
stackoverflow_0074256547_insert_python_questdb_response.txt
Q: python webscraping pricing and hidden elements with selenium In this webpage: https://www.centris.ca/en/properties~for-sale~brossard?view=Thumbnail I am trying to do two things: get the price of the listings get the MLS number of the listings from selenium import webdriver from webdriver_manager.chrome import C...
python webscraping pricing and hidden elements with selenium
In this webpage: https://www.centris.ca/en/properties~for-sale~brossard?view=Thumbnail I am trying to do two things: get the price of the listings get the MLS number of the listings from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import O...
[ "You were close to the right approach.\nOnce you have a listings elements list by this line listings = driver.find_elements(By.CLASS_NAME, 'description') you can iterate over the listings and grab their prices and MLSs as following:\ndef scrap_pages(driver):\n listings = driver.find_elements(By.CLASS_NAME, 'desc...
[ 1, 0 ]
[]
[]
[ "html", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074257959_html_python_selenium_selenium_webdriver_xpath.txt
Q: Selecting random periods by date For each id in my dataframe, I want to sample rows between a random date range period (can be 1, 2, 4 weeks) that is inside the min and max dates of that given id. For example, for given id I have data between 2022-09-01 and 2022-09-28 I want to sample random 7 days which would giv...
Selecting random periods by date
For each id in my dataframe, I want to sample rows between a random date range period (can be 1, 2, 4 weeks) that is inside the min and max dates of that given id. For example, for given id I have data between 2022-09-01 and 2022-09-28 I want to sample random 7 days which would give me all records between a random star...
[ "IIUC, here is one way you can do it:\nBasically you groupby account_id, then create a pd.date_range of the group, starting at its minimum, ending at its maximum minus the interval of days (or anything else. For more information, read the documentation of pandas.tseries.offsets.DateOffset) you chose, because you ca...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074261960_dataframe_pandas_python_python_3.x.txt
Q: Why is the returned result of the Elasticsearch response still caped at 10000 when the parameter max_result_window has been changed? I have a Django application with Elasticsearch. I have an index search_index where I need to render more than 10 000 results. I manually changed the parameter max_result_window to ge...
Why is the returned result of the Elasticsearch response still caped at 10000 when the parameter max_result_window has been changed?
I have a Django application with Elasticsearch. I have an index search_index where I need to render more than 10 000 results. I manually changed the parameter max_result_window to generate more than the 10 000 initial limits But after changing the parameter max_result_window and the size in the body_search of my reques...
[ "Tldr;\nI am 99% sure you would be better off using the scroll api / pagination.\nBut to solve you issue you need to tell elastic to track the exact score\nIt can be done via \"track_total_hits\": true in your query.\n" ]
[ 0 ]
[]
[]
[ "django", "elasticsearch", "elasticsearch_dsl", "python" ]
stackoverflow_0074237966_django_elasticsearch_elasticsearch_dsl_python.txt
Q: How to read digital digits from an image (LCD screen) using python I need to extract digital digits from the digital weighing scale. OCR and Pytesseract libraries are not working for this problem statement. Is there any better libraries or solution? Below is the input image from which I'm trying to extract the dig...
How to read digital digits from an image (LCD screen) using python
I need to extract digital digits from the digital weighing scale. OCR and Pytesseract libraries are not working for this problem statement. Is there any better libraries or solution? Below is the input image from which I'm trying to extract the digits. Input image
[ "Perhaps this article is what you're looking for: https://pyimagesearch.com/2017/02/13/recognizing-digits-with-opencv-and-python/\nThe article demonstrates the use of OpenCV to read LCD-digits off of tiny displays.\n" ]
[ 0 ]
[]
[]
[ "computer_vision", "image_processing", "ocr", "opencv", "python" ]
stackoverflow_0074261915_computer_vision_image_processing_ocr_opencv_python.txt
Q: Many2one field display x.y 1 , x.y 2 ... etc , instead of values in x.y table in odoo 15 im trying to display values of x.y in Many2one field , here is my code this is the module of x.y from email.policy import default from odoo import fields,models,api,_ class XY(models.Model): _name = 'x.y' pat_fullname ...
Many2one field display x.y 1 , x.y 2 ... etc , instead of values in x.y table in odoo 15
im trying to display values of x.y in Many2one field , here is my code this is the module of x.y from email.policy import default from odoo import fields,models,api,_ class XY(models.Model): _name = 'x.y' pat_fullname = fields.Char(string='Full Name') pat_age = fields.Integer(string='Age') XY class is work...
[ "Odoo uses the combination of the model's fields and id as display name at many2one fields, to change it we use _rec_name attribute in x.y model, which contains one of the field's of the model. notice value of _rec_name should be unique for every record , so you can use combination of columns with an arbitrary comp...
[ 1, 0 ]
[]
[]
[ "odoo", "odoo_15", "python", "ubuntu" ]
stackoverflow_0074248517_odoo_odoo_15_python_ubuntu.txt
Q: How can I Print a clickable text in python, which go to a URL I would like to print a text using python [ on pycharm terminal ] with a URL. Can any one suggest how can I do that. `url = https://stackoverflow.com/.com print ("Click me")` I am expecting the text "Click me" to be printed as a clickable text, which c...
How can I Print a clickable text in python, which go to a URL
I would like to print a text using python [ on pycharm terminal ] with a URL. Can any one suggest how can I do that. `url = https://stackoverflow.com/.com print ("Click me")` I am expecting the text "Click me" to be printed as a clickable text, which can go to https://stackoverflow.com/.com
[ "There are two possibilites to open a hyperlink.\n1. Open with the standard terminal:\nHere you can not influence the click feature by Python code.\nTo open a link in the Terminal just print() the link with Python to the Terminal with Stdout and use Ctrl + Left-Click to open the link.\nprint(\"https://www.stackover...
[ 0, 0 ]
[]
[]
[ "hyperlink", "python", "url" ]
stackoverflow_0074261472_hyperlink_python_url.txt
Q: Selenium Won't Iterate Through All Pages Using XPATH. Keep receiving "NoSuchElementException" error Currently the below code gets to the second page and then I get a "NoSuchElementException" error. I have tried iterating using the HREF as well. The link text works slightly better but I encounter issues when I reac...
Selenium Won't Iterate Through All Pages Using XPATH. Keep receiving "NoSuchElementException" error
Currently the below code gets to the second page and then I get a "NoSuchElementException" error. I have tried iterating using the HREF as well. The link text works slightly better but I encounter issues when I reach the "..." portion of the iteration, so would prefer to stick with the XPATH. Feel like I have tried eve...
[ "@David Kahn, Seems the number of elements on each page are different. So in your xpath tr[98] is not always the case. You can do the following changes and it should work.\nYour xpath_string should be the following. Where I have removed the dependency on position of the page numbers on 98th row of the table.\nxpath...
[ 0 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0074259870_python_selenium_xpath.txt
Q: Calculate the sum of every 5 elements in a python array I have a python array in which I want to calculate the sum of every 5 elements. In my case I have the array c with ten elements. (In reality it has a lot more elements.) c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0] So finally I would like to have a new array (c_new) ...
Calculate the sum of every 5 elements in a python array
I have a python array in which I want to calculate the sum of every 5 elements. In my case I have the array c with ten elements. (In reality it has a lot more elements.) c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0] So finally I would like to have a new array (c_new) which should show the sum of the first 5 elements, and the se...
[ "You can use np.add.reduceat by passing indices where you want to split and sum:\nimport numpy as np\nc = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]\nnp.add.reduceat(c, np.arange(0, len(c), 5))\n# array([1, 2])\n\n", "Heres one way of doing it - \nc = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]\nprint [sum(c[i:i+5]) for i in range(0, len...
[ 18, 10, 5, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0042444046_arrays_numpy_python.txt
Q: Extract a public key from certificate I'm trying to extract a public key from my certificate but i keep getting this error: ValueError: RSA key format is not supported.. Below is my code: from Crypto.PublicKey import RSA bob_crt = 'bob.crt' public_key = RSA.import_key(bob_crt) if isinstance(public_key, RSA.RsaKe...
Extract a public key from certificate
I'm trying to extract a public key from my certificate but i keep getting this error: ValueError: RSA key format is not supported.. Below is my code: from Crypto.PublicKey import RSA bob_crt = 'bob.crt' public_key = RSA.import_key(bob_crt) if isinstance(public_key, RSA.RsaKey): print("RSA public key") else: p...
[ "RSA.import_key expects the content, not the filename. If you read the content first, your script works.\nfrom Crypto.PublicKey import RSA\n\nwith open(\"bob.crt\") as f:\n bob_crt = f.read()\n\npublic_key = RSA.import_key(bob_crt)\nif isinstance(public_key, RSA.RsaKey):\n print(public_key.export_key())\nelse...
[ 2 ]
[]
[]
[ "cryptography", "python", "x509" ]
stackoverflow_0074262109_cryptography_python_x509.txt
Q: NameError: name 'setup' is not defined Trying to build a simple app integrate with cython. Anyway I keep getting: When I enter in CMD: python setup.py build_ext --inplace Traceback (most recent call last): File "setup.py", line 3, in <module> setup( NameError: name 'setup' is not defined File: from set...
NameError: name 'setup' is not defined
Trying to build a simple app integrate with cython. Anyway I keep getting: When I enter in CMD: python setup.py build_ext --inplace Traceback (most recent call last): File "setup.py", line 3, in <module> setup( NameError: name 'setup' is not defined File: from setuptools import Extension from setuptool...
[ "Looks like it's just some confusion about where all the names are coming from, and exactly how they're spelled/capitalized. I'm writing based on the examples on this page\nfrom setuptools import Extension\nfrom subzero import Executable, setup\n\nsetup(name='main.py', ...)\n\n", "Try import\nfrom setuptools impo...
[ 1, 0 ]
[]
[]
[ "cython", "python", "python_3.x" ]
stackoverflow_0047426546_cython_python_python_3.x.txt
Q: Adding django import_export to Abstract User Model Below is my admin.py file. I want to implement the import_export feature on the Employee model which is Abstract User Model. from django.contrib import admin from inventory.models import Employee from django.contrib.auth.admin import UserAdmin from django.contrib....
Adding django import_export to Abstract User Model
Below is my admin.py file. I want to implement the import_export feature on the Employee model which is Abstract User Model. from django.contrib import admin from inventory.models import Employee from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from import_export.admin import...
[ "The ImportExportModelAdmin [readthedocs.io] is just a ModelAdmin with a ImportExportMixin [readthedocs.io], so probably the most clean solution is use the ImportExportMixin:\nfrom django.contrib import admin\nfrom inventory.models import Employee\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contri...
[ 0, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0064145389_django_django_admin_python.txt
Q: Convert bytes in string using python I have bson file, and i dont know what have inside of the document. I see the data type, and conclude the type of data is bytes. So, for undertsand the content the file, i need to save in readable formart. So, the firt step was convert my bytes in a string.. But, i return the f...
Convert bytes in string using python
I have bson file, and i dont know what have inside of the document. I see the data type, and conclude the type of data is bytes. So, for undertsand the content the file, i need to save in readable formart. So, the firt step was convert my bytes in a string.. But, i return the following message: TypeError: descriptor 'd...
[ "You are saving the type object into your bytes_content variable.\nbytes_content = read_content[\"data\"]\n\n" ]
[ 0 ]
[]
[]
[ "bson", "byte", "python", "string", "type_conversion" ]
stackoverflow_0074262267_bson_byte_python_string_type_conversion.txt
Q: convert nested dictionary json response to df I am receiving a nested dictionary as a response to an API call. I tried converting it into a dataframe but I am not able to get the output I want. I wrote some code to handle the file, but I have a massive chunk of nested dictionary data in the "items" columns. How do...
convert nested dictionary json response to df
I am receiving a nested dictionary as a response to an API call. I tried converting it into a dataframe but I am not able to get the output I want. I wrote some code to handle the file, but I have a massive chunk of nested dictionary data in the "items" columns. How do I parse that and create a dataframe from it? df1 =...
[ "you can use:\ndf=df.explode('items')\nmask=pd.json_normalize(df.pop('items'))\ndf=df.join(mask)\n\nThere are two columns left to convert.\nprint(df[['tags','productConfiguration.allowedOrderQuantities']])\n'''\n tags productConfiguration.allowedOrderQuantities\n0 [popular, onsale] []\n0 [p...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074262175_dataframe_pandas_python.txt
Q: How to extract paragaphs between two strings in Python and store each paragraphn in different columns of datframe Text = "This email is confidential dont share with others From : user1@email,To: reciver1@email.com, Subject:Test1, ******emailBody*********, Regards,User1." From : user2@email,To: reciver2@email.com, ...
How to extract paragaphs between two strings in Python and store each paragraphn in different columns of datframe
Text = "This email is confidential dont share with others From : user1@email,To: reciver1@email.com, Subject:Test1, ******emailBody*********, Regards,User1." From : user2@email,To: reciver2@email.com, Subject:Test2, ******emailBody*********, Regards,User2. This email is confidential dont share with others" From this i...
[ "Try this:\nstrings = Text.split('From')\n\nThis will result in a list of the different strings\nYou can validate each sentence later, e.g. if 'To:' is present and if so add back the 'From:' to the beginning\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "text_extraction" ]
stackoverflow_0074262335_dataframe_pandas_python_text_extraction.txt
Q: Any idea why paramiko sends \x07 instead of \t to remote server? I am struggling for the past couple of days to figure out why is paramiko sending \x07 instead of tab to remote session. I am using paramikos invoke_shell because i need to run several interconnected commands. Everything works except for this part: c...
Any idea why paramiko sends \x07 instead of \t to remote server?
I am struggling for the past couple of days to figure out why is paramiko sending \x07 instead of tab to remote session. I am using paramikos invoke_shell because i need to run several interconnected commands. Everything works except for this part: check_export = f'echo -e \"this\tis\tjust a test\" > /tmp/export' This...
[ "That's all probably a side effect of you abusing an interactive shell for command automation. What happens if you type echo -e \"this in the shell and then you press Tab key? The shell will try to expand this to a filename and beep (ASCII 7), if no such file is found. That's what your code does. It's not Paramiko ...
[ 5 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0074262379_paramiko_python.txt
Q: Classify version strategies into different labels as a new pandas column I have a dataframe that looks like this: df = pd.DataFrame({'id': {0: 84, 1: 84, 2: 84, 3: 84, 4: 124},'info_version': {0: '1.1.0',1: 'alpha', 2: '7.20345.98', 3: '2', 4: '${git.build.version}', 5: 'version not set'}}) The column info_versio...
Classify version strategies into different labels as a new pandas column
I have a dataframe that looks like this: df = pd.DataFrame({'id': {0: 84, 1: 84, 2: 84, 3: 84, 4: 124},'info_version': {0: '1.1.0',1: 'alpha', 2: '7.20345.98', 3: '2', 4: '${git.build.version}', 5: 'version not set'}}) The column info_version is full of values all different from each other, decimals, words,values in c...
[ "Made an additional df1 dataframe to check for values. In which the 'kkk' column is checked for a match and if the values match, it gets the values from the 'aaa' column.\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'id': {0: 84, 1: 84, 2: 84, 3: 84, 4: 124},\n 'info_version': {0...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074253181_dataframe_pandas_python.txt
Q: How to do indexing in python dictionary using html template def send_template(request): my_folders = Folders.objects.filter(parent=None).order_by('name') new_headers = {} for foldr in my_folders: en_count = FolderEntries.objects.filter(folder = foldr.id ).count() new_h...
How to do indexing in python dictionary using html template
def send_template(request): my_folders = Folders.objects.filter(parent=None).order_by('name') new_headers = {} for foldr in my_folders: en_count = FolderEntries.objects.filter(folder = foldr.id ).count() new_headers[foldr.id] = en_count return render(request, 'folders....
[ "Indexing is deliberately not supported in the Django template language, because it is writing business logic in the template. For a fixed key, you can use new_headers.190, you can also register a custom lookup, but usually that means that the logic is not effective.\nYou can .annotate(…) [Django-doc] with:\nfrom d...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074262555_django_html_python.txt
Q: Problem with understanding the code of 968. Binary Tree Cameras I am studying algorithms and trying to solve the LeetCode problem 968. Binary Tree Cameras: You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate ch...
Problem with understanding the code of 968. Binary Tree Cameras
I am studying algorithms and trying to solve the LeetCode problem 968. Binary Tree Cameras: You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all no...
[ "The base case is set for a None, i.e. the absence of a node. Such a virtual position is never a problem, so we can count it as \"covered\", but there is no camera there. This is why the base case returns 2.\nNow when a leaf node is encountered, then obviously both recursive calls will get None as argument and retu...
[ 0 ]
[]
[]
[ "binary_tree", "depth_first_search", "python", "recursion" ]
stackoverflow_0074261890_binary_tree_depth_first_search_python_recursion.txt
Q: Install numpy with Pyhon 3.7 on Macbook M1 I'm working on a project that requires Python 3.7. I'm trying to resolve the mismatch between my setup.py and requirements.txt by running: pip-compile --output-file=requirements.txt setup.py but I get this error compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG...
Install numpy with Pyhon 3.7 on Macbook M1
I'm working on a project that requires Python 3.7. I'm trying to resolve the mismatch between my setup.py and requirements.txt by running: pip-compile --output-file=requirements.txt setup.py but I get this error compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=...
[ "I was facing this error too. It happens because pip-compile can't/won't use the pre-compiled numpy wheel (which is what pip install normally does), and instead tries to compile it locally. It appears numpy and macOS's built-in BLAS (Basic Linear Algebra Subprograms) library don't like each other (at least for Pyth...
[ 3 ]
[]
[]
[ "apple_m1", "numpy", "python" ]
stackoverflow_0074113427_apple_m1_numpy_python.txt
Q: How to merge two XML files with different child elements into single XML file The below given are my sample xml files. (XML 1) <?xml version="1.0" encoding="utf-8"?> <objects> <object> <record> <organization>1010</organization> <code>000010001</code> <name>A &amp; SOLICITORS</na...
How to merge two XML files with different child elements into single XML file
The below given are my sample xml files. (XML 1) <?xml version="1.0" encoding="utf-8"?> <objects> <object> <record> <organization>1010</organization> <code>000010001</code> <name>A &amp; SOLICITORS</name> <address_1>NORTH</address_1> <address_2/> <city/> ...
[ "Using pandas:\nS1.xml:\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<objects>\n <object>\n <record>\n <organization>1010</organization>\n <code>000010001</code>\n <name>A &amp; SOLICITORS</name>\n <address_1>NORTH</address_1>\n <address_2/>\n <city/>\n ...
[ 0 ]
[]
[]
[ "django", "python", "xml" ]
stackoverflow_0074261186_django_python_xml.txt
Q: How to move multiple grouped Sprite images simultaneously in Pygame Sprite I am making a game with groups of birds, when I press a key I want all the birds to move at the same time but only one is moving. There are five birds that I create with a loop, but only one of them is moving. How can I move all of them at ...
How to move multiple grouped Sprite images simultaneously in Pygame Sprite
I am making a game with groups of birds, when I press a key I want all the birds to move at the same time but only one is moving. There are five birds that I create with a loop, but only one of them is moving. How can I move all of them at the same time class Birds(pygame.sprite.Sprite): def __init__(self, image, ...
[ "You have to call the method movement in a loop for each object in the group birds_sprite:\nwhile run:\n # [...]\n\n for target in birds_sprite:\n target.movement()\n\n # [...]\n\n\nAlter natively you can implement an update method. Just rename movement to update. See pygame.sprite.Group.update:\n\n...
[ 1, 0 ]
[]
[]
[ "pygame", "python", "sprite" ]
stackoverflow_0074260170_pygame_python_sprite.txt
Q: Trigger long process in Django view I have a view (start_job_view) in Django that should trigger a very long process. I'd like the view to return immediately and add a message to the user ("your job has started" using the message framework) and I'd like that when the long process terminates it sends a new message ...
Trigger long process in Django view
I have a view (start_job_view) in Django that should trigger a very long process. I'd like the view to return immediately and add a message to the user ("your job has started" using the message framework) and I'd like that when the long process terminates it sends a new message to the user ("your job has finished"). Ho...
[ "in views.py\ndef your_view(self, request):\n # your code \n t = BackgroundTasksUtils(user) # Not required to pass parameter (it's up to you)\n t.start()\n return something\n\nin bg_task.py\nimport threading\n\nclass BackgroundTasksUtils(threading.Thread):\n def __init__(self, user):\n supe...
[ 1, 0, 0, 0 ]
[]
[]
[ "django", "django_views", "python", "python_3.x" ]
stackoverflow_0074108699_django_django_views_python_python_3.x.txt
Q: Set default value for undefined variables in Jinja2 template Let's say I have the following str: sql = "SELECT c1, c2 FROM {{ table1 }} LEFT JOIN {{ table2 }}" And I want to render it without specifying the values of table1 and table2, and they should have a default value specified by me i.e "table". So the rende...
Set default value for undefined variables in Jinja2 template
Let's say I have the following str: sql = "SELECT c1, c2 FROM {{ table1 }} LEFT JOIN {{ table2 }}" And I want to render it without specifying the values of table1 and table2, and they should have a default value specified by me i.e "table". So the rendered str would be: rendered_sql = "SELECT c1, c2 FROM table LEFT JO...
[ "It sounds at first like you're looking for the default filter:\nsql = \"SELECT c1, c2 FROM {{ table1|default('foo') }} LEFT JOIN {{ table2|default('bar') }}\"\n\n...but I'm unclear about that last sentence in your question, \"The numbers of variables that are going to be not defined is arbitrary, as well as the na...
[ 1 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0074262644_jinja2_python.txt
Q: How to elegantly handle multiple .find() checks in an if check elegantly? So right now I have a line in my code with multiple value checks that gets extremely bulky. How would I declutter it? if string.find(a) != -1 and string.find(b) != -1 string.find(b) != -1 and string.find(c)==-1 and string.find(d)==-1 string ...
How to elegantly handle multiple .find() checks in an if check elegantly?
So right now I have a line in my code with multiple value checks that gets extremely bulky. How would I declutter it? if string.find(a) != -1 and string.find(b) != -1 string.find(b) != -1 and string.find(c)==-1 and string.find(d)==-1 string not in list: I tried to handle everything in a for loop, which turned out to b...
[ "An example using map and all\na = \"abc 123 321\"\ni = [\"abc\", \"123\", \"321\"]\n\nif all(map(lambda f: f in a, i)):\n print(\"All elements of i are in a\")\n\n" ]
[ 1 ]
[]
[]
[ "conditional_statements", "if_statement", "python" ]
stackoverflow_0074262738_conditional_statements_if_statement_python.txt
Q: Selenium finds element on a page but not on another Im trying to get the location for sotre from google maps but my code sometimes gets it for a store and sometimes it doesnt get it for another. here the link to the google colab https://colab.research.google.com/drive/1ncrffQMGyeudUkMiGSrCfssifVScfYa-?usp=sharing ...
Selenium finds element on a page but not on another
Im trying to get the location for sotre from google maps but my code sometimes gets it for a store and sometimes it doesnt get it for another. here the link to the google colab https://colab.research.google.com/drive/1ncrffQMGyeudUkMiGSrCfssifVScfYa-?usp=sharing you can see in the end that it gets it for "blaze" and no...
[ "You are using Xpath to find your element, so depending on the structure of the page it could change.\nI have completed some test with your data using BeautifulSoup library with Selenium.\nI think it is more reliable to find address with CSS Selector.\nTo help you, consider this documentation :\nhttps://saucelabs.c...
[ 2, 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "web_scraping", "xpath" ]
stackoverflow_0074262062_python_selenium_selenium_chromedriver_web_scraping_xpath.txt
Q: How To Remove Characters from String based on Some Conditions Dears, How To Remove Characters from String based on Some Conditions ? Knowing that I have one string where I need to : STEP 01 : Remeove vowels STEP 02 : Remove Duplicate consonants and keep the 1st appeared one. STEP 03 : Remove 1st and Last Characte...
How To Remove Characters from String based on Some Conditions
Dears, How To Remove Characters from String based on Some Conditions ? Knowing that I have one string where I need to : STEP 01 : Remeove vowels STEP 02 : Remove Duplicate consonants and keep the 1st appeared one. STEP 03 : Remove 1st and Last Characters if string starts/Ends with a given letter. Example : Word : Tra...
[ "Here's another version of Step 01:\nword = 'THERMOCHEMISTRY'\n\nvowels={'a','e','i','o','u'}\nresult = ''.join([letter for letter in word if letter.lower() not in vowels])\n\nFor step 02, you could do this (there are probably more efficient methods, but this works):\nresult2 = \"\"\nfor i in result:\n if i.lowe...
[ 0, 0 ]
[]
[]
[ "conditional_statements", "procedure", "pysimplegui", "python", "string" ]
stackoverflow_0074262620_conditional_statements_procedure_pysimplegui_python_string.txt
Q: How to apply torch.topk only on non-zero elements of a tensor? I want to apply the function torch.topk, but only on the non-zero elements of the tensor (i.e, not to count zero elements in the counting process). Currently I do this: torch.topk(tensor.view(-1), k) But this also considers the zero elements in variab...
How to apply torch.topk only on non-zero elements of a tensor?
I want to apply the function torch.topk, but only on the non-zero elements of the tensor (i.e, not to count zero elements in the counting process). Currently I do this: torch.topk(tensor.view(-1), k) But this also considers the zero elements in variable tensor and returns the top largest among them. What should I do t...
[ "# get the top k values in a tensor excluding zeros\ntop_vals = torch.topk(tensor.view(-1), k)[0]\nmask = top_vals != 0\nvalues = top_vals[mask]\nprint(values)\n\n# Get Indices of Top K Values\nindices = torch.nonzero(mask)\nprint(indices)\n\ncredits: this question and its answers\n" ]
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074261488_python_pytorch.txt
Q: How can I embed a quote inside an f-string? I'm currently conducting a PR review and came across this: value = "" for i in uuids: value = value + "'" + i + "'" + "," where_clause = field + " IN (" + value.rstrip(",") + ")" Nothing particularly wrong with it but I figure it can ...
How can I embed a quote inside an f-string?
I'm currently conducting a PR review and came across this: value = "" for i in uuids: value = value + "'" + i + "'" + "," where_clause = field + " IN (" + value.rstrip(",") + ")" Nothing particularly wrong with it but I figure it can be improved using f-strings, join() and a list co...
[ "Actually, this works pretty well, and is \"good enough\" in this case\nuuids = [\"a\", \"b\", \"c\"]\nfield = \"myfield\"\nwhere_clause = f\"{field} IN (\" + (', '.join([f'\"{i}\"' for i in uuids])) + \")\"\nwhere_clause\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074262777_python.txt
Q: Asynchronous requests inside the for loop in python I have this snippet config = {10: 'https://www.youtube.com/', 5: 'https://www.youtube.com/', 7: 'https://www.youtube.com/', 3: 'https://sportal.com/', 11: 'https://sportal.com/'} def test(arg): for key in arg.keys(): requests.get(arg[key], tim...
Asynchronous requests inside the for loop in python
I have this snippet config = {10: 'https://www.youtube.com/', 5: 'https://www.youtube.com/', 7: 'https://www.youtube.com/', 3: 'https://sportal.com/', 11: 'https://sportal.com/'} def test(arg): for key in arg.keys(): requests.get(arg[key], timeout=key) test(config) On that way the things are happ...
[ "Here is the solution:\ndef addresses(adr, to):\n requests.get(adr, timeout=to)\n\nasync def test(arg):\n\n loop = asyncio.get_event_loop()\n tasks = [loop.run_in_executor(None, addresses, arg[key], key) for key in arg.keys()]\n await asyncio.gather(*tasks)\n\n\n\nasyncio.run(test(config))\n\nNow it ...
[ 0, 0 ]
[]
[]
[ "asynchronous", "python" ]
stackoverflow_0071843245_asynchronous_python.txt
Q: Watermarking Image using Pillow I'am trying to watermark an image however iam not able to do so without pasting the watermark with its background color. (see below example) I tried to implement the tutorial from the following website. As can be seen from below images, the Current outcome shows watermark with its b...
Watermarking Image using Pillow
I'am trying to watermark an image however iam not able to do so without pasting the watermark with its background color. (see below example) I tried to implement the tutorial from the following website. As can be seen from below images, the Current outcome shows watermark with its black background which is not desirabl...
[ "You are pasting an Image with no transparency in it.\nBeing a PNG, it doesn't mean it contains transparency, but an alpha layer, in which case, every pixel is equal to 255\nThere is no need to make it transparent with putalpha, you just need a PNG file with the black area transparent\n", "from PIL import Image\n...
[ 1, 0 ]
[]
[]
[ "python", "python_imaging_library", "watermark" ]
stackoverflow_0067965574_python_python_imaging_library_watermark.txt
Q: Read in random line from text file as tweet status update I've been struggling with this and would really appreciate a guru's help, I probabaly need a FOR loop to read in the text from a text file, something like the following (lifted from other code). I will also confess that I wouldn't know the appropriate plac...
Read in random line from text file as tweet status update
I've been struggling with this and would really appreciate a guru's help, I probabaly need a FOR loop to read in the text from a text file, something like the following (lifted from other code). I will also confess that I wouldn't know the appropriate place to put that FOR loop: for s in twt: if s.id not in process...
[ "Turns out it was achievable with this line:\napi.update_status('@' + mention.user.screen_name + ' ' + random.choice(open('tweets.txt').readlines()).strip(\"\\n\"))\n\n" ]
[ 0 ]
[]
[]
[ "api", "python", "status", "tweepy" ]
stackoverflow_0074251700_api_python_status_tweepy.txt
Q: Accessing sub key of dict in list I have a list of dictionnaries of the following format: myList = [ {'keyA': {'key1': 'valueA1_1', 'key2': 'valueA2_1'}, 'keyB': 'valueB_1', }, {'keyA': {'key1': 'valueA1_2', 'key2': 'valueA2_2'}, 'keyB': 'valueB_2', } ] I want...
Accessing sub key of dict in list
I have a list of dictionnaries of the following format: myList = [ {'keyA': {'key1': 'valueA1_1', 'key2': 'valueA2_1'}, 'keyB': 'valueB_1', }, {'keyA': {'key1': 'valueA1_2', 'key2': 'valueA2_2'}, 'keyB': 'valueB_2', } ] I want to output a list of shape: outputlist ...
[ "Seems like you have a typo in the collection names.\nDo you have mylist collection in your code only? Or also myList?\nThis construction works pretty well, by the way.\noutputlist = [x[\"keyA\"]['key1'] + \" - \" + x[\"keyB\"] for x in mylist]\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074262883_python_python_3.x.txt
Q: Convert negative results from the list into 0 I've done a program which counts income per family member and gives a result of funding. There is a problem when one of the family member's "earns negative value" (has a loss), I want it to count negative values as 0. Example of right answer: Family members: 4 Children...
Convert negative results from the list into 0
I've done a program which counts income per family member and gives a result of funding. There is a problem when one of the family member's "earns negative value" (has a loss), I want it to count negative values as 0. Example of right answer: Family members: 4 Children in family: 2 Input family member income (yearly): ...
[ "The best approach is to use a conditional comprehension, as suggested by @Swifty, in the comments.\nHere is your code fixed and using more descriptive variable names:\nmembers = int(input('Family members: '))\nchildren = int(input('Children in family: '))\nadults = members - children\n\nif members < children and m...
[ 1, 0, 0 ]
[]
[]
[ "list", "python", "sum" ]
stackoverflow_0074262612_list_python_sum.txt
Q: Twitter API get list of users with a keyword in their name I want to get a list of twitter users with a keyword in their name, i don't think it is possible with given api. Example: Getting a list of users with "John" in their name. This can return: "John2782" "John Stamoss" "JohnJohn"... Is there a way to achieve ...
Twitter API get list of users with a keyword in their name
I want to get a list of twitter users with a keyword in their name, i don't think it is possible with given api. Example: Getting a list of users with "John" in their name. This can return: "John2782" "John Stamoss" "JohnJohn"... Is there a way to achieve this query with twitter api? (Extra: i want to eliminate users w...
[ "Twitter currently doesn't have this API. As a workaround we used: https://rapidapi.com/letscrape-6bRBa3QguO5/api/social-links-search/\n" ]
[ 0 ]
[]
[]
[ "api", "python", "tweepy", "twitter", "twitterapi_python" ]
stackoverflow_0071742795_api_python_tweepy_twitter_twitterapi_python.txt
Q: Pylint considers "timeout-methods" option as unrecognised Versions: Python: 3.10.4 Pylint: 2.15.3 Visual Studio Code: 1.72.2 The .pylintrc file was generated using pylint --generate-rcfile command. It has the following option configured: [METHOD_ARGS] # List of qualified names (i.e., library.method) which requ...
Pylint considers "timeout-methods" option as unrecognised
Versions: Python: 3.10.4 Pylint: 2.15.3 Visual Studio Code: 1.72.2 The .pylintrc file was generated using pylint --generate-rcfile command. It has the following option configured: [METHOD_ARGS] # List of qualified names (i.e., library.method) which require a timeout # parameter e.g. 'requests.api.get,requests.api.p...
[ "As the comments under the original code showed, the pylint version bundled in the VS Code extension and the one that was used to generate the .pylintrc file differ.\nNormally, the VS Code Pylint extension should use the pylint version installed in the Python environment that you configured to use for your project,...
[ 2, 1 ]
[]
[]
[ "pylint", "python", "visual_studio_code" ]
stackoverflow_0074195577_pylint_python_visual_studio_code.txt
Q: How to edit a .conf file in Python? My test.conf is like this: First.Name: Abc Age: 20 I want to update the .conf file by updating Name and age First.Name: XYZ Age: 30 Please note in my .conf I am using a semicolon (:) and not an equals (=) character for the key-value. Also, there is dot (.) character in the key...
How to edit a .conf file in Python?
My test.conf is like this: First.Name: Abc Age: 20 I want to update the .conf file by updating Name and age First.Name: XYZ Age: 30 Please note in my .conf I am using a semicolon (:) and not an equals (=) character for the key-value. Also, there is dot (.) character in the key.
[ "You can use the built-in csv module's csv.reader and csv.writer.\nWhile the \"c\" in \"csv\" does mean \"comma\"-delimited, the reader and writer objects can be configured to use a different delimiter, like in your case, make it use \":\" to be the delimiter (or to be exact, \": \" with an extra space).\nReading f...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074151457_python_python_3.x.txt
Q: Is there a way to fetch the author's name of a Sharepoint file in Python? I want to get the author's name (Created By/Modified By) of several files contained in a Sharepoint folder in Python. I have used the Shareplum library to connect to the site and was able to retrieve some details (for ex- Time Modified/ Time...
Is there a way to fetch the author's name of a Sharepoint file in Python?
I want to get the author's name (Created By/Modified By) of several files contained in a Sharepoint folder in Python. I have used the Shareplum library to connect to the site and was able to retrieve some details (for ex- Time Modified/ Time Created) about the files but not the name of the author who has added the file...
[ "You have to use the internal name of columns in API calls to get the column values from SharePoint list.\nBelow are internal names for created by and modified by columns:\n\nCreated By: Author\nModified By: Editor\n\nUse these column names in your API call along with \"Created\" and \"Modified (which fetches dates...
[ 0 ]
[]
[]
[ "python", "shareplum", "sharepoint" ]
stackoverflow_0074232781_python_shareplum_sharepoint.txt
Q: Can't find toga.style python error message hi i'm trying to create a application with python, so i'm using the beeware, i installed toga with pip3 install toga and pip3 install beeware when i try to run a test script it gives me this error messages: Import "toga.style" could not be resolved Import "toga.style.pack...
Can't find toga.style python error message
hi i'm trying to create a application with python, so i'm using the beeware, i installed toga with pip3 install toga and pip3 install beeware when i try to run a test script it gives me this error messages: Import "toga.style" could not be resolved Import "toga.style.pack" could not be resolved this is the test code th...
[ "The documentation on the Toga website is for version 0.3.0, which is currently in a pre-release state. You can upgrade as follows:\npip3 install --pre --upgrade toga\n\n" ]
[ 1 ]
[]
[]
[ "beeware", "python" ]
stackoverflow_0074233406_beeware_python.txt
Q: How to prevent plotly from adding the wrong label (via bar.update_traces()) to my barplot if I use the color option (px.bar())? New to plotly and going crazy trying to solve this issue. I can color code my data by the value of the 'Generation' column below. I can add the value of my 'Round_Emax' column above the b...
How to prevent plotly from adding the wrong label (via bar.update_traces()) to my barplot if I use the color option (px.bar())?
New to plotly and going crazy trying to solve this issue. I can color code my data by the value of the 'Generation' column below. I can add the value of my 'Round_Emax' column above the bars. However, I can't do both at the same time. It seems like when I specify the color in px.bar(color='Generation) and then try to u...
[ "The most basic addition of a label is to set a text item and then add a setting for automatic text display. px.bar does not allow setting the display position of the label, so the label position is set in the graph update. In this example, some of the text is cut off, so change the y-axis limit. The format for lab...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074262434_plotly_python.txt
Q: InvalidArgumentError: Input filename tensor must be scalar, but had shape: [1] [Op:ReadFile] I have trained an image classifier. Now I want to feed some images to get some predictions, using the below code. def fd(t_embeddings, imagesss, k=1, normalize=True): imgr = tf.io.read_file(imagesss) imgr = tf.expand_d...
InvalidArgumentError: Input filename tensor must be scalar, but had shape: [1] [Op:ReadFile]
I have trained an image classifier. Now I want to feed some images to get some predictions, using the below code. def fd(t_embeddings, imagesss, k=1, normalize=True): imgr = tf.io.read_file(imagesss) imgr = tf.expand_dims(imgr, axis=0) i_embedding = vision_encoder(tf.image.resize(imgr, (299, 299))) if normalize...
[ "The input type for tf.io.read_file has to be a string. It cannot be a list [im].\nTry:\nimport tensorflow as tf\n\nimagesss = '/content/result_image.png'\n\nimgr = tf.io.read_file(imagesss)\n\nIf you have multiple images, you can use a loop to go through them all.\nSee the docs for more information.\n" ]
[ 1 ]
[]
[]
[ "deep_learning", "keras", "python", "tensorflow" ]
stackoverflow_0074254333_deep_learning_keras_python_tensorflow.txt
Q: AttributeError: module 'os' has no attribute 'uname' (drf with docker) Hi Im using docker and drf, and here is my actions and problems. first, I run this instruction: pip install -r requirements.txt --use-deprecated=legacy-resolver and my requirements file is this.: asgiref==3.5.2 backports.zoneinfo==0.2.1 Django...
AttributeError: module 'os' has no attribute 'uname' (drf with docker)
Hi Im using docker and drf, and here is my actions and problems. first, I run this instruction: pip install -r requirements.txt --use-deprecated=legacy-resolver and my requirements file is this.: asgiref==3.5.2 backports.zoneinfo==0.2.1 Django==4.1.2 django-dotenv==1.4.2 djangorestframework==3.14.0 mysql-connector-pyt...
[ "If you check the documentation of uname you will see;\nAvailability: recent flavors of Unix.\nYou may want to check this answer.\nPython program running inside docker container relies upon 'uname -r'\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "operating_system", "python" ]
stackoverflow_0074262782_django_django_rest_framework_operating_system_python.txt
Q: why does it say Syntax,Error: invalid syntax at line 5 from random import* def saisie(): ch1="" for i in range (1,9): ch1[i]=chr(randint(ord'A',ord'Z')) ch1=ch1+ch1[i] return ch1 i wanted to get a word randomly selected with capital and 8 letters A: ord is a function, so you should ...
why does it say Syntax,Error: invalid syntax at line 5
from random import* def saisie(): ch1="" for i in range (1,9): ch1[i]=chr(randint(ord'A',ord'Z')) ch1=ch1+ch1[i] return ch1 i wanted to get a word randomly selected with capital and 8 letters
[ "ord is a function, so you should change your code like this\nfrom random import*\ndef saisie():\n ch1=\"\"\n for i in range (1,9):\n ch1[i]=chr(randint(ord('A'),ord('Z')))\n ch1=ch1+ch1[i]\n return ch1\n\nUPD\nas @John Coleman said there is still bugs in code\n\nindex will be out of bounds\n...
[ 1 ]
[]
[]
[ "chr", "letter", "ord", "python", "random" ]
stackoverflow_0074263160_chr_letter_ord_python_random.txt
Q: How to import or inject dependencies with `Depends()` in an interactive shell? I'm using FastAPI and finding some features related with interactive shell. Unfortunately, I couldn't find it and just tried to run below code on ipython. # src/repositories/__init__.py class A: def greet(self) -> str: prin...
How to import or inject dependencies with `Depends()` in an interactive shell?
I'm using FastAPI and finding some features related with interactive shell. Unfortunately, I couldn't find it and just tried to run below code on ipython. # src/repositories/__init__.py class A: def greet(self) -> str: print('hello') return 'hello' class B: def __call__(self, a: A = Depends()...
[ "The issue isn't related at all to running it in a Python interactive shell (be it IPython, Jupyter, etc.), because you'll get the same problem if you run it is a regular Python script:\n$ cat test.py \nfrom fastapi import Depends\n\nclass A:\n def greet(self) -> str:\n print('hello')\n return 'hel...
[ 0 ]
[]
[]
[ "fastapi", "ipython", "python" ]
stackoverflow_0073890754_fastapi_ipython_python.txt
Q: Grouping a Pandas df by two columns and aggregate over lvl 1 in group I'm new to programming overall, and I'm struggling with some pandas df aggregation. I'm trying to group a df by two columns "A" and "B" and then the series to display the frequency of B, over all the data, not only the group. I'm trying the belo...
Grouping a Pandas df by two columns and aggregate over lvl 1 in group
I'm new to programming overall, and I'm struggling with some pandas df aggregation. I'm trying to group a df by two columns "A" and "B" and then the series to display the frequency of B, over all the data, not only the group. I'm trying the below. group = df.groupby(['A', 'B']).size() ###this will show only the group f...
[ "You can use the pd.pivot_table to do the summary:\n# Import packages\nimport pandas as pd, numpy as np\n\n# Initialize a sample dataframe\ndf = pd.DataFrame({\n \"Transacion_ID\": [1, 2, 3, 4, 5, 6, 7, 8, 9],\n \"Product\": [\"milk\", \"milk\", \"milk\", \"milk\", \"milk\",\n \"bread...
[ 0 ]
[]
[]
[ "pandas_groupby", "python" ]
stackoverflow_0072016212_pandas_groupby_python.txt
Q: Expand bounding boxes in edges of images to square I have a function designed to expand bounding boxes in images to squares. def expand_bbox(bbox, img_shape): h, w = bbox[2] - bbox[0], bbox[3] - bbox[1] if h < w: d = w - h u = min(bbox[0], d // 2) v = d - u bbox[0] -= u ...
Expand bounding boxes in edges of images to square
I have a function designed to expand bounding boxes in images to squares. def expand_bbox(bbox, img_shape): h, w = bbox[2] - bbox[0], bbox[3] - bbox[1] if h < w: d = w - h u = min(bbox[0], d // 2) v = d - u bbox[0] -= u bbox[2] += v else: d = h - w u...
[ "I am pretty sure all this code could be prettier, but if you search for a working code, I would go for adding some ifs:\n# if increasing the upper edge position would go outside the img_shape, do not increase it, decrease bottom instead.\nif bbox[2] + v > img_shape[0]:\n bbox[0] -= u + v\nelse:\n bbox[0] -= ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074263072_python.txt
Q: adding items to a dictionary I'm converting adjacency matrix to adjacency list. I need to add items to a dictionary and return it in a function, but output is the only last item. How to makes an output full list of items? def adjmat_to_adjlist(adjmat: List[List[int]]) -> Dict[int, List[int]]: for key, i in en...
adding items to a dictionary
I'm converting adjacency matrix to adjacency list. I need to add items to a dictionary and return it in a function, but output is the only last item. How to makes an output full list of items? def adjmat_to_adjlist(adjmat: List[List[int]]) -> Dict[int, List[int]]: for key, i in enumerate(adjmat, start = 1): ...
[ "Before both cycles:\nadjlist = {}\n\nThen, instead of:\nadjlist = {key : g}\n\ndo:\nadjlist[key] = g\n\n" ]
[ 1 ]
[]
[]
[ "adjacency_list", "adjacency_matrix", "python" ]
stackoverflow_0074263203_adjacency_list_adjacency_matrix_python.txt
Q: Python Networkx graph on x, y axis and having the edge attribute plot on the z axis matching the Networkx graph edges I have a 2D directional networkx graph representing underground pipeline networks, where the edge of the Networkx graph represent a single pipeline. I have set the attribute of each edge in the gra...
Python Networkx graph on x, y axis and having the edge attribute plot on the z axis matching the Networkx graph edges
I have a 2D directional networkx graph representing underground pipeline networks, where the edge of the Networkx graph represent a single pipeline. I have set the attribute of each edge in the graph to be a NumPy array containing the following pressure distribution. Length (each pipe) Pressure 0 100 10 90 ...
[ "Personally, I would draw the network in 2D and use color to denote pressure.\nHowever, you absolutely can use the z-axis instead. Networkx doesn't support custom edge paths, so you have to compute and draw them yourself.\n\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as...
[ 1 ]
[]
[]
[ "3d", "graph", "networkx", "python", "visualization" ]
stackoverflow_0074229910_3d_graph_networkx_python_visualization.txt
Q: How to iterate over nested list to input missing values I have two objects, a variable (username), and a list (products) of products and costs usernames = ['Dave','mary','John'] products (nested list) [['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'], ['pr1', '23.0', 'pr...
How to iterate over nested list to input missing values
I have two objects, a variable (username), and a list (products) of products and costs usernames = ['Dave','mary','John'] products (nested list) [['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'], ['pr1', '23.0', 'pr2', '45,4']] All prices are unique to each customer. Similar...
[ "you can try dict\nusernames = ['Dave','mary','John']\n\nproducts = [['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'],['pr1', '23.0', 'pr2', '45,4']]\ndef get_products(data):\n template = {f'pr{i}': 'N/A' for i in range(1,5)}\n template.update(**data)\n return lis...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074262873_python_python_3.x.txt
Q: Python Pandas Web Scraping I'm trying to turn a list of tables on this page into a Pandas DataFrame: https://intermediaries.hsbc.co.uk/products/product-finder/ I want to select the customer type box only and select one of the elements (from first to last) and then click find product to display the table for each o...
Python Pandas Web Scraping
I'm trying to turn a list of tables on this page into a Pandas DataFrame: https://intermediaries.hsbc.co.uk/products/product-finder/ I want to select the customer type box only and select one of the elements (from first to last) and then click find product to display the table for each one before concatenating all the ...
[ "All data for the table is located inside javascript file. You can use re/json to parse it and then construct the dataframe:\nimport re\nimport json\nimport requests\nimport pandas as pd\n\n\njs_src = \"https://intermediaries.hsbc.co.uk/component---src-pages-products-product-finder-js-9c7004fb8446c3fe0a07.js\"\ndat...
[ 3, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "select", "web_scraping" ]
stackoverflow_0074263178_dataframe_pandas_python_select_web_scraping.txt
Q: Combine lists with common elements Say I have for example the following nested list: L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'], ['Sam','Suri','NewYork'],['Suri','Orlando','Canada']] How can I group these sublists, by getting the union of sublists which have a common element with at least a...
Combine lists with common elements
Say I have for example the following nested list: L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'], ['Sam','Suri','NewYork'],['Suri','Orlando','Canada']] How can I group these sublists, by getting the union of sublists which have a common element with at least another sublist within the group? So for ...
[ "In many cases, modeling a problem as a graph, can make make fairly complicated tasks much easier. In this case, what we'd be looking for from a graph theory point of view, are the connected components of the graph.\nSo a simple way to go about this, is to generate a graph with NetworkX, and add your list as the g...
[ 21, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "networkx", "python" ]
stackoverflow_0053886120_list_networkx_python.txt
Q: Shap library for model explanation gives values outside range of 0 to 1 I have a catboost model and I am trying to draw a decision plot for some of the sample records to see which features are driving the prediction towards 0 or 1. However, I noticed that the range of the model output value is not 0-1 but rather i...
Shap library for model explanation gives values outside range of 0 to 1
I have a catboost model and I am trying to draw a decision plot for some of the sample records to see which features are driving the prediction towards 0 or 1. However, I noticed that the range of the model output value is not 0-1 but rather it ranges from negative 2 to positive 2 Here is a screenshot of 1 such example...
[ "By default, the TreeExplainer does not explain the predicted probabilities, but rather the raw output of the trees, which varies by model. This should explain why you don't recover the probability value of 0.82 for this specific sample.\nTo work with probabilities, you have to change in shap.TreeExplainer() the va...
[ 0 ]
[]
[]
[ "catboost", "python", "shap" ]
stackoverflow_0071086040_catboost_python_shap.txt
Q: BeautifulSoup: Search and replace in the text parts of HTML I want to do a search and replace on the textual part of the content of the HTML elements. E.g., replacing foo with <b>bar</b> in <div id="foo">foo <i>foo</i> hi foo hi</div> should result in <div id="foo"><b>bar</b> <i><b>bar</b></i> hi <b>bar</b> hi</d...
BeautifulSoup: Search and replace in the text parts of HTML
I want to do a search and replace on the textual part of the content of the HTML elements. E.g., replacing foo with <b>bar</b> in <div id="foo">foo <i>foo</i> hi foo hi</div> should result in <div id="foo"><b>bar</b> <i><b>bar</b></i> hi <b>bar</b> hi</div> I already have a working version in Perl, but the HTML parse...
[ "\nSearch all text nodes containing foo\nCreate a b element\nReplace the text with the new element\nInsert the desired text into the b\n\nfrom bs4 import BeautifulSoup, NavigableString, Tag\nimport re\nimport html\n\nhtmlString = '''\n<div id=\"foo\">foo <i>foo</i> hi foo hi</div>\n'''\n\nsoup = BeautifulSoup(htmlS...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "regex" ]
stackoverflow_0074263235_beautifulsoup_html_python_regex.txt
Q: Could not import "D": FLASK_APP from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' I am new to Flask. I wrote this basic code and save it in hello.py in my D:\Cat_vs_Dog\scripts folder. Then in command prompt, I wrote the following commands. C:\Users\Ketan...
Could not import "D": FLASK_APP
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' I am new to Flask. I wrote this basic code and save it in hello.py in my D:\Cat_vs_Dog\scripts folder. Then in command prompt, I wrote the following commands. C:\Users\Ketan Ingale>set FLASK_APP=D:\Cat_vs_Dog\s...
[ "Flask v1.1.x\nhttps://flask.palletsprojects.com/en/1.1.x/cli/#application-discovery\nThe above documentation link describes:\n\nThe flask command is installed by Flask, not your application; it must be told where to find your application in order to use it. The FLASK_APP environment variable is used to specify how...
[ 24, 9, 1, 1, 0, 0, 0 ]
[ "If it shows an import error, it most likely means you didn't set the environment variable for FLASK_APP properly.\nIf you're on windows, use $env:FLASK_APP=\"nameofyourapp.py\"\nOn Mac and Linux bash:\nset FLASK_APP=nameofyourapp.py\nIf it still shows the error, make sure you're in the powershell terminal not the ...
[ -1 ]
[ "cmd", "flask", "python", "user_interface" ]
stackoverflow_0052581576_cmd_flask_python_user_interface.txt
Q: SQL to Django ORM for group by with distinct What would be the django orm translation of the below query? select date(start_date) as start, count(*) as tournament_count, count(distinct(user_id)) from tournament group by start I think it should look something like Tournament.objects.annotate(date=TruncDate('start_...
SQL to Django ORM for group by with distinct
What would be the django orm translation of the below query? select date(start_date) as start, count(*) as tournament_count, count(distinct(user_id)) from tournament group by start I think it should look something like Tournament.objects.annotate(date=TruncDate('start_date')).values('date').annotate(tournaments=Count(...
[ "You can use distinct=True in your Count function like this one.\n# your query \ntournaments=Count('id', distinct=True)\n\nThis is the SQL equivalent of COUNT(DISTINCT your_field ).\nFor more detail have a look at the django docs\n" ]
[ 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0074263440_django_django_orm_python.txt
Q: multiply a column by a number in pandas skip or make it zeros if the column does not exists So I have table whuich I created a pivot from After the pivot I made the index, columns and used one of the column values as columns from which the expected counts are represented. I'd like to multiply each column(values tu...
multiply a column by a number in pandas skip or make it zeros if the column does not exists
So I have table whuich I created a pivot from After the pivot I made the index, columns and used one of the column values as columns from which the expected counts are represented. I'd like to multiply each column(values turn columns) to a figure, but because some of the values were not created at that point in time, t...
[ "Use DataFrame.dot with mapping columns names:\nd = {'Apple':14,'Banana':110,'Mango':18,'grape':10,'peach':140}\n\ndf1 = pivot.select_dtypes(np.number)\npivot['total'] = df1.dot(df1.columns.map(d).fillna(0))\n#alternative solution\n#pivot['total'] = df1.mul(df1.columns.map(d).fillna(0)).sum(axis=1)\nprint (pivot)\n...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074263506_pandas_python.txt
Q: Do I have to override .__init__ in my subclass, or can I just add a few variables? In my Class Items(): I have an .__init__ function that initiates 7 variables. Then I have a subclass Toys(Items): it uses all 7 variables initiated as the Items + 3 extra variables. All of the variables are set when the object is cr...
Do I have to override .__init__ in my subclass, or can I just add a few variables?
In my Class Items(): I have an .__init__ function that initiates 7 variables. Then I have a subclass Toys(Items): it uses all 7 variables initiated as the Items + 3 extra variables. All of the variables are set when the object is created. Simplified Example of what I’m doing now: Class Items(): def __init__(self, ...
[ "you can use args, kewargs\nclass Items():\n def __init__(self, name, color, size):\n self.name = name\n self.color = color\n self.size = size\n\nclass Toys(Items):\n def __init__(self, shape, noise, *args, **kwargs):\n self.shape = shape\n self.noise = noise\n super(...
[ 2, 0 ]
[]
[]
[ "class", "init", "oop", "python" ]
stackoverflow_0074263494_class_init_oop_python.txt
Q: Celery worker not work in docker container I have a k8s cluster where I deploy my django application. I don't use celery beat so I deploy a worker in every container along with django. But for some reason this doesn’t work, if I go into the pod and execute the command manually, then everything is fine, but it does...
Celery worker not work in docker container
I have a k8s cluster where I deploy my django application. I don't use celery beat so I deploy a worker in every container along with django. But for some reason this doesn’t work, if I go into the pod and execute the command manually, then everything is fine, but it doesn’t work through the dockerfile. FROM python:3.1...
[ "\nThere can only be one CMD instruction in a Dockerfile. If you list\nmore than one CMD then only the last CMD will take effect.\n\nsource https://docs.docker.com/engine/reference/builder/#cmd\nI can suggest you to create shell script containing all you commands e.g. run.sh\nand add CMD [\"run.sh\"]\n" ]
[ 1 ]
[]
[]
[ "celery", "docker", "dockerfile", "kubernetes", "python" ]
stackoverflow_0074263525_celery_docker_dockerfile_kubernetes_python.txt
Q: Python Regex - Summing the total of times strings from a list appear in a separate string Regex and text data noob here. I have a list of terms and I want to get a single sum of the total times the strings from my list appear in a separate string. In the example below, the letter "o" appears 3 times in my string ...
Python Regex - Summing the total of times strings from a list appear in a separate string
Regex and text data noob here. I have a list of terms and I want to get a single sum of the total times the strings from my list appear in a separate string. In the example below, the letter "o" appears 3 times in my string and the letter "b" appears 2 times. I've created a variable called allcount which I know doesn'...
[ "You have to find different patterns in your string.\nThis can be done by using pipe | sign\nimport re\n\nmylist = ['o', 'b']\nmy_string = 'Bob is cool'\nonecount = len(re.findall(\"o|b|B\", my_string)) #this works\n\nprint(onecount)\n\n", "Building a Counter and iterating over the list elements would be easier a...
[ 1, 1, 1 ]
[]
[]
[ "count", "python", "python_re", "regex", "text" ]
stackoverflow_0074210675_count_python_python_re_regex_text.txt
Q: Can scrapy start_request not yield or return? I have a scraper which I want to check the url before calling http request and parsing. The url might be None since it is an input arg to the call: def start_requests(self): # url as input to system if url: yield scrapy.Request(url, callback=se...
Can scrapy start_request not yield or return?
I have a scraper which I want to check the url before calling http request and parsing. The url might be None since it is an input arg to the call: def start_requests(self): # url as input to system if url: yield scrapy.Request(url, callback=self.parse) From the docs the start_request function...
[ "What scrapy does with that is\nstart_requests = iter(self.spider.start_requests())\n\nIt works because of yield keyword. This changes return type to generator, so even if url is None, empty generator will be returned and that's why it works (and is perfectly fine). But be careful, if you decide to use list:\ndef s...
[ 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074263029_python_scrapy.txt
Q: Spyder crashed during last session After upgrading Spyder in Anaconda from 3.3.6 to 4.0.1 using pip install --upgrade spyder the error message below popped up when I open the upgraded version of spyder: Spyder crashed during last session. If Spyder does not start at all and before submitting a bug report, please t...
Spyder crashed during last session
After upgrading Spyder in Anaconda from 3.3.6 to 4.0.1 using pip install --upgrade spyder the error message below popped up when I open the upgraded version of spyder: Spyder crashed during last session. If Spyder does not start at all and before submitting a bug report, please try to reset setting to default by runnin...
[ "I had the same problem in win10 which I resolved by updating Spyder. Open Anaconda Prompt:\nconda install -c anaconda spyder\nIt might take several minutes to complete.\n", "This problem is usually caused by not saving correctly the last time you exited.\nAnaconda3 provides a self-contained tool called\nReset Sp...
[ 2, 0 ]
[]
[]
[ "python", "spyder" ]
stackoverflow_0059872073_python_spyder.txt
Q: Increment MAC address in ansible I have a mac address with me. Let's suppose 00:ae:cd:09:db:4f I need to create a loop in which each time this mac address is incremented by value 1. Let's say the loop will be iterated 2 times. Expected output: 00:ae:cd:09:db:50 00:ae:cd:09:db:51 I need to create a list of the ou...
Increment MAC address in ansible
I have a mac address with me. Let's suppose 00:ae:cd:09:db:4f I need to create a loop in which each time this mac address is incremented by value 1. Let's say the loop will be iterated 2 times. Expected output: 00:ae:cd:09:db:50 00:ae:cd:09:db:51 I need to create a list of the output. I tried ipmath(1), tried convert...
[ "Use with_sequence. For example,\n- hosts: localhost\n\n vars:\n\n mac: 00:ae:cd:09:db:4f\n count: 2\n macs: []\n\n tasks:\n\n - set_fact:\n macs: \"{{ macs + [new|join(':')] }}\"\n with_sequence: count=\"{{ count }}\"\n vars:\n arr: \"{{ mac.split(':') }}\"\n ar5: \"{{ ...
[ 3 ]
[]
[]
[ "ansible", "ansible_inventory", "jinja2", "python" ]
stackoverflow_0074262060_ansible_ansible_inventory_jinja2_python.txt
Q: Filtering by column - multiple pd.arrays I have multiple Dataframes from the same measurements at different times. Now I want to find correlating measurements (which can be located by a string in one of the columns called abmn). The problem is that I cannot iterate since all datasets have a different length. Would...
Filtering by column - multiple pd.arrays
I have multiple Dataframes from the same measurements at different times. Now I want to find correlating measurements (which can be located by a string in one of the columns called abmn). The problem is that I cannot iterate since all datasets have a different length. Would you know any solution? example df1 | res | a...
[ "Here is a possible answer to your question. I first see which values are common to both, and then create two new dataframes based on the values to keep.\nHere is the code:\nimport pandas as pd\n\n# generate the dataframes as per the example\ndf1 = pd.DataFrame({\"res\":[3,0,2], \"abmn\":[1234,1245,1256]})\ndf2 = p...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074263166_python.txt
Q: How To Copy Data From Multiple Excel Workbooks&Paste in Multiple Different Excel Workbooks Python I have 40 excel workbooks that are source files, and 40 corresponding excel workbooks that are the destination files, every week I open the 40 source files and manually copy the data from a specific worksheet in each ...
How To Copy Data From Multiple Excel Workbooks&Paste in Multiple Different Excel Workbooks Python
I have 40 excel workbooks that are source files, and 40 corresponding excel workbooks that are the destination files, every week I open the 40 source files and manually copy the data from a specific worksheet in each file and paste it into the corresponding destination file. I want to automate this task with Python and...
[ "I don't think your code is working but maybe this can guide you a bit:\nimport os\nfrom glob import glob\nfrom openpyxl import load_workbook\n\n\ndef copy_data(src_file: str, dst_file: str) -> None:\n # open files\n ws_src = load_workbook(src_file)[\"Report Data\"]\n wb_dst = load_workbook(dst_file, keep_...
[ 1 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0074256536_openpyxl_python.txt
Q: Tasks and operators order in airflow I have a dag with operator and two tasks. I can't understand how to make tasks and operators linear. I expected to have scheme like FIRST -> SECOND -> THIRD But have FIRST and SECOND in parallel and after THIRD My code: first = MyOwnOperator( task_id='first', ) @task() d...
Tasks and operators order in airflow
I have a dag with operator and two tasks. I can't understand how to make tasks and operators linear. I expected to have scheme like FIRST -> SECOND -> THIRD But have FIRST and SECOND in parallel and after THIRD My code: first = MyOwnOperator( task_id='first', ) @task() def second(): return 'some value to thi...
[ "You can do like this using a temporary variable.\nsecond_ret = second()\nfirst >> second_ret\nthird(second_ret)\n\nIt will be prettier, if you add a dummy argument to the second() like this.\n@task()\ndef second(dummy):\n ...\n\nthird(second(first()))\n\n" ]
[ 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074256114_airflow_python.txt
Q: How can I be sure that a Library like Pandas is not sending my API Key Secrets to places outside from my Local? Let's say: I have my python code in main.py and I am using Pandas I am storing my API Key(to some azure service) in a Windows Environment Variable ( variable name = "AZURE_KEY" and variable_value = "abc...
How can I be sure that a Library like Pandas is not sending my API Key Secrets to places outside from my Local?
Let's say: I have my python code in main.py and I am using Pandas I am storing my API Key(to some azure service) in a Windows Environment Variable ( variable name = "AZURE_KEY" and variable_value = "abc123abc") I will import this API Key in main.py using azure_key = os.environ.get("AZURE_KEY") Question: How can I be ...
[ "\nFor a production system (on a server), you could use a firewall to filter outgoing connections\nFor a development system (your machine), you could add restrictions to the \"API Key\" account (e.g. only access test data, only access systems you really need, etc.)\n\n" ]
[ 1 ]
[]
[]
[ "azure", "python", "secret_key" ]
stackoverflow_0074263612_azure_python_secret_key.txt
Q: AssertionError using dissolve function from GeoPandas v0.11 I am having an issue lately with the latest version of geopandas (0.11) that was not present when I run this code some months ago (around April 2022). I am wondering if this is due to a new update on this package. I have a GeoDataframe called shapefile_HD...
AssertionError using dissolve function from GeoPandas v0.11
I am having an issue lately with the latest version of geopandas (0.11) that was not present when I run this code some months ago (around April 2022). I am wondering if this is due to a new update on this package. I have a GeoDataframe called shapefile_HD with the following data: heat demand ("HD"), geometry (squares o...
[ "Have simulated an equivalent GeoDataFrame. This does not fail on my env using geopandas v0.11\nimport geopandas as gpd\nimport numpy as np\nimport shapely.geometry\n\ngdfp = gpd.read_file(gpd.datasets.get_path(\"naturalearth_cities\")).loc[lambda d: d[\"name\"].eq(\"London\")]\ncrs = gdfp.estimate_utm_crs()\nSTEP ...
[ 0, 0 ]
[]
[]
[ "assertion", "geopandas", "jupyter", "python" ]
stackoverflow_0074127988_assertion_geopandas_jupyter_python.txt
Q: Retrieving all tags with multiple conditions without knowing the names of the respective attributes I want to find all tags that have attribute values equal to "ATTR1" and "ATTR2" without knowing the corresponding attribute names. Let's assume I have the following: page_content = '''<a href="ATTR1">text1</a> <div ...
Retrieving all tags with multiple conditions without knowing the names of the respective attributes
I want to find all tags that have attribute values equal to "ATTR1" and "ATTR2" without knowing the corresponding attribute names. Let's assume I have the following: page_content = '''<a href="ATTR1">text1</a> <div class="random_value" type="ATTR2">text2</div> <script class="ATTR1" id="ATTR2">text3</script> <span class...
[ "Knowing the attribute names, simply chain your conditions e.g. with css selector:\nselect('#ATTR2.ATTR1')\n\nOr without knowing the attributes and just checking all values against:\nfor e in soup():\n attr_list = [v for i in list(e.attrs.values()) for v in (i if isinstance(i,list) else [i])]\n if all(x in at...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074263623_beautifulsoup_python_web_scraping.txt
Q: Is there a maximum number of classes I can train in keras? Hey i train a neural network with keras. I have 14 categories. Everything works and there is no error. But when I look at the result I see that the last 3 trained categories are completely wrong. No testobject is connected to the 3 categories. I already ...
Is there a maximum number of classes I can train in keras?
Hey i train a neural network with keras. I have 14 categories. Everything works and there is no error. But when I look at the result I see that the last 3 trained categories are completely wrong. No testobject is connected to the 3 categories. I already changed the order of the input but also the last 3 categories ar...
[ "Maybe there is a small mistake that your third Dense layer has an input_dim = 56, but your second Dense layer has 50 nodes.\n", "There is no maximum theoretically, but your results will be limited by the performance of your training machine and the amount of relevant data per class you can collect. If there are ...
[ 0, 0 ]
[]
[]
[ "classification", "keras", "neural_network", "python" ]
stackoverflow_0055646730_classification_keras_neural_network_python.txt
Q: Concatenate a .xls file list into .csv I'm trying to concatenate a .xls file list into .csv: import glob import pandas as pd file_xls = glob.glob(location + "\*.xls") print(file_xls) read_file = pd.read_excel(location + file_xls) but I have an error about the concatenation of the list: TypeError: can only concat...
Concatenate a .xls file list into .csv
I'm trying to concatenate a .xls file list into .csv: import glob import pandas as pd file_xls = glob.glob(location + "\*.xls") print(file_xls) read_file = pd.read_excel(location + file_xls) but I have an error about the concatenation of the list: TypeError: can only concatenate str (not "list") to str Is there a sp...
[ "I think instead of concatenating strings, you should use os.path.join():\nfile_xls = glob.glob(location + \"\\*.xls\")\n\nWill return a list of all the file names in the specified root (defined by the user as location)\nfiles = [pd.read_excel(os.path.join(location,x)) for x in file_xls]\n\nReturns a list of all fi...
[ 2 ]
[]
[]
[ "csv", "glob", "pandas", "python", "xls" ]
stackoverflow_0074263827_csv_glob_pandas_python_xls.txt
Q: Too Much Wait TIme So I was trying to use a procedure(with a parameter)...I asked the user for inputs and created a validate function to check the inputs and see if they are strings...I checked it but the outputs are taking too long to output. How do I fix this? I tried: # Create Validate function def validate_in...
Too Much Wait TIme
So I was trying to use a procedure(with a parameter)...I asked the user for inputs and created a validate function to check the inputs and see if they are strings...I checked it but the outputs are taking too long to output. How do I fix this? I tried: # Create Validate function def validate_input(LETTER): while Tru...
[ "the input() function in python always take the inputs as string, if you want to get integer as input then the following functions would be used => int(input())\nit is not taking too long to execute it just a logical error in your code ;)\nlets say the the input is \"hello\" so the len(\"hello\") is 5\nnow , the in...
[ 1 ]
[]
[]
[ "input", "procedure", "python" ]
stackoverflow_0074263683_input_procedure_python.txt
Q: Import "phonenumber_field.modelfields" could not be resolved I have django project and I try to add phonenumber package, I've done 'pip install django-phonenumber-field[phonenumbers]' and I imported the library to my .models but it shows up as an error but it works anyways, the error is called: "Import "phonenumbe...
Import "phonenumber_field.modelfields" could not be resolved
I have django project and I try to add phonenumber package, I've done 'pip install django-phonenumber-field[phonenumbers]' and I imported the library to my .models but it shows up as an error but it works anyways, the error is called: "Import "phonenumber_field.modelfields" could not be resolved(reportMissingImports)" ...
[ "Try adding it to settings as well. Here’s the example from the docs:\nINSTALLED_APPS = [\n ...\n 'phonenumber_field',\n ...\n]\n\n", "Don’t do that pip install django-phonenumber-field[phonenumbers] and try this instead pip install django-phonenumber-field\n" ]
[ 0, 0 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0073437460_django_import_python.txt
Q: Bar chart help in python with value label alignment in the center I use the below code in order to display the bar chart. CODE import numpy as np import matplotlib.pyplot as plt %matplotlib inline #creating the dataset data = {'apples':20,'Mangoes':15,'Lemon':30,'Oranges':10} names = list(data.keys()) values = li...
Bar chart help in python with value label alignment in the center
I use the below code in order to display the bar chart. CODE import numpy as np import matplotlib.pyplot as plt %matplotlib inline #creating the dataset data = {'apples':20,'Mangoes':15,'Lemon':30,'Oranges':10} names = list(data.keys()) values = list(data.values()) bars = plt.bar(names, height=values, width=0.9) for ...
[ "you can use this code to fix your problem. your arbitrary bar chart figure\n%matplotlib notebook\nimport matplotlib.pyplot as plt\ndata = {'apples' : 20, 'Mangoes' : 15,\n 'Lemon' : 30, 'oranges' : 10}\n\n# we apply asterisk sign on a list of tuples which is returened by \n# sorted() function.\nnames, values = ...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python", "python_3.x" ]
stackoverflow_0063389892_matplotlib_python_python_3.x.txt
Q: How do i hide a variable in Github i am trying to hide a password in my deployment on Github, but neither .gitignore with a config.py file nor dotenv works when i try to deploy. Anyone who knows a solution? I connected my .gitignore to a config.py with my variable: APP_PASSWORD = "blablabla". However, it does not ...
How do i hide a variable in Github
i am trying to hide a password in my deployment on Github, but neither .gitignore with a config.py file nor dotenv works when i try to deploy. Anyone who knows a solution? I connected my .gitignore to a config.py with my variable: APP_PASSWORD = "blablabla". However, it does not load when i run github through Heroku. D...
[ "I faced a similar issue; I had worked on a Discord bot, and I was trying to deploy it through Heroku. Instead of dotenv, I went on my Heroku dyno / project, and under settings, I created a config var, with the key being \"TOKEN\" and the value being my bot token. I was able to access this in my main.py by saying o...
[ 0 ]
[]
[]
[ "dotenv", "environment_variables", "github", "python" ]
stackoverflow_0074263464_dotenv_environment_variables_github_python.txt
Q: How to map month name to month number and vice versa? I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online. I was thinking about the calendar module. I ...
How to map month name to month number and vice versa?
I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online. I was thinking about the calendar module. I see that to convert from month number to abbreviated month ...
[ "Create a reverse dictionary using the calendar module (which, like any module, you will need to import):\n{month: index for index, month in enumerate(calendar.month_abbr) if month}\n\nIn Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do\ndict((mo...
[ 123, 91, 75, 28, 25, 15, 9, 5, 0, 0, 0 ]
[ "Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:\nfrom time import strptime\nmonthWord = 'september'\n\nnewWord = monthWord [0].upper() + monthWord [1:3].lower() \n# converted to \"Sep\"\n\nprint(strptime(newWord,'%b').tm_mon) \n# \"Sep\" converted to ...
[ -1, -1, -1, -1 ]
[ "calendar", "python" ]
stackoverflow_0003418050_calendar_python.txt
Q: Python find substring between two markers Please note i have read other answers on here but they havent worked for me (or I have applied them incorrectly, sorry if I have). I have a list which I have then converted to Dataframe. I have then converted to string using: df['URL'] = pd.Series(df['URL'], dtype="string"...
Python find substring between two markers
Please note i have read other answers on here but they havent worked for me (or I have applied them incorrectly, sorry if I have). I have a list which I have then converted to Dataframe. I have then converted to string using: df['URL'] = pd.Series(df['URL'], dtype="string") However, when i go to use .find, .partition...
[ "You have to use Series.str to access values of the series as strings so that you can start applying the string method(like .find, partition).\nBut a better approach in this case would be use extract which allows to extract capture groups in the regex entry/(\\d+)/event as columns\ndf['URL'].str.extract(\"entry/(\\...
[ 2, 2 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074263806_list_python_python_3.x.txt
Q: Exception has occurred: OSError -> OSError: No such file or directory from nltk.corpus import CategorizedPlaintextCorpusReader reader = (r'/[볼륨명]/Data/NLPCookBook/Reviews/txt_sentoken',r'*\.txt', cat_pattern=r'(\w+/*') Print(reader.categories()) print(reader.fileids()) I tried to learner natural language processi...
Exception has occurred: OSError -> OSError: No such file or directory
from nltk.corpus import CategorizedPlaintextCorpusReader reader = (r'/[볼륨명]/Data/NLPCookBook/Reviews/txt_sentoken',r'*\.txt', cat_pattern=r'(\w+/*') Print(reader.categories()) print(reader.fileids()) I tried to learner natural language processing with python by myself.So I followed exactly what the book said and I got...
[ "Exception has occurred: OSError No such file or directory\nIt just means that the file you are looking for doesnt exist in the path you have specified, try changing the file path.\n" ]
[ 0 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0074263979_nlp_python.txt
Q: How to read and write the data that the user has selected to the database? WTForms Faced with such a situation, I can not understand what needs to be written so that I consider what I choose to use from the select. Here are the working parts of the code: Models.py class Customer(db.Model): __tablename__ = 'cus...
How to read and write the data that the user has selected to the database? WTForms
Faced with such a situation, I can not understand what needs to be written so that I consider what I choose to use from the select. Here are the working parts of the code: Models.py class Customer(db.Model): __tablename__ = 'customer' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(2...
[ "this helped me:\ncondition_id = SelectField('condition', choices=[], coerce=int)\n status_id = SelectField('status', choices=[], coerce=int)\n payment_method_id = SelectField('payment_method', choices=[], coerce=int)\n payment_type_id = SelectField('payment_type', choices=[], coerce=int)\n\nWhen selected,...
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "flask_wtforms", "python", "sqlalchemy" ]
stackoverflow_0074141406_flask_flask_sqlalchemy_flask_wtforms_python_sqlalchemy.txt
Q: ValueError: multilabel-indicator format is not supported, cannot make an ROC curve due to error Assuming that I have the following: x_train y_train x_test y_test And there is 7 labels total (0 through 6), I am trying to create a ROC curve for each individual label type of the testing data. I already looked at thi...
ValueError: multilabel-indicator format is not supported, cannot make an ROC curve due to error
Assuming that I have the following: x_train y_train x_test y_test And there is 7 labels total (0 through 6), I am trying to create a ROC curve for each individual label type of the testing data. I already looked at this post,https://stackoverflow.com/questions/65236646/valueerror-multilabel-indicator-format-is-not-sup...
[ "The roc_curve and auc functions only work on 1-d arrays. In your case, you must loop for each label.\nfpr_list = []\ntpr_list = []\nthreshold_list = []\nroc_auc_list = []\n\nfor i in range(7): # you can make this more general\n fpr, tpr, threshold = metrics.roc_curve(y_test[:, i], y_pred[:, i])\n roc_auc = m...
[ 1 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "python_3.x", "roc" ]
stackoverflow_0074258347_deep_learning_machine_learning_python_python_3.x_roc.txt
Q: Bottle framework and OOP, using method instead of function I've done some coding with Bottle. It's really simple and fits my needs. However, I got stick when I tried to wrap the application into a class : import bottle app = bottle class App(): def __init__(self,param): self.param = param # Doe...
Bottle framework and OOP, using method instead of function
I've done some coding with Bottle. It's really simple and fits my needs. However, I got stick when I tried to wrap the application into a class : import bottle app = bottle class App(): def __init__(self,param): self.param = param # Doesn't work @app.route("/1") def index1(self): ret...
[ "Your code does not work because you are trying to route to non-bound methods. Non-bound methods do not have a reference to self, how could they, if instance of App has not been created?\nIf you want to route to class methods, you first have to initialize your class and then bottle.route() to methods on that object...
[ 42, 30, 29, 3, 3, 0 ]
[]
[]
[ "bottle", "class", "methods", "oop", "python" ]
stackoverflow_0008725605_bottle_class_methods_oop_python.txt
Q: Sum one dataframe based on value of other dataframe in same index/row I would like to sum values of a dataframe conditionally, based on the values of a different dataframe. Say for example I have two dataframes: df1 = pd.DataFrame(data = [[1,-1,5],[2,1,1],[3,0,0]],index=[0,1,2],columns = [0,1,2]) index 0 1 ...
Sum one dataframe based on value of other dataframe in same index/row
I would like to sum values of a dataframe conditionally, based on the values of a different dataframe. Say for example I have two dataframes: df1 = pd.DataFrame(data = [[1,-1,5],[2,1,1],[3,0,0]],index=[0,1,2],columns = [0,1,2]) index 0 1 2 ----------------- 0 1 -1 5 1 2 1 1 2 ...
[ "Another option with Pandas' query:\ndf2.query(\"@df1==1\").sum().sum()\n# 4\n\n", "You can use a mask with where:\ndf2.where(df1.eq(1)).to_numpy().sum()\n# or\n# df2.where(df1.eq(1)).sum().sum()\n\noutput: 4.0\nintermediate:\ndf2.where(df1.eq(1))\n 0 1 2\n0 1.0 NaN NaN\n1 NaN 1.0 2.0\n2 NaN NaN...
[ 4, 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0073728700_dataframe_pandas_python.txt
Q: Nested json files - Python Good afternoon all, I've been reading through the various posts regarding reading .json files using pandas but so far I've not been sucessful extract. I need to read a specific 'score' in the json file of which I'll then iterate through all the json files I have as the label would be the...
Nested json files - Python
Good afternoon all, I've been reading through the various posts regarding reading .json files using pandas but so far I've not been sucessful extract. I need to read a specific 'score' in the json file of which I'll then iterate through all the json files I have as the label would be the same. In the below how would I ...
[ "This is done without pandas\nimport json\n\nwith open(\"my_file.json\", 'r') as f:\n my_dict = json.load(f)\n\nscore = my_dict[\"response_sets\"][\"5b69aee5-0532-46a4-b2f5-d020d4d5381d\"][\"responses\"][0][\"score\"]\n\n" ]
[ 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074264099_json_pandas_python.txt
Q: How add to cache file image to Django HttpResponse How can I solve this? How add cache header in HttpResponse? Now the file is not cached.This module is needed to search and return photos or gifs. Just need to cache the file on the client in the browser. my views: def q(request, slug, name): arr = { 'png'...
How add to cache file image to Django HttpResponse
How can I solve this? How add cache header in HttpResponse? Now the file is not cached.This module is needed to search and return photos or gifs. Just need to cache the file on the client in the browser. my views: def q(request, slug, name): arr = { 'png': 'image/png', 'jpg': 'image/jpeg', 'gif': 'imag...
[ "Django uses middleware to set the cache headers of your responses. In order to override what the middleware is settings, you should use the @cache_control view decorator or the patch_cache_control function, as described here so that the middleware knows this takes precedence and doesn't override the headers:\nfrom...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0056012022_django_python.txt
Q: TypeError: unhashable type: 'Series' While trying to sort DataFrame I got the error when I use the following code: df=df.sort_values(by=['name', 'ID']) I tried also : df=df.sort_values(by=['name', 'ID']).reset_index(drop=True) The error is: TypeError: unhashable type: 'Series' FYI : the dataframe is 21000 rows ...
TypeError: unhashable type: 'Series' While trying to sort DataFrame
I got the error when I use the following code: df=df.sort_values(by=['name', 'ID']) I tried also : df=df.sort_values(by=['name', 'ID']).reset_index(drop=True) The error is: TypeError: unhashable type: 'Series' FYI : the dataframe is 21000 rows × 19 columns
[ "The error occured because there is different data types in the same columns.\nI discovered that values in ID column should be 'np.float64', however some of them are in another type.\nThe dataset is a result of a merge between two dataframes, I think that merge is the main source of the problem.\nI solved the issue...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074262938_dataframe_pandas_python.txt
Q: inspect for functions starting _ I looking at a functions from pyasl module. from PyAstronomy import pyasl import inspect print(inspect.getsource(pyasl.get_lagrange_1)) which shows that the function returns: return _get_lagrange_123(q, eps, 1-eps, getdlrp) How to see the function starting with _, please? A: Si...
inspect for functions starting _
I looking at a functions from pyasl module. from PyAstronomy import pyasl import inspect print(inspect.getsource(pyasl.get_lagrange_1)) which shows that the function returns: return _get_lagrange_123(q, eps, 1-eps, getdlrp) How to see the function starting with _, please?
[ "Since it has a leading _, you need to import it explicitly and then inspect it. From the github repo, it seems that _get_lagrange_123 is defined in src/pyasl/asl/aslExt_1/roche.py, so you might be able to import it using\nfrom PyAstronomy.pyasl.asl.aslExt_1.roche import _get_lagrange_123\nprint(inspect.getsource(_...
[ 2 ]
[]
[]
[ "inspect", "python", "python_3.x" ]
stackoverflow_0074263872_inspect_python_python_3.x.txt
Q: Excecute Python Script When A New Outlook Email Arrives I have created a python script, which I want to run every time a new email arrives in outlook Inbox. So far I have written this VBA code: Sub test() Shell "C:\Users\dimitrios\Anaconda3\Scripts\activate.bat & python C:\Users\dimitrios\test\outlookconnnecti...
Excecute Python Script When A New Outlook Email Arrives
I have created a python script, which I want to run every time a new email arrives in outlook Inbox. So far I have written this VBA code: Sub test() Shell "C:\Users\dimitrios\Anaconda3\Scripts\activate.bat & python C:\Users\dimitrios\test\outlookconnnectivity.py" End Sub The code calls the outlookConnectivity.py s...
[ "Try this\nOption Explicit\n\n'This \"event\" runs whenever there is a new email\nPrivate Sub Application_NewMailEx(ByVal EntryIDCollection As String)\n\n 'Declare as generic Object since we don't know what type of NewMail Item we got yet\n Dim entry As Object\n \n 'Me refers to ThisOutlookSession, the ...
[ 0, 0 ]
[]
[]
[ "automation", "outlook", "python", "vba" ]
stackoverflow_0074262593_automation_outlook_python_vba.txt
Q: How to instantiate a class only once, which is accessible by multiple ProcessPoolExecutor processes? Is it even possible to create a single instance of a class and use ProcessPoolExecutor to access that single instance from multiple processes? Or will ProcessPoolExecutor ALWAYS instantiate a copy of the class for ...
How to instantiate a class only once, which is accessible by multiple ProcessPoolExecutor processes?
Is it even possible to create a single instance of a class and use ProcessPoolExecutor to access that single instance from multiple processes? Or will ProcessPoolExecutor ALWAYS instantiate a copy of the class for every process, even if the class is created outside of main() ? Am trying to load a single Tensorflow save...
[ "There is nothing in your posted class definition of DDQN that would require a single, sharable object or locking across all processes since no attributes are being modified. I also do not see where attributes saveModelName and instanceList are even referenced. Also, if the entire definition of DDQN.get_qs is a cri...
[ 0 ]
[]
[]
[ "class", "locking", "multiprocessing", "python", "tensorflow" ]
stackoverflow_0074214765_class_locking_multiprocessing_python_tensorflow.txt
Q: Avoid writing multiple lines (same piece of code) by using a one line function I would like to write the below piece of code in one line. All 9 lines are same (except the column name, ex: Two, Three, Four, etc.,) Below is my code: Note: 'df' is my data frame name. df['Two'] = df['Two'].map(lambda x: re.sub(r'\W+',...
Avoid writing multiple lines (same piece of code) by using a one line function
I would like to write the below piece of code in one line. All 9 lines are same (except the column name, ex: Two, Three, Four, etc.,) Below is my code: Note: 'df' is my data frame name. df['Two'] = df['Two'].map(lambda x: re.sub(r'\W+', ' ', x)) df['Three'] = df['Three'].map(lambda x: re.sub(r'\W+', ' ', x)) df['Four']...
[ "df.columns holds the column names of the df object. So iterate over the column names, dynamically select each column with df[col] and apply your map function.\nfor col in df.columns:\n df[col]=df[col].map(lambda x: re.sub(r'\\W+', ' ', x))\n\n" ]
[ 0 ]
[]
[]
[ "loops", "optimization", "python" ]
stackoverflow_0074264253_loops_optimization_python.txt
Q: Python 3.9 caused TypeError: int() argument must be a string, a bytes-like object or a number, not '_NoValueType' I am converting python 2.7 to python 3.9 with pandas 1.1.5 currently. The below code working in python 2.7 but caused an error when it is in 3.9 (or due to upgrading pandas as well) agent = 'Mozilla/5....
Python 3.9 caused TypeError: int() argument must be a string, a bytes-like object or a number, not '_NoValueType'
I am converting python 2.7 to python 3.9 with pandas 1.1.5 currently. The below code working in python 2.7 but caused an error when it is in 3.9 (or due to upgrading pandas as well) agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' headers = {'...
[ "I think data = pd.DataFrame(data.loc['quoteResponse']['result']) could work, let me know if it did\nEDIT:\ndo this before, to turn the dictionary into a dataframe, and then you can use .loc\npd.DataFrame.from_dict(data)\n", "This is problem with python 3.9 with pandas 1.1.5.\nBy running python 3.8 with pandas 1....
[ 0, 0 ]
[]
[]
[ "json", "pandas", "python", "python_3.x" ]
stackoverflow_0074253559_json_pandas_python_python_3.x.txt
Q: Using in range(..) in an if-else statment python 2.7 Is it possible to do this: print "Enter a number between 1 and 10:" number = raw_input("> ") if number in range(1, 5): print "You entered a number in the range of 1 to 5" elif number in range(6, 10): print "You entered a number in the range of 6 to 10" ...
Using in range(..) in an if-else statment
python 2.7 Is it possible to do this: print "Enter a number between 1 and 10:" number = raw_input("> ") if number in range(1, 5): print "You entered a number in the range of 1 to 5" elif number in range(6, 10): print "You entered a number in the range of 6 to 10" else: print "Your number wasn't in the corr...
[ "It is because the input data is string. So it flows to else. Convert it into integer then all will be fine.\n>>> number = raw_input(\"> \")\n>>> type(number)\n<type 'str'>\nint(number) converts to <type 'int'>\n\nPlease use:\nif int(number) in range(1, 6):\n print \"You entered a number in the range of 1 to 5\"...
[ 12, 5, 3, 1, 1, 1 ]
[ "print (\"Enter a number between 1 and 10:\")\nnumber = int(input(\"Enter a number: \"))\nif number in range(1, 5):\nprint (\"You entered a number in the range of 1 to 5\")\n\nelif number in range(6, 10):\nprint (\"You entered a number in the range of 6 to 10\")\n\nelse:\nprint (\"Your number wasn't in the correct ...
[ -2 ]
[ "python" ]
stackoverflow_0012140185_python.txt
Q: Expand pandas columns with dict while keeping fragment of column name I have a dataset in which some columns have lookup values. There are several such columns in the dataset. I need to expand these columns so that the column name consists of the name of the column itself and the keys in the dict. Example df: df c...
Expand pandas columns with dict while keeping fragment of column name
I have a dataset in which some columns have lookup values. There are several such columns in the dataset. I need to expand these columns so that the column name consists of the name of the column itself and the keys in the dict. Example df: df col1 col2 col3 a '{key_1: 1a, key_2: 2a}' ...
[ "If in columns are dictionaries, not strings use list comprehension with json_normalize:\ncols = ['col2','col3']\n\nprint (type(df['col2'].iat[0]))\n<class 'dict'>\n\ndfs = [pd.json_normalize(df.pop(x)).add_prefix(f'{x}_') for x in cols]\ndf = df.join(pd.concat(dfs, axis=1))\n\nprint (df)\n col1 col2_key_1 col2_ke...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074264140_dataframe_pandas_python.txt
Q: Read file.csv (two columns; x and y) then calculate cumulative moving average of second column I wanted to read my CSV file first. https://github.com/hamzaal014/file/blob/main/file.csv the .csv file contains two columns X and Y here is my script: import numpy as np from pandas import DataFrame as df import csv or...
Read file.csv (two columns; x and y) then calculate cumulative moving average of second column
I wanted to read my CSV file first. https://github.com/hamzaal014/file/blob/main/file.csv the .csv file contains two columns X and Y here is my script: import numpy as np from pandas import DataFrame as df import csv origin_data = open("file.csv", "r") dato = list(csv.reader(origin_data, delimiter=",")) print(dato) r...
[ "When reading from a file you are returned strings. This is the source of your problem since the strings are never converted into numbers. You can fix it by:\ndati = df(dato, columns=['x', 'y'], dtype_float)\n\nIf it is helpful to you I would also like to poit out a few things that may improve your code:\n\nyou are...
[ 1, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074264146_numpy_pandas_python.txt