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:
clean_list() --> ValueError: Wrong number of items passed 3, placement implies 1
I inherited this code from previous employee, and I tried to run this code but I'm getting an error.
def replaceitem(x):
if x in ['ORION', 'ACTION', 'ICE', 'IRIS', 'FOCUS']:
return 'CRM Application'
else:
retur... | clean_list() --> ValueError: Wrong number of items passed 3, placement implies 1 | I inherited this code from previous employee, and I tried to run this code but I'm getting an error.
def replaceitem(x):
if x in ['ORION', 'ACTION', 'ICE', 'IRIS', 'FOCUS']:
return 'CRM Application'
else:
return x
def clean_list(row):
new_list = sorted(set(row['APLN_NM']), key=lambda x:... | [
"I identified the error is occurring only if the data frame is empty, so I tried if else to filter the empty data frame and it worked.\nif df_agg.empty:\n df_agg['APLN_NM_DISTINCT'] = ''\nelse:\n df_agg['APLN_NM_DISTINCT'] = df_agg.apply(clean_list, axis = 1)\n \n\nif df_agg_single.empty:\n ... | [
0
] | [] | [] | [
"dataframe",
"keyerror",
"pandas",
"python",
"valueerror"
] | stackoverflow_0074554336_dataframe_keyerror_pandas_python_valueerror.txt |
Q:
How to not change value if an input is empty
I have written this code for a form I was working on.
<div class="col-md-6">
<label class="labels">Doğum Günü:</label>
<input method="POST"name="birtdate" class="form-control" {% if student.birtdate%} type="text"value="{{student.birtdate}}" onfocus="(this.type='... | How to not change value if an input is empty | I have written this code for a form I was working on.
<div class="col-md-6">
<label class="labels">Doğum Günü:</label>
<input method="POST"name="birtdate" class="form-control" {% if student.birtdate%} type="text"value="{{student.birtdate}}" onfocus="(this.type='date')"onblur="(this.type='text')" {%else %}type="... | [
"I'm not sure but if your input changes onblur then does it retain and translate the value from date to text. I think the value resets to default when you change the type. it would be better to write a function to parse the date to text and then set this.value to that instead of just simply using one line statement... | [
0
] | [] | [] | [
"django",
"html",
"javascript",
"python"
] | stackoverflow_0070632417_django_html_javascript_python.txt |
Q:
Is it possible to use properties on module variables instead of instance attributes?
What I wish:
# main.py
import config
config.test = True # prints 'config: test is set to True'
print(config.test) # True
What I tried:
# config.py
_test = False
@property
def test():
return _test
@test.setter
def test(new... | Is it possible to use properties on module variables instead of instance attributes? | What I wish:
# main.py
import config
config.test = True # prints 'config: test is set to True'
print(config.test) # True
What I tried:
# config.py
_test = False
@property
def test():
return _test
@test.setter
def test(new_value):
global _test
_test = new_value
logger.info(f'config: test is set to {... | [
"Make it a class\nclass Config:\n @property\n def test(self):\n return self._test\n\n @test.setter\n def test(self, value):\n self._test = value\n\n def __init__(self, **kwargs):\n self._test = None\n\nHowever, in a way this makes no sense, and the reason is because you have a ge... | [
0
] | [] | [] | [
"module",
"properties",
"python"
] | stackoverflow_0074576773_module_properties_python.txt |
Q:
Why is scipy's probability density function not accepting size of my mean?
I am using a function to calculate a likelihood density.
I am running through two xs which are vectors of length 7.
def lhd(x0, x1, dt): #Define a function to calculate the likelihood density given two values.
d = len(x0) #Save the len... | Why is scipy's probability density function not accepting size of my mean? | I am using a function to calculate a likelihood density.
I am running through two xs which are vectors of length 7.
def lhd(x0, x1, dt): #Define a function to calculate the likelihood density given two values.
d = len(x0) #Save the length of the inputs for the below pdf input.
print(d)
print(len(x1))
l... | [
"If dt is a (7,7) array, (1-dt) is also (7,7), the * operator in (1-dt)*x0 is the element-wise multiplication, if x0 is a vector of length 7 the result will be a (7,7) array.\nI guess you meant to use matrix multiplication, you can that this using the x0 - dt @ x0 (where @ denotes the matrix multiplication operator... | [
0
] | [] | [] | [
"python",
"scipy",
"scipy.stats"
] | stackoverflow_0074571987_python_scipy_scipy.stats.txt |
Q:
input to sklearn pipeline from previous step and from the fitted data
I have a sklearn pipeline like the following:
features = Pipeline([
('feats_A', Function_transformer_A())
('feats_B', Function_transformer_B())
])
features.fit(X)
The input to feats_A is the fitted data X. And, the input to ... | input to sklearn pipeline from previous step and from the fitted data | I have a sklearn pipeline like the following:
features = Pipeline([
('feats_A', Function_transformer_A())
('feats_B', Function_transformer_B())
])
features.fit(X)
The input to feats_A is the fitted data X. And, the input to feats_B is the output from feats_A.
Instead, I want to be the input to fea... | [
"You can try using FeatureUnion\ndef blank(df):\n return df\n\nsubpipe = FeatureUnion(\n [('prep_data', Function_transformer(blank)),\n ('feats_A', Function_transformer_A())])\n \nfeatures = Pipeline([\n\n ('subpipe', subpipe)\n ('feats_B', Function_transformer_B())\n ])\n\n... | [
0
] | [] | [] | [
"pipeline",
"python",
"scikit_learn"
] | stackoverflow_0056969723_pipeline_python_scikit_learn.txt |
Q:
Is there any way to get username from USERID?
Code I'm using to get userid:
user = update.message.from_user
userid = user['id']
Is there any way to turn userid into username?
A:
Since you have the full user available, you can just use user.username: python-telegram-bot docs, telegram docs. If you only h... | Is there any way to get username from USERID? | Code I'm using to get userid:
user = update.message.from_user
userid = user['id']
Is there any way to turn userid into username?
| [
"Since you have the full user available, you can just use user.username: python-telegram-bot docs, telegram docs. If you only have the user id and not the full User object, you can query info about the user using getChat: PTB docs, TG docs.\n\nDisclaimer: I'm currently the maintainer of python-telegram-bot\n"
] | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram"
] | stackoverflow_0074575159_python_python_telegram_bot_telegram.txt |
Q:
get ip address using os.system in python
Im new to python and Im trying to get the IP Address of my network card using the following:
import sys
import os
ip_address = os.system('/sbin/ifconfig ens33 | grep "inet" |awk '/inet / { print $2 }' | cut -d":" -f2')
However it returns the following error:
ip_address = ... | get ip address using os.system in python | Im new to python and Im trying to get the IP Address of my network card using the following:
import sys
import os
ip_address = os.system('/sbin/ifconfig ens33 | grep "inet" |awk '/inet / { print $2 }' | cut -d":" -f2')
However it returns the following error:
ip_address = os.system('/sbin/ifconfig ens33 | grep "ine... | [
"Here is a way:\nimport subprocess\n\ncmd = \"\"\"/sbin/ifconfig eth0 | grep \"inet\" | awk '/inet / { print $2 }' | cut -d: -f2\"\"\"\nr = subprocess.run(cmd, shell=True, capture_output=True, universal_newlines=True)\nprivate_ip = r.stdout.strip()\n\n>>> obfuscate_ip(private_ip) # see footnote\n'55.3.93.202'\n\n(... | [
1
] | [] | [] | [
"os.system",
"python",
"python_3.x"
] | stackoverflow_0074575573_os.system_python_python_3.x.txt |
Q:
How to convert different formats of date timestamp to the format of timestamp in hive table
I have a list of different formats of timestamp. How to change its for to the format accepted in hive tables.
For eg.
20210811:12:55:56.563 to 2021-08-11 12:55:56.563
25/05/1999 02:35:05.532 to 1999-05-25 02:35:05.532 .
How... | How to convert different formats of date timestamp to the format of timestamp in hive table | I have a list of different formats of timestamp. How to change its for to the format accepted in hive tables.
For eg.
20210811:12:55:56.563 to 2021-08-11 12:55:56.563
25/05/1999 02:35:05.532 to 1999-05-25 02:35:05.532 .
How to do it in python. I have around 7-8 different formats.
Does anyone have any ideas or approach ... | [
"You can use below py function to check the format. If below functions returns not none values, then its in expected format else no. Return value will be a date time in yyyy-MM-dd HH:MI:SS.SSSSS format. You can easily insert this into hive date time field.\nimport datetime\n\n#formats to be checked\nfmts=['%d/%m/%Y... | [
0
] | [] | [] | [
"hive",
"python"
] | stackoverflow_0074572248_hive_python.txt |
Q:
How can I use MyPy to overload the __init__ method to adjust a getter's return value?
Let's say I have a class like this (pseudo-code, please ignore the odd db structure):
class Blog():
title = StringProperty()
comments = StringProperty(repeated=True)
I want to type check StringProperty such that Blog().t... | How can I use MyPy to overload the __init__ method to adjust a getter's return value? | Let's say I have a class like this (pseudo-code, please ignore the odd db structure):
class Blog():
title = StringProperty()
comments = StringProperty(repeated=True)
I want to type check StringProperty such that Blog().title returns a str type, and Blog().comments returns a List[str] type. MyPy mentions that s... | [
"__init__ can be overloaded. self will become the given type.\nTypeVar needs to become some kind of real type during type analysis. It can't stay as T or U or V. It must be filled in with a type like str or Literal[\"foo\"].\nfrom __future__ import annotations\nfrom typing import TypeVar, overload, Literal, Generic... | [
2,
0
] | [] | [] | [
"mypy",
"python"
] | stackoverflow_0064161037_mypy_python.txt |
Q:
Errors editing python with Vim
When I edit a python file in Vim (using MacVim), and I press o to insert a new line, Vim throws the following errors:
Error detected while processing function <SNR>20_CheckAlign..GetPythonIndent:
line 30:
E121: Undefined variable: dummy
Press ENTER or type command to continue
Error... | Errors editing python with Vim | When I edit a python file in Vim (using MacVim), and I press o to insert a new line, Vim throws the following errors:
Error detected while processing function <SNR>20_CheckAlign..GetPythonIndent:
line 30:
E121: Undefined variable: dummy
Press ENTER or type command to continue
Error detected while processing function ... | [
"I figured out the problem. It was throwing an error whenever the file's tab settings were different from the editor's tab settings. For example, my test.py file was set to 2 spaces per tab, with tabs expanded into spaces, whereas my editor was set to 4 spaces per tab, no expand.\nSo the solution workaround was to ... | [
2,
1,
1,
0
] | [] | [] | [
"macvim",
"python",
"vim"
] | stackoverflow_0004840851_macvim_python_vim.txt |
Q:
How do I parse using for-loop?
My aim is parse "funpay.com"'s offer page. It has to be easy, cause all offer names are inside the same class 'tc-item'.
However I can't use bs4+requests, because this page loads only if you're logged in, which I'm doing via cookies (selenium+pickle).
Idk how to make it at all, so I'... | How do I parse using for-loop? | My aim is parse "funpay.com"'s offer page. It has to be easy, cause all offer names are inside the same class 'tc-item'.
However I can't use bs4+requests, because this page loads only if you're logged in, which I'm doing via cookies (selenium+pickle).
Idk how to make it at all, so I'll appreciate any hints.
The code I ... | [
"Based on the rather thin starting point, I suspect it's an error that occurs during iterations, so here's what I would do.\nIn order not to discard everything directly, check inside the loop whether the element you are looking for is available or not and let output the result accordingly.\n...\nsoup = bs(driver.pa... | [
0
] | [] | [] | [
"beautifulsoup",
"for_loop",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074576726_beautifulsoup_for_loop_python_selenium_web_scraping.txt |
Q:
How to display user profile picutre from sql database stored as blob data in python flask
im creating a website in python flask where i want to display a photo for loggin users.
My database looks like this:
And i dont know how decode ProfilePicutre data and then display it in flask(diffrent for everyuser, like tw... | How to display user profile picutre from sql database stored as blob data in python flask | im creating a website in python flask where i want to display a photo for loggin users.
My database looks like this:
And i dont know how decode ProfilePicutre data and then display it in flask(diffrent for everyuser, like twitter profile picture)
| [
"Looks like you're storing your ProfilePicture file in some sort of binary (displayed in hex) column. Since you haven't mentioned any tools used to query the database (SqlAlchemy or similar) I can't be specific in the solution but,\ntry retrieving the data ans inspect it to figure out if it's returned in bytes, str... | [
0
] | [] | [] | [
"database",
"flask",
"python"
] | stackoverflow_0074576495_database_flask_python.txt |
Q:
How to resample time series dataframe to show average hourly data?
I am aware that pandas resample function has **hourly ** rule. However, it returns the average for every hour for the whole dataset.
When using that method (df.Value.resample('H').mean()), I get the following output:
Time&date
Value
2021-01-01 00... | How to resample time series dataframe to show average hourly data? | I am aware that pandas resample function has **hourly ** rule. However, it returns the average for every hour for the whole dataset.
When using that method (df.Value.resample('H').mean()), I get the following output:
Time&date
Value
2021-01-01 00:00:00
23
2021-01-01 01:00:00
25
However, I would like hourl... | [
"groupby can give you the result you want. Can you try this?\ndfx=df.groupby(df['date_column'].dt.hour).mean()\n\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"python",
"series",
"time"
] | stackoverflow_0074576827_dataframe_python_series_time.txt |
Q:
How to get the items in Queue without removing the items?
get() removes and returns an item from Queue in Python.
import queue
q = queue.Queue() # Here
q.put("Apple")
q.put("Orange")
q.put("Banana")
print(q.get())
print(q.get())
print(q.get())
Output:
Apple
Orange
Banana
Now, I want to get the items in Queue ... | How to get the items in Queue without removing the items? | get() removes and returns an item from Queue in Python.
import queue
q = queue.Queue() # Here
q.put("Apple")
q.put("Orange")
q.put("Banana")
print(q.get())
print(q.get())
print(q.get())
Output:
Apple
Orange
Banana
Now, I want to get the items in Queue without removing the items.
Is it possible to do this?
| [
"queue_object.queue will return copy of your queue in a deque object which you can then use the slices of. It is of course, not syncronized with the original queue, but will allow you to peek at the queue at the time of the copy.\nThere's a good rationalization for why you wouldn't want to do this explained in deta... | [
32,
12,
9,
0,
0
] | [] | [] | [
"data_structures",
"python",
"queue"
] | stackoverflow_0016686292_data_structures_python_queue.txt |
Q:
is there someway I can turn these lists inside of a list into different keys and values
So I have this list:
[['chocolate', '10225.25', '9025.0', '9505.0', '8750.0'], ['cookie dough', '7901.25', '4267.0', '7056.5', '3550.25'], ['rocky road', '6700.1', '5012.45', '6011.0', '5225.15'], ['strawberry', '9285.15', '827... | is there someway I can turn these lists inside of a list into different keys and values | So I have this list:
[['chocolate', '10225.25', '9025.0', '9505.0', '8750.0'], ['cookie dough', '7901.25', '4267.0', '7056.5', '3550.25'], ['rocky road', '6700.1', '5012.45', '6011.0', '5225.15'], ['strawberry', '9285.15', '8276.1', '8705.0', '7655.1'], ['vanilla', '8580.0', '7201.25', '8900.0', '3500.25']]
is there a... | [
"Let your list be:\nl=[['chocolate', '10225.25', '9025.0', '9505.0', '8750.0'], ['cookie dough', '7901.25', '4267.0', '7056.5', '3550.25'], ['rocky road', '6700.1', '5012.45', '6011.0', '5225.15'], ['strawberry', '9285.15', '8276.1', '8705.0', '7655.1'], ['vanilla', '8580.0', '7201.25', '8900.0', '3500.25']]\n\nYou... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074470878_dictionary_list_python.txt |
Q:
How to checkin list of divs if there is a span within with class 'new'
In Beautifulsoup i receive a list of divs. Each of these divs has an span included:
<div role="news_item" class="ni_nav_9tg">
<span class="nav_element_new_S5g">Germany vs. Japan</span>
</div>
...
<div role="news_item" class="ni_nav_9tg">
... | How to checkin list of divs if there is a span within with class 'new' | In Beautifulsoup i receive a list of divs. Each of these divs has an span included:
<div role="news_item" class="ni_nav_9tg">
<span class="nav_element_new_S5g">Germany vs. Japan</span>
</div>
...
<div role="news_item" class="ni_nav_9tg">
<span class="nav_element_new_S5g">Brasil vs. Serbia</span>
</div>
What i wa... | [
"You could select them directly like:\nsoup.select('div[role=\"news_item\"]:has(span[class*=\"new\"])')\n\nto get True or False check the len() of the ResultSet:\nlen(soup.select('div[role=\"news_item\"]:has(span[class*=\"new\"])')) > 0\n\nExample\nfrom bs4 import BeautifulSoup\nhtml='''\n<div role=\"news_item\" cl... | [
1
] | [] | [] | [
"beautifulsoup",
"list",
"python",
"web_scraping"
] | stackoverflow_0074576984_beautifulsoup_list_python_web_scraping.txt |
Q:
Creating a dataframe from different lists
I am new to python, so the question could be trivial.
I have a pair of lists, containing solid names and the associated counts, of which I am providing a sample here below:
volumes1 = ['Shield', 'Side', 'expHall', 'Funnel', 'gridpiece']
counts1= [3911, 1479, 553, 368, 342]... | Creating a dataframe from different lists | I am new to python, so the question could be trivial.
I have a pair of lists, containing solid names and the associated counts, of which I am providing a sample here below:
volumes1 = ['Shield', 'Side', 'expHall', 'Funnel', 'gridpiece']
counts1= [3911, 1479, 553, 368, 342]
and a second pair of lists
volumes2 = ['Shield... | [
"quess not optimal, but one solution\nimport pandas as pd\n\nvolumes1 = ['Shield', 'Side', 'expHall', 'Funnel', 'gridpiece']\ncounts1= [3911, 1479, 553, 368, 342]\nvolumes2 = ['Shield', 'leg', 'Funnel', 'gridpiece','wafer']\ncounts2= [291, 469, 73, 28, 32]\n\nvolumes12=list(set(volumes1+volumes2))\ncounts1R=[0]*len... | [
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074576892_list_pandas_python.txt |
Q:
Browsing context has been discarded using GeckoDriver Firefox through Selenium
I didn't make any changes to my python selenium program and it worked fine 3 days ago. Now when i try to use it i get:
Browsing context has been discarded
Failed to decode response from marionette
Any idea what could have caused this o... | Browsing context has been discarded using GeckoDriver Firefox through Selenium | I didn't make any changes to my python selenium program and it worked fine 3 days ago. Now when i try to use it i get:
Browsing context has been discarded
Failed to decode response from marionette
Any idea what could have caused this outside the code? (since no changes were made)
I'm using firefox and geckodriver. Aft... | [
"This error message...\nBrowsing context has been discarded\n.\nFailed to decode response from marionette\n\n...implies that the communication between GeckoDriver and Marionette was broken.\nSome more information regarding the binary version interms of:\n\nSelenium Server/Client\nGeckoDriver\nFirefox\n\nAdditionall... | [
3,
1,
1,
0
] | [] | [] | [
"firefox",
"geckodriver",
"python",
"selenium",
"selenium_firefoxdriver"
] | stackoverflow_0054525301_firefox_geckodriver_python_selenium_selenium_firefoxdriver.txt |
Q:
Apply exec function to pandas DataFrame
I have following pandas DataFrame to which I need to apply the exec function to all the rows.
import pandas as pd
var = 2.5
df = pd.DataFrame(["var*1", "var*3", "var*5"])
Expected result
The expected result I need is:
0
0 2.5
1 7.5
2 12.5
Using exec function wit... | Apply exec function to pandas DataFrame | I have following pandas DataFrame to which I need to apply the exec function to all the rows.
import pandas as pd
var = 2.5
df = pd.DataFrame(["var*1", "var*3", "var*5"])
Expected result
The expected result I need is:
0
0 2.5
1 7.5
2 12.5
Using exec function with apply
However if I do the following:
df.app... | [
"Take a look at pandas.eval. You can reference local variables using @var syntax.\nAs for arbitrary code execution, you should explicitly pass local variables as dict and use eval to get a return value, e.g. eval(\"a + 2\", {\"a\": 1})\nAs for your question:\ndf[0].apply(eval, args=({}, {\"var\": var}))\n\n"
] | [
1
] | [] | [] | [
"apply",
"dataframe",
"exec",
"pandas",
"python"
] | stackoverflow_0074576920_apply_dataframe_exec_pandas_python.txt |
Q:
How to fix website picture problem on HTML
{% extends 'base.html' %}
{% block content %}
<hi>Products</hi>
<div class="row">
{% for products in products %}
<div class="col">
<div class="card" style="width: 70rem;">
<img src="{{ products.image_url }}" class="car... | How to fix website picture problem on HTML | {% extends 'base.html' %}
{% block content %}
<hi>Products</hi>
<div class="row">
{% for products in products %}
<div class="col">
<div class="card" style="width: 70rem;">
<img src="{{ products.image_url }}" class="card-img-top" alt="...">
<div class... | [
"I am not exactly sure what your problem is but I see problem in code, try replacing:\n{% for products in products %}\n\nto\n{% for single_product in products %}\n\nand then update this lines with new variable name single_product\n<img src=\"{{ single_product.image_url }}\" class=\"card-img-top\" alt=\"...\">\n<h5 ... | [
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0074577098_django_django_templates_python.txt |
Q:
'IndexError: list index out of range'. What's wrong?
response = requests.get('https://store.steampowered.com/genre/Free%20to%20Play/?tab=1')
soup = BeautifulSoup(response.text, 'html.parser')
product = random.choice(soup.find_all(class_='gamehover_GameTitle_mrkD1'))
print('Рассмотрите эту игру: ' + product.text)
... | 'IndexError: list index out of range'. What's wrong? | response = requests.get('https://store.steampowered.com/genre/Free%20to%20Play/?tab=1')
soup = BeautifulSoup(response.text, 'html.parser')
product = random.choice(soup.find_all(class_='gamehover_GameTitle_mrkD1'))
print('Рассмотрите эту игру: ' + product.text)
I tried taking a different class. Then it returned an empt... | [
"When I checked it out, there were no elements with the class gamehover_GameTitle_mrkD1 on the website. This results in soup.find_all returning an empty list. Because random.choice then doesn't have any items to choose from, it will raise an indexerror.\nYou can fix this error by choosing a class name that does act... | [
1
] | [] | [] | [
"parsing",
"python",
"python_3.x"
] | stackoverflow_0074576913_parsing_python_python_3.x.txt |
Q:
write specific columns to a csv file with csv module
hi I am trying to write on a csv file using csv module (can't use panda's).
so issue is I am getting keys like this :
name_keys = ['DATASET ID', 'SOURCE NAME', 'NAME']
data = [
{
"DATASET ID":112313,
"SOURCE NAME":"source 1",
"NAME":"0",
... | write specific columns to a csv file with csv module | hi I am trying to write on a csv file using csv module (can't use panda's).
so issue is I am getting keys like this :
name_keys = ['DATASET ID', 'SOURCE NAME', 'NAME']
data = [
{
"DATASET ID":112313,
"SOURCE NAME":"source 1",
"NAME":"0",
"TYPE":1,
"Random":1
},
{
"DATASET ... | [
"You need to set extrasaction='ignore' as an argument of DictWriter :\n\nIf the dictionary passed to the writerow() method\ncontains a key not found in fieldnames, the optional extrasaction\nparameter indicates what action to take.\n\nimport csv\n\nwith open(\"outputcsv.csv\", 'w', encoding='UTF8', newline='') as f... | [
0
] | [] | [] | [
"csv",
"python",
"python_3.x"
] | stackoverflow_0074576994_csv_python_python_3.x.txt |
Q:
Can't pickle Enum after reloading it : not the same object
This is a follow up of my previous question : Enum comparison become False after reloading module
Ultimately, I would like to be able to pickle my enum.
Let's start from myenum.py again :
# myenum.py
import enum
class MyEnum(enum.Enum):
ONE = 1
TW... | Can't pickle Enum after reloading it : not the same object | This is a follow up of my previous question : Enum comparison become False after reloading module
Ultimately, I would like to be able to pickle my enum.
Let's start from myenum.py again :
# myenum.py
import enum
class MyEnum(enum.Enum):
ONE = 1
TWO = 2
I again import this file in my script. I create a variabl... | [
"Short answer: Stop using reload. It's a hack for use during active development, not for production use.\nIf this is just for active development in an interactive session, move the definition of the enum somewhere aside from the module you're actively editing and reloading, so it doesn't get caught up in the reload... | [
2,
0
] | [] | [] | [
"enums",
"pickle",
"python",
"python_importlib"
] | stackoverflow_0066460582_enums_pickle_python_python_importlib.txt |
Q:
How to Rearrange Some Strings in a List and Find the Average of It's Integers?
For my class, I have to take a file and turn it into a list with lists inside of it separating each "contestant" and from there, rearrange the Strings in it to where if it were a name, the name John Doe would instead become Doe John. On... | How to Rearrange Some Strings in a List and Find the Average of It's Integers? | For my class, I have to take a file and turn it into a list with lists inside of it separating each "contestant" and from there, rearrange the Strings in it to where if it were a name, the name John Doe would instead become Doe John. On top of this, I also have to take the integers in each list and calculate their aver... | [
"It is better if you use file.readlines() instead of file.read(), because it splits it into each line, separating each contestant.\nWith that, you can do stuff with each contestant, like so:\nfin = open(\"sample-1.txt.txt\")\ncontestants = fin.readlines()\nfinal = []\nfor contestant_string in contestants:\n if c... | [
0
] | [] | [] | [
"integer",
"list",
"python",
"string"
] | stackoverflow_0074577031_integer_list_python_string.txt |
Q:
Image classifier project
python predict.py /path/to/image checkpoint
what is the path to image here. i need to give an image as an input, the image is in a folder 1 which is in folder test, which is in the folder flowers. so i have written it as /flowers/test/1/image.jpg, but i am getting it as "no file or direct... | Image classifier project | python predict.py /path/to/image checkpoint
what is the path to image here. i need to give an image as an input, the image is in a folder 1 which is in folder test, which is in the folder flowers. so i have written it as /flowers/test/1/image.jpg, but i am getting it as "no file or directory"
i have tried writing th... | [
"Unless the flower/ directory is at the root of the file system, you shouldn't have a leading slash in front of the path. To reference the current directory, you should instead do python predict.py ./flowers/test/1/image.jpg checkpoint.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074577219_python.txt |
Q:
Problem with logging in Django using django.contrib.auth views
When I try to login via LoginView, the process seems successful. I'm redirected to LOGIN_REDIRECT_URL.
from django.contrib.auth import views as auth_views
urlpatterns = [
...
path('login', auth_views.LoginView.as_view(), name='login'),
]
But ... | Problem with logging in Django using django.contrib.auth views | When I try to login via LoginView, the process seems successful. I'm redirected to LOGIN_REDIRECT_URL.
from django.contrib.auth import views as auth_views
urlpatterns = [
...
path('login', auth_views.LoginView.as_view(), name='login'),
]
But when I try to access a view which requires login, I am redirected to... | [
"Try something like this:\nfrom rest_framework.permissions import IsAuthenticated\n\n\nclass MyView(viewsets.ViewSet):\n permission_classes = [IsAuthenticated]\n\n def list(self, request, server_id):\n .... \n\nViewSet is djangoREST class, and sometimes there are some differences in usage between defaul... | [
0
] | [] | [] | [
"django",
"django_authentication",
"python"
] | stackoverflow_0074576771_django_django_authentication_python.txt |
Q:
IPython Notebook and SQL: 'ImportError: No module named sql' when running '%load_ext sql'
Just set up an IPython Notebook on Ubuntu 16.04 but I can't use %load_ext sql.
I get: ImportError: No module named sql
I've tried using pip and pip3 with and without sudo to install ipython-sql. All 4 times it installed witho... | IPython Notebook and SQL: 'ImportError: No module named sql' when running '%load_ext sql' | Just set up an IPython Notebook on Ubuntu 16.04 but I can't use %load_ext sql.
I get: ImportError: No module named sql
I've tried using pip and pip3 with and without sudo to install ipython-sql. All 4 times it installed without issue but nothing changes on the notebook.
Thanks in advance!
| [
"I know it's been a long time, but I faced the same issue, and Thomas' advice solved my problem. Just outlining what I did here.\nWhen I ran sys.executable in the notebook I saw /usr/bin/python2, while the pip I used to install the package was /usr/local/bin/pip (to find out what pip you are using, just do which pi... | [
5,
5,
1,
0,
0
] | [] | [] | [
"ipython",
"ipython_sql",
"pip",
"python"
] | stackoverflow_0037149748_ipython_ipython_sql_pip_python.txt |
Q:
Gdown is giving Permission error for particular file,although it is opening up fine manually
I am not able to download file using gdown package.It is giving permission error.
But when i am opening it manually.It is giving no such error and opening up fine.
Here is the code i am using and link
import gdown
url='htt... | Gdown is giving Permission error for particular file,although it is opening up fine manually | I am not able to download file using gdown package.It is giving permission error.
But when i am opening it manually.It is giving no such error and opening up fine.
Here is the code i am using and link
import gdown
url='https://drive.google.com/uc?id=0B1lRQVLFjBRNR3Jqam1menVtZnc'
output='letter.pdf'
gdown.download(url, ... | [
"In my case, I ran the following command and try using gdown, and problem was solved:\npip install --upgrade --no-cache-dir gdown\n\nIf you are using google-colab, try:\n!pip install --upgrade --no-cache-dir gdown\n\nthen:\n!gdown --id [id of your file]\n",
"If you're working with big files (in my case was a >1gb... | [
36,
7,
2,
2,
1
] | [] | [] | [
"google_drive_api",
"python"
] | stackoverflow_0060739653_google_drive_api_python.txt |
Q:
Get features names from scikit pipelines
I am working on ML regression problem where I defined a pipeline like below based on a tutorial online.
My code looks like below
pipe1 = Pipeline([('poly', PolynomialFeatures()),
('fit', linear_model.LinearRegression())])
pipe2 = Pipeline([('poly', Polynomi... | Get features names from scikit pipelines | I am working on ML regression problem where I defined a pipeline like below based on a tutorial online.
My code looks like below
pipe1 = Pipeline([('poly', PolynomialFeatures()),
('fit', linear_model.LinearRegression())])
pipe2 = Pipeline([('poly', PolynomialFeatures()),
('fit', linear... | [
"You can use the transform method to generate the polynomial feature matrix.\nTo do so, you'll first have to access the corresponding step in the pipeline which, in this case, is at the 0th index. Here is how you can get the polynomial features array for pipe2:\nfeature_matrix = model3['Lasso'][0].transform(X_train... | [
1
] | [] | [] | [
"feature_extraction",
"machine_learning",
"pipeline",
"python",
"scikit_learn"
] | stackoverflow_0074570293_feature_extraction_machine_learning_pipeline_python_scikit_learn.txt |
Q:
Pandas How to use a column value as an index to another row
I have the following line of code
df["high_int"] = df.Slope * (df.index - df.max_idx) + df,loc['max_idx', 'High]
max_idx contains the indexes of the highest highs over a period eg: 15 or 30.
I have tried .loc, .iloc, .at, .iat .get, .shift(), as well a... | Pandas How to use a column value as an index to another row | I have the following line of code
df["high_int"] = df.Slope * (df.index - df.max_idx) + df,loc['max_idx', 'High]
max_idx contains the indexes of the highest highs over a period eg: 15 or 30.
I have tried .loc, .iloc, .at, .iat .get, .shift(), as well as df['max_idx'].map(df['High'])
Most errors seem to be related ... | [
"Last part doesn't really make sense, df.loc[index, columns] takes index filters, and column, or list of columns, not 2 columns. Another thing - assuming you wanted to write df[[\"max_id\", \"High\"]] - it would also fail, since you cannot force 2 columns into one in this way.\nConsider the below as example of what... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074577173_pandas_python.txt |
Q:
How to mock mongodb for python unittests?
I am using mock module for Python 2.7 to mock my other functions and using
unittest for writing unit tests.
I am wondering if mocking the MongoDB is different than using mock functionality (mock.patch a function that is being called?) Or I need to use another different pac... | How to mock mongodb for python unittests? | I am using mock module for Python 2.7 to mock my other functions and using
unittest for writing unit tests.
I am wondering if mocking the MongoDB is different than using mock functionality (mock.patch a function that is being called?) Or I need to use another different package for that purpose?
I do not think I want to... | [
"I recommend using mongomock for mocking mongodb. It's basically an in-memory mongodb with pymongo interface and made specifically for this purpose.\nhttps://github.com/mongomock/mongomock\n",
"You can also do this if you're just doing something simple, and you don't really need to retrieve by field.\n@mock.patch... | [
22,
8,
2,
2,
1,
0,
0
] | [] | [] | [
"mocking",
"mongodb",
"pymongo",
"python",
"unit_testing"
] | stackoverflow_0042239241_mocking_mongodb_pymongo_python_unit_testing.txt |
Q:
Run multiple terminals from python script and execute commands (Ubuntu)
What I have is a text file containing all items that need to be deleted from an online app. Every item that needs to be deleted has to be sent 1 at a time. To make deletion process faster, I divide the items in text file in multiple text files... | Run multiple terminals from python script and execute commands (Ubuntu) | What I have is a text file containing all items that need to be deleted from an online app. Every item that needs to be deleted has to be sent 1 at a time. To make deletion process faster, I divide the items in text file in multiple text files and run the script in multiple terminals (~130 for deletion time to be under... | [
"I used threading to run multiple functions simultaneously:\nfrom fileinput import filename\nfrom WitApiClient import WitApiClient\nimport os\nfrom threading import Thread\n\ndirname = os.path.dirname(__file__)\nparent_dirname = os.path.dirname(dirname)\ntoken = input(\"Enter the token\")\nfile_name = os.path.join(... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074553769_python_python_3.x.txt |
Q:
Python requests SSL error - certificate verify failed
This code
import requests
requests.get("https://hcaidcs.phe.org.uk/WebPages/GeneralHomePage.aspx")
is giving me this error
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
I know practically nothing about SSL, but I've tried downloading... | Python requests SSL error - certificate verify failed | This code
import requests
requests.get("https://hcaidcs.phe.org.uk/WebPages/GeneralHomePage.aspx")
is giving me this error
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
I know practically nothing about SSL, but I've tried downloading the site's certificate and pointing to that file using the... | [
"As already pointed out in a comment: the site has a bad SSL implementation as can be seen from the SSLLabs report. The main part of this report regarding your problem is:\n\nThis server's certificate chain is incomplete. Grade capped to B.\n\nThis means that the server is not sending the full certificate chain as ... | [
43,
2,
0
] | [
"If you can avoid the certificate verification (not secure), set PYTHONHTTPSVERIFY environment variable to 0:\nexport PYTHONHTTPSVERIFY=0\n\nThis will skip the certificate verification.\n",
"import requests\nhtml = requests.get(\"https://hcaidcs.phe.org.uk/WebPages/GeneralHomePage.aspx\",verify=False).text\n\nYou... | [
-1,
-5
] | [
"https",
"python",
"python_requests",
"ssl",
"ssl_certificate"
] | stackoverflow_0046604114_https_python_python_requests_ssl_ssl_certificate.txt |
Q:
Pull large amounts of data from a remote server, into a DataFrame
To give as much context as I can / is needed, I'm trying to pull some data stored on a remote postgres server (heroku) into a pandas DataFrame, using psycopg2 to connect.
I'm interested in two specific tables, users and events, and the connection w... | Pull large amounts of data from a remote server, into a DataFrame | To give as much context as I can / is needed, I'm trying to pull some data stored on a remote postgres server (heroku) into a pandas DataFrame, using psycopg2 to connect.
I'm interested in two specific tables, users and events, and the connection works fine, because when pulling down the user data
import pandas.io.sq... | [
"I suspect there's a couple of (related) things at play here causing slowness:\n\nread_sql is written in python so it's a little slow (especially compared to read_csv, which is written in cython - and carefully implemented for speed!) and it relies on sqlalchemy rather than some (potentially much faster) C-DBAPI. T... | [
5,
0,
0,
0
] | [] | [] | [
"pandas",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0025633830_pandas_postgresql_psycopg2_python.txt |
Q:
Assign a variable to none if the resulting dataframe is empty after filtering columns
I'm trying to get values in column z that contains null values or integers:
df = pd.DataFrame({'X': [1, 2, 3, 4],
'Y': [2, 10, 13, 18],
'Z': [3, None, 5, None]})
a = df[(df.X == 1) & (df.Y =... | Assign a variable to none if the resulting dataframe is empty after filtering columns | I'm trying to get values in column z that contains null values or integers:
df = pd.DataFrame({'X': [1, 2, 3, 4],
'Y': [2, 10, 13, 18],
'Z': [3, None, 5, None]})
a = df[(df.X == 1) & (df.Y == 2)].Z.item()
print(a)
#output: 3
b = df[(df.X == 7) & (df.Y == 18)].Z.item()
print(b)
#o... | [
"One alternative is to use next(..., None), which returns None if the iterator is empty:\nb = next(iter(df[(df.X == 7) & (df.Y == 18)].Z), None)\nprint(b)\n# None\n\n",
"2 things - your result is empty, hence error - .item() apparently throws an error on empty pd.Series.\nSecondly - the more canonical way of achi... | [
1,
0
] | [] | [] | [
"dataframe",
"filtering",
"pandas",
"python"
] | stackoverflow_0074577374_dataframe_filtering_pandas_python.txt |
Q:
How to generate Sphynx docs when there are imports of folders as modules?
I have the following project structure with my code and documentation:
├───docs
│ ├───_build
│ ├───_static
│ ├───...
│ ├───conf.py
│ ├───index.srt
│ ├───make.bat
| └───Makefile
├───source
│ ├───script1.py
│ ├───script2.p... | How to generate Sphynx docs when there are imports of folders as modules? | I have the following project structure with my code and documentation:
├───docs
│ ├───_build
│ ├───_static
│ ├───...
│ ├───conf.py
│ ├───index.srt
│ ├───make.bat
| └───Makefile
├───source
│ ├───script1.py
│ ├───script2.py
| └───script3.py
my conf.py:
import os
import sys
sys.path.insert(0, os.pa... | [
"I had the same error with similar structure\nmaking output directory... done\nbuilding [mo]: targets for 0 po files that are out of date\nbuilding [html]: targets for 3 source files that are out of date\nupdating environment: [new config] 3 added, 0 changed, 0 removed\nreading sources... [100%] source ... | [
0
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0064213870_python_python_sphinx.txt |
Q:
Pydantic nested model field throws value_error.missing
Having following code running fine with Django and Ninja API framework. Schema for data validation:
class OfferBase(Schema):
"""Base offer schema."""
id: int
currency_to_sell_id: int
currency_to_buy_id: int
amount: float
exchange_rate:... | Pydantic nested model field throws value_error.missing | Having following code running fine with Django and Ninja API framework. Schema for data validation:
class OfferBase(Schema):
"""Base offer schema."""
id: int
currency_to_sell_id: int
currency_to_buy_id: int
amount: float
exchange_rate: float
user_id: int
added_time: datetime = None
... | [
"This is what I was looking for:\nclass OfferWithDealOut(OfferBase):\n \"\"\"Offer schema for POST method.\"\"\"\n\n deal: List[DealBase] = Field(..., alias=\"deal_set\")\n\nclass UserBase(Schema):\n \"\"\"Base user schema for GET method.\"\"\"\n\n id: int\n username: str\n first_name: str\n la... | [
0
] | [] | [] | [
"django",
"pydantic",
"python"
] | stackoverflow_0074537704_django_pydantic_python.txt |
Q:
NaN when converting df to a series
I have a dataframe with OHLC data. I need to get the close price into the pandas series, using the timestamp column as the index.
I am reading from a sqlite db into my df:
conn = sql.connect('allStockData.db')
price = pd.read_sql_query("SELECT * from ohlc_minutes", conn)
price['... | NaN when converting df to a series | I have a dataframe with OHLC data. I need to get the close price into the pandas series, using the timestamp column as the index.
I am reading from a sqlite db into my df:
conn = sql.connect('allStockData.db')
price = pd.read_sql_query("SELECT * from ohlc_minutes", conn)
price['timestamp'] = pd.to_datetime(price['time... | [
"It's because price['close'] has it's own index which is incompatible with timestamp. Try use .values instead:\nprice = pd.Series(price['close'].values, index=price['timestamp'])\n\n",
"I needed to set the timestamp to the index before getting the the close as a series:\nconn = sql.connect('allStockData.db') \npr... | [
1,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074577408_numpy_pandas_python.txt |
Q:
Extracting polynomial coefficients from file in Python
I have recently been working with text files that contain data like the following:
A = a_0 + a_1*x + ... + a_l*x^l
B = b_0 + b_1*x + ... + b_m*x^m
.
.
.
G = g_2*x^2 + g_n
where l and m are not necessarily the same, and B might not be the longest equation. Is ... | Extracting polynomial coefficients from file in Python | I have recently been working with text files that contain data like the following:
A = a_0 + a_1*x + ... + a_l*x^l
B = b_0 + b_1*x + ... + b_m*x^m
.
.
.
G = g_2*x^2 + g_n
where l and m are not necessarily the same, and B might not be the longest equation. Is there a way to import the coefficients into a NumPy array, ... | [
"This is very custom type of text you have to write a parser to do so:\nconsidering the txt file is read, example here s\nyou probably have to read from file, with open('..') as fid ...\ns = \"\"\"A = 2*x + 3*x^5\nB = 3 + 2*x + 3*x^5\nC = 8 + 20*x + 3*x^9\"\"\"\n\nlike this:\nequations = s.split('\\n')\n\ndef ... | [
1
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python",
"python_3.x"
] | stackoverflow_0074575553_numpy_numpy_ndarray_python_python_3.x.txt |
Q:
How can I implement a working return function in Python
So basically, I have a main menu function.
The user makes a choice in this menu which is tied to a variable.
The main menu function then calls that function.
The user chooses a product and its amount there.
So it works until here.
Then after the user enters e... | How can I implement a working return function in Python | So basically, I have a main menu function.
The user makes a choice in this menu which is tied to a variable.
The main menu function then calls that function.
The user chooses a product and its amount there.
So it works until here.
Then after the user enters everything, I want the user to stay in that main menu
until th... | [
"I would refactor the submenus into a while loop:\ndef dishes():\n while True:\n print(“1) Buy a dish”)\n print(“2) Go to main menu”)\n choice = int(input(“Make a choice: “))\n\n if choice==1:\n # Select which dish to buy\n # Select product amount etc.\n i... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074577196_python_python_3.x.txt |
Q:
Python - Inherited methods break when overriding __init__
I have a geometric base class ExtrudedSurface and a child class Cylinder, which is a 'kind of' extruded surface.
The base class has a method to translate itself (not in-place) by constructing a modified version of itself.
I would like to re-use this method ... | Python - Inherited methods break when overriding __init__ | I have a geometric base class ExtrudedSurface and a child class Cylinder, which is a 'kind of' extruded surface.
The base class has a method to translate itself (not in-place) by constructing a modified version of itself.
I would like to re-use this method by the child class Cylinder, and have it return a new, translat... | [
"Short story short: the by-the-book approach there is to override the translate() method, as well, and call the updated constructor from there.\nNow, you can refactor your class initialization and separate attribute setting from other needed actions, and then create a new class-method to clone an instance with all ... | [
2
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0074577383_inheritance_oop_python.txt |
Q:
Printing username on stdout with Django + Gunicorn Application
Right now my Django + Gunicorn app is printing only this info:
[03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200
If request is authorized, I would like to show also user (username/email) behind the status code, somethin... | Printing username on stdout with Django + Gunicorn Application | Right now my Django + Gunicorn app is printing only this info:
[03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200
If request is authorized, I would like to show also user (username/email) behind the status code, something like:
[03.10.2022 19:43:14] INFO [django.request:middleware] GET /... | [
"It's not clear where this log line comes from. As far as I can see, Django only logs 4xx and 5xx requests to django.request logger. This doesn't look like a gunicorn access log line either. And if you initiated this log line in your own code, you should be able to add the user easily.\nSo, here are a few generic s... | [
2,
1
] | [] | [] | [
"django",
"gunicorn",
"python",
"python_3.x",
"web"
] | stackoverflow_0074322307_django_gunicorn_python_python_3.x_web.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'tostring' in application, but works fine in PC
I'm trying to make apk file from using python. This code is using cv2.VideoCapture(0) to make phone camera application. Here's my code
# Import kivy dependencies first
from kivy.app import App
from kivy.uix.boxlayout... | AttributeError: 'NoneType' object has no attribute 'tostring' in application, but works fine in PC | I'm trying to make apk file from using python. This code is using cv2.VideoCapture(0) to make phone camera application. Here's my code
# Import kivy dependencies first
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
# Import kivy UX components
from kivy.uix.image import Image
# Import other kivy stu... | [
"try to do this:\ndef update(self, *args):\n ret, self.frame = self.vid.read()\n\n #frame = cv2.flip(frame, 0)\n\n # Flip horizontal and convert image to texture\n buf = cv2.flip(self.frame, 0).tobytes()\n\n img_texture = Texture.create(size=(self.frame.shape[1], self.frame.shape[0]), colorfmt='bgr')... | [
0
] | [] | [] | [
"kivy",
"opencv",
"python"
] | stackoverflow_0072197918_kivy_opencv_python.txt |
Q:
How to use Desktop object to connect to app with changing window titles
I am new to pywinauto but I have read all the documentation. I am trying to automate the Spotify app on Windows (i.e. the Microsoft Store option). I am using UIA backend. The only problem I am having is that because pywinauto's Desktop object ... | How to use Desktop object to connect to app with changing window titles | I am new to pywinauto but I have read all the documentation. I am trying to automate the Spotify app on Windows (i.e. the Microsoft Store option). I am using UIA backend. The only problem I am having is that because pywinauto's Desktop object is looking for a specific window title, it doesn't allow me to automate as Sp... | [
"From the How To's page in the docs How to specify a dialog of the application, you should be able to use the top_window() method to get the window with the highest Z-Order (although the docs say that it's\n\nfairly untested ... It will definitely be a top level window of the application - it just might not be the ... | [
1
] | [] | [] | [
"python",
"pywinauto"
] | stackoverflow_0074577497_python_pywinauto.txt |
Q:
Fill NaN base on several 'IFS' conditions
This is going to be a rather long post to cover all the edge cases and with examples for clarity. A sample of my input data is as below:
df = pd.DataFrame({"Set" : [100, 100, 110, 110, 130, 130, 130, 140, 140, 150, 150, 150, 160, 170, 170],
"measure" : [n... | Fill NaN base on several 'IFS' conditions | This is going to be a rather long post to cover all the edge cases and with examples for clarity. A sample of my input data is as below:
df = pd.DataFrame({"Set" : [100, 100, 110, 110, 130, 130, 130, 140, 140, 150, 150, 150, 160, 170, 170],
"measure" : [np.nan, np.nan, 11, 10, np.nan, np.nan, np.nan, ... | [
"There you go. Comments will go a long way helping you understand the flow, but more or less translated your written logic into code. Also, added an additional condition_met column to help you see which condition was met for the different cases. This can be optimised for sure, but it will certainly provide a solid ... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074576974_numpy_pandas_python.txt |
Q:
Deleting a line in a txt file that contains a certain string
I want to search a text file for the user input and delete the line that contains it.Below is the text file.
course work.txt:-
Eric/20/SL/merc/3433
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
If the user input is 'Eric', I want the li... | Deleting a line in a txt file that contains a certain string | I want to search a text file for the user input and delete the line that contains it.Below is the text file.
course work.txt:-
Eric/20/SL/merc/3433
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
If the user input is 'Eric', I want the line containing 'Eric' to be deleted and then the text file to be sa... | [
"You can write a function to take care of that and also by making good use of shutil to copy temp.txt after writing in order to update source-work.txt .\nimport shutil\n\n\ndef modify_original_file():\n word = input('Search: ').strip().lower()\n\n track = 0\n with open(\"course-work.txt\", 'r') as original... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074573502_python.txt |
Q:
Multiprocessing With kivy. A process in the process pool was terminated abruptly while the future was running or pending error
I have "A process in the process pool was terminated abruptly while the future was running or pending." error and I cant figure it out how to solve it. Pls Help me.
I have 2 program "proba... | Multiprocessing With kivy. A process in the process pool was terminated abruptly while the future was running or pending error | I have "A process in the process pool was terminated abruptly while the future was running or pending." error and I cant figure it out how to solve it. Pls Help me.
I have 2 program "proba.py" is the kivy program and "proba2.py" is the file_read program.
first program
# proba.py for kivy
from kivy.uix.widget import Wid... | [
"I find the solution.\nI take out the concurrent.futures from for cycle.\n# proba2.py for File_read\nimport concurrent.futures\nclass File_read():\ndef __init__(self, **kwargs):\n super(File_read, self).__init__(**kwargs)\n\ndef file_read (self, y, x):\n return y*x*self.Name #Read files and give back to data... | [
0
] | [] | [] | [
"concurrent.futures",
"kivy",
"multiprocessing",
"python"
] | stackoverflow_0074356551_concurrent.futures_kivy_multiprocessing_python.txt |
Q:
Unresolved reference "cv2" inside cv2 (cv2.cv2)
I've looked around and people seem to have similar problems but none described my case exactly, and solutions that worked for them didn't seem to work for me (or there was no answer to the question at all).
Using pycharm, after having installed opencv-python and open... | Unresolved reference "cv2" inside cv2 (cv2.cv2) | I've looked around and people seem to have similar problems but none described my case exactly, and solutions that worked for them didn't seem to work for me (or there was no answer to the question at all).
Using pycharm, after having installed opencv-python and opencv-contrib-python I noticed that import cv2 works, bu... | [
"I'm no expert but the following line worked for me:\nimport cv2.cv2 as cv2\n\nEverything seems to work afterwards. Autocompletion is also back\n",
"Have you installed opencv via terminal?\nFor example, like this.\n$ pip install opencv-python\n$ pip install opencv-contrib-python\n\nI also experienced the same pro... | [
3,
0,
0,
0
] | [] | [] | [
"cv2",
"opencv",
"package",
"python",
"python_import"
] | stackoverflow_0051233491_cv2_opencv_package_python_python_import.txt |
Q:
I can't figure out why the while loop in this MPI code doesn't break
I'm doing a parallelization exercise using mpi4py where 2 dice are thrown a defined number of times (divided by the processes, i.e, npp) and the dots are counted. The results are stored in a dictionary, the mean deviation is calculated and until ... | I can't figure out why the while loop in this MPI code doesn't break | I'm doing a parallelization exercise using mpi4py where 2 dice are thrown a defined number of times (divided by the processes, i.e, npp) and the dots are counted. The results are stored in a dictionary, the mean deviation is calculated and until the condition of
mean_dev being less than 0.001 the number of throws is do... | [
"You are computing the mean deviation only on process zero, so that process will exit. However, the other processes do not get the value and so they never quit. You should broadcast the value after you compute it.\n"
] | [
1
] | [
"You are breaking out of your if statement. Just replace while True: with while mean_dev > 0.001: and you should be good. You can also just do an assignment at the end rather than wrapping it in the if.\nIf that doesn’t work it simply means mean_dev is always greater than 0.001. You calculate mean_dev as (1/11)*sqr... | [
-1
] | [
"mpi",
"mpi4py",
"python"
] | stackoverflow_0074576200_mpi_mpi4py_python.txt |
Q:
How to encrypt and decrypt .csv file to .csv.pgp using python script
I am trying to encrypt a file using pgpy. I am able to encrypt the content of files but unable to save it. I am trying to get output as .csv.pgp
Getting this error:
encrypted_file.write(encrypted_f_t_e)
TypeError: a bytes-like object is required,... | How to encrypt and decrypt .csv file to .csv.pgp using python script | I am trying to encrypt a file using pgpy. I am able to encrypt the content of files but unable to save it. I am trying to get output as .csv.pgp
Getting this error:
encrypted_file.write(encrypted_f_t_e)
TypeError: a bytes-like object is required, not 'PGPMessage'
import pgpy
from pgpy import PGPKey, PGPMessage
PUBLIC_K... | [
"You need to either write bytes or use w file mode (not wb):\n\nBytes option\n\nwith open('data.csv.pgp', 'wb') as encrypted_file:\n encrypted_file.write(bytes(encrypted_f_t_e))\n\n\nText option\n\nwith open('data.csv.pgp', 'w') as encrypted_file:\n encrypted_file.write(str(encrypted_f_t_e))\n\n"
] | [
0
] | [] | [] | [
"cryptography",
"encryption",
"openpgp",
"pgp",
"python"
] | stackoverflow_0073970565_cryptography_encryption_openpgp_pgp_python.txt |
Q:
Adding different colors for markers in plotly
I have a graph that looks like this:
I want to sort the color combinations for the dots on this, to achieve something like one color for all the versions that start with 17, different one for 18 and lastly the 20. I don't know if I can do this in plotly since it is ve... | Adding different colors for markers in plotly | I have a graph that looks like this:
I want to sort the color combinations for the dots on this, to achieve something like one color for all the versions that start with 17, different one for 18 and lastly the 20. I don't know if I can do this in plotly since it is very specific and found no information on this. Is it... | [
"Currently you are assigning marker color based on the 'day' column in your argument marker=dict(color=data1['day'], colorscale='plasma', size=10), but it sounds like you want to assign the color based on the major version.\nYou can extract the major version from the info_version column, and store it in a new colum... | [
1
] | [] | [] | [
"pandas",
"plotly",
"python"
] | stackoverflow_0074575385_pandas_plotly_python.txt |
Q:
Pytest cross suite websocket session
I'm designing an automated test suite to simulate a client which logs in to the backend via api rest and then opens up a websocket communication. I have to test different features over REST and Websocket.
Currently I'm performing each websocket test like this:
-The client logs ... | Pytest cross suite websocket session | I'm designing an automated test suite to simulate a client which logs in to the backend via api rest and then opens up a websocket communication. I have to test different features over REST and Websocket.
Currently I'm performing each websocket test like this:
-The client logs in
-The ws communication starts
-It sends ... | [
"Use pytest fixture on a session scope to share singleton websocket connection across tests https://docs.pytest.org/en/stable/reference/fixtures.html#higher-scoped-fixtures-are-executed-first.\nOmit multiprocesses and splitting into two processes as it would bring additional complexity and will be tricky to impleme... | [
1
] | [] | [] | [
"automation",
"pytest",
"python",
"testing",
"websocket"
] | stackoverflow_0074577526_automation_pytest_python_testing_websocket.txt |
Q:
Returning reverse of a string using stack data structure
My program does return the reverse but in stack form. I want to convert it to a string type
def func(str_input):
s1 = deque(str_input)
s2 = deque()
for i in range(len(str_input)):
s2.append(s1[-1])
s1.pop()
return s2
func("he... | Returning reverse of a string using stack data structure | My program does return the reverse but in stack form. I want to convert it to a string type
def func(str_input):
s1 = deque(str_input)
s2 = deque()
for i in range(len(str_input)):
s2.append(s1[-1])
s1.pop()
return s2
func("hello")
#returns
deque(['o', 'l', 'l', 'e', 'h'])
Also, woul... | [
"you don't want it to be a list? if so just use variable[::-1] it will return the given str but reversed\n"
] | [
0
] | [] | [] | [
"data_structures",
"python",
"stack"
] | stackoverflow_0074577709_data_structures_python_stack.txt |
Q:
list operation using function in python
Ask the user for which team member to assign task and assign it, display the output as team member name and task assigned
Is there any solution using without For and While loop?.
Please let me know if there is any solution.
Member = ["Gahininath", "Vighnesh", "Bhargav", "Am... | list operation using function in python | Ask the user for which team member to assign task and assign it, display the output as team member name and task assigned
Is there any solution using without For and While loop?.
Please let me know if there is any solution.
Member = ["Gahininath", "Vighnesh", "Bhargav", "Amit", "Rahul"]
def myfunction(Member):
Use... | [
"You could achieve the same basic outcome without a for or while loop using recursion - example below. However so long as you want the process to repeat a certain number of times, you're looping - the only difference between my approach below and a for or while loop is the manner in which the same process is repeat... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074574184_python.txt |
Q:
maximizing loglikelihood function with 3 parameters
i would like to find a,b, and c value that maximize this function.
enter image description here
which the constraint of
enter image description here
W are collected from a column of a dataframe, and a,b,c are the parameters that i need to find. help please?
curre... | maximizing loglikelihood function with 3 parameters | i would like to find a,b, and c value that maximize this function.
enter image description here
which the constraint of
enter image description here
W are collected from a column of a dataframe, and a,b,c are the parameters that i need to find. help please?
currently im using a python language and tries to "guess" a,b,... | [
"This is a linear programming problem. In Python, there is a package PuLP, you can try it:\nhttps://pypi.org/project/PuLP/\nAnd you can find more information about Linear Programming: Optimization With Python here:\nhttps://realpython.com/linear-programming-python/\n"
] | [
0
] | [] | [] | [
"log_likelihood",
"python",
"statistics"
] | stackoverflow_0074569095_log_likelihood_python_statistics.txt |
Q:
Which forecast method with only twenty datapoints (yearly)?
i am faced with the challenge of forecasting a specific market. For this purpose, I have market figures for the last 20 years. However, these are really only available on an annual basis. there is therefore no possibility of obtaining the data on a quarte... | Which forecast method with only twenty datapoints (yearly)? | i am faced with the challenge of forecasting a specific market. For this purpose, I have market figures for the last 20 years. However, these are really only available on an annual basis. there is therefore no possibility of obtaining the data on a quarterly or monthly basis. are there any suggestions for this?
the goa... | [
"If I am not wrong with assuming the following in your case:\n\nThere is only 20 years of data on annual basis without seasonality details,\nForecasting is to be made on annual basis for the next 2-3 years,\nNo more data is either available or can be found,\n\nThen, you may try one of the techniques mentioned here:... | [
1
] | [] | [] | [
"machine_learning",
"python",
"regression",
"statistics",
"time_series"
] | stackoverflow_0074559179_machine_learning_python_regression_statistics_time_series.txt |
Q:
Finding the index of an element in a list when there are duplicates in python
So for context, there is a popular problem called the "Fibbonaci Clock." Essentially, you have a list of colors, for example ["white","blue","red","green","white"]. The first item in the list holds a value, of 1, then the second holds ag... | Finding the index of an element in a list when there are duplicates in python | So for context, there is a popular problem called the "Fibbonaci Clock." Essentially, you have a list of colors, for example ["white","blue","red","green","white"]. The first item in the list holds a value, of 1, then the second holds again a value of 1, the third holds a value of 2, the fourth holds a value of 3, and ... | [
"fib = [\n 1,\n 1,\n 2,\n 3,\n 5\n]\n\ncolors = [\n \"red\",\n \"red\",\n \"blue\",\n \"green\",\n \"white\"\n]\n\ndef get_sum_for(color):\n return sum(f for f, c in zip(fib, colors) if c == color)\n\nhours = get_sum_for(\"red\") + get_sum_for(\"blue\")\nminutes = 5 * (get_sum_for(\... | [
0,
0
] | [] | [] | [
"duplicates",
"indexing",
"list",
"python"
] | stackoverflow_0074577795_duplicates_indexing_list_python.txt |
Q:
Finding the lowest value per key in a dictionary with multiple values per key
I have a dictionary with multiple keys, and multiple values per key (sometimes). The dictionary is zipped from two lists which I've pulled from an excel sheet using pandas. I've converted the values to integers. My dictionary looks like ... | Finding the lowest value per key in a dictionary with multiple values per key | I have a dictionary with multiple keys, and multiple values per key (sometimes). The dictionary is zipped from two lists which I've pulled from an excel sheet using pandas. I've converted the values to integers. My dictionary looks like this:
dictionary = {'A223':[1,4,5],'B224':[7,8,9],'A323':[4,5],'B456':[3,3,4,5] }
... | [
"To keep it in the spirit of python one-liners:\n>>> dictionary\n{'A223': [1, 4, 5], 'B224': [7, 8, 9], 'A323': [4, 5], 'B456': [3, 3, 4, 5]}\n>>> dict(map(lambda x: (x[0], min(x[1])), dictionary.items()))\n{'A223': 1, 'B224': 7, 'A323': 4, 'B456': 3}\n\n",
"Alternatively comprehension could be used:\nnewdic = {k... | [
3,
1
] | [] | [] | [
"dictionary",
"pandas",
"python"
] | stackoverflow_0074577766_dictionary_pandas_python.txt |
Q:
remove one charachter from a speficic column in df pandas
I have a df with a column that some values are having ... and some .. and some are without dots.
Type range
Mike 10..13
Ni 3..4
NANA 2...3
Gi 2
desired output should look like this
Type range
Mike 10
Mike 11
Mik... | remove one charachter from a speficic column in df pandas | I have a df with a column that some values are having ... and some .. and some are without dots.
Type range
Mike 10..13
Ni 3..4
NANA 2...3
Gi 2
desired output should look like this
Type range
Mike 10
Mike 11
Mike 12
MIke 13
Ni 3
Ni 4
NANA 2
NANA 3
... | [
"Parse str as list first and then explode:\nimport re\ndef str_to_list(s):\n if not s: return []\n nums = re.split('\\.{2,3}', s)\n if len(nums) == 1:\n return nums\n return list(range(int(nums[0]), int(nums[1]) + 1))\n\ndf['range'] = df['range'].astype(str).map(str_to_list)\ndf.explode('range')\... | [
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074577761_pandas_python.txt |
Q:
College assignment: Logistic regression in python
I have an assignment to do at university in Quantitative Methods course. We have been given a popular and well known paper where my job is to replicate some of the results from that paper. The paper is about labour market discrimination and claims to have evidence ... | College assignment: Logistic regression in python | I have an assignment to do at university in Quantitative Methods course. We have been given a popular and well known paper where my job is to replicate some of the results from that paper. The paper is about labour market discrimination and claims to have evidence that people with white sounding names have a higher cha... | [
"Your teacher suggests adding an interaction term in your model by multiplying those two columns. That idea is based on the thought that increasing the first variable may also increase the impact of the second variable, leading to a higher slope for the latter. In other words, when two variables get into the model,... | [
0
] | [] | [] | [
"binary",
"dummy_variable",
"logistic_regression",
"python",
"statistics"
] | stackoverflow_0074525290_binary_dummy_variable_logistic_regression_python_statistics.txt |
Q:
Outputting the line number of a text in a .txt-file, which doesn´t include spaces with list-comprehension
I have a question reagarding my code, if anybody has some clues how to solve it. I need to write only one line of code, which outputs the line numbers of those lines that don´t include spaces between the words... | Outputting the line number of a text in a .txt-file, which doesn´t include spaces with list-comprehension | I have a question reagarding my code, if anybody has some clues how to solve it. I need to write only one line of code, which outputs the line numbers of those lines that don´t include spaces between the words. My attempt was the following:
[line for line in range(len(open('test.txt').readlines())) if ' ' not in open('... | [
"The first step is to write your loop as a regular loop, then compress it into a list comprehension. What you have is:\nlines = []\n\nfor line in range(len(open('test.txt').readlines()):\n if ' ' not in open('test.txt').readlines(line):\n lines.append(line)\n\nOpening the file twice and using readlines() ... | [
2,
1
] | [] | [] | [
"enumerate",
"list_comprehension",
"python"
] | stackoverflow_0074577765_enumerate_list_comprehension_python.txt |
Q:
python z3 printing a sorted model
In this question here:
How to print z3 solver results print(s.model()) in order?
the first answer points out the problem of 10 coming after 1, and it only being sorted by the first digit, however he says with more processing it could be fixed, what would this processing be?
A:
P... | python z3 printing a sorted model | In this question here:
How to print z3 solver results print(s.model()) in order?
the first answer points out the problem of 10 coming after 1, and it only being sorted by the first digit, however he says with more processing it could be fixed, what would this processing be?
| [
"Post-processing simply means you just use your Python programming skills to manipulate the output; at this point the problem has nothing to do with z3. For the specific example you're referring to, you can modify it to:\nfrom z3 import *\n\nv = [Real('v_%s' % (i+1)) for i in range(10)]\n\ns = Solver()\nfor i in ra... | [
0
] | [] | [] | [
"list",
"list_comprehension",
"python",
"z3",
"z3py"
] | stackoverflow_0074568155_list_list_comprehension_python_z3_z3py.txt |
Q:
Pandas - How to sort values in one column ascending and another column descending?
I have a dataframe with 2 columns. I'm trying to sort one column ('values') by descending order, and when two values are the same, sort another column by ascending order. Currently, my code is:
br_df = br_imgfeatures_df.mean().reset... | Pandas - How to sort values in one column ascending and another column descending? | I have a dataframe with 2 columns. I'm trying to sort one column ('values') by descending order, and when two values are the same, sort another column by ascending order. Currently, my code is:
br_df = br_imgfeatures_df.mean().reset_index(name='value').sort_values(by='value', ascending=False)
Which is producing this o... | [
"Since pandas.DataFrame.sort_values accepts lists for the by parameter, you can use the code below and replace Column_X by the name of the first/other column :\nbr_df = (\n br_imgfeatures_df.mean()\n .reset_index(name='value')\n .sort_values(by=['value', 'Column_X'],\n ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074577980_dataframe_pandas_python_python_3.x.txt |
Q:
I wish to print a pandas dataframe name
Please be patient I am new to Python and Pandas.
I have a lot of pandas dataframe, but some are duplicates. So I wrote a function that check if 2 dataframes are equal, if they are 1 will be deleted:
def check_eq(df1, df2):
if df1.equals(df2):
del[df2]
pri... | I wish to print a pandas dataframe name | Please be patient I am new to Python and Pandas.
I have a lot of pandas dataframe, but some are duplicates. So I wrote a function that check if 2 dataframes are equal, if they are 1 will be deleted:
def check_eq(df1, df2):
if df1.equals(df2):
del[df2]
print( "Deleted %s" (df_name) )
The function wo... | [
"What you are trying to use is an f-string.\ndef check_eq(df1, df2):\n if df1.equals(df2):\n del[df2]\n print(f\"Deleted {df2.name}\")\n\nI'm not certain whether you can call this print method, though. Since you deleted the dataframe right before you call its name attribute. So df2 is unbound.\nIns... | [
1
] | [] | [] | [
"dataframe",
"function",
"pandas",
"printing",
"python"
] | stackoverflow_0074577994_dataframe_function_pandas_printing_python.txt |
Q:
Python - How to take multiple inputs, and repeat code for each one?
I'm very new to this. I just started programming last week. I need some basic help. My assignment is to input five numbers and get the output to print out "odd" or "even" for each one. This is how I have started:
num = int(input())
if (num % 2) ==... | Python - How to take multiple inputs, and repeat code for each one? | I'm very new to this. I just started programming last week. I need some basic help. My assignment is to input five numbers and get the output to print out "odd" or "even" for each one. This is how I have started:
num = int(input())
if (num % 2) == 0:
print('even')
else:
print('odd')
How can I have five numbe... | [
"Hi Hope you are doing well!\nIf I understood your question correctly, you are trying to achieve something similar to this:\nimport random\n\n# you can define your own limits\n# or you can use numpy to generate random numbers from the different distributions\nnumber = random.randint(0, 999)\nprint(f\"Current number... | [
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074576804_python.txt |
Q:
Insert blank slide with python-pptx in existing presentation
I'm working with the python-pptx library and I'm trying to insert a blank slide at a specific place (slide with the same dimensions).
I know how to delete a slide :
def delete_slides(presentation, index):
xml_slides = presentation.slides._sldIdLst
... | Insert blank slide with python-pptx in existing presentation | I'm working with the python-pptx library and I'm trying to insert a blank slide at a specific place (slide with the same dimensions).
I know how to delete a slide :
def delete_slides(presentation, index):
xml_slides = presentation.slides._sldIdLst
slides = list(xml_slides)
xml_slides.remove(slides[index])... | [
"Someone will probably come along with a better solution but you could just create a blank slide and then move it to the location you want.\nfrom pptx import Presentation\n\ndef move_slide(old_index, new_index):\n xml_slides = presentation.slides._sldIdLst\n slides = list(xml_slides)\n xml_slides.remove(sl... | [
0
] | [] | [] | [
"python",
"python_pptx"
] | stackoverflow_0074562537_python_python_pptx.txt |
Q:
For loop with if conditional statement
I am trying to understand why first code run only once vs second code is running until it checks all the items in the list.
1.
def get_word_over_10_char(list_of_words):
for word in list_of_words:
if len(word) > 10:
return word
else:
... | For loop with if conditional statement | I am trying to understand why first code run only once vs second code is running until it checks all the items in the list.
1.
def get_word_over_10_char(list_of_words):
for word in list_of_words:
if len(word) > 10:
return word
else:
return ""
for word in list_of_words:
... | [
"How are the items in your list ordered? Because the when the return statement in a function is called, the function returns the argument and stops. In the first piece of code, either the return in the if clause or the else is called after the first item in list_of_words, so the function stops there. In the second ... | [
1,
0
] | [] | [] | [
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074577699_for_loop_if_statement_python.txt |
Q:
reading file by pickle module
good afternoon!
saving list(dict(),dict(),dict()) struct with pickle module, but when reading I get: <class 'function'>, and <function lesson at 0x00000278BA3A0D30>
what am I doing wrong?
def lesson(user, date):
with open(user+"_"+date+".data", 'wb') as file:
pickle.dump(l... | reading file by pickle module | good afternoon!
saving list(dict(),dict(),dict()) struct with pickle module, but when reading I get: <class 'function'>, and <function lesson at 0x00000278BA3A0D30>
what am I doing wrong?
def lesson(user, date):
with open(user+"_"+date+".data", 'wb') as file:
pickle.dump(lesson, file)
file.close()
def ... | [
"\"saving list(dict(),dict(),dict()) struct with pickle module\". No, you're not. You're saving the lesson function. See line 3 of your code.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074578037_python.txt |
Q:
Which of these variables is the best predictor for winning a match given this logit model
My goal is to find the best predictor variable for winning a match. I have a slight knowledge of basic statistics, so I decided to use logistic regression because result of match is a binary variable.
logit_model=sm.Logit(y,X... | Which of these variables is the best predictor for winning a match given this logit model | My goal is to find the best predictor variable for winning a match. I have a slight knowledge of basic statistics, so I decided to use logistic regression because result of match is a binary variable.
logit_model=sm.Logit(y,X)
result=logit_model.fit()
result.summary()
This comes out with following result:
============... | [
"The first thing that you should pay attention to is if a variable is significant or not given the level of threshold. It seems from your results that all are significant. Z-scores are used to see the level of significance. The second thing is to look at the coefficients to see which one has more impact on the labe... | [
1
] | [] | [] | [
"data_science",
"logistic_regression",
"machine_learning",
"python",
"statistics"
] | stackoverflow_0074577402_data_science_logistic_regression_machine_learning_python_statistics.txt |
Q:
Using ProccessPoolExecutor for functions with I/O
Lately I have been using ProcessPoolExecutor for accelerating the processing of some functions I wrote.
I have a question regarding one function I would like to accelerate.
This function
def thefunction(input_file, output_file, somepar)
Involves opening and readin... | Using ProccessPoolExecutor for functions with I/O | Lately I have been using ProcessPoolExecutor for accelerating the processing of some functions I wrote.
I have a question regarding one function I would like to accelerate.
This function
def thefunction(input_file, output_file, somepar)
Involves opening and reading the input file, processing it and writing the results... | [
"If the files are different, IO operations from different processes at once are completely reasonable.\nIf the files are the same, such an operation is unsafe and would require to use a synchronization primitive such as a lock, which would render the multiprocessing inefficient.\n"
] | [
0
] | [] | [] | [
"process_pool",
"python"
] | stackoverflow_0074568519_process_pool_python.txt |
Q:
How do I print lines from a file in python after and before a match?
I would like to print some specific lines from a file, only those lines that come after a certain word appears on a line ('Ingredients:') and before another word appears ('Instructions:').
The file is a list of recipes and I want to be able to pr... | How do I print lines from a file in python after and before a match? | I would like to print some specific lines from a file, only those lines that come after a certain word appears on a line ('Ingredients:') and before another word appears ('Instructions:').
The file is a list of recipes and I want to be able to print out only the ingredients.
example of the text:
RECIPE : CACIO E PEPE #... | [
"def get_all_ingredients():\n flag = False\n with open('recipes.txt', 'r') as f:\n for line in f:\n if 'Instructions' in line:\n flag = False\n\n if flag:\n print(line.rstrip())\n\n if 'Ingredients' in line:\n flag = True\n\n... | [
1,
0,
0
] | [] | [] | [
"loops",
"python",
"readfile"
] | stackoverflow_0074577567_loops_python_readfile.txt |
Q:
How to detect circle defects?
Is there any way to tell if a circle has such defects? Roundness does not work. Or is there a way to eliminate them?
perimeter = cv2.arcLength(cnts[0],True)
area = cv2.contourArea(cnts[0])
roundness = 4*pi*area/(perimeter*perimeter)
print("Roundness:", roundness)
A:
... | How to detect circle defects? | Is there any way to tell if a circle has such defects? Roundness does not work. Or is there a way to eliminate them?
perimeter = cv2.arcLength(cnts[0],True)
area = cv2.contourArea(cnts[0])
roundness = 4*pi*area/(perimeter*perimeter)
print("Roundness:", roundness)
| [
"The \"roundness\" measure is sensitive to a precise estimate of the perimeter. What cv2.arcLength() does is add the lengths of each of the polygon edges, which severely overestimates the length of outlines. I think this is the main reason that this measure hasn't worked for you. With a better perimeter estimator ... | [
4,
0,
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074523496_image_processing_opencv_python.txt |
Q:
How to get values of dataframe that has characteres
I have a dataframe:
df = pd.DataFrame({'col' : [1,2, 10, np.nan, 'a'],
'col2': ['a', 10, 30, 'c',50],
'col3': [1,2,3,4,5.0]})
How I obtein about the column col2 a new dataframe with has characters.
In this case
df_final = [... | How to get values of dataframe that has characteres | I have a dataframe:
df = pd.DataFrame({'col' : [1,2, 10, np.nan, 'a'],
'col2': ['a', 10, 30, 'c',50],
'col3': [1,2,3,4,5.0]})
How I obtein about the column col2 a new dataframe with has characters.
In this case
df_final = ['a', 'c']
I try to verify if not number but this doesn't... | [
"You could use pandas.Series.str.contains in this case by using a regex that does not match numbers. It should be noted that we need to set na argument to False because as per documentation\n\nSpecifying na to be False instead of NaN replaces NaN values with\nFalse. If Series or Index does not contain NaN values th... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074578035_dataframe_pandas_python.txt |
Q:
Why when web scraping does the valueError: Not enough values to unpack in BeautifulSoup happen and what does it mean
So I am scraping a [website][1] and I want to
Retrieve the webpages based on these URLs and convert each into a beautifulsoup object
Retrieve Car Manufacturing Year, Engine, Price, Dealer informatio... | Why when web scraping does the valueError: Not enough values to unpack in BeautifulSoup happen and what does it mean | So I am scraping a [website][1] and I want to
Retrieve the webpages based on these URLs and convert each into a beautifulsoup object
Retrieve Car Manufacturing Year, Engine, Price, Dealer information (if it is available), and the URL (href) to access the detailed car information.
When I run the code I get the error "Va... | [
"You can make a check if the car contains model or not:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://jammer.ie/used-cars?page={}&per-page=12\"\n\nall_data = []\n\nfor page in range(1, 3): # <-- increase number of pages here\n soup = BeautifulSoup(requests.get(url.for... | [
1
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"request",
"web_scraping"
] | stackoverflow_0074575234_beautifulsoup_pandas_python_request_web_scraping.txt |
Q:
Django Rest Framework Scope Throttling on function based view
Wanted to ask if someone knows a way or a workaround to how to set different throttle scopes for different request methods in a function-based view.
For example
@api_view(['GET', 'POST'])
def someFunction(request):
if request.method == 'GET':
... | Django Rest Framework Scope Throttling on function based view | Wanted to ask if someone knows a way or a workaround to how to set different throttle scopes for different request methods in a function-based view.
For example
@api_view(['GET', 'POST'])
def someFunction(request):
if request.method == 'GET':
# set scope for get requests
elif request.method == 'POST':... | [
"You can solve this by creating all the custom throttling classes first. Note: Only the throttles are in classes but the views are functions.\nclass PostAnononymousRateThrottle(throttling.AnonRateThrottle):\n scope = 'post_anon'\n def allow_request(self, request, view):\n if request.method == \"GET\":\... | [
4,
1,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"throttling"
] | stackoverflow_0063454449_django_django_rest_framework_python_throttling.txt |
Q:
What is the best way to sanitize inputs with Flask and when using MongoDB?
I'm writing my application backend with Python Flask.
As part of the registration process, I have a form that sends the new user's information to my backend and then adds it to my MongoDB database.
I'm pretty new in this world and never wro... | What is the best way to sanitize inputs with Flask and when using MongoDB? | I'm writing my application backend with Python Flask.
As part of the registration process, I have a form that sends the new user's information to my backend and then adds it to my MongoDB database.
I'm pretty new in this world and never wrote something that has to be secured..
My Python code looks like that:
from flask... | [
"One of the best way to avoid injections is to use ORM and avoid raw queries. For MongoDB it can be flask_mongoengine or motor. Both of them provide escaping out of the box (except for some cases).\nBut you should take care of variable types that you pass to queries.\nFor example,\nquery = Model.objects.filter(fiel... | [
1,
0
] | [] | [] | [
"flask",
"mongodb",
"python",
"security"
] | stackoverflow_0043925397_flask_mongodb_python_security.txt |
Q:
python list of dictionaries find paired values
I have this csv containing some paired rows such as:
LabebStoreId,catalog_uuid,lang,cat_0_name,cat_1_name,cat_2_name,cat_3_name,catalogname,description,properties,price,price_before_discount,externallink,Rating,delivery,discount,instock
6021,89028,en,Electronics & App... | python list of dictionaries find paired values | I have this csv containing some paired rows such as:
LabebStoreId,catalog_uuid,lang,cat_0_name,cat_1_name,cat_2_name,cat_3_name,catalogname,description,properties,price,price_before_discount,externallink,Rating,delivery,discount,instock
6021,89028,en,Electronics & Appliances,Batteries & Power,Batteries,Alkaline Batteri... | [
"As I understand correctly, you can group the data by LabebStoreId and catalog_uuid and then you make payloads according each group:\nimport csv\n\ndata = {}\nwith open(\"data.csv\", \"r\") as f_in:\n reader = csv.DictReader(f_in)\n for row in reader:\n data.setdefault((row[\"LabebStoreId\"], row[\"cat... | [
2
] | [] | [] | [
"csv",
"dictionary",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074577770_csv_dictionary_pandas_python_python_3.x.txt |
Q:
How can I clear console but leave needed print-line?
For example I have code:
print("Your status - online")
while(True):
print("Searching for server")
And I need to clear console, but leave "Your status - online", so "Searching for server" isn't overlapping.
A:
You can use a carriage return to get back to t... | How can I clear console but leave needed print-line? | For example I have code:
print("Your status - online")
while(True):
print("Searching for server")
And I need to clear console, but leave "Your status - online", so "Searching for server" isn't overlapping.
| [
"You can use a carriage return to get back to the beginning of the line. Then, when you print, it overrides the previously printed line.\nprint(\"Your status - online\")\nwhile True:\n print(\"Searching for server\", end=\"\\r\")\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074578153_python.txt |
Q:
Restricting access of some roles to some specific pages
@bp.route("/products/wishlist", methods=["GET"])
@login_required
@roles_required(
"ADMIN",
"CUSTOMER_STORE_MANAGER"
)
def product_wishlist():
return product_wishlist_page()
I have role restrictions like this where each page has some role requirem... | Restricting access of some roles to some specific pages | @bp.route("/products/wishlist", methods=["GET"])
@login_required
@roles_required(
"ADMIN",
"CUSTOMER_STORE_MANAGER"
)
def product_wishlist():
return product_wishlist_page()
I have role restrictions like this where each page has some role requirements, what I need to do is restricting some roles so they cou... | [] | [] | [
"Why don't you filter in the template based on the roles\n{% if current_user.role == CUSTOMER_STORE_MANAGER %}\n {# show what this role can view or do #}\n{% elif current_user.role == \"Admin\"%}\n ...\n{% endif %}\n\nThis is simple and rendered on the backend so it is the same as doing multiple templates with... | [
-1
] | [
"flask",
"python"
] | stackoverflow_0074570576_flask_python.txt |
Q:
Stopping scroll on a specific page when LinkedIn scraping - python
I am trying to webscrape jobs on LinkedIn based on url and the specific number of jobs. The code below uses infinite scrolling and scrolls until page 39, this creates 1000 elements in my 'jobs; lost but I only want 500. How can I make it stop so th... | Stopping scroll on a specific page when LinkedIn scraping - python | I am trying to webscrape jobs on LinkedIn based on url and the specific number of jobs. The code below uses infinite scrolling and scrolls until page 39, this creates 1000 elements in my 'jobs; lost but I only want 500. How can I make it stop so that it only scrolls to so that I have 500 elements.
url = 'https://www.li... | [
"Looks like you are trying to scroll down while it's possible and only then extract jobs from resulting page.\nTry to extract jobs after every scroll down and add break statement when you reach 500 jobs.\nAlso pass here is unnecessary:\nexcept:\n pass\n time.sleep(2)\n\nYour code should be like this:\ndef ext... | [
0
] | [] | [] | [
"linkedin",
"python",
"scroll",
"selenium",
"web_scraping"
] | stackoverflow_0074578236_linkedin_python_scroll_selenium_web_scraping.txt |
Q:
I'm looking for Regular expressions to exclude a specific substring from a match
Basically I have these strings and I'm programming on Python 3.9 :
'P425-TK-1501'
'P425-UN-1840'
'P900-TP-1001'
What if I want to match each of these strings EXCEPT the one with TP (P900-TP-1001).
As you can see, my challenge here wa... | I'm looking for Regular expressions to exclude a specific substring from a match | Basically I have these strings and I'm programming on Python 3.9 :
'P425-TK-1501'
'P425-UN-1840'
'P900-TP-1001'
What if I want to match each of these strings EXCEPT the one with TP (P900-TP-1001).
As you can see, my challenge here was to INCLUDE the P425-TK-1501 but EXCLUDE P900-TP-1001
I tried excluding but it doesn'... | [
"To exclude a substring, simply accept the strings which do not have it. No regex needed.\ndata = ['P425-TK-1501', 'P425-UN-1840', 'P900-TP-1001']\n\nnew = [x for x in data if 'P900' not in x]\n\nproduces\n['P425-TK-1501', 'P425-UN-1840']\n\n"
] | [
0
] | [] | [] | [
"expression",
"multiple_matches",
"python",
"regex"
] | stackoverflow_0074578160_expression_multiple_matches_python_regex.txt |
Q:
Keras multiprocessing model prediction
I have a simple MNIST Keras model to make predictions and save the loss. I am running on a server with multiple CPUs, so I want to use multiprocessing for speedup.
I have successfully used multiprocessing with some basic functions, but for model prediction these processes nev... | Keras multiprocessing model prediction | I have a simple MNIST Keras model to make predictions and save the loss. I am running on a server with multiple CPUs, so I want to use multiprocessing for speedup.
I have successfully used multiprocessing with some basic functions, but for model prediction these processes never finish, while using the non-multiprocessi... | [
"I found the answer. First of all, Keras has issues with multiprocessing 1, 2. Moreover, TensorFlow should always have one session. So, it must be imported only in the function, not anywhere else. And the model should be loaded from the disk in each function. This may be the source of improvement (moving the model ... | [
0
] | [] | [] | [
"keras",
"multiprocessing",
"python",
"tensorflow"
] | stackoverflow_0074540699_keras_multiprocessing_python_tensorflow.txt |
Q:
how to crop a colour 8 bit per pixel png image and save in colour in python
I have a png image that I want to crop, removing the top and bottom white space.
I use the following code:
from PIL import Image
for f in pa_files:
img = f
im = Image.open(img)
width, height = im.size
pixels = list(im.getda... | how to crop a colour 8 bit per pixel png image and save in colour in python | I have a png image that I want to crop, removing the top and bottom white space.
I use the following code:
from PIL import Image
for f in pa_files:
img = f
im = Image.open(img)
width, height = im.size
pixels = list(im.getdata())
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
... | [
"The thing is that you have to consider many different cases.\n\n8 bits R,G,B,A images (that is what you have, apparently, at first)\n8 bits R,G,B images\n8 bits gray level\n8 bits indexed images\n\nFor 8 bits gray level, pixels are not 4-uplets (R,G,B,A) but numbers. So, sum(x) should be replaced by x. And then yo... | [
0,
0
] | [] | [] | [
"colors",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0074577896_colors_image_python_python_imaging_library.txt |
Q:
How do you modify a dictionary from a text file when you only need to get specific values?
So say we have some sort of file with maybe like 6 columns, and 6 rows. If I wanted to get one specific column that reads one line, and modify a current dictionary I have, how would I approach that?
The output should be all ... | How do you modify a dictionary from a text file when you only need to get specific values? | So say we have some sort of file with maybe like 6 columns, and 6 rows. If I wanted to get one specific column that reads one line, and modify a current dictionary I have, how would I approach that?
The output should be all the data with the the key being the second column, and the 2 values being the first column and 4... | [
"split returns a list. Use the list instead of expanding into named variables.\ndata = {}\nfor line in file:\n row = line.strip().split()\n data[int(row[1])] = row[0], row[3]\nprint (data)\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"file",
"python"
] | stackoverflow_0074578298_dictionary_file_python.txt |
Q:
Call OpenAI API with Python requests is missing a model parameter
I'm trying to call OpenAI API from Python. I know they have their own openai package, but I want to use a generic solution. I chose the requests package for its flexibility. Here is my call
>>> headers = {"Authorization": "Bearer xxx"}
>>> url = 'ht... | Call OpenAI API with Python requests is missing a model parameter | I'm trying to call OpenAI API from Python. I know they have their own openai package, but I want to use a generic solution. I chose the requests package for its flexibility. Here is my call
>>> headers = {"Authorization": "Bearer xxx"}
>>> url = 'https://api.openai.com/v1/completions'
>>> data = {'model': 'text-davinci... | [
"The API expects a JSON request body,not a form-encoded request. And, you need to use the requests.post() method to send the right HTTP method.\nUse the json argument, not the data argument, and the right method:\nrequests.post(url, headers=headers, json=data)\n\nSee the Create completion section of the OpenAI docu... | [
2
] | [] | [] | [
"api",
"openai",
"python",
"python_requests"
] | stackoverflow_0074578315_api_openai_python_python_requests.txt |
Q:
Filling a template slot, content doesn't appear
In my folder Templates I created 2 html files:
main.html
user.html
The structure of the main.html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="wid... | Filling a template slot, content doesn't appear | In my folder Templates I created 2 html files:
main.html
user.html
The structure of the main.html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DJANG... | [
"When you render main.html directly, your user.html gets ignored.\nIf you render user.html from django, you will get expected result.\nTo inject user.html contents to main.html you should use something like {% include \"user.html\" %} insead of blocks statement.\n",
"Extension in templates follows the same logic ... | [
0,
0
] | [] | [] | [
"django",
"jinja2",
"python"
] | stackoverflow_0074578213_django_jinja2_python.txt |
Q:
Replace space in between double quote to underscore
I want to replace a space to underscore, if the space is in between double quotes. Example:
given = 'hello "welcome to" python "blog"'
expected = 'hello "welcome_to" python "blog"'
My actual string is in SQL code and I need to transform it to use underscore f... | Replace space in between double quote to underscore | I want to replace a space to underscore, if the space is in between double quotes. Example:
given = 'hello "welcome to" python "blog"'
expected = 'hello "welcome_to" python "blog"'
My actual string is in SQL code and I need to transform it to use underscore for migration purpose.
What I tried
import re
s = 'hello ... | [
"If you aren't forced to use regex, don't, because that's not a good option here.\ninp = 'hello \"welcome to\" python \"blog\"'\ndata = inp.split('\"')\nfor i, part in enumerate(data[:-1]):\n if i % 2 == 1:\n data[i] = part.replace(' ', '_')\nout = '\"'.join(data)\nprint(out)\n\n'hello \"welcome_to\" pyth... | [
5,
0,
0
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0074569246_python_replace_string.txt |
Q:
How to set colors for nodes in NetworkX?
I created my graph, everything looks great so far, but I want to update color of my nodes after creation.
My goal is to visualize DFS, I will first show the initial graph and then color nodes step by step as DFS solves the problem.
If anyone is interested, sample code is av... | How to set colors for nodes in NetworkX? | I created my graph, everything looks great so far, but I want to update color of my nodes after creation.
My goal is to visualize DFS, I will first show the initial graph and then color nodes step by step as DFS solves the problem.
If anyone is interested, sample code is available on Github
| [
"All you need is to specify a color map which maps a color to each node and send it to nx.draw function. To clarify, for a 20 node I want to color the first 10 in blue and the rest in green. The code will be as follows:\nG = nx.erdos_renyi_graph(20, 0.1)\ncolor_map = []\nfor node in G:\n if node < 10:\n ... | [
126,
7,
2,
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0027030473_networkx_python.txt |
Q:
How to trigger DAG in Airflow everytime an external event state is True (Event based triggering)
The basic concept of Airflow does not allow to trigger a Dag on an irregular interval.
Actually I want to trigger a dag everytime a new file is placed on a remote server (like https, sftp, s3 ...)
But Airflow requires ... | How to trigger DAG in Airflow everytime an external event state is True (Event based triggering) | The basic concept of Airflow does not allow to trigger a Dag on an irregular interval.
Actually I want to trigger a dag everytime a new file is placed on a remote server (like https, sftp, s3 ...)
But Airflow requires a defined data_interval. Using e.g. HttpSensor works only once during the scheduled time window. In my... | [
"You have to take care about the following two points to have a Dag that runs everytime a sensor recognize an external event.\n\nschedule_interval: Use the preset None\nUse TriggerDagRunOperator\n\nIt is by design to create an infinite loop to check out the external\n\"\"\" DAG for operational District heating \"\"... | [
0
] | [] | [] | [
"airflow",
"event_handling",
"python",
"python_3.x"
] | stackoverflow_0074578403_airflow_event_handling_python_python_3.x.txt |
Q:
How to explore elements in a nested boolean list and get aggregated scores?
Hello this is a pretty simple question but i wanted to follow the dry principles correctly and couldn't think of a way to do it without repeating code
so given game outcomes in this format
game outcome = [['wins', 'loses'], ['loses', 'wins... | How to explore elements in a nested boolean list and get aggregated scores? | Hello this is a pretty simple question but i wanted to follow the dry principles correctly and couldn't think of a way to do it without repeating code
so given game outcomes in this format
game outcome = [['wins', 'loses'], ['loses', 'wins'], ['loses', 'wins']]
the gameoutcome[0][0] till gameoutcome[2][0] are all user ... | [
"Here you get the 2 results:\ngame_outcome = [['wins', 'loses'], ['loses', 'wins'], ['loses', 'wins']]\nuser_outcome = sum([i[0] == 'wins' for i in game_outcome])\ncomputer_outcome = sum([i[1] == 'wins' for i in game_outcome])\n\n",
"Should you have only 2 possible outcomes, you can skip the second calculation:\n... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074522566_python.txt |
Q:
How to print a float with underscores separating thousandths?
If possible, i want to format (via f-string or any older way) a float, so that it's thousandths get separated by underscores.
I know you can do:
print(f"{10000000:_}")
# 10_000_000
But i want:
print(f"{7.012345678:<something>}")
# 7.012_345_678
A:
Ho... | How to print a float with underscores separating thousandths? | If possible, i want to format (via f-string or any older way) a float, so that it's thousandths get separated by underscores.
I know you can do:
print(f"{10000000:_}")
# 10_000_000
But i want:
print(f"{7.012345678:<something>}")
# 7.012_345_678
| [
"Hopefully someone has a better idea than I do, but if worse comes to worse you could do something like this:\ndef format_decimals(f):\n s = str(f)\n parts = s.split('.')\n if len(parts) != 2:\n raise ValueError(f'{s} not a valid decimal number')\n n,d = parts\n d = '_'.join(d[i:i+3] for i in ... | [
0
] | [] | [] | [
"mantissa",
"printing",
"python"
] | stackoverflow_0074578246_mantissa_printing_python.txt |
Q:
Creating new value inside registry Run key with Python?
I am trying to create a new value under the Run key in Windows 7. I am using Python 3.5 and I am having trouble writing to the key. My current code is creating a new key under the key I am trying to modify the values of.
from winreg import *
aKey = OpenKey(H... | Creating new value inside registry Run key with Python? | I am trying to create a new value under the Run key in Windows 7. I am using Python 3.5 and I am having trouble writing to the key. My current code is creating a new key under the key I am trying to modify the values of.
from winreg import *
aKey = OpenKey(HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\... | [
"Here is a function which can set/delete a run key.\nCode:\ndef set_run_key(key, value):\n \"\"\"\n Set/Remove Run Key in windows registry.\n\n :param key: Run Key Name\n :param value: Program to Run\n :return: None\n \"\"\"\n # This is for the system run variable\n reg_key = winreg.OpenKey(... | [
4,
0
] | [] | [] | [
"python",
"python_3.x",
"pywin32"
] | stackoverflow_0042605055_python_python_3.x_pywin32.txt |
Q:
First N elements of a 2D Numpy array where N is a list
Say I have an M x N array,
>>> M = 5
>>> N = 4
>>> a = np.ones((M, N))
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
and I would like to get the first x elements of each array bu... | First N elements of a 2D Numpy array where N is a list | Say I have an M x N array,
>>> M = 5
>>> N = 4
>>> a = np.ones((M, N))
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
and I would like to get the first x elements of each array but where x is a list of size M. So, if x is
array([2, 3, 1, 4... | [
"you could write what you want by generator but at the end of the way at is loop:\nimport numpy as np\nM = 5\nN = 4\na = np.ones((M, N))\nd = np.array([2, 3, 1, 4])\n\nout = list(map(lambda a:a[0][:a[1]], zip(a, d)))\n\nmaybe you could save slightly compared to for loop (not sure even), but best is to see what is t... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074578424_arrays_numpy_python.txt |
Q:
Python - How can I aggregate a pandas dataframe base on conditions on different rows?
I have a pandas data frame with information about road segments.
PRIRTECODE
PRIM_BMP
PRIM_EMP
SEGMENT_LENGTH
ELEMENT_ID
RAMP
CURVE_YEAR
SEGMENT_TYPE
0001A
0
0.147
0.147
4850943
0
2019
Line
0001A
0.147
0.183
0.036
4850943
0
201... | Python - How can I aggregate a pandas dataframe base on conditions on different rows? | I have a pandas data frame with information about road segments.
PRIRTECODE
PRIM_BMP
PRIM_EMP
SEGMENT_LENGTH
ELEMENT_ID
RAMP
CURVE_YEAR
SEGMENT_TYPE
0001A
0
0.147
0.147
4850943
0
2019
Line
0001A
0.147
0.183
0.036
4850943
0
2019
Line
0001A
0.183
0.24
0.057
4850943
0
2019
Arc left
0001A
0.24
0.251
0.011
485... | [
"Just in case you run out of options, here's convtools based solution. (I must confess - I'm the author).\nfrom convtools import conversion as c\nfrom convtools.contrib.tables import Table\n\n\nrows = [\n {'PRIRTECODE': '0001A', 'PRIM_BMP': 0.0, 'PRIM_EMP': 0.147, 'SEGMENT_LENGTH': 0.147, 'ELEMENT_ID': 4850943, ... | [
0
] | [] | [] | [
"aggregation",
"dataframe",
"group_by",
"python"
] | stackoverflow_0074504250_aggregation_dataframe_group_by_python.txt |
Q:
Python: Group and count number of consecutive repetitive values in a column in a dataframe
I am desperate over a data analysis task that I would like to perform on a dataframe in python.
So, this is the dataframe that I have:
df = pd.DataFrame({"Person": ["P1", "P1","P1","P1","P1","P1","P1","P1","P1","P1", "P2", "... | Python: Group and count number of consecutive repetitive values in a column in a dataframe | I am desperate over a data analysis task that I would like to perform on a dataframe in python.
So, this is the dataframe that I have:
df = pd.DataFrame({"Person": ["P1", "P1","P1","P1","P1","P1","P1","P1","P1","P1", "P2", "P2","P2","P2","P2","P2","P2","P2","P2","P2"],
"Activity": ["A", "A", "A", "B... | [
"You can process the data as a stream without creating a dataframe, which should fit into memory. I'd suggest trying convtools library (I must confess - I'm the author).\nSince you already have a dataframe, let's use it as an input:\nimport pandas as pd\n\nfrom convtools import conversion as c\nfrom convtools.contr... | [
0,
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074575294_dataframe_group_by_pandas_python.txt |
Q:
How can I remove files that have an unknown number in them?
I have some code that writes out files with names like this:
body00123.txt
body00124.txt
body00125.txt
body-1-2126.txt
body-1-2127.txt
body-1-2128.txt
body-3-3129.txt
body-3-3130.txt
body-3-3131.txt
Such that the first two numbers in the file can be 'n... | How can I remove files that have an unknown number in them? | I have some code that writes out files with names like this:
body00123.txt
body00124.txt
body00125.txt
body-1-2126.txt
body-1-2127.txt
body-1-2128.txt
body-3-3129.txt
body-3-3130.txt
body-3-3131.txt
Such that the first two numbers in the file can be 'negative', but the last 3 numbers are not.
I have a list such as t... | [
"Because all the files end in .txt, you can cut that part out and use the str.endswith() function. str.endswith() accepts a tuple of strings, and sees if your string ends in any of them. As a result, you can do something like this:\nall_file_list = [...]\nkeep_list = [...]\n\nfiles_to_remove = []\n\nfile_to_remove_... | [
0
] | [] | [] | [
"filenames",
"python",
"wildcard"
] | stackoverflow_0074578460_filenames_python_wildcard.txt |
Q:
How do I remove the border of a Image Button in Tkinter?
I know how to remove the border of a Tkinter Button and Image. It is done pretty much exactly like how you do it for everything else
borderwidth=0
What I need help with if why, even though I put that in the widget's 'design parameters', it still has a borde... | How do I remove the border of a Image Button in Tkinter? | I know how to remove the border of a Tkinter Button and Image. It is done pretty much exactly like how you do it for everything else
borderwidth=0
What I need help with if why, even though I put that in the widget's 'design parameters', it still has a border.
My code is below.
# Imports the tkinter library.
from tkint... | [
"try hightlightthickness:\ntheme1Button = Button(root, image=theme1, borderwidth=0, highlightthickness=0, background=selectedBackground, command=openCipher)\n\n",
"It's because of MacOs. I had a similar problem; the only fix was using a label instead and then binding the click event with a function.\nYou could do... | [
4,
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_button",
"tkinter_label"
] | stackoverflow_0072920042_python_tkinter_tkinter_button_tkinter_label.txt |
Q:
How to sort my output form my program without changing the order of my whole loop?
I have this code:
words = open(input('Enter the name of the file: ')).read().lower().split()
number_of_words = int(input('Enter how many top words you want to see: '))
uniques = []
stop_words = ["a", "an", "and", "in", "is"]
for wor... | How to sort my output form my program without changing the order of my whole loop? | I have this code:
words = open(input('Enter the name of the file: ')).read().lower().split()
number_of_words = int(input('Enter how many top words you want to see: '))
uniques = []
stop_words = ["a", "an", "and", "in", "is"]
for word in words:
check_special = False
if word.isalnum():
check_special = True
if w... | [
"Use sorted:\n print('The following words appeared %d times each: %s' % (count, ', '.join(sorted(counts_dict[count]))))\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074578550_python_python_3.x.txt |
Q:
I did it by the tutorial and it's not working
I found some projects on youtube, and this is one of them.
I'm trying with the password manager program. Here's the link: https://www.youtube.com/watch?v=DLn3jOsNRVE
And here's my code:
from cryptography.fernet import Fernet
'''
def write_key():
key = Fernet.gener... | I did it by the tutorial and it's not working | I found some projects on youtube, and this is one of them.
I'm trying with the password manager program. Here's the link: https://www.youtube.com/watch?v=DLn3jOsNRVE
And here's my code:
from cryptography.fernet import Fernet
'''
def write_key():
key = Fernet.generate_key()
with open("key.key", "wb") as key_fil... | [
"The only possible code that could write to the key.key file is both:\n\ncommented out; and\nnot called even if it were not commented out,\n\nSo, no, it's not correct to say that \"the key.key file generate[s] itself\".\n\nLooking over the linked video, the presenter at some point (at 1:29:50, more precisely) had t... | [
0
] | [] | [] | [
"file",
"filenotfounderror",
"python"
] | stackoverflow_0074578541_file_filenotfounderror_python.txt |
Q:
how to print a string a certain number of times on a line then move to a new line
I have the list ['a','b','c','d','e','f','g']. I want to print it a certain way like this:
a b c
d e f
g
this is what I've tried:
result = ''
for i in range(len(example)):
result += example[i] + ' '
if len(result) == 3:
... | how to print a string a certain number of times on a line then move to a new line | I have the list ['a','b','c','d','e','f','g']. I want to print it a certain way like this:
a b c
d e f
g
this is what I've tried:
result = ''
for i in range(len(example)):
result += example[i] + ' '
if len(result) == 3:
print('\n')
print(result)
but with this I continue to get one single line
| [
"Iterate over a range of indices and step by 3, creating slices of three elements at a time.\n>>> a = ['a','b','c','d','e','f','g']\n>>> for i in range(0, len(a), 3):\n... print(a[i:i+3])\n... \n['a', 'b', 'c']\n['d', 'e', 'f']\n['g']\n>>> \n\nTo format the data, you could either join the slice with ' ' or expand... | [
2,
0
] | [
"Using enumerate\nexample = ['a','b','c','d','e','f','g'] \nmax_rows = 3\nresult = \"\"\nfor index, element in enumerate(example):\n if (index % max_rows) == 0:\n result += \"\\n\"\n result += element\n\nprint(result)\n\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074578552_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.