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:
Python: Finding a trend in a set of numbers
I have a list of numbers in Python, like this:
x = [12, 34, 29, 38, 34, 51, 29, 34, 47, 34, 55, 94, 68, 81]
What's the best way to find the trend in these numbers? I'm not interested in predicting what the next number will be, I just want to output the trend for many se... | Python: Finding a trend in a set of numbers | I have a list of numbers in Python, like this:
x = [12, 34, 29, 38, 34, 51, 29, 34, 47, 34, 55, 94, 68, 81]
What's the best way to find the trend in these numbers? I'm not interested in predicting what the next number will be, I just want to output the trend for many sets of numbers so that I can compare the trends.
E... | [
"Possibly you mean you want to plot these numbers on a graph and find a straight line through them where the overall distance between the line and the numbers is minimized? This is called a linear regression \ndef linreg(X, Y):\n \"\"\"\n return a,b in solution to y = ax + b such that root mean square distanc... | [
32,
27,
7,
6,
4,
2,
0,
0
] | [
"Compute the beta coefficient.\ny = [12, 34, 29, 38, 34, 51, 29, 34, 47, 34, 55, 94, 68, 81]\nx = range(1,len(y)+1)\n\ndef var(X):\n S = 0.0\n SS = 0.0\n for x in X:\n S += x\n SS += x*x\n xbar = S/float(len(X))\n return (SS - len(X) * xbar * xbar) / (len(X) -1.0)\n\ndef cov(X,Y):\n ... | [
-2
] | [
"math",
"python"
] | stackoverflow_0010048571_math_python.txt |
Q:
Flask page wont redirect after registration form is validated
After the user registers on the register form, it should redirect them to the home page, but instead it doesn't do anything. It simply reloads the page without the user's password in the password fields.
This is home.py
` from flask import Flask, render... | Flask page wont redirect after registration form is validated | After the user registers on the register form, it should redirect them to the home page, but instead it doesn't do anything. It simply reloads the page without the user's password in the password fields.
This is home.py
` from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationF... | [
"\nHi,\n@app.route(\"/register\", methods=['GET','POST'])\ndef register():\n form = RegistrationForm()\n if form.validate_on_submit():\n flash(f'Account created for {form.username.data}!', 'success')\n return redirect(url_for('home'))\n return render_template('register.html', title='Register'... | [
0
] | [] | [] | [
"flask",
"flask_login",
"flask_wtforms",
"html",
"python"
] | stackoverflow_0074623116_flask_flask_login_flask_wtforms_html_python.txt |
Q:
reasons for serializer not validating data DRF
I am sending the data through postman as follows
my model.py is as follows
def get_upload_path(instance, filename):
model = instance._meta
name = model.verbose_name_plural.replace(' ', '_')
return f'{name}/images/{filename}'
class ImageAlbum(models.Model):
def defau... | reasons for serializer not validating data DRF | I am sending the data through postman as follows
my model.py is as follows
def get_upload_path(instance, filename):
model = instance._meta
name = model.verbose_name_plural.replace(' ', '_')
return f'{name}/images/{filename}'
class ImageAlbum(models.Model):
def default(self):
return self.images.filter(default=True... | [
"Here is the problem, on the ImageAlbumSerializer\n ...\n album_data = PhotoSerializer(many=True, read_only=True)\n ...\n\nThe data is bieng passed from the request.data but u declared it as read_only field. so as the name implies that attr is a read_only so it wont be validated or even passed to the valid... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0074641604_django_django_rest_framework_django_serializer_python.txt |
Q:
unable to send image through discord webhooks
i created a method that takes a screenshot
def send_screenshot_to_discord(self):
webhook=discord_webhooks.DiscordWebhooks("https://discord.com/api/webhooks/xyz")
img=ImageGrab.grab()
webhook.set_image(image=img)
webhook.set_footer(text="... | unable to send image through discord webhooks | i created a method that takes a screenshot
def send_screenshot_to_discord(self):
webhook=discord_webhooks.DiscordWebhooks("https://discord.com/api/webhooks/xyz")
img=ImageGrab.grab()
webhook.set_image(image=img)
webhook.set_footer(text="img")
webhook.send()
the result :
| [
"Unfortunately, the discord_webhooks package you're using does not support file attachments, making it impossible to set the locally saved images or Pil-created images as embed images.\nThe way you set local images as embed images is by using attachment://image.png as the embed.set_image function's url argument, an... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_imaging_library",
"webhooks"
] | stackoverflow_0074653202_discord_discord.py_python_python_imaging_library_webhooks.txt |
Q:
predict new user using lightfm
I want to give a recommendation to a new user using lightfm.
Hi, I've got model, interactions, item_features.
The new user is not in interactions and the only information of the new user is their ratings.(list of book_id and rating pairs)
I tried to use predict() or predict_rank(), b... | predict new user using lightfm | I want to give a recommendation to a new user using lightfm.
Hi, I've got model, interactions, item_features.
The new user is not in interactions and the only information of the new user is their ratings.(list of book_id and rating pairs)
I tried to use predict() or predict_rank(), but I failed to figure out how.
Could... | [
"I was having the same problem,\nWhat I did was\n\nCreated a user_features matrix (based on their preferences) using Dataset class\n dataset = Dataset()\n dataset.fit(user_ids,item_ids)\n user_features = build_user_features([[user_id_1,[user_features_1]],..], normalize=True)\n\n\nProvide it during training along wi... | [
3,
0
] | [] | [] | [
"data_science",
"lightfm",
"python",
"recommendation_engine"
] | stackoverflow_0068857138_data_science_lightfm_python_recommendation_engine.txt |
Q:
How to receive a num at each step and continue until zero is entered; then this program should print the sum of enter nums
How to Write a program that receive a number from the input at each step and continue to work until zero is entered. After the zero digit is entered, this program should print the sum of the ... | How to receive a num at each step and continue until zero is entered; then this program should print the sum of enter nums | How to Write a program that receive a number from the input at each step and continue to work until zero is entered. After the zero digit is entered, this program should print the sum of the entered numbers. I want to get n different numbers in n different lines and it stops when it reaches Zero
For ex:(input:)
3
4
5... | [
"Here I'm using a while loop that continues until the user input is 0 then prints out the sum.\nres = 0\nuser_input = int(input('Input a number: '))\nwhile user_input != 0:\n user_input=int(input('Input a number: '))\n res+= user_input\nprint(\"You entered 0 so the program stopped. The sum of your inputs is: ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074620898_python.txt |
Q:
UserWarning: no type annotations present -- not typechecking test... (def __init__(self, *args, **kwargs): # type: ignore[no-untyped-def])
Context
Suppose one creates a test object, and during its initialization, one also creates some test object properties, like shown below:
class Test_mdsa(unittest.TestCase):
... | UserWarning: no type annotations present -- not typechecking test... (def __init__(self, *args, **kwargs): # type: ignore[no-untyped-def]) | Context
Suppose one creates a test object, and during its initialization, one also creates some test object properties, like shown below:
class Test_mdsa(unittest.TestCase):
"""Tests whether MDSA algorithm specification detects invalid
specifications."""
# Initialize test object
@typechecked
def __... | [
"I noticed I should add the -> None: at the end of the __init__(), and that removed the warning when I added:\ndef __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]\n super().__init__(*args, **kwargs)\n\nLimitations\nHowever, in that case any additional arguments like:\ndef __init__(se... | [
0
] | [] | [] | [
"keyword_argument",
"python",
"typechecking",
"warnings"
] | stackoverflow_0074654091_keyword_argument_python_typechecking_warnings.txt |
Q:
How can I copy styled pandas dataframes from Jupyter Notebooks to powerpoint without loss of formatting
I am trying to copy styled pandas dataframes from Jupyter Notebooks to powerpoint without loss of formatting. I currently just take a screenshot to preserve formatting, but this is not ideal. Does anyone know of... | How can I copy styled pandas dataframes from Jupyter Notebooks to powerpoint without loss of formatting | I am trying to copy styled pandas dataframes from Jupyter Notebooks to powerpoint without loss of formatting. I currently just take a screenshot to preserve formatting, but this is not ideal. Does anyone know of a better way? I search for an extension that maybe has a screenshot button, but no luck.
| [
"One way seems to be to copy the styled pandas table from jupyter notebook to excel. It will keep a lot of the formatting. Then you can copy it to powerpoint and it will maintain its style.\n",
"Using the pandas styler object you can save directly to Excel. For example you can save the excel of your dataframe wit... | [
0,
0
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"powerpoint",
"python"
] | stackoverflow_0049222299_dataframe_jupyter_notebook_pandas_powerpoint_python.txt |
Q:
hide chromeDriver console in python
I'm using chrome driver in Selenium to open chrome , log into a router, press some buttons ,upload configuration etc. all code is written in Python.
here is the part of the code to obtain the driver:
chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory... | hide chromeDriver console in python | I'm using chrome driver in Selenium to open chrome , log into a router, press some buttons ,upload configuration etc. all code is written in Python.
here is the part of the code to obtain the driver:
chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory": self.user_local}
chrome_options.add_e... | [
"You will have to edit Selenium Source code to achieve this. I am a noob too, and I dont fully understand the overall consequences of editing source code but here is what I did to achieve hiding the webdriver console window on Windows 7, Python 2.7.\nLocate and edit this file as follows:\nlocated at \nLib\\site-pac... | [
30,
13,
8,
1,
1,
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0033983860_python_selenium_selenium_chromedriver.txt |
Q:
How to change dictionary format in python?
I need to transform dict { name : department } to { department : [ name ] } and print all names after transformation, but it prints me only one, what is wrong here?
I need to use dictionary comprehension method.
Tried this, but it doesn't work as expected:
orig_dict = {'T... | How to change dictionary format in python? | I need to transform dict { name : department } to { department : [ name ] } and print all names after transformation, but it prints me only one, what is wrong here?
I need to use dictionary comprehension method.
Tried this, but it doesn't work as expected:
orig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': \
'M... | [
"It appears that you want values to become keys in a new dictionary and the values to be a list. If so, then:\norig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}\nnew_dict = {}\nfor k, v in orig_dict.items():\n new_dict.setdefault(v, [])... | [
1
] | [
"Full Code\nold_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing',\n 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}\n# Printing original dictionary\nprint(\"Original dictionary is : \")\nprint(old_dict)\n\nprint()\nnew_dict = {}\nfor key, value in old_dict.items():\n if value i... | [
-1
] | [
"dictionary",
"python"
] | stackoverflow_0074653996_dictionary_python.txt |
Q:
Formatting python with Black in VSCode is causing arrays to expand vertically, any way to compress them?
I'm using Black to format python in VSCode, and it's making all my arrays super tall instead of wide. I've set max line length to 150 for pep8 and flake8 and black (but I'm new to Black, and not sure if it uses... | Formatting python with Black in VSCode is causing arrays to expand vertically, any way to compress them? | I'm using Black to format python in VSCode, and it's making all my arrays super tall instead of wide. I've set max line length to 150 for pep8 and flake8 and black (but I'm new to Black, and not sure if it uses either of those settings):
"python.formatting.blackArgs": ["--line-length", "150"],
Here's how it looks:
expe... | [
"Black will always explode a list into multiple lines if it has a trailing comma. You can remove the trailing comma for black to compress the list. You can also use --skip-magic-trailing-comma:\n\"python.formatting.blackArgs\": [\"--line-length\", \"150\", \"--skip-magic-trailing-comma\"],\n\n",
"Option --skip-ma... | [
2,
0
] | [] | [] | [
"python",
"python_black",
"visual_studio_code"
] | stackoverflow_0074323625_python_python_black_visual_studio_code.txt |
Q:
Uncompyle6 convert pyc to py file python 3 (Whole directory)
I have 200 pyc files I need to convert in a folder. I am aware of converting pyc to py files through uncompyle6 -o . 31.pyc however as I have so many pyc files, this would take a long period of time. I've founds lots of documentation but not much in bul... | Uncompyle6 convert pyc to py file python 3 (Whole directory) | I have 200 pyc files I need to convert in a folder. I am aware of converting pyc to py files through uncompyle6 -o . 31.pyc however as I have so many pyc files, this would take a long period of time. I've founds lots of documentation but not much in bulk converting to py files. uncompyle6 -o . *.pyc was not supported... | [
"Might not be perfect but it worked great for me. \nimport os\nimport uncompyle6\nyour_directory = ''\nfor dirpath, b, filenames in os.walk(your_directory):\n for filename in filenames:\n if not filename.endswith('.pyc'):\n continue\n\n filepath = dirpath + '/' + filename\n origin... | [
6,
5,
4,
0
] | [] | [] | [
"python",
"uncompyle6"
] | stackoverflow_0047397711_python_uncompyle6.txt |
Q:
filter keys out from list of dicts
Say I have a list of dict:
ld = [{'a':1,'b':2,'c':9},{'a':1,'b':2,'c':10}]
And a list to filter the keys out:
l = ['a','c']
Want to remove key a and c from ld:
Try:
result = [d for d in ld for k in d if k in l]
Desired Result:
[{'b':2},{'b':2}]
A:
Your outer container needs ... | filter keys out from list of dicts | Say I have a list of dict:
ld = [{'a':1,'b':2,'c':9},{'a':1,'b':2,'c':10}]
And a list to filter the keys out:
l = ['a','c']
Want to remove key a and c from ld:
Try:
result = [d for d in ld for k in d if k in l]
Desired Result:
[{'b':2},{'b':2}]
| [
"\nYour outer container needs to be a list : use a (1 dimension) list comprehension\nYour inner container needs to be a dict : ues a dict comprehension\n\nFor you now you're using a 2d list comprehension\n\nThe filtering part should be at the dict level\nld = [{'a': 1, 'b': 2, 'c': 9}, {'a': 1, 'b': 2, 'c': 10}]\nl... | [
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074652918_python.txt |
Q:
XOR Pair Of Elements In A List
I have a list of integer pairs
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1)]
I want to take each element (0,0) then (0,1), etc. pair, to XOR the two numbers between them and the result converted to binary.
Example: the (0,2) pair
0 ... | XOR Pair Of Elements In A List | I have a list of integer pairs
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1)]
I want to take each element (0,0) then (0,1), etc. pair, to XOR the two numbers between them and the result converted to binary.
Example: the (0,2) pair
0 decimal equals to 00110000 and 2 dec... | [
"It's a quite weird thing you try to do, but I believe you want:\nlst = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1)]\n\ndef to_ascii_code(c):\n return str(c).encode('ascii')[0]\n\nout = [bin(to_ascii_code(a)^to_ascii_code(b)) for a,b in lst]\n\nOutput:\n['0b0',... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074653804_python.txt |
Q:
how do i make it print the multiplication table in the created file?
I've been trying to put a print statement inside the loop to no avail.
def individualizing_file(number: int) -> None:
increasing_number: int = number
with open(f"file_{increasing_number}.txt", "w") as f:
f.write(f"Multiplication t... | how do i make it print the multiplication table in the created file? | I've been trying to put a print statement inside the loop to no avail.
def individualizing_file(number: int) -> None:
increasing_number: int = number
with open(f"file_{increasing_number}.txt", "w") as f:
f.write(f"Multiplication table for + {n}")
for _ in range(10):
#print(n*2)
... | [
"You can use print(file=f):\ndef individualizing_file(number: int) -> None:\n with open(f\"file_{number}.txt\", \"w\") as f:\n f.write(f\"Multiplication table for + {n}\")\n for multiple in range(10):\n print(number * multiple, file=f)\n\nUnlike using f.write, print automatically adds a ... | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0074654233_python.txt |
Q:
How to test a FastAPI api endpoint that consumes images?
I am using pytest to test a FastAPI endpoint that gets in input an image in binary format as in
@app.post("/analyse")
async def analyse(file: bytes = File(...)):
image = Image.open(io.BytesIO(file)).convert("RGB")
stats = process_image(image)
re... | How to test a FastAPI api endpoint that consumes images? | I am using pytest to test a FastAPI endpoint that gets in input an image in binary format as in
@app.post("/analyse")
async def analyse(file: bytes = File(...)):
image = Image.open(io.BytesIO(file)).convert("RGB")
stats = process_image(image)
return stats
After starting the server, I can manually test the... | [
"You see a different behavior because requests and TestClient are not exactly same in every aspect as TestClient wraps requests. To dig deeper, refer to the source code: (FastAPI is using TestClient from starlette library, FYI)\nhttps://github.com/encode/starlette/blob/master/starlette/testclient.py\nTo solve, you ... | [
26,
0
] | [] | [] | [
"fastapi",
"multipart",
"pytest",
"python",
"starlette"
] | stackoverflow_0060783222_fastapi_multipart_pytest_python_starlette.txt |
Q:
Kivy: How to make a checkbox "remember" its state/value?
I am trying to make a login screen with a "remember login" feature, a checkbox that, when toggled, will store all user credentials in a text file to access later. I want the app to remember the value of the checkmark so that when I open it again, the checkma... | Kivy: How to make a checkbox "remember" its state/value? | I am trying to make a login screen with a "remember login" feature, a checkbox that, when toggled, will store all user credentials in a text file to access later. I want the app to remember the value of the checkmark so that when I open it again, the checkmark is in the "on" or "off" position, depending on its previous... | [
"Store the value to a ini file and read it on launch\n",
"You can make file and write here login parameters(you must write here the last login and if smbd log out clear file) and when app start read this file and put every login parameters where you check them. It works for me.\n"
] | [
0,
0
] | [] | [] | [
"kivy",
"python"
] | stackoverflow_0073502461_kivy_python.txt |
Q:
Accessing a Python traceback from the C API
I'm having some trouble figuring out the proper way to walk a Python traceback using the C API. I'm writing an application that embeds the Python interpreter. I want to be able to execute arbitrary Python code, and if it raises an exception, to translate it to my own a... | Accessing a Python traceback from the C API | I'm having some trouble figuring out the proper way to walk a Python traceback using the C API. I'm writing an application that embeds the Python interpreter. I want to be able to execute arbitrary Python code, and if it raises an exception, to translate it to my own application-specific C++ exception. For now, it i... | [
"This is an old question but for future reference, you can get the current stack frame from the thread state object and then just walk the frames backward. A traceback object isn't necessary unless you want to preserve the state for the future.\nFor example:\nPyThreadState *tstate = PyThreadState_GET();\nif (NULL ... | [
16,
15,
9,
6,
4,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001796510_python.txt |
Q:
Load and Retrain PyTorch model…
Hi all! Can you help me? I have a question: "How can I retrain a PyTorch model with just a .pt file ?”
I've looked at many guides but haven't found the answer. Everything there has a model class.
I tried to import using torch.load() and others. But it doesn't work. When I load ... | Load and Retrain PyTorch model… | Hi all! Can you help me? I have a question: "How can I retrain a PyTorch model with just a .pt file ?”
I've looked at many guides but haven't found the answer. Everything there has a model class.
I tried to import using torch.load() and others. But it doesn't work. When I load the model with torch.load() I can't g... | [
"To retrain a PyTorch model with just a .pt file, you will need to use the PyTorch API to create a new model instance and load the .pt file as the initial weights for the model. This can be done using the torch.load() function to load the .pt file, and then using the model.load_state_dict() method to load the weigh... | [
0
] | [] | [] | [
"artificial_intelligence",
"python",
"pytorch"
] | stackoverflow_0074654315_artificial_intelligence_python_pytorch.txt |
Q:
Why I receive ImportError: cannot import name 'just_fix_windows_console' from 'colorama'?
I have to use BayesianOptimization for hyper parameter tuning for neural networks, for the same when I'm importing it using, from bayes_opt import BayesianOptimization, the following error is obtained
`ImportError ... | Why I receive ImportError: cannot import name 'just_fix_windows_console' from 'colorama'? | I have to use BayesianOptimization for hyper parameter tuning for neural networks, for the same when I'm importing it using, from bayes_opt import BayesianOptimization, the following error is obtained
`ImportError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_28896\17196... | [
"Based on the changelog for colorama, that function was added in the latest version of the library, 0.4.6.\nMake sure you have that version installed, with e.g. pip install -U colorama.\n"
] | [
0
] | [] | [] | [
"colorama",
"python"
] | stackoverflow_0074654425_colorama_python.txt |
Q:
Append the last level in Multiindex Dataframe on same length
I have a dataframe like this
df = pd.DataFrame({'A': [1, 2], 'B':['x', 'y'], 'C':[1, 2], 'D':[0, 0]})
df.groupby(['A', 'B', 'C']).mean()
D
A B C
1 x 1 0.0
2 y 2 0.0
I want it to have the same index in C.
... | Append the last level in Multiindex Dataframe on same length | I have a dataframe like this
df = pd.DataFrame({'A': [1, 2], 'B':['x', 'y'], 'C':[1, 2], 'D':[0, 0]})
df.groupby(['A', 'B', 'C']).mean()
D
A B C
1 x 1 0.0
2 y 2 0.0
I want it to have the same index in C.
D
A B C
1 x 1 0.0
2 NaN
2 y 1 NaN
... | [
"Use Series.unstack, add not exist value(s) in range by Series.reindex with DataFrame.stack, last add Series.to_frame:\ndf1 = df.groupby(['A', 'B', 'C']).mean()\n\nr = range(1, 5)\ndf2 = df1['D'].unstack().reindex(columns=r).stack(dropna=False).to_frame(name='D')\nprint (df2)\n D\nA B C \n1 x 1 0.0\n ... | [
0
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074654475_multi_index_pandas_python.txt |
Q:
HEIC to JPEG conversion with metadata
I'm trying to convert heic file in jpeg importing also all metadadata (like gps info and other stuff), unfurtunately with the code below the conversion is ok but no metadata are stored on the jpeg file created.
Anyone can describe me what I need to add in the conversion method... | HEIC to JPEG conversion with metadata | I'm trying to convert heic file in jpeg importing also all metadadata (like gps info and other stuff), unfurtunately with the code below the conversion is ok but no metadata are stored on the jpeg file created.
Anyone can describe me what I need to add in the conversion method?
heif_file = pyheif.read("/transito/126APP... | [
"Thanks, i found a solution, I hope can help others:\n# Open the file\nheif_file = pyheif.read(file_path_heic)\n\n# Creation of image \nimage = Image.frombytes(\n heif_file.mode,\n heif_file.size,\n heif_file.data,\n \"raw\",\n heif_file.mode,\n heif_file.stride,\n)\n# Retrive the metadata\nfor me... | [
6,
1,
0
] | [] | [] | [
"data_conversion",
"exif",
"heic",
"jpeg",
"python"
] | stackoverflow_0065045644_data_conversion_exif_heic_jpeg_python.txt |
Q:
Group columns if coordinates are not more distant than a threshold
Sps Gps start end
SP1 G1 2 322
SP1 G1 318 1368
SP1 G1 21125 22297
SP2 G2 2 313
SP2 G2 334 1359
SP2 G2 11716 11964
SP2 G2 20709 20885
SP2 G2 21080 22297
SP3 ... | Group columns if coordinates are not more distant than a threshold | Sps Gps start end
SP1 G1 2 322
SP1 G1 318 1368
SP1 G1 21125 22297
SP2 G2 2 313
SP2 G2 334 1359
SP2 G2 11716 11964
SP2 G2 20709 20885
SP2 G2 21080 22297
SP3 G3 2 313
SP3 G3 328 1368
SP3 G3 21116 2229... | [
"I believe you might want:\ndf['Threshold_gps'] = (df\n .groupby(['Sps', 'Gps'], group_keys=False)\n .apply(lambda d: (s:=d['end'].shift().rsub(d['start'])\n .gt(500))\n .cumsum().add(1-s.iloc[0])\n .astype(str).radd('G')\n )\n)\n\nfor python <... | [
4
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074653913_pandas_python_python_3.x.txt |
Q:
Django login/ payload visible in plaintext in Chrome DevTools
This is weird. I have created login functions so many times but never noticed this thing.
When we provide a username and password in a form and submit it, and it goes to the server-side as a Payload like this, I can see the data in the Chrome DevTools n... | Django login/ payload visible in plaintext in Chrome DevTools | This is weird. I have created login functions so many times but never noticed this thing.
When we provide a username and password in a form and submit it, and it goes to the server-side as a Payload like this, I can see the data in the Chrome DevTools network tab:
csrfmiddlewaretoken:
mHjXdIDo50tfygxZualuxaCBBdKboeK2R... | [
"\nIt's supposed to be in the encrypted format right?\n\nNo.\nWhat you're seeing in Chrome DevTools is the username and password before they get encrypted.\nIf you were to run tcpdump or Wireshark when you make the request, you'd see that it is encrypted over the network.\nIn order for the data to be usable by anyo... | [
2,
0
] | [] | [] | [
"authentication",
"django",
"payload",
"python"
] | stackoverflow_0074612555_authentication_django_payload_python.txt |
Q:
How do I return true, for two arrays that are the same length and value? (Python)
So, the question I am trying to solve is...
"Return true if two arrays are equal.
The arrays are equal if they are the same length and contain the same value at each particular index.
Two empty arrays are equal."
for example:
input:
... | How do I return true, for two arrays that are the same length and value? (Python) | So, the question I am trying to solve is...
"Return true if two arrays are equal.
The arrays are equal if they are the same length and contain the same value at each particular index.
Two empty arrays are equal."
for example:
input:
a == [1, 9, 4, 6, 3]
b == [1, 9, 4, 6, 3]
output:
true
OR
input:
a == [5, 3, 1]
b... | [] | [] | [
"Use numpy.array_equal:\na = [1, 9, 4, 6, 3]\nb = [1, 9, 4, 6, 3]\nnp.array_equal(a, b)\n# True\n\na = [5, 3, 1]\nb = [6, 2, 9, 4]\nnp.array_equal(a, b)\n# False\n\nnp.array_equal([], [])\n# True\n\n",
"just use a for loop\ndef solution(a, b):\n x = 0\n if (len(a) == len(b)): \n for i in range(len(a)... | [
-1,
-2
] | [
"arrays",
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074653398_arrays_numpy_python_python_3.x.txt |
Q:
Compare value of previous row and next row; create new DF with the rows matching condition
I am trying to compare floating point values with each another within one column; I need a function that doesn't produce an error...
The functione should loop through the column and compare each value within the columns prev... | Compare value of previous row and next row; create new DF with the rows matching condition | I am trying to compare floating point values with each another within one column; I need a function that doesn't produce an error...
The functione should loop through the column and compare each value within the columns previous value and also with the next value and create a new DF with all rows matching conditions.
... | [
"Compare shifted values for greater prevous or next values with DataFrame.shift and chain masks by | for bitwise OR, then omit first and last value of mask and set False in Series.reindex:\nm = a_df.col1.lt(a_df.col1.shift()) | a_df.col1.gt(a_df.col1.shift(-1))\n\n# @mozway alternative\nm = a_df.col1.diff().lt(0) |... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074612326_dataframe_pandas_python.txt |
Q:
How to shift quartile lines in seaborn grouped violin plots?
Consider the following seaborn grouped violinplot with split violins, where I inserted a small space inbetween.
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
fi... | How to shift quartile lines in seaborn grouped violin plots? | Consider the following seaborn grouped violinplot with split violins, where I inserted a small space inbetween.
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
fig, ax = plt.subplots()
sns.violinplot(
data=tips, x="day", y="... | [
"You can do it exactly the same way as you did with the violins:\nfor i, line in enumerate(ax.get_lines()):\n line.get_path().vertices[:, 0] += delta if i // 3 % 2 else -delta\n\n\n"
] | [
2
] | [] | [] | [
"matplotlib",
"plot",
"python",
"seaborn",
"violin_plot"
] | stackoverflow_0074653509_matplotlib_plot_python_seaborn_violin_plot.txt |
Q:
How to check if Python is running on an M1 mac, even under Rosetta?
I have python 3.10 code that launches a process but it needs to run a different process if it is running on an M1 Mac.
Is there a way to reliably detect if you are on an M1 Mac even if the python process is running in Rosetta?
I've tried this:
pri... | How to check if Python is running on an M1 mac, even under Rosetta? | I have python 3.10 code that launches a process but it needs to run a different process if it is running on an M1 Mac.
Is there a way to reliably detect if you are on an M1 Mac even if the python process is running in Rosetta?
I've tried this:
print(sys.platform)
# On Intel silicon:
darwin
# On M1 silicon:
darwin
b... | [
"You could just check for the Processor Name, and check it that way. The easiest way to get it is by using the cpuinfo module. cpuinfo.get_cpu_info()['brand_raw'] returns a string with the processor brand and name, for example \"Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz\". If you only want to have \"i5-6500\", you ca... | [
1,
1,
0
] | [] | [] | [
"apple_m1",
"python"
] | stackoverflow_0072888632_apple_m1_python.txt |
Q:
converting series to dataframe using 'as_index' and 'reset_index' not working
I am trying to convert this series of data into dataframe using as_index = False inside groupby method. My goal is to show the total value for month and weekday.
My data
This is my main data uber-15.
Dispatching Pickup_date Affi... | converting series to dataframe using 'as_index' and 'reset_index' not working | I am trying to convert this series of data into dataframe using as_index = False inside groupby method. My goal is to show the total value for month and weekday.
My data
This is my main data uber-15.
Dispatching Pickup_date Affiliated locationID month weekDay day hour minute
0 B02617 2015-05-17 09:47:00... | [
"To convert a Pandas Series object to a DataFrame with columns named after the Series indices, you can use the to_frame() method on the Series object. This method converts the Series to a DataFrame with a single column, where the column name is the name of the Series index. Here is an example of how you can use thi... | [
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074654704_dataframe_jupyter_notebook_pandas_python.txt |
Q:
Missing dataframe column percentage
I have a dataset with 21 columns there are 2 columns that has 25% missing values, I'm reluctant to drop them or not?
Is it make sence to drop columns that has more than 20% of its data as missing, or how can I determine the percentage of missing values that decide to drop the co... | Missing dataframe column percentage | I have a dataset with 21 columns there are 2 columns that has 25% missing values, I'm reluctant to drop them or not?
Is it make sence to drop columns that has more than 20% of its data as missing, or how can I determine the percentage of missing values that decide to drop the column
I dropped the columns that have 20% ... | [
"One approach\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randint(0, 5, 21 * 5).reshape(-1, 21)).replace({0: np.nan})\nprint('Original df\\n',df)\ndf = df.loc[:, df.isna().sum().div(df.shape[0]).le(0.25)]\nprint('\\nResult df without columns > 25% missing values\\n',df)\n\nOriginal df\n ... | [
0,
0
] | [] | [] | [
"data_cleaning",
"dataframe",
"missing_data",
"pandas",
"python"
] | stackoverflow_0074654503_data_cleaning_dataframe_missing_data_pandas_python.txt |
Q:
Exponential Regression in Python
I have a set of x and y data and I want to use exponential regression to find the line that best fits those set of points. i.e.:
y = P1 + P2 exp(-P0 x)
I want to calculate the values of P0, P1 and P2.
I use a software "Igor Pro" that calculates the values for me, but want a Pytho... | Exponential Regression in Python | I have a set of x and y data and I want to use exponential regression to find the line that best fits those set of points. i.e.:
y = P1 + P2 exp(-P0 x)
I want to calculate the values of P0, P1 and P2.
I use a software "Igor Pro" that calculates the values for me, but want a Python implementation. I used the curve_fit... | [
"Well, when comparing fit results, it is always important to include uncertainties in the fitted parameters. That is, when you say that the values\nfrom Igor (P1=376.91, P2=5393.9, P0=3.7776), and from curve_fit\n(P1=702.45, P2=-13.33. P0=-2.6744) are different, what is it that leads to conclude those values are a... | [
0,
0
] | [
"It looks like the curve_fit function is not the right tool for this problem, because the function you are trying to fit your data to (y = P1 + P2 * exp(-P0 * x)) has three parameters, while curve_fit expects a function with only one parameter (the independent variable, in this case t). You can use curve_fit to fit... | [
-1
] | [
"curve_fitting",
"exponential",
"non_linear_regression",
"python",
"scipy"
] | stackoverflow_0074647310_curve_fitting_exponential_non_linear_regression_python_scipy.txt |
Q:
ValueError: multi-line expressions are only valid in the context of data, use DataFrame.eval even after backslash
I am trying to run a multiline query using df.query but I seem to be getting the following error even after adding backslashes:
column = 'method'
idx = df.query(
f"""{column} == 'One' and ... | ValueError: multi-line expressions are only valid in the context of data, use DataFrame.eval even after backslash | I am trying to run a multiline query using df.query but I seem to be getting the following error even after adding backslashes:
column = 'method'
idx = df.query(
f"""{column} == 'One' and \
number.notnull() and \
flag.isnull()""").index
My df looks like this:
df
'method' 'number' 'flag'
23 ... | [
"I would suggest avoiding df.query, it is easier and more reliable to use the masking feature to filter your data. The triple quotes are also taking the indentation characters, you should avoid that.\nNow, in your case,\nBetter syntax, with string concatenation:\ncolumn = 'method'\n\nidx = df.query(\n f\"{column... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074654274_pandas_python.txt |
Q:
How to add delay between loop python?
i want to ask , i try with my coding but it still not working, i want to execute 2 loop with delay and print each word with delay.
here my coding
import threading,time
def func_name1():
fruits = ["apple", "banana", "cherry"]
for i in fruits:
time.sleep(2)
print(i)
de... | How to add delay between loop python? | i want to ask , i try with my coding but it still not working, i want to execute 2 loop with delay and print each word with delay.
here my coding
import threading,time
def func_name1():
fruits = ["apple", "banana", "cherry"]
for i in fruits:
time.sleep(2)
print(i)
def func_name2():
fruits2 = ["1", "2", "3"]
f... | [
"Try this.\nI have updated my code Now it matches your scenario. The whole Script takes approximatly 25.03 seconds.\ndef func_name1():\n fruits = [\"apple\", \"banana\", \"cherry\"]\n a = 0\n for i in fruits:\n a += 1\n print(i)\n if a == len(fruits):\n return\n time.... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074654712_python_python_3.x.txt |
Q:
Simple Captcha Solver with Python
I'm reaching to you to get some help and advices on creating a "Captcha Solver" using python and any image detection to text package
This is an example of the captcha (it contains only 4 character and its always numbers):
I am not sure if I should use a complex solver with AI and... | Simple Captcha Solver with Python | I'm reaching to you to get some help and advices on creating a "Captcha Solver" using python and any image detection to text package
This is an example of the captcha (it contains only 4 character and its always numbers):
I am not sure if I should use a complex solver with AI and CNN and Machine Learning or just somet... | [
"I would recommend you use Tesseract or Tesseract.JS. You will find plenty of useful tutorials and articles on how to use Tesseract. you might wanna explore some additional Algorithms to reduce the noise in the image.\n"
] | [
0
] | [] | [] | [
"captcha",
"python",
"python_tesseract"
] | stackoverflow_0074642350_captcha_python_python_tesseract.txt |
Q:
WebDriverException Message: 'chromedriver' executable needs to be in PATH ( Error on mac M1)
I am trying web scrapping with selenium and therefore following the below code.
However, I encounter an error with chromedriver path, I am unable to figure out on mac M1 . I've tried several methods to solve this.
Any hint... | WebDriverException Message: 'chromedriver' executable needs to be in PATH ( Error on mac M1) | I am trying web scrapping with selenium and therefore following the below code.
However, I encounter an error with chromedriver path, I am unable to figure out on mac M1 . I've tried several methods to solve this.
Any hints?
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from sel... | [
"You need to provide also the file name of the webdriver in the path, so in your case:\nusr/local/bin/chromedriver\n\nshould be like:\nusr/local/bin/chromedriver/chromedriver \n\nif the name of the folder matches the webdriver file name.\nAt least according to the error it seems like chromedriver is a folder where ... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074654297_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Find element with compound class in Selenium
I can see some posts about this topic but unfortunately, none worked in my case. I am trying to locate elements with compounded classes in its name. This is the name of the elements class:
class="group-header__wrapper is-grid-view-active section--prematch markets-optimi... | Find element with compound class in Selenium | I can see some posts about this topic but unfortunately, none worked in my case. I am trying to locate elements with compounded classes in its name. This is the name of the elements class:
class="group-header__wrapper is-grid-view-active section--prematch markets-optimized--3"
I tried with this line of code, which is ... | [
"EDIT:\nTested your code and you can select the elements you want with this...\nSBdriver.find_elements(By.CSS_SELECTOR, \".group-header__wrapper.section--prematch.markets-optimized--3\")\n\nyou need it constructed like this\n.group-header__wrapper.is-grid-view-active.section--prematch.markets-optimized--3\n\nyou ha... | [
1
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074654803_python_selenium_web_scraping.txt |
Q:
Python networkx graph appears jumbled when drawn
Note:
I already tried solution in
Python networkx graph appears jumbled when drawn in matplotlib
But it didnt work. As you can see below, i placed the position in the end but still the graph appears to be jumbled.
Question:
I have a flow A->B->C->D->E->F->G->H. Gene... | Python networkx graph appears jumbled when drawn | Note:
I already tried solution in
Python networkx graph appears jumbled when drawn in matplotlib
But it didnt work. As you can see below, i placed the position in the end but still the graph appears to be jumbled.
Question:
I have a flow A->B->C->D->E->F->G->H. Generally the directed graph should form a circle. But des... | [
"\nGenerally the directed graph should form a circle.\n\nThat is not the lowest energy configuration for a path graph with a spring node layout. If you do want a circular node layout, there is nx.circular_layout. However, it (also) doesn't reduce edge crossings.\nIf you are open to using other libraries, netgraph w... | [
0
] | [] | [] | [
"graph",
"networkx",
"python"
] | stackoverflow_0074625413_graph_networkx_python.txt |
Q:
How do I sort a dataframe by distance from zero value
I'll start by saying I am a Python beginner, I did try and find an answer to this via similar questions but I'm struggling to grasp some of the solutions in order to tailor them for my own use.
If I have a Pandas dataframe as follows:
What code would I need in... | How do I sort a dataframe by distance from zero value | I'll start by saying I am a Python beginner, I did try and find an answer to this via similar questions but I'm struggling to grasp some of the solutions in order to tailor them for my own use.
If I have a Pandas dataframe as follows:
What code would I need in order to sort it as per the below whilst excluding the 0 v... | [
"IIUC, you can set abs as a key parameter of pandas.DataFrame.sort_values.\nTry this :\nout = df.sort_values(by=\"Score\", key=abs)\n\n# Output :\nprint(out)\n\n Name Score\n3 maggie 0\n2 sally -5\n1 jane -10\n4 peter 15\n6 andy 25\n0 bob -30\n5 mike 50\n\n",
"You... | [
2,
1
] | [] | [] | [
"dataframe",
"python",
"sorting"
] | stackoverflow_0074654696_dataframe_python_sorting.txt |
Q:
How to iterate through list of dictionary, extract values and fill in another data dictionary in python
I have a list of dictionary as below.
[
{'name':['mallesh'],'email':['m@gmail.com']},
{'name':['bhavik'],'ssn':['1000011']},
{'name':['jagarini'],'email':['m@gmail.com'],'phone':['111111']},
{'na... | How to iterate through list of dictionary, extract values and fill in another data dictionary in python | I have a list of dictionary as below.
[
{'name':['mallesh'],'email':['m@gmail.com']},
{'name':['bhavik'],'ssn':['1000011']},
{'name':['jagarini'],'email':['m@gmail.com'],'phone':['111111']},
{'name':['mallesh'],'email':['m@gmail.com'],'phone':['1234556'],'ssn':['10000012']}
]
I would like to extract t... | [
"Here is one way you could accomplish this using a for loop and the update method of the dictionary:\ndata = [\n {'name': ['mallesh'], 'email': ['m@gmail.com']},\n {'name': ['bhavik'], 'ssn': ['1000011']},\n {'name': ['jagarini'], 'email': ['m@gmail.com'], 'phone': ['111111']},\n {'name': ['mallesh'], '... | [
2,
1
] | [] | [] | [
"dictionary",
"pandas",
"python"
] | stackoverflow_0074650064_dictionary_pandas_python.txt |
Q:
Gunicorn/Nginx/Flask not playing together well
I have been trying the last couple days to build a nginx/gunicorn/flask stack in Puppet to deploy repeatedly in our environment. Unfortunately, I am coming up short at the last moment and could really use some help. I have dumped anything I though relevant below, if a... | Gunicorn/Nginx/Flask not playing together well | I have been trying the last couple days to build a nginx/gunicorn/flask stack in Puppet to deploy repeatedly in our environment. Unfortunately, I am coming up short at the last moment and could really use some help. I have dumped anything I though relevant below, if anyone can lend a hand it would be very helpful!
guni... | [
"in your gunicorn service file, Instead of\nExecStart=/home/bit-web/pyvenv/bin/gunicorn --workers 3 --bind unix:project1.sock -m 007 wsgi:application\n\ntry this (means add .sock file path)\nExecStart=/home/bit-web/pyvenv/bin/gunicorn --workers 3 --bind unix:/home/bit-web/pyvenv/project1/project1.sock -m 007 wsgi:a... | [
0
] | [] | [] | [
"flask",
"gunicorn",
"nginx",
"puppet",
"python"
] | stackoverflow_0074646683_flask_gunicorn_nginx_puppet_python.txt |
Q:
How to display property method as a message in class based view?
I have a property method defined inside my django model which represents an id.
status_choice = [("Pending","Pending"), ("In progress", "In progress") ,("Fixed","Fixed"),("Not Fixed","Not Fixed")]
class Bug(models.Model):
name = models.CharField... | How to display property method as a message in class based view? | I have a property method defined inside my django model which represents an id.
status_choice = [("Pending","Pending"), ("In progress", "In progress") ,("Fixed","Fixed"),("Not Fixed","Not Fixed")]
class Bug(models.Model):
name = models.CharField(max_length=200, blank= False, null= False)
info = models.TextFiel... | [
"Assuming that your UploadForm is a ModelForm it's worth noting that calling .save() on it will return an instance of your model.\nIf you have:\nclass UploadForm(ModelForm):\n class Meta:\n model = Bug\n\nThis means that your .save() will return an instance of a Bug\nNow that everything went well and you ... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0074654780_django_django_forms_django_models_django_views_python.txt |
Q:
How to create an event listener for mp3 sounds
I have a mp3 file namd 'audio.mp3' but for some reason no matter how hard I try I cannot find a useful link to help me code a programm that will listen to the computer and when hearing a specific sound that is exactly like my file 'audio.mp3', do something (that ofc i... | How to create an event listener for mp3 sounds | I have a mp3 file namd 'audio.mp3' but for some reason no matter how hard I try I cannot find a useful link to help me code a programm that will listen to the computer and when hearing a specific sound that is exactly like my file 'audio.mp3', do something (that ofc i'll code)
I kept searching online for modules i coul... | [
"module playsound is for diferent use, he PLAYSOUND, not listen\n"
] | [
0
] | [] | [] | [
"audio",
"python",
"record",
"voice"
] | stackoverflow_0070552948_audio_python_record_voice.txt |
Q:
Why ProcessPoolExecutor on Windows needs __main__ guard when submitting function from another module?
Let's say I have a program
import othermodule, concurrent.futures
pool = concurrent.futures.ProcessPoolExecutor()
and then I want to say
fut = pool.submit(othermodule.foo, 5)
print(fut.result())
Official docs sa... | Why ProcessPoolExecutor on Windows needs __main__ guard when submitting function from another module? | Let's say I have a program
import othermodule, concurrent.futures
pool = concurrent.futures.ProcessPoolExecutor()
and then I want to say
fut = pool.submit(othermodule.foo, 5)
print(fut.result())
Official docs say I need to guard these latter two statements with if __name__ == '__main__'. It's not hard to do, I would ... | [
"Old question, but now there is a good answer to this.\n\nIs maybe the only reason, that on Unix this is solved by forking __main__, so on Windows (where fork doesn't really work) they did the closest imitation of the procedure, instead of the closest imitation of the intent? In this case, could it be fixed on Wind... | [
0
] | [] | [] | [
"python",
"python_module",
"python_multiprocessing"
] | stackoverflow_0038801229_python_python_module_python_multiprocessing.txt |
Q:
Why does StableDiffusionPipeline return black images when generating multiple images at once?
I am using the StableDiffusionPipeline from the Hugging Face Diffusers library in Python 3.10.2, on an M2 Mac (I tagged it because this might be the issue). When I try to generate 1 image from 1 prompt, the output looks f... | Why does StableDiffusionPipeline return black images when generating multiple images at once? | I am using the StableDiffusionPipeline from the Hugging Face Diffusers library in Python 3.10.2, on an M2 Mac (I tagged it because this might be the issue). When I try to generate 1 image from 1 prompt, the output looks fine, but when I try to generate multiple images using the same prompt, the images are all either bl... | [
"Apparently it is indeed an Apple Silicon (M1/M2) issue, of which Hugging Face is not yet sure why this is happening, see this GitHub issue for more details.\n",
"I think it might be a PyTorch issue given that a pure MPS version of the code (in Swift) worked fine last time I tested:\nimport MetalPerformanceShader... | [
1,
0
] | [] | [] | [
"apple_m1",
"huggingface_transformers",
"python",
"pytorch",
"stable_diffusion"
] | stackoverflow_0074642594_apple_m1_huggingface_transformers_python_pytorch_stable_diffusion.txt |
Q:
How to create a Python package from a PyBind11 module created with CMake
I have a C++ code using Cmake & make for the building part.
I also have python bindings to this code thanks to PyBind11.
I use pybind11_add_module inside CMakeLists.txt and now when I build (cmake -Bbuild && cd build && make) it creates a pyt... | How to create a Python package from a PyBind11 module created with CMake | I have a C++ code using Cmake & make for the building part.
I also have python bindings to this code thanks to PyBind11.
I use pybind11_add_module inside CMakeLists.txt and now when I build (cmake -Bbuild && cd build && make) it creates a python_module.so in the build directory.
I can move it manually elsewhere, and if... | [
"If I understand your question correctly, you want to be able to import your module without having to move the .so file manually.\nRunning python3 setup.py install should both compile your module via cmake and do the necessary linking. After that you should be able to import your module as usual.\n"
] | [
0
] | [] | [] | [
"pybind11",
"python",
"python_packaging"
] | stackoverflow_0074545298_pybind11_python_python_packaging.txt |
Q:
How to get name of all email attachments of a particular mail using imaplib, python?
this is my first task on my new job please help...
Hi i am trying to fetch all the attachments of mails and make a list of those attachments for that particular mail and save that list in a json file.
I have been instructed to use... | How to get name of all email attachments of a particular mail using imaplib, python? | this is my first task on my new job please help...
Hi i am trying to fetch all the attachments of mails and make a list of those attachments for that particular mail and save that list in a json file.
I have been instructed to use imaplib only.
this is the function that i am using to extract the mails data but the par... | [
"it was easy i just had to do this.\nimport re\n# getting filenames \nfilenames = mailbox.uid('fetch', num, '(BODYSTRUCTURE)')[1][0]\nfilenames = re.findall('\\(\"name\".*?\\)', str(filenames))\n\nfilenames = [filenames[i].split('\" \"')[1][:-2] for i in range(len(filenames))]\n\n\nexplaination - mailbox.uid will f... | [
0
] | [] | [] | [
"imap",
"imaplib",
"python"
] | stackoverflow_0074623655_imap_imaplib_python.txt |
Q:
How to iterate until a condition is met in python for loop
I have been working on this simple interest calculator and I was trying to make the for loop iterate until the amount inputted by the user is reached. But I am stuck at the range part, if I assign a range value like range(1 ,11) it will iterate it correctl... | How to iterate until a condition is met in python for loop | I have been working on this simple interest calculator and I was trying to make the for loop iterate until the amount inputted by the user is reached. But I am stuck at the range part, if I assign a range value like range(1 ,11) it will iterate it correctly and print the year in in contrast to the amount but I want the... | [
"Instead, you can use a while loop. What I mean here is you can simply:\nprincipal = float(input(\"How much money to start? :\"))\napr = float(input(\"What is the apr? :\"))\namount = float(input(\"What is the amount you want to get to? :\"))\n\n\ndef interestCalculator():\n global principal\n i = 1\n\n if... | [
4,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0066522306_loops_python.txt |
Q:
Discarding alpha channel from images stored as Numpy arrays
I load images with numpy/scikit. I know that all images are 200x200 pixels.
When the images are loaded, I notice some have an alpha channel, and therefore have shape (200, 200, 4) instead of (200, 200, 3) which I expect.
Is there a way to delete that last... | Discarding alpha channel from images stored as Numpy arrays | I load images with numpy/scikit. I know that all images are 200x200 pixels.
When the images are loaded, I notice some have an alpha channel, and therefore have shape (200, 200, 4) instead of (200, 200, 3) which I expect.
Is there a way to delete that last value, discarding the alpha channel and get all images to a nice... | [
"Just slice the array to get the first three entries of the last dimension:\nimage_without_alpha = image[:,:,:3]\n\n",
"scikit-image builtin:\nfrom skimage.color import rgba2rgb\nfrom skimage import data\nimg_rgba = data.logo()\nimg_rgb = rgba2rgb(img_rgba)\n\nhttps://scikit-image.org/docs/dev/user_guide/transfor... | [
109,
3
] | [
"Use PIL.Image to remove the alpha channel\nfrom PIL import Image\nimport numpy as np\n\nimg = Image.open(\"c:\\>path_to_image\")\nimg = img.convert(\"RGB\") # remove alpha\nimage_array = np.asarray(img) # converting image to numpy array\nprint(image_array.shape)\nimg.show()\n\nIf images are in numpy array to conve... | [
-1
] | [
"math",
"numpy",
"python"
] | stackoverflow_0035902302_math_numpy_python.txt |
Q:
Manipulating data in Polars
A dumb question. How to manipulate columns in Polars?
Explicitly, I have a table with 3 columns : N , Survivors, Deaths
I want to replace Deaths by Deaths * N and Survivors by Survivors * N
the following code is not working
table["SURVIVORS"] = table["SURVIVORS"]*table["N"]
I have thi... | Manipulating data in Polars | A dumb question. How to manipulate columns in Polars?
Explicitly, I have a table with 3 columns : N , Survivors, Deaths
I want to replace Deaths by Deaths * N and Survivors by Survivors * N
the following code is not working
table["SURVIVORS"] = table["SURVIVORS"]*table["N"]
I have this error:
TypeError: 'DataFrame' o... | [
"You can use polars.DataFrame.with_column to overwrite/replace the values of a column.\n\nReturn a new DataFrame with the column added or replaced.\n\nHere is an example :\nimport polars as pl\n\ntable = pl.DataFrame({\"N\": [5, 2, 6],\n \"SURVIVORS\": [1, 10, 3],\n \"Deaths\":... | [
1,
1
] | [
"Maybe something like this:\n# Import the pandas library\nimport pandas as pd\n\n# Load the table data into a DataFrame object\ntable = pd.read_csv(\"table.csv\")\n\n#Create a new DataFrame object with the modified columns .with_columns()\ntable = table.with_columns(\"SURVIVORS\": table[\"SURVIVORS\"]*table[\"N\"],... | [
-2
] | [
"python",
"python_polars"
] | stackoverflow_0074654355_python_python_polars.txt |
Q:
Count number of classes in a semantic segmented image
I have an image that is the output of a semantic segmentation algorithm, for example this one
I looked online and tried many pieces of code but none worked for me so far.
It is clear to the human eye that there are 5 different colors in this image: blue, black... | Count number of classes in a semantic segmented image | I have an image that is the output of a semantic segmentation algorithm, for example this one
I looked online and tried many pieces of code but none worked for me so far.
It is clear to the human eye that there are 5 different colors in this image: blue, black, red, and white.
I am trying to write a script in python t... | [
"Something has gone wrong - your image has 1277 unique colours, rather than the 5 you suggest.\nHave you maybe saved/shared a lossy JPEG rather than the lossless PNG you should prefer for classified images?\nA fast method of counting the unique colours with Numpy is as follows:\ndef withNumpy(img):\n # Ignore A ... | [
0,
0,
0
] | [] | [] | [
"image_segmentation",
"python",
"python_imaging_library"
] | stackoverflow_0070122809_image_segmentation_python_python_imaging_library.txt |
Q:
How to set Playwright not automatically follow the redirect?
I want to open a website using Playwright,
but I don't want to be automatically redirected.
In some other web clients, they have parameter link follow=False to disable automatically following the redirection. But I can't find it on Playwright.
async def ... | How to set Playwright not automatically follow the redirect? | I want to open a website using Playwright,
but I don't want to be automatically redirected.
In some other web clients, they have parameter link follow=False to disable automatically following the redirection. But I can't find it on Playwright.
async def run(playwright):
chromium = playwright.chromium
browser = ... | [
"You can use the wait_for_event method to wait for the response event to be emitted, and then check the response status to see if it is a redirect. If the response is a redirect, you can prevent Playwright from automatically following the redirect by calling the abort method on the response object.\nHere is an exam... | [
1
] | [] | [] | [
"playwright",
"playwright_python",
"python"
] | stackoverflow_0071407454_playwright_playwright_python_python.txt |
Q:
Is there a way to use SQL syntax highlighting in triple-quoted literals in Jupyter notebook?
I'm doing ETL development using pyspark in a Jupyter notebook. I generally prefer to use SQL queries instead of pyspark functions, since I find SQL more readable than pyspark functions most of the time. However, SQL querie... | Is there a way to use SQL syntax highlighting in triple-quoted literals in Jupyter notebook? | I'm doing ETL development using pyspark in a Jupyter notebook. I generally prefer to use SQL queries instead of pyspark functions, since I find SQL more readable than pyspark functions most of the time. However, SQL queries in Python scripts take the form of literal strings, which are treated as, well, strings, not cod... | [
"Here's the answer:\nhttps://github.com/CybercentreCanada/jupyterlab-sql-editor\nThis package has a feature that allows you to highlight SQL syntax within a string as well as run sql directly in the notebook. This is designed specifically for spark-sql, which is what I'm using.\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"pyspark",
"python",
"sql"
] | stackoverflow_0074621188_jupyter_notebook_pyspark_python_sql.txt |
Q:
How to remove the space between subplots in matplotlib.pyplot?
I am working on a project in which I need to put together a plot grid of 10 rows and 3 columns. Although I have been able to make the plots and arrange the subplots, I was not able to produce a nice plot without white space such as this one below from ... | How to remove the space between subplots in matplotlib.pyplot? | I am working on a project in which I need to put together a plot grid of 10 rows and 3 columns. Although I have been able to make the plots and arrange the subplots, I was not able to produce a nice plot without white space such as this one below from gridspec documentatation..
I tried the following posts, but still n... | [
"A note at the beginning: If you want to have full control over spacing, avoid using plt.tight_layout() as it will try to arange the plots in your figure to be equally and nicely distributed. This is mostly fine and produces pleasant results, but adjusts the spacing at its will.\nThe reason the GridSpec example you... | [
38,
15,
4,
0,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0041071947_matplotlib_numpy_python.txt |
Q:
What is the `current` correct format for Python Docstrings according to PEP standards?
I've been looking all over the web for the current standards for Python Docstrings and I've come across different answers for different scenarios. What is the currently most-accepted and wide-spread docstring format that I shoul... | What is the `current` correct format for Python Docstrings according to PEP standards? | I've been looking all over the web for the current standards for Python Docstrings and I've come across different answers for different scenarios. What is the currently most-accepted and wide-spread docstring format that I should use?
These are the ones that I've found so far:
Sphinx format (1): :param type name: descr... | [
"The most widely accepted and standardized format for Python docstrings is the one defined in the PEP 257 - Docstring Conventions. This format is supported by most IDEs, including VS Code and PyCharm, and is also used by the Sphinx and NumPy documentation tools.\nThe PEP 257 format for documenting function paramete... | [
1
] | [] | [] | [
"docstring",
"python",
"python_3.x"
] | stackoverflow_0074655149_docstring_python_python_3.x.txt |
Q:
import pyautogui does not work in VSCode, despite having everything installed
Im learning Python at the moment and I am trying to work with pyautogui at the moment but I have encountered a very basic problem and while I found other questions like this, I did not find a solution.
My "Setup":
I am on Windows 10 64 b... | import pyautogui does not work in VSCode, despite having everything installed | Im learning Python at the moment and I am trying to work with pyautogui at the moment but I have encountered a very basic problem and while I found other questions like this, I did not find a solution.
My "Setup":
I am on Windows 10 64 bit, I have installed python 3.11, I have the 22.3.1 pip version and the 0.9.53 vers... | [
"This is not the visual studio code problem, It is because you have the Code Spell Checker extension installed in your VScode. This extension checks the spelling of the pyautogui word and because the extension is not found in their dictionary it highlights the word.\nThis extension only checks the spelling. So your... | [
2
] | [] | [] | [
"pyautogui",
"python",
"python_import"
] | stackoverflow_0074655148_pyautogui_python_python_import.txt |
Q:
Inserting python variable in SPARQL
I have a string variable I want to pass in my SPARQL query and I can't get it to work.
title = 'Good Will Hunting'
[str(s) for s, in graph.query('''
PREFIX ddis: <http://ddis.ch/atai/>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.o... | Inserting python variable in SPARQL | I have a string variable I want to pass in my SPARQL query and I can't get it to work.
title = 'Good Will Hunting'
[str(s) for s, in graph.query('''
PREFIX ddis: <http://ddis.ch/atai/>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX schema: <htt... | [
"String interpolation in python can be achieved with the %s symbol (for string variables):\ntitle = 'Good Will Hunting'\n\n[str(s) for s, in graph.query('''\n PREFIX ddis: <http://ddis.ch/atai/> \n PREFIX wd: <http://www.wikidata.org/entity/> \n PREFIX wdt: <http://www.wikidata.org/prop/direct/> \n PREF... | [
0
] | [] | [] | [
"python",
"sparql",
"variables"
] | stackoverflow_0074654886_python_sparql_variables.txt |
Q:
Why are these for loops running incredibly slow in python?
I'm working on a short programme which will create a 2d array for the Tabula Recta. However, I am finding it is running incredibly slow, especially the further down the for loop I get. What is the reason for this, as I've never had a for loop run so slow b... | Why are these for loops running incredibly slow in python? | I'm working on a short programme which will create a 2d array for the Tabula Recta. However, I am finding it is running incredibly slow, especially the further down the for loop I get. What is the reason for this, as I've never had a for loop run so slow before, which is especially confusing as I don't think any of the... | [
"It looks like the code is running slowly because of the way the inner for loop is being implemented. Specifically, the line alphabet = alphabet[:len(alphabet)-1] + alphabet[1:] is causing the loop to run slower over time because it is changing the length of the alphabet string on each iteration of the loop. This m... | [
-1
] | [] | [] | [
"iteration",
"performance",
"python"
] | stackoverflow_0074655196_iteration_performance_python.txt |
Q:
How to scrape multiple href values?
Hello, I want to pull the links from this page. All the knowledge in that field comes in according to my own methods. But I just need the links. How can I scrape links?(Pyhton-Beautifulsoup)
make_list = base_soup.findAll('div', {'a class': 'link--muted no--text--decoration resu... | How to scrape multiple href values? |
Hello, I want to pull the links from this page. All the knowledge in that field comes in according to my own methods. But I just need the links. How can I scrape links?(Pyhton-Beautifulsoup)
make_list = base_soup.findAll('div', {'a class': 'link--muted no--text--decoration result-item'})
one_make = make_list.findAll(... | [
"Note: In newer code avoid old syntax findAll() instead use find_all() or select() with css selectors - For more take a minute to check docs\nIterate your ResultSet and extract the value of href attribute:\nmake_list = soup.find_all('a', {'class': 'link--muted no--text--decoration result-item'})\n for e in make_... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074653863_beautifulsoup_python_web_scraping.txt |
Q:
pytesseract import error on anaconda
I import pytesseract module by using the following command,
sudo pip install -U pytesseract
But while I import pytesseract module to a program which is compile on spyder shows
import pytesseract
ImportError: No module named pytesseract
Could you please give a solution for th... | pytesseract import error on anaconda | I import pytesseract module by using the following command,
sudo pip install -U pytesseract
But while I import pytesseract module to a program which is compile on spyder shows
import pytesseract
ImportError: No module named pytesseract
Could you please give a solution for this issue
| [
"If you are using anaconda, try:\nconda install -c auto pytesseract\n\n",
"alternatively, if not using anaconda,you can try:\nopen cmd.exe as administrator \ntype in \npython -m pip install --user pytesseract\n\n",
"you can try to download the file locally from this link (https://pypi.org/project/pytesseract/) ... | [
2,
1,
0,
0
] | [] | [] | [
"import",
"python",
"python_tesseract"
] | stackoverflow_0049525880_import_python_python_tesseract.txt |
Q:
How to convert dictionary to default dictionary?
mapfile = {
1879048192: 0,
1879048193: 0,
1879048194: 0,
1879048195: 0,
1879048196: 4,
1879048197: 3,
1879048198: 2,
1879048199: 17,
1879048200: 0,
1879048201: 1,
1879048202: 0,
1879048203: 0,
1879048204: 4,
# ... | How to convert dictionary to default dictionary? | mapfile = {
1879048192: 0,
1879048193: 0,
1879048194: 0,
1879048195: 0,
1879048196: 4,
1879048197: 3,
1879048198: 2,
1879048199: 17,
1879048200: 0,
1879048201: 1,
1879048202: 0,
1879048203: 0,
1879048204: 4,
# intentionally missing byte
1879048206: 2,
1879... | [
"You can convert a dictionary to a defaultdict:\n>>> a = {1:0, 2:1, 3:0}\n>>> from collections import defaultdict\n>>> defaultdict(int,a)\ndefaultdict(<type 'int'>, {1: 0, 2: 1, 3: 0})\n\n",
"Instead of re-creating the dictionary, you can use get(key, default). key is the key that you want to retrieve and default... | [
13,
8,
4,
2,
0
] | [] | [] | [
"defaultdict",
"dictionary",
"python"
] | stackoverflow_0031581751_defaultdict_dictionary_python.txt |
Q:
nested loop returns the same results for multiple rows while webscraping - beautiful soup
I'm trying to scrape an apartment website and it's not looping. I get different apartments but the rest of the information is the same. Yesterday it was pulling a different address.
url = "https://www.apartments.com/atlanta-... | nested loop returns the same results for multiple rows while webscraping - beautiful soup | I'm trying to scrape an apartment website and it's not looping. I get different apartments but the rest of the information is the same. Yesterday it was pulling a different address.
url = "https://www.apartments.com/atlanta-ga/?bb=lnwszyjy-H4lu8uqH"
header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/... | [
"Try:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.apartments.com/atlanta-ga/?bb=lnwszyjy-H4lu8uqH\"\nheader = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\"\n}\npage = requests.get(ur... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074647356_beautifulsoup_python_web_scraping.txt |
Q:
Python return statement not returning correct output
I have a simple function to return True or False when a condition is met. But the return statement is not functioning as I expected. Could anyone help me out to point out the mistake I am making.
graph = {
'f': ['g', 'i'],
'g': ['h'],
'h': [],
'i': ['g', 'k'],
'... | Python return statement not returning correct output | I have a simple function to return True or False when a condition is met. But the return statement is not functioning as I expected. Could anyone help me out to point out the mistake I am making.
graph = {
'f': ['g', 'i'],
'g': ['h'],
'h': [],
'i': ['g', 'k'],
'j': ['i'],
'k': []
}
def hasPath(graph,source,des):
a... | [
"In the hasPath function, you are calling the function recursively on each element in the arr list, and the return value of the recursive calls is not being used. This means that even if the des value is present in the arr list and the print statement is executed, the return False statement at the end of the functi... | [
2,
1
] | [] | [] | [
"function",
"python",
"return_value"
] | stackoverflow_0074655184_function_python_return_value.txt |
Q:
How to convert SQLAlchemy row object to a Python dict?
Is there a simple way to iterate over column name and value pairs?
My version of SQLAlchemy is 0.5.6
Here is the sample code where I tried using dict(row):
import sqlalchemy
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from ... | How to convert SQLAlchemy row object to a Python dict? | Is there a simple way to iterate over column name and value pairs?
My version of SQLAlchemy is 0.5.6
Here is the sample code where I tried using dict(row):
import sqlalchemy
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
print "sqlalchemy versio... | [
"You may access the internal __dict__ of a SQLAlchemy object, like the following:\nfor u in session.query(User).all():\n print u.__dict__\n\n",
"I couldn't get a good answer so I use this:\ndef row2dict(row):\n d = {}\n for column in row.__table__.columns:\n d[column.name] = str(getattr(row, colum... | [
344,
186,
185,
116,
60,
32,
31,
21,
15,
13,
12,
12,
11,
10,
9,
9,
8,
6,
4,
4,
3,
2,
2,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Here is a super simple way of doing it\nrow2dict = lambda r: dict(r.items())\n\n",
"In most scenarios, column name is fit for them. But maybe you write the code like follows:\nclass UserModel(BaseModel):\n user_id = Column(\"user_id\", INT, primary_key=True)\n email = Column(\"user_email\", STRING)\n\nthe ... | [
-1,
-1,
-1,
-2,
-2,
-3
] | [
"python",
"sqlalchemy"
] | stackoverflow_0001958219_python_sqlalchemy.txt |
Q:
Is there a more elegant way to fuse two lists of certain keys in a dictionary into one list in a different dictionary?
I have a dictionary with lists as values and i want to concatenate lists of certain keys to one and store it in another dictionary.
Right now i always do this:
plot_history = {}
for key in history... | Is there a more elegant way to fuse two lists of certain keys in a dictionary into one list in a different dictionary? | I have a dictionary with lists as values and i want to concatenate lists of certain keys to one and store it in another dictionary.
Right now i always do this:
plot_history = {}
for key in history.keys():
plot_key = key[3:]
if plot_key in scores:
if plot_key in plot_history.keys():
plot_hist... | [
"You can use dictionary comprehension:\nplot_history = {score: [history[f\"tl_{score}\"], history[f\"ft_{score}\"]] for score in scores}\n\n",
"With defaultdict\nfrom collections import defaultdict\n\nplot_history_dd = defaultdict(list)\nfor key in history.keys():\n plot_key = key[3:]\n if plot_key in score... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074655193_python.txt |
Q:
BS4 not displaying text in Flask
I'm learning Python(Flask) and BeautifulSoup. For my first project I just wanted to wanted to get a video name from YT and display it on the homepage of my web app.
An error returns:
AttributeError: 'NoneType' object has no attribute 'text'
import requests
from flask import Bluepri... | BS4 not displaying text in Flask | I'm learning Python(Flask) and BeautifulSoup. For my first project I just wanted to wanted to get a video name from YT and display it on the homepage of my web app.
An error returns:
AttributeError: 'NoneType' object has no attribute 'text'
import requests
from flask import Blueprint, render_template
from bs4 import Be... | [
"Beautifulsoup can capture only static HTML source code. YT contains the javascript content which is code that runs on the client. Use a tool that can handle javascript, such as, selenium.\nfor example,\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\nurl = 'https://www.youtube.com/'\n\n# your path... | [
1
] | [] | [] | [
"beautifulsoup",
"flask",
"python",
"web_scraping",
"youtube"
] | stackoverflow_0074654051_beautifulsoup_flask_python_web_scraping_youtube.txt |
Q:
Get current user Flask-User
I have step up a basic web app with the Flask-User 1.0 connected it to my Mongodb. And the registration and login work. But once the logged in user enters the member_page I want to be able to send and receive information between the client and server. Planning on using socket.io since I... | Get current user Flask-User | I have step up a basic web app with the Flask-User 1.0 connected it to my Mongodb. And the registration and login work. But once the logged in user enters the member_page I want to be able to send and receive information between the client and server. Planning on using socket.io since I have used it before. But I have ... | [
"From flask import current_user\n"
] | [
0
] | [] | [] | [
"flask",
"flask_login",
"python"
] | stackoverflow_0052263969_flask_flask_login_python.txt |
Q:
Loop or function to make changes in multiple dataframes
Python loop or function to make changes in multiple dataframes (with same headers).
The following loop does not work:
df1 = pd.read_csv('D1.csv')
df2 = pd.read_csv('D2.csv')
P1=['x', 'y', 'z', 'w']
T1=['t1','t2','t3','t4']
df_list = [df1, df2]
for df in df_... | Loop or function to make changes in multiple dataframes | Python loop or function to make changes in multiple dataframes (with same headers).
The following loop does not work:
df1 = pd.read_csv('D1.csv')
df2 = pd.read_csv('D2.csv')
P1=['x', 'y', 'z', 'w']
T1=['t1','t2','t3','t4']
df_list = [df1, df2]
for df in df_list:
#summarize P1 & T1 and store to new columns
df['P... | [
"Your code would probably raise a KeyError when calling pandas.DataFrame.drop and/or a SyntaxError when calling pandas.DataFrame.rename.\nTry this :\nfor df in df_list:\n #summarize P1 & T1 and store to new columns\n df['P'] = df[P1].sum(axis=1)\n df['T'] = df[T1].sum(axis=1)\n\n #drop initial columns P... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074655404_dataframe_pandas_python.txt |
Q:
Calculate implied correlation between two datasets
I have a data set with the growth in student enrollments by college from one year to the next broken down by age bands (18-19, 20-24, etc.). I have another data set with the growth in student enrollments for the same colleges from one year to the next broken down ... | Calculate implied correlation between two datasets | I have a data set with the growth in student enrollments by college from one year to the next broken down by age bands (18-19, 20-24, etc.). I have another data set with the growth in student enrollments for the same colleges from one year to the next broken down by gender (M, F, O). Unfortunately, we don't have access... | [
"It would be nice with an example of what your two datasets look like. However, I will go out on a limb and guess/assume that they look something like this:\n> df_enrollment.head()\n growth age_group college\n0 0.941251 19-35 E\n1 0.787922 19-35 D\n2 0.677788 36-50 C\n3 0.088465 36-5... | [
1
] | [] | [] | [
"correlation",
"data_science",
"excel",
"python"
] | stackoverflow_0074651022_correlation_data_science_excel_python.txt |
Q:
InvalidArgumentError: logits and labels must be broadcastable: logits_size=[10,10] labels_size=[100,10]
I was following a tutorial online where they took a dog and cats dataset and used this data to create a CNN model. I'm working with Animals-10 from kaggle while following the tutorial. When I fit the model, I ge... | InvalidArgumentError: logits and labels must be broadcastable: logits_size=[10,10] labels_size=[100,10] | I was following a tutorial online where they took a dog and cats dataset and used this data to create a CNN model. I'm working with Animals-10 from kaggle while following the tutorial. When I fit the model, I get InvalidArgumentError: logits and labels must be broadcastable: logits_size=[10,10] labels_size=[100,10] [[{... | [
"Your code working:\nimport tensorflow as tf\nfrom tensorflow import keras\nnew_X_train = tf.random.uniform((26179, 100, 100, 1))\nnew_y_train = tf.random.uniform((26179,))\n# Convert labels to categorical\nnew_y_train = keras.utils.to_categorical(new_y_train, 10)\n\n# Create the model\nmodel = keras.models.Sequent... | [
0,
0,
0
] | [] | [] | [
"deep_learning",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0065053050_deep_learning_keras_machine_learning_python_tensorflow.txt |
Q:
Add a pandas column called age based on existing DOB column
I have a column called DOB which has dates formatted 31.07.1983 for example.
My data frame is named users_pd.
I want to add a column that has the current age of the customer based off the existing DOB column.
from datetime import date, timedelta
users_pd[... | Add a pandas column called age based on existing DOB column | I have a column called DOB which has dates formatted 31.07.1983 for example.
My data frame is named users_pd.
I want to add a column that has the current age of the customer based off the existing DOB column.
from datetime import date, timedelta
users_pd["Age"] = (date.today() - users_pd["DOB"] // timedelta(days=365.24... | [
"Convert column to datetime and then convert timedeltas to years:\nusers_pd[\"DOB\"] = pd.to_datetime(users_pd[\"DOB\"], format='%d.%m.%Y')\n\nusers_pd[\"Age\"] = (pd.to_datetime('today') - users_pd[\"DOB\"]).astype('<m8[Y]').astype(int)\n\n",
"Your parenthesis was incorrectly placed, and you probably failed to c... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074655574_dataframe_pandas_python.txt |
Q:
Change default attribution text location in Contextily
Using this code:
import contextily as ctx
from shapely.geometry import box
import geopandas as gpd
minx, miny = 1.612359e+06, 0.950860e+07
maxx, maxy = 4.320331e+06, 1.007808e+07
rectangle = box(minx, miny, maxx, maxy)
gdf = gpd.GeoDataFrame(
index=['Amaz... | Change default attribution text location in Contextily | Using this code:
import contextily as ctx
from shapely.geometry import box
import geopandas as gpd
minx, miny = 1.612359e+06, 0.950860e+07
maxx, maxy = 4.320331e+06, 1.007808e+07
rectangle = box(minx, miny, maxx, maxy)
gdf = gpd.GeoDataFrame(
index=['Amazon'],
geometry=[rectangle],
crs='EPSG:5641')
dy = 1... | [
"It looks like you can't define the attribution in the add_basemap function, and while contextily does provide a more adaptable add_attribution function, that doesn't allow you to specify the text position. There is another way though: manipulate the matplotlib text object generated by add_basemap:\ntxt = ax.texts[... | [
1
] | [] | [] | [
"contextily",
"python"
] | stackoverflow_0070641563_contextily_python.txt |
Q:
TemplateDoesNotExist at / customer/index.html Request Method
enter image description hereenter image description herei get the error of Template does not exist # [[e](https://i.stack.imgur.com/gSKFa.png)](https://i.stack.imgur.com/795HN.png)
this is my urls
when i run i get the error emplateDoesNotExist at / custo... | TemplateDoesNotExist at / customer/index.html Request Method | enter image description hereenter image description herei get the error of Template does not exist # [[e](https://i.stack.imgur.com/gSKFa.png)](https://i.stack.imgur.com/795HN.png)
this is my urls
when i run i get the error emplateDoesNotExist at / customer/index.html Request Method
from django.contrib import admin
fro... | [
"Your Templates settings in settings.py should look like this\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [\"templates\"],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.tem... | [
0
] | [] | [] | [
"conda",
"django",
"miniconda",
"plotly_dash",
"python"
] | stackoverflow_0074655554_conda_django_miniconda_plotly_dash_python.txt |
Q:
Validate class attributes when overwriting using pydantic
I am using Pydantic to validate my class data.
In some cases after the class has been instantiated, I want to overwrite the value of a field, but I want to verify that the new value has the same type as defined in the Model.
I expect I should be able to use... | Validate class attributes when overwriting using pydantic | I am using Pydantic to validate my class data.
In some cases after the class has been instantiated, I want to overwrite the value of a field, but I want to verify that the new value has the same type as defined in the Model.
I expect I should be able to use validators but I haven't seen an option for protecting the fie... | [
"Sorry I found the solution -- use Config and some validator parameters.\nclass MyModel(BaseModel):\n some_field : str = None\n\n class Config:\n validate_assignment = True \n \n \n @validator(\n \"some_field\", always=True, pre=True,\n )\n def verify_string(cls, v):\n ... | [
0
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074655580_pydantic_python.txt |
Q:
How to merge dicts, collecting values from matching keys?
I have multiple dicts (or sequences of key-value pairs) like this:
d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
How can I efficiently get a result like this, as a new dict?
d = {key1: (x1, x2), key2: (y1, y2)}
A:
Here's a general solution that wil... | How to merge dicts, collecting values from matching keys? | I have multiple dicts (or sequences of key-value pairs) like this:
d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
How can I efficiently get a result like this, as a new dict?
d = {key1: (x1, x2), key2: (y1, y2)}
| [
"Here's a general solution that will handle an arbitrary amount of dictionaries, with cases when keys are in only some of the dictionaries:\nfrom collections import defaultdict\n\nd1 = {1: 2, 3: 4}\nd2 = {1: 6, 3: 7}\n\ndd = defaultdict(list)\n\nfor d in (d1, d2): # you can list as many input dicts as you want here... | [
108,
61,
5,
5,
4,
4,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [
"A better representation for two or more dicts with the same keys is a pandas Data Frame IMO:\nd1 = {\"key1\": \"x1\", \"key2\": \"y1\"} \nd2 = {\"key1\": \"x2\", \"key2\": \"y2\"} \nd3 = {\"key1\": \"x3\", \"key2\": \"y3\"} \n\nd1_df = pd.DataFrame.from_dict(d1, orient='index')\nd2_df = pd.DataFrame.from_dict(d... | [
-1,
-1,
-1,
-4
] | [
"dictionary",
"merge",
"python"
] | stackoverflow_0005946236_dictionary_merge_python.txt |
Q:
mpl_connect key_press_event event does not fire in Scrollable Window on Python Matplotlib
I have multiple plot inside scrollable window QT5 widget as below.
class ScrollableWindow(QtWidgets.QMainWindow):
def __init__(self, fig):
self.qapp = QtWidgets.QApplication([])
QtWidgets.QMainWindow.__in... | mpl_connect key_press_event event does not fire in Scrollable Window on Python Matplotlib | I have multiple plot inside scrollable window QT5 widget as below.
class ScrollableWindow(QtWidgets.QMainWindow):
def __init__(self, fig):
self.qapp = QtWidgets.QApplication([])
QtWidgets.QMainWindow.__init__(self)
self.widget = QtWidgets.QWidget()
self.setCentralWidget(self.widget)... | [
"Have a look at this matplotlib issue. Basically, you need to activate the focus of Qt onto your matplotlib canvas.\n self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)\n self.canvas.setFocus()\n\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074650441_matplotlib_python.txt |
Q:
Python distibution package based on local git commit
I am trying to create a python distribution package following https://packaging.python.org/en/latest/tutorials/packaging-projects/. My source folder contains many irrelevant files and subfolders which should be excluded from the distribution, such as temporary f... | Python distibution package based on local git commit | I am trying to create a python distribution package following https://packaging.python.org/en/latest/tutorials/packaging-projects/. My source folder contains many irrelevant files and subfolders which should be excluded from the distribution, such as temporary files, auxiliary code, test output files, private notes, et... | [
"To automatically include files from a Git or Mercurial repository you can use setuptools_scm. The tool can also automatically set the software version from a repository tag and the amount of changes since the tag.\nThe tool prepares data for the standard setuptools.\n"
] | [
1
] | [] | [] | [
"git",
"packaging",
"pip",
"pyproject.toml",
"python"
] | stackoverflow_0074627438_git_packaging_pip_pyproject.toml_python.txt |
Q:
How to return json from FastAPI (Backend) with websocket to vue (Frontend)
I have an application, in which the Frontend is through Vue and the backend is FastAPI, the communication is done through websocket.
Currently, the frontend allows the user to enter a term, which is sent to the backend to generate the autoc... | How to return json from FastAPI (Backend) with websocket to vue (Frontend) | I have an application, in which the Frontend is through Vue and the backend is FastAPI, the communication is done through websocket.
Currently, the frontend allows the user to enter a term, which is sent to the backend to generate the autocomplete and also perform a search on a URL that returns a json. In which, I save... | [
"First, instead of using Python requests module (which would block the event loop, see here for more details), I would highly suggest you use httpx, which offers an async API as well. Have a look at this answer and this answer for more details and working examples.\nSecond, to send data as JSON, you need to use awa... | [
1,
0,
0
] | [] | [] | [
"fastapi",
"html",
"python",
"vue.js",
"websocket"
] | stackoverflow_0074618868_fastapi_html_python_vue.js_websocket.txt |
Q:
Who can help me with python task?
You are given an integer n. There are also three types of operations:
Reduce by 1.
Increase by 1.
If n is evenly divisible by 3, divide n by 3.
For what minimum number of operations can you earn a number in row 1?
Input data
The first line contains one integer n (1≤n≤10
18
).
Outp... | Who can help me with python task? | You are given an integer n. There are also three types of operations:
Reduce by 1.
Increase by 1.
If n is evenly divisible by 3, divide n by 3.
For what minimum number of operations can you earn a number in row 1?
Input data
The first line contains one integer n (1≤n≤10
18
).
Output data
Output one number - the minimum... | [
"To solve this problem in Python without using functions, you can use a while loop to iterate over the different operations until the number reaches 1.\nHere is one possible solution:\n# Get the input number\nn = int(input())\n\n# Initialize the number of operations to 0\nnum_ops = 0\n\n# Keep looping until the num... | [
1
] | [] | [] | [
"math",
"python",
"solver"
] | stackoverflow_0074655717_math_python_solver.txt |
Q:
specific sumproduct list comprehension in pandas
suppose i have a dataframe
df = pd.DataFrame({"age" : [0, 5, 10, 15, 20], "income": [5, 13, 23, 18, 12]})
age income
0 0 5
1 5 13
2 10 23
3 15 18
4 20 12
i want to iterate through df["income"] and calculate the sumproduct a... | specific sumproduct list comprehension in pandas | suppose i have a dataframe
df = pd.DataFrame({"age" : [0, 5, 10, 15, 20], "income": [5, 13, 23, 18, 12]})
age income
0 0 5
1 5 13
2 10 23
3 15 18
4 20 12
i want to iterate through df["income"] and calculate the sumproduct as follows (example for age 15): 18+23*(15-10)+13*(15-... | [
"Numpy solution - you can use broadcasting for avoid loops for improve performance:\ndf = pd.DataFrame({\"age\" : [0, 5, 10, 15, 20], \"income\": [5, 13, 23, 18, 12]})\n\ninterest = 1.03\nage = df['age'].to_numpy()\n\nUse power with subtracted values of mask:\narr = interest ** (age[:, None] - age ) \nprint (arr)\n... | [
2,
1,
0
] | [] | [] | [
"list_comprehension",
"pandas",
"python",
"sumproduct"
] | stackoverflow_0074655392_list_comprehension_pandas_python_sumproduct.txt |
Q:
AttributeError: 'InputStream' object has no attribute 'decode' using pandas_read_xml to flatten xml
I'm still a beginner to this, but I will try to explain my problem as coherently as I can.
In case you're not familiar with Azure Cloud programming, I have a "blob trigger" where this script runs or triggers when a ... | AttributeError: 'InputStream' object has no attribute 'decode' using pandas_read_xml to flatten xml | I'm still a beginner to this, but I will try to explain my problem as coherently as I can.
In case you're not familiar with Azure Cloud programming, I have a "blob trigger" where this script runs or triggers when a file is uploaded into a container in Azure. When this script triggers it passes an InputStream object to ... | [
"\nAttributeError: 'InputStream' object has no attribute 'decode'\n\nIn General, this error will occur because of decoding the already decoded string. If your Azure Functions Python Version is 3.X, then no need to decode.\nIf it is throwing the decode error, there is some error in datatype of that object so you sho... | [
0
] | [] | [] | [
"azure_functions",
"dataframe",
"pandas",
"python",
"xml"
] | stackoverflow_0074539979_azure_functions_dataframe_pandas_python_xml.txt |
Q:
Upload files and resume in azure blob storage python
Below is the code for uploading files in chunks:
azure_container = "dummy-container"
file_path = "test.txt"
chunk_size=4*1024*1024
blob_service_client = BlobServiceClient.from_connection_string(azure_connection_string)
blob_client = blob_service_client.get_bl... | Upload files and resume in azure blob storage python | Below is the code for uploading files in chunks:
azure_container = "dummy-container"
file_path = "test.txt"
chunk_size=4*1024*1024
blob_service_client = BlobServiceClient.from_connection_string(azure_connection_string)
blob_client = blob_service_client.get_blob_client(container=azure_container, blob="testingfile.tx... | [
"For this \"async\" and \"await\" is working fine. But if there is better solution then please post.\nasync def uploadin_files(file_path):\n for files_to_upload in file_path:\n time.sleep(2)\n blob_client = blob_service_client.get_blob_client(container=azure_container, blob=files_to_upload)\n ... | [
0
] | [] | [] | [
"azure_active_directory",
"azure_blob_storage",
"azure_files",
"chunks",
"python"
] | stackoverflow_0074653289_azure_active_directory_azure_blob_storage_azure_files_chunks_python.txt |
Q:
Google Cloud Function: Access folders in a Google Storage bucket and process files from them
I'm fairly new to GCP and I'm trying to write a Google Cloud Function that would be triggered by a new file once it appears in a bucket. I made this work, but the thing is that the Cloud Function is also supposed to perfor... | Google Cloud Function: Access folders in a Google Storage bucket and process files from them | I'm fairly new to GCP and I'm trying to write a Google Cloud Function that would be triggered by a new file once it appears in a bucket. I made this work, but the thing is that the Cloud Function is also supposed to perform another action: it needs to access a folder which is already present the bucket (that means, bef... | [
"As mentioned in the comments listing using glob does not work as it intended for local filesystem.\nThus the minimal example to list objects underneath some virtual folder in object storage on GCS (Google cloud storage) might look like this:\n#!/usr/bin/env python\n\nfrom google.cloud import storage\nimport os\n\n... | [
0
] | [] | [] | [
"google_cloud_functions",
"google_cloud_platform",
"python"
] | stackoverflow_0074645979_google_cloud_functions_google_cloud_platform_python.txt |
Q:
RTSP on Django using OpenCV
I need to stream a surveillance camera onto a Django based website. I found a tutorial on Youtube but it is very simple. Down below is my code:
from django.shortcuts import render
from django.views.decorators import gzip
from django.http import StreamingHttpResponse
import cv2
# Creat... | RTSP on Django using OpenCV | I need to stream a surveillance camera onto a Django based website. I found a tutorial on Youtube but it is very simple. Down below is my code:
from django.shortcuts import render
from django.views.decorators import gzip
from django.http import StreamingHttpResponse
import cv2
# Create your views here.
@gzip.gzip_pa... | [
"try this in class videoCamera dont forget to import threading\nclass VideoCamera(object):\n def __init__(self):\n self.video = cv2.VideoCapture(\"put your video link here\")\n (self.grabbed , self.frame) = self.video.read()\n threading.Thread(target=self.update , args=()).start()\n \n \n ... | [
0
] | [] | [] | [
"django",
"opencv",
"python"
] | stackoverflow_0074342952_django_opencv_python.txt |
Q:
Time difference with datetime
I have a variable called df with three colums with the following data in datetime64:
start_time
end_time
extra_time
2022-12-01 09:53:02
2022-12-05 09:53:21
1 days 23:30:15
I want to add a 4th column saying that if extra_time is positive, then it's Intime. Otherwise, it's offtime.
I... | Time difference with datetime | I have a variable called df with three colums with the following data in datetime64:
start_time
end_time
extra_time
2022-12-01 09:53:02
2022-12-05 09:53:21
1 days 23:30:15
I want to add a 4th column saying that if extra_time is positive, then it's Intime. Otherwise, it's offtime.
I tried using for like this... | [
"Convert to timedelta\ndf[\"extra_time\"] = pd.to_timedelta(df[\"extra_time\"]).dt.total_seconds()\ndf[\"intime\"] = df[\"extra_time\"] >= 0\n\noutput:\n start_time end_time extra_time intime\n0 2022-12-01 09:53:02 2022-12-05 09:53:21 171015.0 True\n1 2022-12-01 10:53:02 2022-12-0... | [
2
] | [] | [] | [
"datetime",
"pandas",
"python",
"timedelta"
] | stackoverflow_0074655775_datetime_pandas_python_timedelta.txt |
Q:
Print nested list in a particular way
I have this list:
top_list = [['Recent news', '52', '15.1'], ['Godmorning', '5', '1.5'], ['Sports news', '47', '13.7'], ['Report with weather', '34', '9.9'], ['The angel and the lawless', '33', '9.6'], ['Thundercats', '3', '0.9'], ["Mother's legacy", '3', '0.9'], ['UR: Summer ... | Print nested list in a particular way | I have this list:
top_list = [['Recent news', '52', '15.1'], ['Godmorning', '5', '1.5'], ['Sports news', '47', '13.7'], ['Report with weather', '34', '9.9'], ['The angel and the lawless', '33', '9.6'], ['Thundercats', '3', '0.9'], ["Mother's legacy", '3', '0.9'], ['UR: Summer evenings with Europe of the Times', '3', '0... | [
"To format the list of programs as shown in your example, you can use a for loop to iterate over the elements in the top_list array, and print each program's name, viewer count, and percentage in the desired format.\nHere is an example of how you could implement this:\ntop_list = [['Recent news', '52', '15.1'], ['G... | [
0
] | [] | [] | [
"list",
"nested",
"printing",
"python",
"string"
] | stackoverflow_0074655847_list_nested_printing_python_string.txt |
Q:
How to draw only outer edges on a 3D shape
I am working on a physics simulator that takes in a bunch of mass coordinates and applies spring forces to each mass. I'm trying to draw only outer edges of the 3D shape. In a simple case, the shape is at first a cube, and then because of gravity and spring forces the cub... | How to draw only outer edges on a 3D shape | I am working on a physics simulator that takes in a bunch of mass coordinates and applies spring forces to each mass. I'm trying to draw only outer edges of the 3D shape. In a simple case, the shape is at first a cube, and then because of gravity and spring forces the cube deforms. I'm sort of able to draw the outer ed... | [
"I don't know what is a deformed cube but once you have the vertices of a convex polyhedron, you can get and plot its edges as follows.\nTo get the convex hull and its edges, use pycddlib (the cdd library):\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport cdd as pcdd\nimport matplotlib.pyplot as plt\n\n# vertic... | [
0
] | [] | [] | [
"3d",
"class",
"math",
"matplotlib",
"python"
] | stackoverflow_0074637925_3d_class_math_matplotlib_python.txt |
Q:
Flask.redirect(url_for()) not redirecting
So I know that there are many already similar question and I've browsed about 5 now.
Problem is, though, I can't seem to find a similar problem to mine. Here's the deal:
When posting my form, I get from the server:
> 127.0.0.1 - - [02/Dec/2022 10:37:53] "POST /create-artis... | Flask.redirect(url_for()) not redirecting | So I know that there are many already similar question and I've browsed about 5 now.
Problem is, though, I can't seem to find a similar problem to mine. Here's the deal:
When posting my form, I get from the server:
> 127.0.0.1 - - [02/Dec/2022 10:37:53] "POST /create-artist HTTP/1.1" 302 -
> 127.0.0.1 - - [02/Dec/2022 ... | [
"You can't redirect page through flask(back end) if posting form through JS(front end). You need to use JS redirection method for that because you are getting response in JS call where you can redirect based on response from back end.\n"
] | [
1
] | [] | [] | [
"flask",
"javascript",
"python",
"redirect"
] | stackoverflow_0074653786_flask_javascript_python_redirect.txt |
Q:
I want to convert multiple characters to Python regular expressions
I want to convert only numbers in this str
"ABC234TSY65234525erQ"
I tried to change only areas with numbers to the * sign
This is what I wanted
"ABC*TSY*erQ"
But when I actually did it, it came out like this
"ABC***TSY********erQ"
How do I chan... | I want to convert multiple characters to Python regular expressions | I want to convert only numbers in this str
"ABC234TSY65234525erQ"
I tried to change only areas with numbers to the * sign
This is what I wanted
"ABC*TSY*erQ"
But when I actually did it, it came out like this
"ABC***TSY********erQ"
How do I change it?
Thanks you!
| [
"use \\d+. + in a regular expression means \"match the preceding character one or more times\"\nimport re\ns = re.sub(r'\\d+', '*', s)\n\noutput:\n'ABC*TSY*erQ'\n\n",
"The re.sub() solution given by @JayPeerachi is probably the best option, but we could also use re.findall() here:\ninp = \"ABC234TSY65234525erQ\"\... | [
1,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0074655880_python_regex_string.txt |
Q:
Np.where with optional condition
For my database I need to create a new column based on a condition.
In a seperate file I have add all the conditions like this:
conditions = [{year: 2016, price: 30000, fuel: Petrol, result: 12},
{year: 2017, price: 45000, fuel: Elektricity, result: 18},
... | Np.where with optional condition | For my database I need to create a new column based on a condition.
In a seperate file I have add all the conditions like this:
conditions = [{year: 2016, price: 30000, fuel: Petrol, result: 12},
{year: 2017, price: 45000, fuel: Elektricity, result: 18},
{year: 2018, price: None, fuel: Petro... | [
"you can reduce the conditions to separate the creation of each condition from their application, you will need an if conditions for each optional condition, but not their combinations.\nfrom operator import and_\nfrom functools import reduce\n\nconditions = []\nif dict['year'] != None:\n conditions.append(df['y... | [
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074655786_numpy_pandas_python.txt |
Q:
Create a single categorical variable based on many dummy variables
I have several category dummies that are mutually exclusive
id cat1 cat2 cat3
A 0 0 1
B 1 0 0
C 1 0 0
D 0 0 1
E 0 1 0
F 0 0 1
..
I want to create a new column that contains all categories
id ... | Create a single categorical variable based on many dummy variables | I have several category dummies that are mutually exclusive
id cat1 cat2 cat3
A 0 0 1
B 1 0 0
C 1 0 0
D 0 0 1
E 0 1 0
F 0 0 1
..
I want to create a new column that contains all categories
id cat1 cat2 cat3 type
A 0 0 1 cat3
B 1 0 0 cat1
C ... | [
"You can use pandas.from_dummies and filter to select the columns starting with \"cat\":\ndf['type'] = pd.from_dummies(df.filter(like='cat'))\n\nOutput:\n id cat1 cat2 cat3 type\n0 A 0 0 1 cat3\n1 B 1 0 0 cat1\n2 C 1 0 0 cat1\n3 D 0 0 1 cat3\n4 E 0 ... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074656004_dataframe_pandas_python.txt |
Q:
PyBind11 destructor not invoked?
I have a c++ class wrapped with PyBind11. The issue is: when the Python script ends the c++ destructor is not being automatically invoked. This causes an untidy exit because networking resources need to be released by the destructor.
As a work-around it is necessary to explicitly ... | PyBind11 destructor not invoked? | I have a c++ class wrapped with PyBind11. The issue is: when the Python script ends the c++ destructor is not being automatically invoked. This causes an untidy exit because networking resources need to be released by the destructor.
As a work-around it is necessary to explicitly delete the Python object, but I don't ... | [
"As was mentioned in a comment, the proximate cause of this behavior is the Python garbage collector: When the reference counter for an object gets to zero, the garbage collector may destroy the object (and thereby invoke the c++ destructor) but it doesn't have to do it at that moment.\nThis idea is elaborated mor... | [
0,
0,
0
] | [] | [] | [
"c++",
"destructor",
"pybind11",
"python"
] | stackoverflow_0055452762_c++_destructor_pybind11_python.txt |
Q:
Modify the range of values of the color bar of a graph in python
I have the following issue.
I have a graph of which has colored segments. The problem is in relating those segments to the color bar (which also contains text), so that each color segment is aligned with the color bar.
The code is the following:
fro... | Modify the range of values of the color bar of a graph in python | I have the following issue.
I have a graph of which has colored segments. The problem is in relating those segments to the color bar (which also contains text), so that each color segment is aligned with the color bar.
The code is the following:
from matplotlib.colorbar import colorbar_factory
x_v = datosg["Hour"]+div... | [
"I guess it's much easier to just draw a second Axes and fill it with axhspans the same way you did it with the main Axes, but if you want to use a colorbar, you can do it as follows:\nimport itertools\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncolors = ['green', 'blue','red',... | [
0
] | [] | [] | [
"colorbar",
"matplotlib",
"python"
] | stackoverflow_0074651289_colorbar_matplotlib_python.txt |
Q:
how to qoute comma in printf that is used with rofi?
I'm creating a project to display keybindings of different wms using rofi but I always get this error in rofi or maybe due to printf
full code
Mode r} bspc {quitwm r}
' is not found
the lines it is trying to display using printf and subprocess
super + alt ... | how to qoute comma in printf that is used with rofi? | I'm creating a project to display keybindings of different wms using rofi but I always get this error in rofi or maybe due to printf
full code
Mode r} bspc {quitwm r}
' is not found
the lines it is trying to display using printf and subprocess
super + alt + {q ,r} # I reckon the comma is causing the error
bsp... | [
"The error message you are seeing is likely due to the comma in the printf command you are using in your code. In the Bash shell, the comma is used as a command separator, so the shell is trying to treat the text after the comma as a separate command.\nTo fix this issue, you can escape the comma in the printf comma... | [
0
] | [] | [] | [
"formatting",
"printf",
"python",
"shell",
"string"
] | stackoverflow_0074656049_formatting_printf_python_shell_string.txt |
Q:
Exploding a data frame row by row and storing the exploded values in a new dataframe
I have the following code.
I want to go through the 'outlierdataframe' dataframe row by row and explode the values in the 'x' and 'y' columns.
For each exploded row, I then want to store this exploded row as its own dataframe, wit... | Exploding a data frame row by row and storing the exploded values in a new dataframe | I have the following code.
I want to go through the 'outlierdataframe' dataframe row by row and explode the values in the 'x' and 'y' columns.
For each exploded row, I then want to store this exploded row as its own dataframe, with columns 'newID', 'x' and 'y'.
However, the following code prints everything in one colum... | [
"You can use pandas.DataFrame.apply with pandas.Series.explode to explode your selected (list) columns (e.g, x and y).\nTry this :\nout = (\n df\n .loc[:, [\"newID\", \"x\", \"y\"]]\n .apply(lambda x: pd.Series(x).explode())\n )\n\n# Output :\nprint(out)\n\n newID x y\n0 6100... | [
1,
0
] | [] | [] | [
"dataframe",
"indexing",
"numpy",
"pandas",
"python"
] | stackoverflow_0074655919_dataframe_indexing_numpy_pandas_python.txt |
Q:
4 bit per pixel image from binary file in Python with Numpy and CV2?
Suppose I want to represent binary data as a black and white image, with only sixteen distinct levels for the gray values for each pixel so that each two adjacent pixels (lengthwise) represent a single byte. How can I do this? If, for example, I ... | 4 bit per pixel image from binary file in Python with Numpy and CV2? | Suppose I want to represent binary data as a black and white image, with only sixteen distinct levels for the gray values for each pixel so that each two adjacent pixels (lengthwise) represent a single byte. How can I do this? If, for example, I use the following:
import numpy as np
path = r'mybinaryfile.bin'
bin_data ... | [
"I have understood that you want to take an 8-bit number and split the upper four bits and the lower four bits.\nThis can be done with a couple of bitwise operations.\ndef split_octet(data):\n \"\"\"\n For each 8-bit number in array, split them into two 4-bit numbers\"\"\"\n split_data = []\n for octet ... | [
1
] | [] | [] | [
"bits_per_pixel",
"image",
"numpy",
"opencv",
"python"
] | stackoverflow_0074636650_bits_per_pixel_image_numpy_opencv_python.txt |
Q:
Python. Deleting Excel rows while iterating. Alternative for OpenPyXl or solution for ws.max_rows wrong output
I'm working with Python on Excel files. Until now I was using OpenPyXl. I need to iterate over the rows and delete some of them if they do not meet specific criteria let's say I was using something like:
... | Python. Deleting Excel rows while iterating. Alternative for OpenPyXl or solution for ws.max_rows wrong output | I'm working with Python on Excel files. Until now I was using OpenPyXl. I need to iterate over the rows and delete some of them if they do not meet specific criteria let's say I was using something like:
current_row = 1
while current_row <= ws.max_row
if 'something' in ws[f'L{row}'].value:
data_ws.delete_ro... | [
"If max rows doesn't report what you expect you'll need to sort the issue best you can and perhaps that might be by manually deleting; \"delete those entire rows by selecting rows number on the left of your spreadsheet and deleting them (right click on selected row number(s) -> Delete)\" or making some other determ... | [
0
] | [] | [] | [
"delete_row",
"excel",
"iteration",
"openpyxl",
"python"
] | stackoverflow_0074647281_delete_row_excel_iteration_openpyxl_python.txt |
Q:
How to more efficiently test if data anomalies occur in transaction (Django)
I want to test if data anomalies such as dirty read, non-repeatable read, phantom read, lost update and so on occur in transaction.
Actually, I used person table which has id and name as shown below.
person table:
id
name
1
John
2
Davi... | How to more efficiently test if data anomalies occur in transaction (Django) | I want to test if data anomalies such as dirty read, non-repeatable read, phantom read, lost update and so on occur in transaction.
Actually, I used person table which has id and name as shown below.
person table:
id
name
1
John
2
David
Then, I tested non-repeatable read with test view below and one comma... | [
"With threads, you can more efficiently test if data anomalies occur in transaction.\nI created 5 sets of code with threads to test 5 common data anomalies dirty read, non-repeatable read, phantom read, lost update and write skew with the Django's default isolation level READ COMMITTED and PostgreSQL as shown below... | [
0
] | [] | [] | [
"data_anomalies",
"django",
"python",
"python_3.x",
"testing"
] | stackoverflow_0074183272_data_anomalies_django_python_python_3.x_testing.txt |
Q:
Extracting the first day of month of a datetime type column in pandas
I have the following dataframe:
user_id purchase_date
1 2015-01-23 14:05:21
2 2015-02-05 05:07:30
3 2015-02-18 17:08:51
4 2015-03-21 17:07:30
5 2015-03-11 18:32:56
6 2015-03-03 11:02:30
... | Extracting the first day of month of a datetime type column in pandas | I have the following dataframe:
user_id purchase_date
1 2015-01-23 14:05:21
2 2015-02-05 05:07:30
3 2015-02-18 17:08:51
4 2015-03-21 17:07:30
5 2015-03-11 18:32:56
6 2015-03-03 11:02:30
and purchase_date is a datetime64[ns] column. I need to add a new column df... | [
"Simpliest and fastest is convert to numpy array by to_numpy and then cast:\ndf['month'] = df['purchase_date'].to_numpy().astype('datetime64[M]')\nprint (df)\n user_id purchase_date month\n0 1 2015-01-23 14:05:21 2015-01-01\n1 2 2015-02-05 05:07:30 2015-02-01\n2 3 2015-02-18 17:08:... | [
98,
13,
11,
8,
6,
3,
2,
0,
0
] | [
"try this Pandas libraries, where 'purchase_date' is date parameter placed into the module.\ndate['month_start'] = pd.to_datetime(sched_slim.purchase_date)\n.dt.to_period('M')\n.dt.to_timestamp()\n\n"
] | [
-1
] | [
"dataframe",
"datetime64",
"pandas",
"python"
] | stackoverflow_0045304531_dataframe_datetime64_pandas_python.txt |
Q:
Jinja2 - getting users selected value from a table and saving it as a variable
So, I am trying to develop a small site where the user selects a time from a drop-down box and that time select gets displayed on another page. I am struggling to capture the user's input from the drop-down box and send it to the functi... | Jinja2 - getting users selected value from a table and saving it as a variable | So, I am trying to develop a small site where the user selects a time from a drop-down box and that time select gets displayed on another page. I am struggling to capture the user's input from the drop-down box and send it to the function which generates the page that shows the users selected input.
I generate the drop... | [
"Create a java-script based onClickEvent(). Which should be triggered when clicked on the value in drop-down and post data to back-end application and then capture response and process accordingly.\nHelpful Blog:-\nCrud Using Ajax and JSON\n"
] | [
0
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0074655674_flask_jinja2_python.txt |
Q:
Problems with gradient in python
I'm trying to estimate the gradient of my graph.
#define the function
def gradient(y1,y2,x1,x2):
gradient = ((y1 - y2)/(x2 - x1))
y1 = 1.07
y2 = 1.39
x1 = 283
x2 = 373
print('The gradient of this graph is', gradient)
All it prints is
The gradient of this graph ... | Problems with gradient in python | I'm trying to estimate the gradient of my graph.
#define the function
def gradient(y1,y2,x1,x2):
gradient = ((y1 - y2)/(x2 - x1))
y1 = 1.07
y2 = 1.39
x1 = 283
x2 = 373
print('The gradient of this graph is', gradient)
All it prints is
The gradient of this graph is <function gradient at 0x7fb95096bd3... | [
"It looks like you're trying to print the value of the gradient function, rather than calling it and printing the result. You can fix this by adding parentheses after gradient to call the function, and by providing the function with the necessary arguments:\nprint('The gradient of this graph is', gradient(y1, y2, x... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074656137_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.