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: How can I count the keys in list of dictionaries? | python For example there is a list: list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969} ...] I want to count there are how many model from each. How can I do it? By the way sorry for the bad formatti...
How can I count the keys in list of dictionaries? | python
For example there is a list: list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969} ...] I want to count there are how many model from each. How can I do it? By the way sorry for the bad formatting I am new here yet. I tried this method: model_count = {} for...
[ "Assuming the key \"Model\" appears in every dictionary capitalized like this, you can use the code below\nmy_list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'Model': 'Skyline', 'year': 1969}]\n\nmodels = {}\nfor dictionary in my_list:\n model = dictionary.get('Model', None)\n ...
[ 0, 0 ]
[]
[]
[ "count", "dictionary", "each", "list", "python" ]
stackoverflow_0074524306_count_dictionary_each_list_python.txt
Q: Is it possible to use pandas.DataFrame.rolling with a step greater than 1? In R you can compute a rolling mean with a specified window that can shift by a specified amount each time. However maybe I just haven't found it anywhere but it doesn't seem like you can do it in pandas or some other Python library? Does a...
Is it possible to use pandas.DataFrame.rolling with a step greater than 1?
In R you can compute a rolling mean with a specified window that can shift by a specified amount each time. However maybe I just haven't found it anywhere but it doesn't seem like you can do it in pandas or some other Python library? Does anyone know of a way around this? I'll give you an example of what I mean: Here ...
[ "So, I know it is a long time since the question was asked, by I bumped into this same problem and when dealing with long time series you really would want to avoid the unnecessary calculation of the values you are not interested at. Since Pandas rolling method does not implement a step argument, I wrote a workarou...
[ 7, 6, 6, 1, 0, 0 ]
[]
[]
[ "numpy", "pandas", "python", "r", "zoo" ]
stackoverflow_0054301042_numpy_pandas_python_r_zoo.txt
Q: If python doesn't find certain value inside JSON, append something inside list I'm making a script with Python to search for competitors with a Google API. Just for you to see how it works: First I make a request and save data inside a Json: # make the http GET request to Scale SERP api_result = requests.g...
If python doesn't find certain value inside JSON, append something inside list
I'm making a script with Python to search for competitors with a Google API. Just for you to see how it works: First I make a request and save data inside a Json: # make the http GET request to Scale SERP api_result = requests.get('https://api.scaleserp.com/search', params) # Save data inside Json dado...
[ "you should use the get method for dicts so you can set a default value incase the key doesn't exist:\nfor sCompetitors in dados['organic_results']:\n sPositions.append(sCompetitors.get('position', 'no position'))\n sDomains.append(sCompetitors.get('domain', 'no domain'))\n sUrls.append(sCompetitors.get('l...
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074524284_json_python.txt
Q: MSEdgeDriver - session not created: No matching capabilities found error on Selenium with Python Having some trouble getting our automation to run on Microsoft Edge. Have the correct browser version driver installed and have tried a few other 'fixes' to no avail. This is using Selenium with Python3 on PyCharm. Goi...
MSEdgeDriver - session not created: No matching capabilities found error on Selenium with Python
Having some trouble getting our automation to run on Microsoft Edge. Have the correct browser version driver installed and have tried a few other 'fixes' to no avail. This is using Selenium with Python3 on PyCharm. Going back to the beginning, this is my code... from selenium import webdriver from selenium.webdriver.su...
[ "I guess you're using Edge Chromium, you can refer to the steps below to automate Edge browser using Selenium python code:\n\nDownload and install the Python from this link.\n\nLaunch the command prompt as an Administrator.\n\nRun the command below to install the Edge Selenium tools.\npip install msedge-selenium-to...
[ 1, 0 ]
[]
[]
[ "automation", "microsoft_edge", "python", "selenium", "selenium_edgedriver" ]
stackoverflow_0066479396_automation_microsoft_edge_python_selenium_selenium_edgedriver.txt
Q: Understanding NumPy split function to extract sub-grid So I was given a worksheet exercise as follows: Given the following grid of 25 values, extract the central 3 x 3 sub-grid of 9s from the larger grid using the split() function: 1 2 3 4 5 1 9 9 9 5 1 9 9 9 5 1 9 9 9 5 1 2 3 4 5 And the solution is as follows:...
Understanding NumPy split function to extract sub-grid
So I was given a worksheet exercise as follows: Given the following grid of 25 values, extract the central 3 x 3 sub-grid of 9s from the larger grid using the split() function: 1 2 3 4 5 1 9 9 9 5 1 9 9 9 5 1 9 9 9 5 1 2 3 4 5 And the solution is as follows: x = np.array([[1,2,3,4,5], [1, 9, 9, 9, 5], ...
[ "In [755]: x = np.array([[1,2,3,4,5],\n ...: [1, 9, 9, 9, 5],\n ...: [1, 9, 9, 9, 5],\n ...: [1, 9, 9, 9, 5],\n ...: [1, 2, 3, 4, 5]])\n\nIf all you need is one block, just slice directly:\nIn [756]: x[1:4,1:4]\nOut[756]: \narray([[9, 9, 9],\n [9, 9, 9],\n ...
[ 0 ]
[]
[]
[ "numpy", "python", "split" ]
stackoverflow_0074524188_numpy_python_split.txt
Q: Is it possible to use Tweepy to gather a random sample of all Tweets on Twitter for a given time interval? I'm currently using Tweepy (academic access) to obtain Tweets over a given time interval. I am using a general query, and I only want a 100,000 Tweets. The Twitter API gives back the most recent 100,000 Tweet...
Is it possible to use Tweepy to gather a random sample of all Tweets on Twitter for a given time interval?
I'm currently using Tweepy (academic access) to obtain Tweets over a given time interval. I am using a general query, and I only want a 100,000 Tweets. The Twitter API gives back the most recent 100,000 Tweets for the given time interval. Instead, I want 100,000 random Tweets from the given time interval. Here is what ...
[ "Measure the recent mean daily tweet rate,\nso you have a conversion factor\nto go back and forth between\nnum_tweets and interval_duration.\nExhaustively query some recent timeframe,\nobtaining some tens of thousands of tweets.\nThis is ground truth,\nit captures distributions of interest.\nVerify it by re-queryin...
[ 0 ]
[]
[]
[ "python", "tweepy" ]
stackoverflow_0074513562_python_tweepy.txt
Q: finding specific values in text file python I have a text file that looks like the one above. How do I get python to read the file such that I only obtain the values for 'gps_alt' 'lat' and 'lon'? A: I can't really see how the text file is structured exactly but it looks like a json file so you could try somethi...
finding specific values in text file python
I have a text file that looks like the one above. How do I get python to read the file such that I only obtain the values for 'gps_alt' 'lat' and 'lon'?
[ "I can't really see how the text file is structured exactly but it looks like a json file so you could try something like this to store the text file into a dict:\nimport json\n\nwith open('file.txt') as f:\n data = json.load(f)\n\nthen you have a normal python dictionary and can loop through the keys/values and...
[ 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074524419_file_python.txt
Q: list() method in API causing TypeError: 'list' object is not callable in unit test I'm working on code that retrieves information from Twilio's Flow system through their API. That part of the code functions fine, but when I try to mock it for unit testing, it's throwing an error from the mocked api response. Here ...
list() method in API causing TypeError: 'list' object is not callable in unit test
I'm working on code that retrieves information from Twilio's Flow system through their API. That part of the code functions fine, but when I try to mock it for unit testing, it's throwing an error from the mocked api response. Here is the code being tested: from twilio.rest import Client class FlowChecker: def _...
[ "The problem isn't with .list(), it's with .flows().\nmock_client.studio.v2.flows = [mock_flow]\nmock_client.studio.v2.flows(mock_flow.sid).executions.list().return_value = [mock_execution]\n\nYou assign .flows to be a list, and then you try to call it like a function, which causes the error.\nI think maybe you int...
[ 0 ]
[]
[]
[ "list", "python", "twilio", "twilio_api", "unit_testing" ]
stackoverflow_0074524468_list_python_twilio_twilio_api_unit_testing.txt
Q: How does ZoneInfo handle DST in the distant future? I'm trying to understand how the zoneinfo module figures out daylight savings time transitions in the distant future while it seems that dateutil and pytz both give up on daylight savings time transitions. I know these transitions aren't really meaningful that fa...
How does ZoneInfo handle DST in the distant future?
I'm trying to understand how the zoneinfo module figures out daylight savings time transitions in the distant future while it seems that dateutil and pytz both give up on daylight savings time transitions. I know these transitions aren't really meaningful that far in the future but the inconsistency is potentially a pr...
[ "Unlike dateutil.tz and pytz, the zoneinfo module is capable of parsing Version 3 TZif files, and Version 3 MAY (read: usually do) contain a footer describing a recurring rule for DST transitions. The part of the Python implementation of zoneinfo relating to these rule-based transitions can be found here. This capa...
[ 2 ]
[]
[]
[ "datetime", "python", "python_dateutil", "pytz", "zoneinfo" ]
stackoverflow_0074520944_datetime_python_python_dateutil_pytz_zoneinfo.txt
Q: Unable to use Python keyring module from systemd service I want a python script to automatically start after boot on a linux computer. To achieve this I set up a systemd service: [Unit] Description=My Script Service Wants=network-online.target After=network-online.target After=multi-user.target StartLimitIntervalS...
Unable to use Python keyring module from systemd service
I want a python script to automatically start after boot on a linux computer. To achieve this I set up a systemd service: [Unit] Description=My Script Service Wants=network-online.target After=network-online.target After=multi-user.target StartLimitIntervalSec=3600 StartLimitBurst=60 [Service] Type=idle User=masterofp...
[ "Thanks to the hints, I now got it working via a user unit service.\nThe file is located at ~/.config/systemd/user/myuserunit.service\n[Unit]\nStartLimitIntervalSec=3600\nStartLimitBurst=60\n\n[Service]\nType=simple\nRestart=on-failure\nRestartSec=60s\nExecStart=/home/masterofpuppets/mypythonscript.py\n\n[Install]\...
[ 0 ]
[]
[]
[ "linux", "python", "python_keyring", "systemd" ]
stackoverflow_0074517933_linux_python_python_keyring_systemd.txt
Q: How to split input text into equal size of tokens, not character length, and then concatenate the summarization results for Hugging Face transformers I am using the below methodology to summarize longer than 1024 token size long texts. Current method splits the text by half. I took this from another user's post an...
How to split input text into equal size of tokens, not character length, and then concatenate the summarization results for Hugging Face transformers
I am using the below methodology to summarize longer than 1024 token size long texts. Current method splits the text by half. I took this from another user's post and modified it slightly. So what I want to do is, instead of splitting into half, split whole text into 1024 equal sized tokens and get summarization each o...
[ "I like splitting text using nltk. You can also do it with spacy and the quality is better, but it takes a bit longer. nltk and spacy allow you to cut text into sentences and this is better because the text pieces are more coherent. You want to cut it less than 1024 to be on the safe side. 512 should be better and ...
[ 1 ]
[]
[]
[ "huggingface", "huggingface_tokenizers", "huggingface_transformers", "nlp", "python" ]
stackoverflow_0074244702_huggingface_huggingface_tokenizers_huggingface_transformers_nlp_python.txt
Q: How to get the items inside of an OpenAIobject in python? I would like to get the text inside this data structure that is outputted via GPT3 OpenAI. I'm using Python. When I print the object I get: <OpenAIObject text_completion id=cmpl-6F7ScZDu2UKKJGPXTiTPNKgfrikZ at 0x7f7648cacef0> JSON: { "choices": [ { ...
How to get the items inside of an OpenAIobject in python?
I would like to get the text inside this data structure that is outputted via GPT3 OpenAI. I'm using Python. When I print the object I get: <OpenAIObject text_completion id=cmpl-6F7ScZDu2UKKJGPXTiTPNKgfrikZ at 0x7f7648cacef0> JSON: { "choices": [ { "finish_reason": "stop", "index": 0, "logprobs"...
[ "x = {&quot;choices&quot;: [{&quot;finish_reason&quot;: &quot;length&quot;,\n &quot;text&quot;: &quot;, everyone, and welcome to the first installment of the new opening&quot;}], }\n\ntext = x['choices'][0]['text']\nprint(text) # , everyone, and welcome to the first installment of the new opening\...
[ 1 ]
[]
[]
[ "gpt_3", "openai", "python" ]
stackoverflow_0074524530_gpt_3_openai_python.txt
Q: Trying to run Tortoise-TTS program, getting errors I am trying to run this text-to-speech program I followed instructions verbatim, but when I go to run the first line of code (below) python tortoise/do_tts.py --text "I'm going to speak this" --voice random --preset fast I get he following error code: C:\Users\cha...
Trying to run Tortoise-TTS program, getting errors
I am trying to run this text-to-speech program I followed instructions verbatim, but when I go to run the first line of code (below) python tortoise/do_tts.py --text "I'm going to speak this" --voice random --preset fast I get he following error code: C:\Users\chase\anaconda3\lib\site-packages\torchaudio\_internal\modu...
[ "Try on linux, it works fine for me.\n" ]
[ 0 ]
[]
[]
[ "conda", "github", "pip", "python", "text_to_speech" ]
stackoverflow_0074503208_conda_github_pip_python_text_to_speech.txt
Q: Adding string after each vowel I am currently on a project to develop a small, fun program that takes a name as an input and returns the name with the string "bi" after each vowel in the name. I am encountering the problem that my program runs in an infinite loop when I have a name that has same the same vowel twi...
Adding string after each vowel
I am currently on a project to develop a small, fun program that takes a name as an input and returns the name with the string "bi" after each vowel in the name. I am encountering the problem that my program runs in an infinite loop when I have a name that has same the same vowel twice, for example: the name "aya". tec...
[ "You can also do this by using str.translate which you can give multiple-characters to change one character into many:\nusername = input(\"Please enter your name to be BoBied :D : \")\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\nvowels += [i.upper() for i in vowels]\ntranslation_table = str.maketrans({i: i+\"bi\"...
[ 1, 0, 0 ]
[]
[]
[ "for_loop", "if_statement", "nested_for_loop", "python" ]
stackoverflow_0074523921_for_loop_if_statement_nested_for_loop_python.txt
Q: multiprocessing loop over a simple list? I have a function that calls a custom function that compares rows in a dataframe and calculates some stats. vt.make_breakpts it needs a dataframe (data), a key (unique identifier), and a datefield (date) to do it's thing. I can run this and wait a very long time and it will...
multiprocessing loop over a simple list?
I have a function that calls a custom function that compares rows in a dataframe and calculates some stats. vt.make_breakpts it needs a dataframe (data), a key (unique identifier), and a datefield (date) to do it's thing. I can run this and wait a very long time and it will go through and entire dataframe and output a ...
[ "you just pass the list itself.\nwith Pool(14) as pool:\n for results in pool.imap_unordered(partial_task, vidList):\n ResultsList.append(results[0])\n\nexplaination: imap expects an iterable, both lists and df.iterrows are iterables ... specifically anything that you can be put in a for loop is an iterab...
[ 1 ]
[]
[]
[ "list", "multiprocessing", "python" ]
stackoverflow_0074523667_list_multiprocessing_python.txt
Q: How do i put an array into dynamoDB as a nested String Set? I've got a dynamoDB table with 5 columns. First 2 columns are PK and SK, third column is a boolean, and I want my 4th and 5th columns to be String Sets. I've got a python function that looks something like this so far. def dbupload(id,imgid,isDuplicate,la...
How do i put an array into dynamoDB as a nested String Set?
I've got a dynamoDB table with 5 columns. First 2 columns are PK and SK, third column is a boolean, and I want my 4th and 5th columns to be String Sets. I've got a python function that looks something like this so far. def dbupload(id,imgid,isDuplicate,labeltypes,labelnames,): response = client.put_item( TableName=...
[ "A StringSet can be saved by just providing a list of strings:\n\"SS\": [\"Giraffe\", \"Hippo\" ,\"Zebra\"]\ndef dbupload(id,imgid,isDuplicate,labeltypes,labelnames,):\nresponse = client.put_item(\n TableName='labels',\n Item={\n 'instanceID':{\n 'S':\"{}\".format(id),\n },\n '...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "aws_lambda", "boto3", "python" ]
stackoverflow_0074523479_amazon_dynamodb_aws_lambda_boto3_python.txt
Q: Dynamically call staticmethod in Python I have a python object that has various attrs, one of them is check=None. class MenuItem: check: bool = True During the __init__() process, it parses it's own attrs and looks if they are callable. If so, it calls the function, and replaces it's instance variable with th...
Dynamically call staticmethod in Python
I have a python object that has various attrs, one of them is check=None. class MenuItem: check: bool = True During the __init__() process, it parses it's own attrs and looks if they are callable. If so, it calls the function, and replaces it's instance variable with the result of the function: def __init__(se...
[ "Is this what you are looking for?\nclass A:\n check: bool = True\n def __init__(self):\n self.request = 'request'\n if callable(self.check):\n self.check = self.__class__.check(self.request)\n\nclass B(A):\n check = lambda request: len(request)\n\nb = B()\nprint(b.check)\n\noutput...
[ 2 ]
[]
[]
[ "callable", "instance", "python" ]
stackoverflow_0074524547_callable_instance_python.txt
Q: Python pandas : How to find difference between two dataframe based on single column I have two dataframes df1 = pd.DataFrame({ 'Date':['2013-11-24','2013-11-24','2013-11-25','2013-11-25'], 'Fruit':['Banana','Orange','Apple','Celery'], 'Num':[22.1,8.6,7.6,10.2], 'Color':['Yellow','Orange','Green','G...
Python pandas : How to find difference between two dataframe based on single column
I have two dataframes df1 = pd.DataFrame({ 'Date':['2013-11-24','2013-11-24','2013-11-25','2013-11-25'], 'Fruit':['Banana','Orange','Apple','Celery'], 'Num':[22.1,8.6,7.6,10.2], 'Color':['Yellow','Orange','Green','Green'], }) print(df1) Date Fruit Num Color 0 2013-11-24 Banana 22.1...
[ "You can use the negated isin:\noutput = df2.loc[~df2['Fruit'].isin(df1['Fruit'])]\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074524559_dataframe_pandas_python.txt
Q: Eigen Matrix vs Numpy Array multiplication performance I read in this question that eigen has very good performance. However, I tried to compare eigen MatrixXi multiplication speed vs numpy array multiplication. And numpy performs better (~26 seconds vs. ~29). Is there a more efficient way to do this eigen? Here i...
Eigen Matrix vs Numpy Array multiplication performance
I read in this question that eigen has very good performance. However, I tried to compare eigen MatrixXi multiplication speed vs numpy array multiplication. And numpy performs better (~26 seconds vs. ~29). Is there a more efficient way to do this eigen? Here is my code: Numpy: import numpy as np import time n_a_rows =...
[ "My question has been answered by @Jitse Niesen and @ggael in the comments.\nI need to add a flag to turn on the optimizations when compiling: -O2 -DNDEBUG (O is capital o, not zero).\nAfter including this flag, eigen code runs in 0.6 seconds as opposed to ~29 seconds without it.\n", "Change:\na = np.arange(n_a_r...
[ 7, 5, 0 ]
[]
[]
[ "c++", "eigen", "numpy", "python" ]
stackoverflow_0024566920_c++_eigen_numpy_python.txt
Q: Use Python Selenium to get CLASS_NAME text I'm trying to find a whatsapp icon "attachment" through the class_name and enter the code below link = f'https://web.whatsapp.com/send?phone={numero}&text={texto}' navegador.get(link) sleep(10) navegador.find_element(By.CLASS_NAME, 'li._2qR8G:nth-child(4) > bu...
Use Python Selenium to get CLASS_NAME text
I'm trying to find a whatsapp icon "attachment" through the class_name and enter the code below link = f'https://web.whatsapp.com/send?phone={numero}&text={texto}' navegador.get(link) sleep(10) navegador.find_element(By.CLASS_NAME, 'li._2qR8G:nth-child(4) > button:nth-child(1) > span:nth-child(1)').send_key...
[ "I have no idea if this locator valid li._2qR8G:nth-child(4) > button:nth-child(1) > span:nth-child(1) but it definitely not looks like a class name. It looks like a CSS Selector.\nSo, instead of navegador.find_element(By.CLASS_NAME, 'li._2qR8G:nth-child(4) > button:nth-child(1) > span:nth-child(1)').send_keys(Keys...
[ 0, 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_firefoxdriver", "selenium_webdriver" ]
stackoverflow_0074524492_automation_python_selenium_selenium_firefoxdriver_selenium_webdriver.txt
Q: How to pass volume to docker container? I am running the below docker command : docker run -d -v /Users/gowthamkrishnaaddluri/Documents/dfki_sse/demo:/quantum-demo/ -it demo python3 /quantum-demo/circuit.py --res './' I am trying to run the above command in python and I have the code as follows: container = client...
How to pass volume to docker container?
I am running the below docker command : docker run -d -v /Users/gowthamkrishnaaddluri/Documents/dfki_sse/demo:/quantum-demo/ -it demo python3 /quantum-demo/circuit.py --res './' I am trying to run the above command in python and I have the code as follows: container = client.create_container( image='demo', stdin_open=T...
[ "Hi Hope you are doing well!\nSo instead of the list, you should use dict and also you should use another method. An example is below:\nimport docker\n\nclient = docker.from_env()\nclient.containers.run(\n image=\"python\",\n auto_remove=True,\n detach=True,\n tty=False,\n stdin_open=True,\n volu...
[ 0 ]
[]
[]
[ "docker", "python", "volumes" ]
stackoverflow_0074517669_docker_python_volumes.txt
Q: Python - Selenium is complaining about element not being scrolled into view after scrolling to that element I have the following code which is supposed to scroll down the page and then click a button. When I run my script, I can see that the page does scroll until the element is at the very bottom of the page, but...
Python - Selenium is complaining about element not being scrolled into view after scrolling to that element
I have the following code which is supposed to scroll down the page and then click a button. When I run my script, I can see that the page does scroll until the element is at the very bottom of the page, but then the script fails when it gets time to click on that button and I get this error: selenium.common.exceptions...
[ "You can apply location_once_scrolled_into_view method to perform scrolling here.\nThe following code worked for me:\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom...
[ 0 ]
[]
[]
[ "python", "scroll", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074524569_python_scroll_selenium_selenium_webdriver_webdriverwait.txt
Q: Chain df.str.split() in pandas dataframe Edit: 2022NOV21 How do we chain df.col.str.split() since this returns the split columns if expand = True I am trying to split a column after performing .melt(). If I use assign I end up using the original column and the melted column actually does not even exist. df = pd.Da...
Chain df.str.split() in pandas dataframe
Edit: 2022NOV21 How do we chain df.col.str.split() since this returns the split columns if expand = True I am trying to split a column after performing .melt(). If I use assign I end up using the original column and the melted column actually does not even exist. df = pd.DataFrame().from_dict({ 'id' : [1,2,3,4], ...
[ "Using expand converts it into a DataFrame, which you do not really want here; secondly with chaining, use an anonymous function to refer to the previous dataframe:\n(df\n.melt(id_vars='id',var_name='fy',value_name='num')\nassign(year = lambda df: df.fy.str.split('_').str[0],\n t = lambda df: df.fy.str.split(...
[ 1, 0 ]
[]
[]
[ "chain", "melt", "pandas", "python", "split" ]
stackoverflow_0074496425_chain_melt_pandas_python_split.txt
Q: How to delete an AMI using boto? (cross posted to boto-users) Given an image ID, how can I delete it using boto? A: You use the deregister() API. There are a few ways of getting the image id (i.e. you can list all images and search their properties, etc) Here is a code fragment which will delete one of your exis...
How to delete an AMI using boto?
(cross posted to boto-users) Given an image ID, how can I delete it using boto?
[ "You use the deregister() API.\nThere are a few ways of getting the image id (i.e. you can list all images and search their properties, etc)\nHere is a code fragment which will delete one of your existing AMIs (assuming it's in the EU region)\nconnection = boto.ec2.connect_to_region('eu-west-1', \\\n ...
[ 7, 7, 6, 0, 0 ]
[]
[]
[ "amazon_ec2", "boto", "python" ]
stackoverflow_0005313726_amazon_ec2_boto_python.txt
Q: Django: ValueError: Cannot create form field because its related model has not been loaded yet I'm having some trouble with a Django project I'm working on. I now have two applications, which require a fair bit of overlap. I've really only started the second project (called workflow) and I'm trying to make my firs...
Django: ValueError: Cannot create form field because its related model has not been loaded yet
I'm having some trouble with a Django project I'm working on. I now have two applications, which require a fair bit of overlap. I've really only started the second project (called workflow) and I'm trying to make my first form for that application. My first application is called po. In the workflow application I have a...
[ "I had a similar problem and was able to resolve this by declaring all my modelForm classes below all my class models in my models.py file. This way the model classes were loaded before the modelForm classes.\n", "Firstly, you can try reduce code to: \n\ndef new2(request, number):\n po=PurcchaseOrder.objects.g...
[ 1, 0, 0, 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0017155379_django_forms_python.txt
Q: IntegrityError at /admin/api/user/6/change/ FOREIGN KEY constraint failed I am developing a website on django. When I am trying to delete a user via admin panel i get an error. I can change e.g. staff status (while still getting an error, but changes are getting apllied) The code is below: models.py from django.co...
IntegrityError at /admin/api/user/6/change/ FOREIGN KEY constraint failed
I am developing a website on django. When I am trying to delete a user via admin panel i get an error. I can change e.g. staff status (while still getting an error, but changes are getting apllied) The code is below: models.py from django.contrib.auth.models import AbstractUser from django.db import models class User...
[ "Possible solutions\nThere are three things that might be causing the issue, at least as far as I can tell. The first you already discounted. I hope it's the second solution, since that will be easier, but I fear it might be the third, which would be hardest to get around.\nCause One\nAs my comment stated, perhap...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074521342_django_python.txt
Q: Is there a way in python to extract only the CORE TEXT (without boxes, footer etc.) from a pdf? I am trying to extract only the core text from a "rich" pdf document, meaning that it has a lot of tables, graphs, boxes, footers etc. in which I am not interested in. I tried with some common python packages like PyPD...
Is there a way in python to extract only the CORE TEXT (without boxes, footer etc.) from a pdf?
I am trying to extract only the core text from a "rich" pdf document, meaning that it has a lot of tables, graphs, boxes, footers etc. in which I am not interested in. I tried with some common python packages like PyPDF2, pdfplumber or pdfreader.The problem is that apparently they extract all the text present in the p...
[ "per D.L's comment, please add some reproducible code and, preferably, a pdf to work with.\nHowever, I think I can answer at least part of your question. jsvine's pdfplumber is an incredibly robust python pdf processing package. pdfplumber contains a bounding box functionality that lets you extract text from withi...
[ 0 ]
[]
[]
[ "pdfplumber", "python", "text", "text_extraction", "text_mining" ]
stackoverflow_0074344614_pdfplumber_python_text_text_extraction_text_mining.txt
Q: Calculate crc32 with seed using Python In linux/crc32.h there is crc32 that define: crc32(seed, data, length) How can I calculate crc32 with seed using Python? A: Go to the docs: import zlib help(zlib.crc32) Help on built-in function crc32 in module zlib: crc32(data, value=0, /) Compute a CRC-32 checksum ...
Calculate crc32 with seed using Python
In linux/crc32.h there is crc32 that define: crc32(seed, data, length) How can I calculate crc32 with seed using Python?
[ "Go to the docs:\nimport zlib\nhelp(zlib.crc32)\n\n\nHelp on built-in function crc32 in module zlib:\n\ncrc32(data, value=0, /)\n Compute a CRC-32 checksum of data.\n\n value\n Starting value of the checksum.\n\n The returned checksum is an integer.\n\nData are the same between the two implementat...
[ 2 ]
[]
[]
[ "crc32", "linux_kernel", "python" ]
stackoverflow_0074524815_crc32_linux_kernel_python.txt
Q: High memory allocation when using dask.bag.map I am using dask for extending dask bag items by information from an external, previously computed object arg. Dask seems to allocate memory for arg for each partition at once in the beginning of the computation process. Is there a workaround to prevent Dask from dupli...
High memory allocation when using dask.bag.map
I am using dask for extending dask bag items by information from an external, previously computed object arg. Dask seems to allocate memory for arg for each partition at once in the beginning of the computation process. Is there a workaround to prevent Dask from duplicating the arg multiple times (and allocating a lot ...
[ "One strategy for dealing with this is to scatter your data to workers first:\nimport dask.bag, dask.distributed\n\nclient = dask.distributed.Client()\n\narg = np.zeros(int(1e7))\narg_f = client.scatter(arg, broadcast=True)\n\n(\n dask.bag\n .read_text(str(in_dir / '*.txt'))\n .map((lambda x, y: x), arg_f)...
[ 0 ]
[]
[]
[ "dask", "memory_management", "python" ]
stackoverflow_0074520150_dask_memory_management_python.txt
Q: Rotating list of lists searching for words, only some of the words are appended I'm trying to get every word in a 15x15 matrix both vertically and horizontally. I get all of the words in the horizontal search. However after I flip I only get some of the words. Is there any obvious flaw I just can't see or is there...
Rotating list of lists searching for words, only some of the words are appended
I'm trying to get every word in a 15x15 matrix both vertically and horizontally. I get all of the words in the horizontal search. However after I flip I only get some of the words. Is there any obvious flaw I just can't see or is there a less redundant way to do this? This is code I have currently: words = [] def stuff...
[ "It seems like you are trying to flatten data and ignore \"empties\". You can do this in one line.\nwords = [cell for row in board for cell in row if cell.strip()]\n\nBelow is the \"long-form\" version of above. Both just iterate over the entire board and store cells that contain more than whitespace.\nwords = []\n...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074524764_python.txt
Q: Confusing Button/PhotoImage/tkinter class behavior In my code, the second implementation correctly shows "some_img.png" as a button background but the first does not. class QuizInterface: def __init__(self): self.window = Tk() self.window.title("Quizzler") self.window.config(bg=THEME_COLOR, padx=20, p...
Confusing Button/PhotoImage/tkinter class behavior
In my code, the second implementation correctly shows "some_img.png" as a button background but the first does not. class QuizInterface: def __init__(self): self.window = Tk() self.window.title("Quizzler") self.window.config(bg=THEME_COLOR, padx=20, pady=20) # Example 1: Works as expected true_ima...
[ "Tkinter images get garbage collected if there is not a reference to them. This is why your first example works and the second does not.\nWhen you create a widget you get a reference to that widget. You can then call pack/ place/grid on that reference, but these functions themselves do not return anything, so assig...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074524854_python_tkinter.txt
Q: Setting global JsonEncoder in Python Basically, I'm fighting with the age-old problem that Python's default json encoder does not support datetime. However all the solutions I can find call to json.dumps and manually pass the "proper" encoder on each invocation. And honestly, that can't be the best way to do it. E...
Setting global JsonEncoder in Python
Basically, I'm fighting with the age-old problem that Python's default json encoder does not support datetime. However all the solutions I can find call to json.dumps and manually pass the "proper" encoder on each invocation. And honestly, that can't be the best way to do it. Especially if you want to use a wrapper lik...
[ "Unfortunately, I could not find a way to set default encoders or decoders for the json module.\nSo the best way is to do what flask do, that is wrapping the calls to dump or dumps, and provide a default in that wrapper.\n", "I don't remember where I got this solution from but I was searching for it again today a...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0060170355_python.txt
Q: Regular expression to extract the last part without domain Good afternoon, I would like to know how to extract the last part of the path from URL as string, but without domain using Regex from Python style. The url is: 'https://ncd.soft.com/lags/prime-amazon.png' (prime-amazon is my objective) I tried with no exit...
Regular expression to extract the last part without domain
Good afternoon, I would like to know how to extract the last part of the path from URL as string, but without domain using Regex from Python style. The url is: 'https://ncd.soft.com/lags/prime-amazon.png' (prime-amazon is my objective) I tried with no exit because we need to exclude the domain (.png or .com, etc) ([^/]...
[ "You can use\n[^/]+(?=\\.png/?$)\n\nSee the regex demo.\nDetails:\n\n[^/]+ - one or more chars other than /\n(?=\\.png/?$) - a positive lookahead that requires .png or .png/ till end of string immediately to the right of the current location.\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074524647_python_regex.txt
Q: Not getting a proper fit Getting an error of "IndexError: index 1 is out of bounds for axis 0 with size 1". I am a newbie. Please help. Thanks in advance. def logistic(x, l, k, x1): return l / 1+np.exp(-k*(x-x1)) distance= [1.000*70, 2.000*70, 3.000*70, 4.000*70, 5.000*70, 6.000*70, 7.000*70, 8.000*70, ...
Not getting a proper fit
Getting an error of "IndexError: index 1 is out of bounds for axis 0 with size 1". I am a newbie. Please help. Thanks in advance. def logistic(x, l, k, x1): return l / 1+np.exp(-k*(x-x1)) distance= [1.000*70, 2.000*70, 3.000*70, 4.000*70, 5.000*70, 6.000*70, 7.000*70, 8.000*70, 9.000*70, 11.00*70, 12.000...
[ "there are few points on your code which had to be fixed.\n\ndistance and amplititle are not same size\nboth are list however inside you logistics definition you treat them as numpy array which you do vector operations\nbounds value for k is wrong, it should be below 1 but you set minimum value to be 10, which make...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074524730_python.txt
Q: Why are the UUIDs from this AWS network socket backwards? When you use the AWS API to run a command on a remote docker container (ECS), the AWS API gives you back a websocket to read the output of your command from. When using the aws command line utility (which also uses the AWS API), reading the websocket stream...
Why are the UUIDs from this AWS network socket backwards?
When you use the AWS API to run a command on a remote docker container (ECS), the AWS API gives you back a websocket to read the output of your command from. When using the aws command line utility (which also uses the AWS API), reading the websocket stream is handled by session-manager-plugin. session-manager-plugin i...
[ "Looking at the source code for session-manager-plugin, it would appear it reads the first eight bytes as the least significant bytes, then reads the next eight bytes as the most significant bytes, then appends it in the order MSB, LSB. Seems to me like that would produce the behavior you're seeing.\n// getUuid get...
[ 2 ]
[]
[]
[ "amazon_web_services", "python" ]
stackoverflow_0074524858_amazon_web_services_python.txt
Q: Creating a new boolean column based on another dataframe in Spark I have a big dataset with many columns: df = my_id attr_1 attr_2 ... attr_n 13900 null USA 384.24 13900 null UK 399.24 13999 3467 USA 314.25 13911 3556 CND 386.77 139...
Creating a new boolean column based on another dataframe in Spark
I have a big dataset with many columns: df = my_id attr_1 attr_2 ... attr_n 13900 null USA 384.24 13900 null UK 399.24 13999 3467 USA 314.25 13911 3556 CND 386.77 13922 5785 USA 684.21 I also have a smaller dataframe w...
[ "Your reasoning is correct: you can do a left join and then using conditional function when, derive the column check basing on the left-joined column. A sample could could look something like this:\nfrom pyspark.sql.functions import col, when, lit\n\n# 1. Do a left join\ndf_3 = df.join(df_2, col(\"my_id\") == col(\...
[ 1 ]
[]
[]
[ "dataframe", "join", "pyspark", "python" ]
stackoverflow_0074519579_dataframe_join_pyspark_python.txt
Q: Parse simple XML to pandas dataframe I hope you are well. I am looking to convert the following XML URL into a pandas dataframe. You can view the XML here; https://clients2.google.com/complete/search?hl=en&output=toolbar&q=how%20garage%20doors Here is the Python 3 code here, which currently returns an empty datafr...
Parse simple XML to pandas dataframe
I hope you are well. I am looking to convert the following XML URL into a pandas dataframe. You can view the XML here; https://clients2.google.com/complete/search?hl=en&output=toolbar&q=how%20garage%20doors Here is the Python 3 code here, which currently returns an empty dataframe. from bs4 import BeautifulSoup import ...
[ "You need to get the attribute of suggestion tag, not the text/string inside the tag. Try this\ndf = pd.DataFrame(columns=['suggestion data','Keyword'])\n\nfor node in obs:\n for suggestion in node:\n df = df.append({'suggestion data': suggestion.attrs['data']}, ignore_index=True)\ndf.head()\n\n", "I always u...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "xml_parsing" ]
stackoverflow_0074524739_pandas_python_xml_parsing.txt
Q: Remove [] in Python I have a list like this: data = [[[1, 2], [1, 1], [2, 3], [5, 5], [6, 6]]] I would like to get like this : data = [[1, 2], [1, 1], [2, 3], [5, 5], [6, 6]] How can i do using python ? A: Reassign data with the 0 index of your array. data = data [0]
Remove [] in Python
I have a list like this: data = [[[1, 2], [1, 1], [2, 3], [5, 5], [6, 6]]] I would like to get like this : data = [[1, 2], [1, 1], [2, 3], [5, 5], [6, 6]] How can i do using python ?
[ "Reassign data with the 0 index of your array.\ndata = data [0]\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074525024_python.txt
Q: Can you use the name of a turtle in the parameters of a variable? import turtle as trtl def position(hold): hold.forward(200) position('trtl') I'm trying to make a program which has multiple turtles use a similar function between all of them, is something like what is shown in the image possible? A: If you w...
Can you use the name of a turtle in the parameters of a variable?
import turtle as trtl def position(hold): hold.forward(200) position('trtl') I'm trying to make a program which has multiple turtles use a similar function between all of them, is something like what is shown in the image possible?
[ "If you want to refer to things by name, store them in a dict; use the name as keys.\nimport turtle\n\nturtles = {\n \"one\": turtle.Turtle(),\n \"two\": turtle.Turtle(),\n}\n\ndef position(turtle_name):\n return turtles[turtle_name].forward(200)\n\nposition('one')\n\n...but it's unclear why you'd do that at all...
[ 1 ]
[]
[]
[ "python", "turtle_graphics" ]
stackoverflow_0074524992_python_turtle_graphics.txt
Q: Python pandas why does my code changes column when I import a dataframe from a csv file and then use concat to merge the two dataframes together? I am trying to create a program in which every time I enter a data, it stores it into a dataframe and the dataframe is stored into a csv file. Now, this whole process is...
Python pandas why does my code changes column when I import a dataframe from a csv file and then use concat to merge the two dataframes together?
I am trying to create a program in which every time I enter a data, it stores it into a dataframe and the dataframe is stored into a csv file. Now, this whole process is in a loop. When I keep on entering the data without importing the data from the csv file, it works fine and the two dataframes are joined together per...
[ "Try to create an empty dataframe with the column names and then append the row you want.\ndf = pd.DataFrame(columns=index1)\ndf = df.append(l1)\n\n" ]
[ 0 ]
[]
[]
[ "concatenation", "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074524959_concatenation_csv_dataframe_pandas_python.txt
Q: Shiny for python - adding an icon to the input_action_button With R Shiny, adding an icon to an actionButton uses icon() function. actionButton( ... , icon = shiny::icon(icon_name) ) How can this be achieved with shiny.ui.input_action_button? ui.input_action_button( ... ic...
Shiny for python - adding an icon to the input_action_button
With R Shiny, adding an icon to an actionButton uses icon() function. actionButton( ... , icon = shiny::icon(icon_name) ) How can this be achieved with shiny.ui.input_action_button? ui.input_action_button( ... icon = ? ) Whatever I try in (?) seems to make it into a label ...
[ "Only example I found used emoji directly like this\nui.input_action_button(\"go\", \"Go!\", icon=\"\")\n\nNot sure you can use icon like R shiny.\n" ]
[ 0 ]
[]
[]
[ "py_shiny", "python", "shiny" ]
stackoverflow_0074506566_py_shiny_python_shiny.txt
Q: How do I access the Salesforce API when single-sign on is enabled? I'm attempting to make SOQL queries to the Salesforce API using the Python salesforce_api and simple-salesforce modules. I had been making these requests with a client object: client = Salesforce(username='MY_USERNAME', password...
How do I access the Salesforce API when single-sign on is enabled?
I'm attempting to make SOQL queries to the Salesforce API using the Python salesforce_api and simple-salesforce modules. I had been making these requests with a client object: client = Salesforce(username='MY_USERNAME', password='MY_PASSWORD', security_token='MY_SALESFORCE_SECURI...
[ "Uh. It's doable but it's an art. I'll try to write it up but you should have a look at \"Identity and Access Management\" Salesforce certification, study guides etc. Try also asking at salesforce.stackexchange.com, might get better answers and Okta specialists.\nI don't know if there's pure server-side access to O...
[ 1, 0 ]
[]
[]
[ "okta", "python", "python_3.x", "salesforce" ]
stackoverflow_0062563315_okta_python_python_3.x_salesforce.txt
Q: Integration Pyspark ans Python in the same Notebook I work in the team of Analytics in X company. We use Microsoft Azure - Data Bricks. There we have to use PysPark. Let say, after different chunks we had a final data frame. I have to make use of visualisations based on this data frame. I think the library Seaborn...
Integration Pyspark ans Python in the same Notebook
I work in the team of Analytics in X company. We use Microsoft Azure - Data Bricks. There we have to use PysPark. Let say, after different chunks we had a final data frame. I have to make use of visualisations based on this data frame. I think the library Seaborn from Python should be more useful that any library from ...
[ "The Databricks includes extra Python libraries natively, so the Seaborn you have mentioned, will work out of the box, with up-to-date runtime releases. Depending whether you use an ML Databricks runtime or just a regular one, the runtime will include a different set of extra Python lib. You can find the complete l...
[ 1 ]
[]
[]
[ "analytics", "databricks", "pyspark", "python" ]
stackoverflow_0074489542_analytics_databricks_pyspark_python.txt
Q: Keep some delimiters and others not with pattern with Regex split I have a code like this: string splitttt ="This week rained all day long but next day will be a sunny day if the news are correct" string[] splitttt = Regex.Split(StringX, @"\s(week|if|)\s"); I get this output: rained all day long but next day wi...
Keep some delimiters and others not with pattern with Regex split
I have a code like this: string splitttt ="This week rained all day long but next day will be a sunny day if the news are correct" string[] splitttt = Regex.Split(StringX, @"\s(week|if|)\s"); I get this output: rained all day long but next day will be a sunny day (in this case delimiters are not included in the patt...
[ "You can include matched text in your output by defining the delimiters with lookaround:\nimport re\n\nstring = \"This week rained all day long but next day will be a sunny day if the news are correct\"\n\npattern = r\" (?=week)|(?<=if) | next \"\n\nsplit = re.split(pattern, string)\n\nfor word in split:\n print...
[ 0 ]
[]
[]
[ ".net", "python", "regex" ]
stackoverflow_0074524883_.net_python_regex.txt
Q: Number formating fraction in Python I'm used to formatting fractions in Google Sheets as '# ##/##', is there any way to do the same in Python or do I have to program it? I have tried: F'Value: {Fraction(a / b).limit_denominator()}' Gives for example: '3/2' I would like: '1 1/2' in this case. A: You can use divm...
Number formating fraction in Python
I'm used to formatting fractions in Google Sheets as '# ##/##', is there any way to do the same in Python or do I have to program it? I have tried: F'Value: {Fraction(a / b).limit_denominator()}' Gives for example: '3/2' I would like: '1 1/2' in this case.
[ "You can use divmod to separate the integer and fractional parts. From there it's a simple matter of using the format method.\n>>> f = Fraction(3, 2)\n>>> '{} {}'.format(*divmod(f, 1))\n'1 1/2'\n\n" ]
[ 3 ]
[]
[]
[ "fractions", "number_formatting", "python" ]
stackoverflow_0074525107_fractions_number_formatting_python.txt
Q: Sorting one array by sorting two other arrays together I apologise for the title of this question that I know is very unclear, I tried my best. I have three arrays that need to be sorted, but the tricky rule is the following: the first array needs to increment every time, and when the maximum is obtained, goes ba...
Sorting one array by sorting two other arrays together
I apologise for the title of this question that I know is very unclear, I tried my best. I have three arrays that need to be sorted, but the tricky rule is the following: the first array needs to increment every time, and when the maximum is obtained, goes back to zero. the second array has to be sorted starting from ...
[ "This is a non-numpy solution. But\nThe desired order can be obtained by doing\nsorted(zip(array2, array1))\n\nTo obtain the list of indices (to reorder the word) you could do\nindices, sorted_arrays = zip(*sorted(enumerate(zip(array2, array1)), key=itemgetter(1)))\n\nindices is then\n(1, 3, 4, 0, 2)\n\nto get the ...
[ 1, 1 ]
[]
[]
[ "arrays", "numpy", "python", "sorting" ]
stackoverflow_0074522277_arrays_numpy_python_sorting.txt
Q: How to redirect 'print' output to a file? I want to redirect the print to a .txt file using Python. I have a for loop, which will print the output for each of my .bam file while I want to redirect all output to one file. So I tried to put: f = open('output.txt','w') sys.stdout = f at the beginning of my script. H...
How to redirect 'print' output to a file?
I want to redirect the print to a .txt file using Python. I have a for loop, which will print the output for each of my .bam file while I want to redirect all output to one file. So I tried to put: f = open('output.txt','w') sys.stdout = f at the beginning of my script. However I get nothing in the .txt file. My scrip...
[ "The most obvious way to do this would be to print to a file object:\nwith open('out.txt', 'w') as f:\n print('Filename:', filename, file=f) # Python 3.x\n print >> f, 'Filename:', filename # Python 2.x\n\nHowever, redirecting stdout also works for me. It is probably fine for a one-off script such as th...
[ 403, 97, 58, 41, 39, 15, 12, 5, 4, 3, 2, 0, 0, 0 ]
[ "Something to extend print function for loops\nx = 0\nwhile x <=5:\n x = x + 1\n with open('outputEis.txt', 'a') as f:\n print(x, file=f)\n f.close()\n\n" ]
[ -2 ]
[ "file_writing", "io", "python" ]
stackoverflow_0007152762_file_writing_io_python.txt
Q: Python multiprocessing.Queue apparently losing data I am trying to make use of multiprocessing to speed up a program. For this I at some point need to parallelize a task between as many processes as possible, let's say n. Because I don't want to create any more processes than I absolutely have to, I create n-1 new...
Python multiprocessing.Queue apparently losing data
I am trying to make use of multiprocessing to speed up a program. For this I at some point need to parallelize a task between as many processes as possible, let's say n. Because I don't want to create any more processes than I absolutely have to, I create n-1 new ones, start them, then run the last of the work on the c...
[ "So, here's your problem:\n\nI initially didn't use queue.cancel_join_thread(), but found that to prevent the processes from joining, even after finishing execution, something about them waiting for a buffer to actually write to the queue, which, in the case of great amounts of data, would not do so until the queue...
[ 0 ]
[]
[]
[ "python", "python_multiprocessing", "queue" ]
stackoverflow_0074520564_python_python_multiprocessing_queue.txt
Q: Matplotlib y axis is not ordered I'm getting data from serial port and draw it with matplotlib. But there is a problem. It is that i cannot order y axis values. import matplotlib.pyplot as plt import matplotlib.animation as animation from deneme_serial import serial_reader collect = serial_reader() fig = plt.fig...
Matplotlib y axis is not ordered
I'm getting data from serial port and draw it with matplotlib. But there is a problem. It is that i cannot order y axis values. import matplotlib.pyplot as plt import matplotlib.animation as animation from deneme_serial import serial_reader collect = serial_reader() fig = plt.figure() ax = fig.add_subplot(1, 1, 1) x...
[ "This happened to me following the same tutorial.\nMy issue was the variables coming from my instrument were strings. Therefore, there is no order. I changed my variables to float and that fixed the problem\nxs.append(float(FROM_INSTRUMENT))\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0060696798_matplotlib_python.txt
Q: How do you scrape a website that doesn't have specific html tags with represented with class names So I am scraping a used car website I've got the make, model, year, and miles but I don't know how to get the others due to them being the li tag as well. I've put all my code here from bs4 import BeautifulSoup impor...
How do you scrape a website that doesn't have specific html tags with represented with class names
So I am scraping a used car website I've got the make, model, year, and miles but I don't know how to get the others due to them being the li tag as well. I've put all my code here from bs4 import BeautifulSoup import requests import pandas as pd url = 'https://jammer.ie/used-cars' response = requests.get(url) response...
[ "To get all features into a dataframe you can do:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://jammer.ie/used-cars\"\nsoup = BeautifulSoup(requests.get(url).text, \"html.parser\")\n\nall_data = []\nfor car in soup.select(\".car\"):\n info = car.select_one(\".top-info\...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074525317_beautifulsoup_python_web_scraping.txt
Q: AttributeError: module 'keras.utils' has no attribute 'get_file' using segmentation_models I'm trying to use segmentation models but I can't fix this error. I've searched for this particular one but couldn't find an answer. I'm using pycharm and this error is linked to this specific line of code BACKBONE = 'resnet...
AttributeError: module 'keras.utils' has no attribute 'get_file' using segmentation_models
I'm trying to use segmentation models but I can't fix this error. I've searched for this particular one but couldn't find an answer. I'm using pycharm and this error is linked to this specific line of code BACKBONE = 'resnet34' model1 = sm.Unet(BACKBONE, weights=None, encoder_weights='imagenet', ...
[ "You can try:\nimport segmentation_models as sm\n\nsm.set_framework('tf.keras')\n\nsm.framework()\n\nWorked for me on google colab!\n", "To solve this issue, try importing the module EfficientNetB0 directly, as the code below:\nimport efficientnet.tfkeras as efn\n\n", "I had same problem but with vgg u-net mode...
[ 18, 0, 0 ]
[ "The other answer provided here didn't work for me. Instead, upgrading keras did the trick for me via:\npip install --upgrade keras\n\n" ]
[ -1 ]
[ "keras", "python" ]
stackoverflow_0067792138_keras_python.txt
Q: How to run external python file in html I want to use my html file to take user input and then I want to use my python program to process my input and then I want my html shows the answer HTML Part ` {% extends 'base.html' %} {% block title %}Home{% endblock title %}Home {% block body %} <style> #body { pa...
How to run external python file in html
I want to use my html file to take user input and then I want to use my python program to process my input and then I want my html shows the answer HTML Part ` {% extends 'base.html' %} {% block title %}Home{% endblock title %}Home {% block body %} <style> #body { padding-left:100px; padding-top:10px; } </s...
[ "if you want every thing run in client side I think you should use pyscript otherwise you must execute all your python code in server side program like django and send result to client with proper html/css/js libraries\n" ]
[ 0 ]
[]
[]
[ "django", "external", "html", "python" ]
stackoverflow_0074524364_django_external_html_python.txt
Q: PyPI index vs simple index I've seen mention both an index and a simple index in relation to PyPI, an example is here in the devpi documentation. Is there some difference between the two indexes? Are they the same or do they have different access controls or functions for example? A: The "simple" index protocol ...
PyPI index vs simple index
I've seen mention both an index and a simple index in relation to PyPI, an example is here in the devpi documentation. Is there some difference between the two indexes? Are they the same or do they have different access controls or functions for example?
[ "The \"simple\" index protocol is read-only, intended for automated use, and is defined in PEP 503. Other protocols with more functionality may be defined by particular repository servers, but are probably only usable with that server's own tools.\n", "As for https://pypi.org/ and some other Python repositories:\...
[ 6, 0 ]
[]
[]
[ "pypi", "python" ]
stackoverflow_0024816148_pypi_python.txt
Q: Google resource manager get all exceptions - Python im making a python script that can manage my google projects. im having a insue with one part when i try to exclude the project its can return to me many errors. i did a peace of code to get this exception: try: # Initialize request argument(s...
Google resource manager get all exceptions - Python
im making a python script that can manage my google projects. im having a insue with one part when i try to exclude the project its can return to me many errors. i did a peace of code to get this exception: try: # Initialize request argument(s) request = DeleteProjectRequest( ...
[ "You can also catch multiple Exceptions by adding additional blocks, though it will choose the first isinstance() match (so if you put Exception first, it will be selected instead, while TypeError would be continued past)\ntry:\n self.project_manager.delete_project(\n request=DeleteProjectRequest(name=pro...
[ 3, 2 ]
[]
[]
[ "google_cloud_platform", "python" ]
stackoverflow_0074524363_google_cloud_platform_python.txt
Q: How to get phase DC offset and amplitude of sine wave in Python I have a sine wave of the known frequency with some noise with uniform samples near Nyquist frequency. I want to get approximate values of amplitude, phase, and DC offset. I searched for an answer and found a couple of answers close to what I needed, ...
How to get phase DC offset and amplitude of sine wave in Python
I have a sine wave of the known frequency with some noise with uniform samples near Nyquist frequency. I want to get approximate values of amplitude, phase, and DC offset. I searched for an answer and found a couple of answers close to what I needed, but still was unable to write a proper code that achieves what I need...
[ "You are catching the phase at an inflection point, where the phase is suddenly transitioning from +pi/2 to -pi/2, and the bin you are looking at is just partway through the downhill slide. This is just because the FFT results are not continuous. A single bin spans a range of frequencies.\nNotice when we plot the ...
[ 0 ]
[]
[]
[ "fft", "python" ]
stackoverflow_0074514831_fft_python.txt
Q: How to start Airflow Dag with a past Data Interval Date I am working in Ariflow 2.2.3 and I can't figure out how to trigger my dag with a past execution date. When I click Trigger dag with Config, I changed the calendar to the date I wanted but when I clicked run, I saw the run but it didn't run. I also tried putt...
How to start Airflow Dag with a past Data Interval Date
I am working in Ariflow 2.2.3 and I can't figure out how to trigger my dag with a past execution date. When I click Trigger dag with Config, I changed the calendar to the date I wanted but when I clicked run, I saw the run but it didn't run. I also tried putting the date in the config section with {"start_date":"date"}...
[ "To create a past Airflow run you have multiple option, but most of them needs to update the start date of your dag to be older than the date of the desired run date (first four options), otherwise the run will be marked as succeeded without being executed.\n\nVia Airflow UI: you can click on the run icon, and choo...
[ 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "gcs", "python" ]
stackoverflow_0074525338_airflow_directed_acyclic_graphs_gcs_python.txt
Q: How to skip if empty item in column in Django DB I;m new to learning Django and ran into a small issue: I'm working on a product display page where some products are in a subcategory. I want to be able to display this subcategory when needed but I do not want it to show up when unused. Right now it will show up on...
How to skip if empty item in column in Django DB
I;m new to learning Django and ran into a small issue: I'm working on a product display page where some products are in a subcategory. I want to be able to display this subcategory when needed but I do not want it to show up when unused. Right now it will show up on my page as 'NONE' which I do not want. How do I fix t...
[ "If the value is NULL at the database side, it is None at the Django/Python side, so you can work with:\n{% for category in categories %}\n<p>\n {% if category.sub_category is None %}\n {{ category.category_name }}\n {% else %}\n {{ category }}\n {% endif %}\n</p>\n{% endfor %}\nBut instead o...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074525466_django_python.txt
Q: Find all possible varients of max pair of 2 Given a string of numbers like 123456, I want to find all the possibilities they can be paired in by 2 or by itself. For example, from the string 123456 I would like to get the following: 12 3 4 5 6, 12 34 5 6, 1 23 4 56, etc. The nearest I was able to come to was this:...
Find all possible varients of max pair of 2
Given a string of numbers like 123456, I want to find all the possibilities they can be paired in by 2 or by itself. For example, from the string 123456 I would like to get the following: 12 3 4 5 6, 12 34 5 6, 1 23 4 56, etc. The nearest I was able to come to was this: strr = list("123456") x = list("123456") for i ...
[ "It's easy to solve this problem with a recursive generator. This is similar to how you solve change-making problems, just here we have only two \"coins\", either two characters together, or one character at a time. The total change we're trying to make is the length of the input string. The fact that the character...
[ 0, 0, 0 ]
[]
[]
[ "list", "python", "range", "string" ]
stackoverflow_0074524232_list_python_range_string.txt
Q: Is there a quicker way than having a for loop in a for loop I am trying to find a quicker way than using a for loop in a for loop to replace the variables in column a in one table with the variables in column b in another table. for x in range(len(a["a"])): for y in range(len(b["a"])): if a["a"][x] == ...
Is there a quicker way than having a for loop in a for loop
I am trying to find a quicker way than using a for loop in a for loop to replace the variables in column a in one table with the variables in column b in another table. for x in range(len(a["a"])): for y in range(len(b["a"])): if a["a"][x] == b["a"][y]: a["a"] = out['a'].replace([a["a"][x]],b["b...
[ "You cannot use the pandas where function because your two dataframes have different numbers of elements. But the code below will work (I renamed your dataframes df1 and df2 for clarity)\ndf1['a'].loc[df1['a'].isin(df2['a'])] = df2['b']\n\nwhich for your sample data results in\n a\n0 alpha\n1 alpha\n2...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074525419_dataframe_pandas_python.txt
Q: I'm trying to create a website for reserving tickets. I need to add as many passengers as needed using one single form. How is that possible? `@views.route('/flight.html',methods = ['GET','POST']) def flight(): if request.method == 'POST': global no_of_passenger no_of_passengers = request....
I'm trying to create a website for reserving tickets. I need to add as many passengers as needed using one single form. How is that possible?
`@views.route('/flight.html',methods = ['GET','POST']) def flight(): if request.method == 'POST': global no_of_passenger no_of_passengers = request.form.get('no_of_passengers')` In the above view, I'm getting the passenger count from an earlier html page which I'm using later. I need to get th...
[ "An easy way to implement your requirements is to use Flask-WTF.\nUsing a FieldList and a FormField, it is possible to create a list of a predefined form.\nIn this way you create a form for your address details and, depending on the required number, you duplicate this. In addition, you can validate the entries made...
[ 0 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074523373_flask_html_python.txt
Q: Use same Airflow task in multiple branch Is there way I can re-use airflow task that needs to be executed in each branch execution. for ex. I have below tasks out of each task_1 and task_2 needs to be run in 1st flow and task_3 in 2nd flow but task_comm needs to be run in both cases. How can i create 1 task and ca...
Use same Airflow task in multiple branch
Is there way I can re-use airflow task that needs to be executed in each branch execution. for ex. I have below tasks out of each task_1 and task_2 needs to be run in 1st flow and task_3 in 2nd flow but task_comm needs to be run in both cases. How can i create 1 task and call it in both flow ? flow_1 = DummyOperator(ta...
[ "In your code, you have two different branches, one of them will be succeeded and the second will be skipped. To run the task_comm after any one of them, you just need to update its trigger rule:\nfrom airflow.utils.trigger_rule import TriggerRule\ntask_comm = DummyOperator(task_id = 'task_comm', trigger_rule=Trigg...
[ 0 ]
[]
[]
[ "airflow", "python", "task" ]
stackoverflow_0074523502_airflow_python_task.txt
Q: Covert OME-TIFF to DZI using python Basically a have an ome.tiff image file that cames from ImageJ, and i want to transform it in .dzi file. Currently i do: (ome.tff -> jpg -> dzi). But i want to transform directly in .dzi is that possible in python? and how? I can't find anything related to this so I decided to a...
Covert OME-TIFF to DZI using python
Basically a have an ome.tiff image file that cames from ImageJ, and i want to transform it in .dzi file. Currently i do: (ome.tff -> jpg -> dzi). But i want to transform directly in .dzi is that possible in python? and how? I can't find anything related to this so I decided to ask here if anyone has any information abo...
[ "You should be able to read an OME-TIFF with tifffile, and write a DZI file with vips.\nAs both of these are Python, I guess there's a way of doing what you want, but you didn't share a representative input image so I cannot suggest much more.\n" ]
[ 0 ]
[]
[]
[ "data_conversion", "image", "python", "tiff" ]
stackoverflow_0074523872_data_conversion_image_python_tiff.txt
Q: Reading and writing multiple files in a consistent order I'm trying to read multiple files and then save them after I have processed each one. Right now I'm able to do so but the order is not correct. As I'm accessing a text file, each third line corresponds to a frame in order (Frame 1=line3, Frame2=line6), so I ...
Reading and writing multiple files in a consistent order
I'm trying to read multiple files and then save them after I have processed each one. Right now I'm able to do so but the order is not correct. As I'm accessing a text file, each third line corresponds to a frame in order (Frame 1=line3, Frame2=line6), so I need my code to read the images in order. path = '/Users/Deskt...
[ "Expanding on the comment by @jasonharper: instead of using\nglob.glob(\"/Users/Desktop/FFMPEG/test25/*.png\")\n\nyou could try to use:\nsorted(glob.glob(\"/Users/Desktop/FFMPEG/test25/*.png\"))\n\nIt is a bit hard to provide an answer without a fully reproducible example, and output (desired and obtained).\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074525192_python.txt
Q: Python calling a property from inside a class I'm trying to call the property protocolo on a new imagefield's upload_to argument What I'm trying to accomplish is to have the saved images use a custom filename. class biopsia(models.Model): paciente = models.CharField(max_length=50) creado = models.DateTimeF...
Python calling a property from inside a class
I'm trying to call the property protocolo on a new imagefield's upload_to argument What I'm trying to accomplish is to have the saved images use a custom filename. class biopsia(models.Model): paciente = models.CharField(max_length=50) creado = models.DateTimeField(auto_now_add=True) foto = models.ImageFiel...
[ "You can follow the official documentation on how to use function as path for ImageField. Basically, you need to define a function in outer scope of the Model class. For your case, you can try the following code:\ndef protocolo(instance, filename):\n return f'fotos_biopsias/{timezone.now().year}/BIO' + str(insta...
[ 1 ]
[]
[]
[ "django", "properties", "python" ]
stackoverflow_0074525494_django_properties_python.txt
Q: Error when using pyrealsense2 with multithreading I'm trying to write a program in Python, where the main thread will read depth frames from a RealSense camera and put them in a queue, and another thread that will run inference on them with a YoloV5 TensorRT model. The program runs on a Jetson Nano. For some reaso...
Error when using pyrealsense2 with multithreading
I'm trying to write a program in Python, where the main thread will read depth frames from a RealSense camera and put them in a queue, and another thread that will run inference on them with a YoloV5 TensorRT model. The program runs on a Jetson Nano. For some reason, after reading about 15 frames the program crashes wi...
[ "this line reserves memory, and limiting the queue size also limits memory usage so you most likely ran out of memory.\na possible solution is to just limit the queue size to 1 sample, you always get the most recent result that is within the timeframe of your processing time.\nanother solution is to use a deque of ...
[ 0 ]
[]
[]
[ "multithreading", "numpy", "nvidia_jetson_nano", "python", "realsense" ]
stackoverflow_0074524107_multithreading_numpy_nvidia_jetson_nano_python_realsense.txt
Q: Remove traceback in Python on Ctrl-C Is there a way to keep tracebacks from coming up when you hit Ctrl+c, i.e. raise KeyboardInterrupt in a Python script? A: Try this: import signal import sys signal.signal(signal.SIGINT, lambda x, y: sys.exit(0)) This way you don't need to wrap everything in an exception han...
Remove traceback in Python on Ctrl-C
Is there a way to keep tracebacks from coming up when you hit Ctrl+c, i.e. raise KeyboardInterrupt in a Python script?
[ "Try this:\nimport signal\nimport sys\nsignal.signal(signal.SIGINT, lambda x, y: sys.exit(0))\n\nThis way you don't need to wrap everything in an exception handler.\n", "import sys\ntry:\n # your code\nexcept KeyboardInterrupt:\n sys.exit(0) # or 1, or whatever\n\nIs the simplest way, assuming you still wan...
[ 40, 32, 8, 3, 2, 2, 1, 0 ]
[ "import sys\ntry:\n print(\"HELLO\")\n english = input(\"Enter your main launguage: \")\n print(\"GOODBYE\")\nexcept KeyboardInterrupt:\n print(\"GET LOST\")\n\n" ]
[ -6 ]
[ "keyboardinterrupt", "python", "traceback" ]
stackoverflow_0007073268_keyboardinterrupt_python_traceback.txt
Q: Why do saved pytorch models retrain after loading? import torch import torchvision n_epochs = 3 batch_size_train = 64 batch_size_test = 1000 learning_rate = 0.01 momentum = 0.5 log_interval = 10 random_seed = 1 torch.backends.cudnn.enabled = False torch.manual_seed(random_seed) train_loader = torch.utils.data.D...
Why do saved pytorch models retrain after loading?
import torch import torchvision n_epochs = 3 batch_size_train = 64 batch_size_test = 1000 learning_rate = 0.01 momentum = 0.5 log_interval = 10 random_seed = 1 torch.backends.cudnn.enabled = False torch.manual_seed(random_seed) train_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('./files', train...
[ "I just tried executing the code, and it works perfect. load_state_dict did not retrain the model:\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d...
[ 0 ]
[]
[]
[ "deep_learning", "mnist", "python", "pytorch" ]
stackoverflow_0074525661_deep_learning_mnist_python_pytorch.txt
Q: Change value of dictionary if it is in another dictionary I have two lists of generated dictionaries. One is like a template structured like: list_of_dicts_template = [{'year': 0, 'week': 38, 'count_tickets': 0}, {'year': 0, 'week': 39, 'count_tickets': 0}]... And another is a dictionary with values that we know:...
Change value of dictionary if it is in another dictionary
I have two lists of generated dictionaries. One is like a template structured like: list_of_dicts_template = [{'year': 0, 'week': 38, 'count_tickets': 0}, {'year': 0, 'week': 39, 'count_tickets': 0}]... And another is a dictionary with values that we know: known_values_list = [{'year': 2022, 'week': 39, 'tickets': 47}...
[ "You could use the following code:\nfor i,d1 in enumerate(list_of_dicts_template):\n for j, known_value_d in enumerate(known_values_list):\n if known_value_d['week'] == d1['week']:\n list_of_dicts_template[i] = known_value_d\n del known_values_list[j]\n\nTo add only delete the elemen...
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074525639_dictionary_list_python.txt
Q: How to add emojis in the code for automating with PYAUTOGUI import time from datetime import datetime import pyautogui import os import emoji text = emoji.emojize(":thumbs_up:") Time = input("Enter your time here:") while(True): present = datetime.now() present = present.strftime("%H:%M") if (present =...
How to add emojis in the code for automating with PYAUTOGUI
import time from datetime import datetime import pyautogui import os import emoji text = emoji.emojize(":thumbs_up:") Time = input("Enter your time here:") while(True): present = datetime.now() present = present.strftime("%H:%M") if (present == Time): pyautogui.write(text , interval=0.25) ti...
[ "you can use\npyautogui.hotkey(\"alt\", \"ALT CODE HERE\") \n\nand place alt code of emoji in the \"ALT CODE HERE\" section\n" ]
[ 0 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0071222250_pyautogui_python.txt
Q: Finding a column within Multi-index Ho would I refer to a column of Price and Small as Example from Code Below ` dx = pd.MultiIndex.from_product([['Quantity', 'Price'], ['medium', 'large', 'small']]) idx MultiIndex([('Quantity', 'medium'), ('Quantity', 'large'), ('Quantity', 'small'), ...
Finding a column within Multi-index
Ho would I refer to a column of Price and Small as Example from Code Below ` dx = pd.MultiIndex.from_product([['Quantity', 'Price'], ['medium', 'large', 'small']]) idx MultiIndex([('Quantity', 'medium'), ('Quantity', 'large'), ('Quantity', 'small'), ( 'Price', 'medium'), ...
[ "When you have a single-level / flat index, the column coordinate is a simple string:\ndf[\"ColumnName\"]\n\nWhen your dataframe columns is a multi-index, the coordinate is an n-tuple:\ndf[(\"NameAtLevel0\", \"NameAtLevel1\", \"NameAtLevel2\")]\n\nFollow that pattern, to retrieve your Price-Small column:\ndf[(\"Pri...
[ 2 ]
[]
[]
[ "multi_index", "pandas", "python" ]
stackoverflow_0074524925_multi_index_pandas_python.txt
Q: Can spacy's text categorizer learn the logic of recognizing two words in order? I'm trying to determine if Spacy's text categorizer can learn a simple logic to detect the presence of two consecutive words in order: "jhon died". After training, for this experiment, the only results that matter are the output for th...
Can spacy's text categorizer learn the logic of recognizing two words in order?
I'm trying to determine if Spacy's text categorizer can learn a simple logic to detect the presence of two consecutive words in order: "jhon died". After training, for this experiment, the only results that matter are the output for the same texts used in the training samples, but I have been unable to have it match on...
[ "Yes it can, it seems impractical to use the train command for trivial examples.\nThe following code does exactly what is requested. Just using the default optimizer and basic updates on the model:\nimport spacy\nfrom spacy.training import Example\n\nsamples = [\n [\"jhon died\", 1],\n [\"died jhon\", 0],\n [\"d...
[ 0 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "spacy_3" ]
stackoverflow_0074514910_deep_learning_machine_learning_python_spacy_3.txt
Q: How to solve extracting data with scrapy because from contacts doesn't do anything? import scrapy import pycountry from locations. Items import GeojsonPointItem from locations. Categories import Code from typing import List, Dict import uuid creating the metadata #class class Trid...
How to solve extracting data with scrapy because from contacts doesn't do anything?
import scrapy import pycountry from locations. Items import GeojsonPointItem from locations. Categories import Code from typing import List, Dict import uuid creating the metadata #class class TridentSpider(scrapy.Spider): name: str = 'trident_dac' spider_type: str = 'c...
[ "There are 6 offices and none of them contain email. It didn't make sense, why have you included email item where it's clear to look that there are no email in 6 offices and the way that you are using to extract data isn't correct and perpect. So you can try yhe next example.\nCode:\nimport scrapy\nclass TestSpid...
[ 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074520769_python_scrapy.txt
Q: Why is this throwing an exception when I try to save the attachment from Outlook? I am trying to iterate through the contents of a subfolder, and if the message contains an .xlsx attachment, download the attachment to a local directory. I have confirmed all other parts of this program work until that line, which t...
Why is this throwing an exception when I try to save the attachment from Outlook?
I am trying to iterate through the contents of a subfolder, and if the message contains an .xlsx attachment, download the attachment to a local directory. I have confirmed all other parts of this program work until that line, which throws an exception each time. I am running the following code in a Jupyter notebook thr...
[ "Looks like the following line of code throws an exception at runtime:\nattachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))\n\nFirst, make sure that you deal with an attached file, not a link to the actual file. The Attachment.Type property returns an OlAttachmentType constant indicating the type of...
[ 1 ]
[]
[]
[ "email_attachments", "office_automation", "outlook", "python", "win32com" ]
stackoverflow_0074525643_email_attachments_office_automation_outlook_python_win32com.txt
Q: Python- Convert string which have numbers and letters to float for np.list I have a text that I use for taking data. I want to take this "line" and make it numpy list. My data is string but it has numbers and E letters. Because of this I can't convert it to float and taking it to list. import numpy as np import re...
Python- Convert string which have numbers and letters to float for np.list
I have a text that I use for taking data. I want to take this "line" and make it numpy list. My data is string but it has numbers and E letters. Because of this I can't convert it to float and taking it to list. import numpy as np import re with open("FEMMeshGmsh.inp", "r") as file: for line in file.readline...
[ "You can do that :\nimport numpy as np\nimport re \n\n\nwith open(\"FEMMeshGmsh.inp\", \"r\") as file: \n for line in file.readlines():\n if \"+\" in line:\n line = line[:-1]\n line_array = line.split(\",\")\n number_array = line_array[-1].split(\"E+\") \n line_arr...
[ 0, 0 ]
[]
[]
[ "arraylist", "numpy", "python", "readfile", "type_conversion" ]
stackoverflow_0074525668_arraylist_numpy_python_readfile_type_conversion.txt
Q: Calculate totals from text file in python How would I split the following: Sample Text file1:(items bought) Rosa,Chocolate,Banana,Strawberry,Apple Carol,Banana,Chocolate,Chocolate,Apple Sample Text File2: (price of items) Apple,$2 Banana,$5 Chocolate,$7 Strawberry,$4 (Question: Would it be easier to convert th...
Calculate totals from text file in python
How would I split the following: Sample Text file1:(items bought) Rosa,Chocolate,Banana,Strawberry,Apple Carol,Banana,Chocolate,Chocolate,Apple Sample Text File2: (price of items) Apple,$2 Banana,$5 Chocolate,$7 Strawberry,$4 (Question: Would it be easier to convert this into a csv file?) List containing names: n...
[ "I don't usually like to do people's homework, but you seem to be pretty far afield here.\nThis does not need to be complicated. First, we read file 2 into a dictionary. We do it line by line, splitting on the commas, and throwing away the dollar sign. I probably should have checked for the dollar sign, but I ju...
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "split" ]
stackoverflow_0074525601_dictionary_list_python_split.txt
Q: I want to sort a dictionary inside a list by number I need to sort a ranking of points by descending order. The users and points are inside lista_ranking which includes de following code [{'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20), 'hora': '13:00hs', 'equipo_local': 'Catar', 'equipo_visitan...
I want to sort a dictionary inside a list by number
I need to sort a ranking of points by descending order. The users and points are inside lista_ranking which includes de following code [{'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20), 'hora': '13:00hs', 'equipo_local': 'Catar', 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado', 'goles_local': 0,...
[ "This will order tuples of points, first name and last name from highest to lowest;\nsorted([(d['usuario']['puntaje'], d['usuario']['nombre'], d['usuario']['apellido']) for d in lista_ranking], reverse=True)\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0074525663_dictionary_list_python_sorting.txt
Q: How to copy image from sub_subfolders to only one folder using python I want to copy images from multi subfolders into only one folder using python or any library that can do with python framework my folders as described in tree below $ tree . ├── main_folder │ ├── Subfolder_1 │ │ └── Subfolder1_1 │ │ ...
How to copy image from sub_subfolders to only one folder using python
I want to copy images from multi subfolders into only one folder using python or any library that can do with python framework my folders as described in tree below $ tree . ├── main_folder │ ├── Subfolder_1 │ │ └── Subfolder1_1 │ │ └── ├── 0.png │ │ ├── 1.png │ │ ├── 2.png │ │ ...
[ "just use a mixture of glob for finding files and shutil for copying files.\nimport glob\nimport os\nimport shutil\n\ndest_folder = 'destination_folder'\nif not os.path.isdir(dest_folder):\n os.mkdir(dest_folder)\n\nfor item in glob.glob('**/*.png',recursive=True):\n filename = os.path.basename(item)\n ful...
[ 1 ]
[]
[]
[ "operating_system", "python", "subdirectory" ]
stackoverflow_0074525745_operating_system_python_subdirectory.txt
Q: How to send a json object pretty printed as an email python I have a python script that gets a cluster health as json and sends me a mail. The issue is that the json is not pretty printed. These are the methods I have tried already: Simple --> json.dumps(health) json.dumps(health, indent=4, sort_keys=True) But ...
How to send a json object pretty printed as an email python
I have a python script that gets a cluster health as json and sends me a mail. The issue is that the json is not pretty printed. These are the methods I have tried already: Simple --> json.dumps(health) json.dumps(health, indent=4, sort_keys=True) But the output in gmail is still unformatted, somewhat like this { "a...
[ "I can't say for certain, but it would seem like your email-sending code is defaulting to sending an \"HTML\" email, and in HTML consecutive spaces collapse into one, that way HTML code like:\n<p>\n This is a paragraph, but it's long so\n I'll break to a new line, and indented\n so I know it's within the `...
[ 7, 0, 0 ]
[]
[]
[ "elasticsearch", "email", "json", "python" ]
stackoverflow_0041458580_elasticsearch_email_json_python.txt
Q: How to remove duplicate rows with a condition in pandas i.e i want to drop duplicates pairs using col1 and col2 as the subset only if the values are the opposite in col3 (one negative and one positive). similar to drop_duplicates function but i want to impose a condition and only want to remove the first pair (i.e...
How to remove duplicate rows with a condition in pandas
i.e i want to drop duplicates pairs using col1 and col2 as the subset only if the values are the opposite in col3 (one negative and one positive). similar to drop_duplicates function but i want to impose a condition and only want to remove the first pair (i.e if 3 duplicates, just remove 2, leave 1) my dataset (df): ...
[ "We can do transform\nout = df[df.groupby(['col1','col2']).col3.transform('sum').ne(0) & df.col3.ne(0)]\nOut[252]: \n col1 col2 col3\n0 1 1 1\n1 2 2 2\n2 1 1 1\n3 3 5 7\n\n", "Recreating the dataset:\nimport pandas as pd\n\ndata = [\n [1, 1, 1],\n [2, 2, ...
[ 0, 0, 0 ]
[]
[]
[ "drop_duplicates", "pandas", "python" ]
stackoverflow_0074513714_drop_duplicates_pandas_python.txt
Q: Send a qweb odoo report via to mobile app via api in odoo 14 I have generated odoo qweb report and convert to base64 encoding using the following code. base64.base64encode(pdf) And i get string like "b'JVBERi0xLjQKMSAwIG9iago8PAovVGl0bGUgKP7/KQovQ3JlYXRvciAo/v8AdwBrAGgAdABtAGwAdAB " now i want to pass this s...
Send a qweb odoo report via to mobile app via api in odoo 14
I have generated odoo qweb report and convert to base64 encoding using the following code. base64.base64encode(pdf) And i get string like "b'JVBERi0xLjQKMSAwIG9iago8PAovVGl0bGUgKP7/KQovQ3JlYXRvciAo/v8AdwBrAGgAdABtAGwAdAB " now i want to pass this string to mobile application via api.. when i used in mobile..it sh...
[ "Base64 conversion is fine.\nNote that python base64.base64encode returns a binary output.\nConsider decoding to UTF-8 after encoding into base64.\nbase64.base64encode(pdf).decode('utf-8')\nIn browser environments (for ex. hybrid mobile or progressive web apps) you should indicate correct mime-type before base64 ha...
[ 0 ]
[]
[]
[ "odoo", "python" ]
stackoverflow_0074515115_odoo_python.txt
Q: How to import a numerical variable inside a function from another file - Python I'm trying to create a welding throat calculator just to practice my Python skills. I have 2 files for the same project, throat_size.py and support.py. I use support.py, just to make the calculus that I need, and I want to call these r...
How to import a numerical variable inside a function from another file - Python
I'm trying to create a welding throat calculator just to practice my Python skills. I have 2 files for the same project, throat_size.py and support.py. I use support.py, just to make the calculus that I need, and I want to call these results throat_size, but I'm getting: name 'a' is not defined. throat_size.py: import ...
[ "The function must return values that can be used.\nimport math as mt\n\n\ndef thickness(espessura):\n \"\"\"\n espessura: string\n return a tuple of numbers: a1, rz1, z1, a2, rz2, z2, esp\n \n >>> # unpacking values:\n >>> a1, rz1, z1, a2, rz2, z2, esp = thickness(\"2\")\n >>> a1\n 1.0\n ...
[ 1 ]
[]
[]
[ "python", "tkinter", "variables" ]
stackoverflow_0074511439_python_tkinter_variables.txt
Q: How to get Json key name if its value is equal to "x" - Python I am working on a python practice, it is about trying to check the availability of products in a json file, the condition is that if Key is equal to 1, then it means that producs is available, so if the product is available, then print key names. The J...
How to get Json key name if its value is equal to "x" - Python
I am working on a python practice, it is about trying to check the availability of products in a json file, the condition is that if Key is equal to 1, then it means that producs is available, so if the product is available, then print key names. The Json format looks like: product={"FooBox": "1", "ZeroB": "0", "Birk":...
[ "In your attempted solution product is a string, not a dictionary like you showed in the first snippet.\nAnd even if it were a dictionary, for x in product: would set x to the keys, not the values.\nUse product.items() to iterate over the keys and values of the dictionary. Then you can check the value and collect t...
[ 1, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074525861_json_python.txt
Q: django.urls.exceptions.NoReverseMatch URLS path seem to be correct I receive the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'journalrep' with arguments '('',)' not found. 2 pattern(s) tried: ['reports/journalrep/(?P[^/]+)/(?P[^/]+)\Z', 'reports/journalrep/\Z'] My urls.py contains: from dja...
django.urls.exceptions.NoReverseMatch URLS path seem to be correct
I receive the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'journalrep' with arguments '('',)' not found. 2 pattern(s) tried: ['reports/journalrep/(?P[^/]+)/(?P[^/]+)\Z', 'reports/journalrep/\Z'] My urls.py contains: from django.urls import path from . import views urlpatterns = [ path('', v...
[ "Try using this instead:\n{% url 'journalrep' column='date' direction='D' %}\n\nAnd also in urls.py:\npath('journalrep/<str:column>/<str:direction>', views.journalrep, name='journalrep')\n\nAnd potentially removing the line above this also as I'm not sure its required.\nIt's possible that django is arching the firs...
[ 1, 1 ]
[]
[]
[ "django", "django_templates", "django_urls", "python" ]
stackoverflow_0074524245_django_django_templates_django_urls_python.txt
Q: Why telegram-bot on Python with Webhooks can't process messages from many users simultaneously unlike a bot with Long Polling? I use aiogram. Logic of my bot is very simple - he receive messages from user and send echo-message after 10 seconds. This is a test bot, but in general, I want to make a bot for buying mo...
Why telegram-bot on Python with Webhooks can't process messages from many users simultaneously unlike a bot with Long Polling?
I use aiogram. Logic of my bot is very simple - he receive messages from user and send echo-message after 10 seconds. This is a test bot, but in general, I want to make a bot for buying movies with very big database of users. So, my bot must be able to process messages from many users simultaneously and must receive me...
[ "Actually telegram-bot on Python with Webhooks can process messages from many users simultaneously. You need just to put @dp.async_task after handler\n@dp.message_handler()\n@dp.async_task\nasync def echo(message: types.Message):\n await asyncio.sleep(10)\n await message.answer(message.text)\n\n" ]
[ 0 ]
[]
[]
[ "aiogram", "python", "simultaneous", "telegram_bot", "webhooks" ]
stackoverflow_0074500287_aiogram_python_simultaneous_telegram_bot_webhooks.txt
Q: how to make easy and efficient plots on Python I use matplotlib for my plots, I find it great, but sometimes too much complicated. Here an example: import matplotlib.pyplot as plt import numpy as np idx1 = -3 idx2 = 3 x = np.arange(-3, 3, 0.01) y = np.sin(np.pi*x*7)/(np.pi*x*7) major_ticks = np.arange(idx1, idx...
how to make easy and efficient plots on Python
I use matplotlib for my plots, I find it great, but sometimes too much complicated. Here an example: import matplotlib.pyplot as plt import numpy as np idx1 = -3 idx2 = 3 x = np.arange(-3, 3, 0.01) y = np.sin(np.pi*x*7)/(np.pi*x*7) major_ticks = np.arange(idx1, idx2, 1) minor_ticks = np.arange(idx1, idx2, 0.1) fig ...
[ "Matplotlib provides an object oriented API. This means that all the elements of the figure are acutally objects for which one can get and set properties and which can be easily manipulated. This makes matplotlib really flexible such that it can produce almost any plot you'd imagine. \nSince a plot may consist of a...
[ 1, 0, 0 ]
[]
[]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0042996834_matplotlib_python_seaborn.txt
Q: Calculate Monthly Churn I am wanting to obtain a monthly customer churn rate by using the following formula: (Number of Customers Lost within 1-month period / Number of Active Customers at the beginning of the 1-month period) Say I have the following data (this is just a small sample of it - note that if "Boolean ...
Calculate Monthly Churn
I am wanting to obtain a monthly customer churn rate by using the following formula: (Number of Customers Lost within 1-month period / Number of Active Customers at the beginning of the 1-month period) Say I have the following data (this is just a small sample of it - note that if "Boolean == True" the customer has lef...
[ "Assuming you have the data stored in an array:\nBoolean = [False, False, True, True, True, True, False, False, True, False]\n\nthe solution is a simple one-liner:\nsum([1 for x in Boolean if x])/len(Boolean)\n\n" ]
[ 0 ]
[]
[]
[ "churn", "pandas", "python" ]
stackoverflow_0074525832_churn_pandas_python.txt
Q: a data collection with web scraping I'am trying to extract data from a site and then to create a DataFrame out of it. the program doesnt work properly. I'am new in web scraping. Hope somoene help me out and find the problem. from urllib.request import urlopen from bs4 import BeautifulSoup url = 'https://www.imdb....
a data collection with web scraping
I'am trying to extract data from a site and then to create a DataFrame out of it. the program doesnt work properly. I'am new in web scraping. Hope somoene help me out and find the problem. from urllib.request import urlopen from bs4 import BeautifulSoup url = 'https://www.imdb.com/chart/top/?sort=rk,asc&mode=simple&pa...
[ "You can try the next example:\n from bs4 import BeautifulSoup\n from urllib.request import urlopen\n import requests\n import pandas as pd\n \n url = 'https://www.imdb.com/chart/top/?sort=rk,asc&mode=simple&page=1'\n \n #soup = BeautifulSoup(requests.get(url).text,'html.parser')# It's the p...
[ 0 ]
[]
[]
[ "python", "urllib", "web_scraping" ]
stackoverflow_0074525787_python_urllib_web_scraping.txt
Q: Convert df.unit8 to df.float32 in TensorFlow I have a ds_train of MNIST data of data type unit8 and i want to convert it to float32 but i am getting the following error. ValueError Traceback (most recent call last) <ipython-input-14-ac6926bc60db> in <module> ----> 1 tf.image.convert_...
Convert df.unit8 to df.float32 in TensorFlow
I have a ds_train of MNIST data of data type unit8 and i want to convert it to float32 but i am getting the following error. ValueError Traceback (most recent call last) <ipython-input-14-ac6926bc60db> in <module> ----> 1 tf.image.convert_image_dtype(ds_trn,dtype=tf.float32, saturate=Fals...
[ "there are multiple causes\n\nIt is between the process and the eager process\nTarget conversion does not support, image type array *\nVariable update\n\n\nSample: Resizes is a lossless process, grays scales and conversion the command are line in order of the program designed with image process knowledge. To protec...
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074523390_python_tensorflow.txt
Q: Rs mutate() and grepl() in Python I have a column in a dataset that lists all of the softwares that a given computer has installed. I have created multiple binary columns from this column so each software has its own column. My R code is below: data <- data %>% mutate(MS_Office_installed = ifelse(grepl("MS Offic...
Rs mutate() and grepl() in Python
I have a column in a dataset that lists all of the softwares that a given computer has installed. I have created multiple binary columns from this column so each software has its own column. My R code is below: data <- data %>% mutate(MS_Office_installed = ifelse(grepl("MS Office", installed_software), 1, 0), ...
[ "You may use str.contains here. For example:\ndf[\"MS_Office_installed\"] = df[\"installed_software\"].str.contains(r'\\bMS Office\\b', regex=True).astype(int)\n\nUse similar logic for the other desired boolean columns.\n" ]
[ 1 ]
[]
[]
[ "grepl", "mutate", "python", "r" ]
stackoverflow_0074526024_grepl_mutate_python_r.txt
Q: Please Help me with selenium on Firefox Good evening, I'm trying to do some tests with selenium in Firefox, but I'm stuck, I can not click on a button, because I got the message accepting cookies and that does not allow me to continue with the test, I do not know how to make selenium accept cookies. This is the me...
Please Help me with selenium on Firefox
Good evening, I'm trying to do some tests with selenium in Firefox, but I'm stuck, I can not click on a button, because I got the message accepting cookies and that does not allow me to continue with the test, I do not know how to make selenium accept cookies. This is the message it gave me: An exception occurred: Elem...
[ "Get Selenium to pause(check docs on how to pause, something like Thread.sleep(2000);) for a minute just before it clicks the \"Accept cookies\" button and try click the button yourself when it's paused. So you will be able to see what element is blocking it.\nThen use \"page scroll up\"/\"page scroll down\"/x/y/wh...
[ 0 ]
[]
[]
[ "geckodriver", "python", "selenium" ]
stackoverflow_0074526008_geckodriver_python_selenium.txt
Q: Vector arithmetic I am trying to create an array of evenly spaced elements ranging from -n to n. (ex: -2, 2, up to 1000 evenly spaced elements). Then using the array to create 2 new arrays using 2 equations by doing vector arithmetic. import numpy as np from math import sqrt width = 4 intervals = 1000 xCoord...
Vector arithmetic
I am trying to create an array of evenly spaced elements ranging from -n to n. (ex: -2, 2, up to 1000 evenly spaced elements). Then using the array to create 2 new arrays using 2 equations by doing vector arithmetic. import numpy as np from math import sqrt width = 4 intervals = 1000 xCoords = np.linspace(-width/...
[ "Use numpy functions on numpy arrays instead of the math library functions. Try np.sqrt and np.abs\n" ]
[ 2 ]
[]
[]
[ "arrays", "python", "vector", "vectorization" ]
stackoverflow_0074526105_arrays_python_vector_vectorization.txt
Q: Python program to extract Combination element available from the data set like Co & Fe available in composition line This is data set(Sample) which I need to extract the combination available in Composition (Like Co & Fe) only that data set to be extracted { "Au": 0.9789814953164448, "Az": 2.39897284406025...
Python program to extract Combination element available from the data set like Co & Fe available in composition line
This is data set(Sample) which I need to extract the combination available in Composition (Like Co & Fe) only that data set to be extracted { "Au": 0.9789814953164448, "Az": 2.398972844060257, "B prime": 4.016727605471411, "B/G": 2.3640597506841443, "Bulk modulus": 165.36806388061723, "C11": 220...
[ "First, you will need to get your data as a list of dictionaries. I am not sure how you are loading your data, so I am calling such a list as list_of_dicts. If you need help how to do that, I'd suggest you submit a different question. Then it's just a matter of looping through the dictionaries, finding the Composit...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074525837_python.txt
Q: How do I convert a struct_time output into DD/MM/YY, Hour:Minute:Second format? I'm relatively uninitiated when it comes to Python, and I'm trying to figure out how to take an output I'm getting from a sensor into proper day, month, year and hour, minute, second format. An example of the output, which also include...
How do I convert a struct_time output into DD/MM/YY, Hour:Minute:Second format?
I'm relatively uninitiated when it comes to Python, and I'm trying to figure out how to take an output I'm getting from a sensor into proper day, month, year and hour, minute, second format. An example of the output, which also includes a basic counter (the first output), and a timestamp (the third output) is shown bel...
[ "time.strftime exists for exactly this purpose:\nimport time\n\nnow_local = time.localtime()\n\nfmt = \"%d/%m/%Y %H:%M:%S\"\nout = time.strftime(fmt, now_local)\n\nprint(out)\n\nHowever, two words of warning:\n\ntime.struct_time is not \"timezone aware\". This will turn out to matter when you least expect it. Unles...
[ 1, 1 ]
[]
[]
[ "python", "sensors", "time" ]
stackoverflow_0074467436_python_sensors_time.txt
Q: Visualising the last layer node embeddings of a model in torch geometric I'm doing my first graph convolutional neural network project with torch_geometric. I want to visualize the last layer node embeddings of my model and don't know how I should get it. I trained my model on the CiteSeer dataset. You can get the...
Visualising the last layer node embeddings of a model in torch geometric
I'm doing my first graph convolutional neural network project with torch_geometric. I want to visualize the last layer node embeddings of my model and don't know how I should get it. I trained my model on the CiteSeer dataset. You can get the full dataset as easily as this: from torch_geometric.datasets import Planetoi...
[ "It is solve by changing the model to this:\nclass GraphClassifier(torch.nn.Module):\n def __init__(self, dataset, hidden_dim):\n super(GraphClassifier, self).__init__()\n self.conv1 = GCNConv(dataset.num_features, hidden_dim)\n self.conv2 = GCNConv(hidden_dim, dataset.num_classes)\n\n de...
[ 0 ]
[]
[]
[ "graph_neural_network", "python", "pytorch", "pytorch_geometric" ]
stackoverflow_0074498230_graph_neural_network_python_pytorch_pytorch_geometric.txt
Q: My threading is not exactly working like i want it to Ok So I am doing a school project for which I am Using threads to go from a phone Home Screen to a chat app and i have used threads in both application. import pygame as pyg, sys, cv2, random, os, handDetector, time, threading import pywhatkit, pyjokes, pyttsx3...
My threading is not exactly working like i want it to
Ok So I am doing a school project for which I am Using threads to go from a phone Home Screen to a chat app and i have used threads in both application. import pygame as pyg, sys, cv2, random, os, handDetector, time, threading import pywhatkit, pyjokes, pyttsx3 as pyt import speech_recognition as sr, chatApp, server1 ...
[ "I don't know every version of Python that's out there, but in the version I'm running (3.9.6), this doesn't do anything useful:\nthreading.Thread(target=(server1.function(),)).start()\n\nThat statement is the same as if you did this:\ntemp_a = server1.function() # call function()\ntemp_b = (temp_a,) ...
[ 0 ]
[]
[]
[ "multithreading", "pygame", "python" ]
stackoverflow_0074522649_multithreading_pygame_python.txt
Q: How to print a list value one below another I need to sort a ranking of points by descending order. The users and points are inside lista_ranking which includes de following code: [{'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20), 'hora': '13:00hs', 'equipo_local': 'Catar', 'equipo_visitante': 'E...
How to print a list value one below another
I need to sort a ranking of points by descending order. The users and points are inside lista_ranking which includes de following code: [{'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20), 'hora': '13:00hs', 'equipo_local': 'Catar', 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado', 'goles_local': 0...
[ "You are close to the solution. You can use a loop and join the part of the name to print the rank of the users.\nimport datetime\n\nlista_ranking = [\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visi...
[ 1, 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0074526183_dictionary_list_python_sorting.txt
Q: How does merging two pandas dataframes worked using the assignment operation? The phenomenon that I am not able to understand is how pandas is able to join two dataframes using the equal operation as in the following code: import pandas as pd import numpy as np from IPython.display import display df1 = pd.DataFra...
How does merging two pandas dataframes worked using the assignment operation?
The phenomenon that I am not able to understand is how pandas is able to join two dataframes using the equal operation as in the following code: import pandas as pd import numpy as np from IPython.display import display df1 = pd.DataFrame({"A": np.arange(1, 5), "B": np.arange(11, 15)}) df1.index = (np.arange(1, 5) + 1...
[ "This is a basic feature of pandas, automatic index alignment. This is indeed one of the core features which distinguishes it from just numpy (on top of which it is built). Briefly, at index 2 of df1, the new column will get the value 23 (from index 2 in df2['C']). At index 3, the new column will get the value 24 f...
[ 1 ]
[]
[]
[ "merge", "pandas", "python" ]
stackoverflow_0074526154_merge_pandas_python.txt
Q: how apply str.contain to every column in pandas? i have a dataframe like this : my data I want to apply this func to all column of the dataframe: data3 = data2.str.contains('|'.join(features)) but i got error AttributeError: 'DataFrame' object has no attribute 'str' “features is a list of word” how i can do this...
how apply str.contain to every column in pandas?
i have a dataframe like this : my data I want to apply this func to all column of the dataframe: data3 = data2.str.contains('|'.join(features)) but i got error AttributeError: 'DataFrame' object has no attribute 'str' “features is a list of word” how i can do this and solve this problem?
[ "The dataframe doesn't have a contains method, but the columns do. Iterate the columns and assign to the result.\nfeature_str = '|'.join(features)\ndata3 = pd.DataFrame()\nfor name, col in data2.items():\n data3[name] = col.str.contains(feature_str)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074525827_pandas_python.txt
Q: How to prevent pytest using local module For reference, this is the opposite of this question. That question asks how to get pytest to use your local module. I want to avoid pytest using the local module. I need to test my module's installation procedure. We should all be testing our modules' installation procedur...
How to prevent pytest using local module
For reference, this is the opposite of this question. That question asks how to get pytest to use your local module. I want to avoid pytest using the local module. I need to test my module's installation procedure. We should all be testing our modules' installation procedures. Therefore, I want my test suite to pretend...
[ "A workaround is to manually edit the PYTHONPATH by changing tests/conftest.py to include\nimport sys\nsys.path.pop(0)\n\nbefore the first time my_module is imported, but it's not pretty and makes the assumption about where in the PYTHONPATH that item is going to show up. Of course, more code could be added to chec...
[ 0, 0 ]
[]
[]
[ "pytest", "python", "pythonpath", "unit_testing" ]
stackoverflow_0067176036_pytest_python_pythonpath_unit_testing.txt
Q: Confused on how the multiple variables work and how to get all 4 values from 1st item in list testdata = ["One,For,The,Money", "Two,For,The,Show", "Three,To,Get,Ready", "Now,Go,Cat,Go"] #My Code: def chop(string): x = 0 y = 0 while x < 5: y = string.find(",") + 1 z = string.find(",", y...
Confused on how the multiple variables work and how to get all 4 values from 1st item in list
testdata = ["One,For,The,Money", "Two,For,The,Show", "Three,To,Get,Ready", "Now,Go,Cat,Go"] #My Code: def chop(string): x = 0 y = 0 while x < 5: y = string.find(",") + 1 z = string.find(",", y) x = x + 1 return y, z #My Code Ends for i in range(4): uno, dos, tres, cuatro =...
[ "I cant figure out why You need to do in that way, but maybe it helps.\ntestdata = [\"One,For,The,Money\", \"Two,For,The,Show\",\n \"Three,To,Get,Ready\", \"Now,Go,Cat,Go\"]\n\nfor i in testdata:\n uno, dos, tres, cuatro = i.split(',')\n print(uno + \":\" + dos + \":\" + tres + \":\" + cuatro)\n\nResul...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074526091_python_python_3.x.txt