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:
Calculate Psi/Phi and/or dihaedral Pymol - Pymol API
I'm struggling a bit tryng to calculate multiple dihedral through residues just giving the atom name. Basically I'd like to interate the dihaedral calcualtion all around a protein / RNA.
For now I'm arrived here:
def myfunc(model,chain,segi,resn,resi,name):
... | Calculate Psi/Phi and/or dihaedral Pymol - Pymol API | I'm struggling a bit tryng to calculate multiple dihedral through residues just giving the atom name. Basically I'd like to interate the dihaedral calcualtion all around a protein / RNA.
For now I'm arrived here:
def myfunc(model,chain,segi,resn,resi,name):
s1 = "/%s/%s/%s/%s`%s/CB" % (model,chain,segi,resn,resi)
... | [
"If I understood you correctly, this should be close to what you are looking for:\ndef dihedral_res(model, segi, chain, resn, resi):\n s1 = \"/{}/{}/{}/{}`{}/CB\".format(model, segi, chain, resn, resi)\n s2 = \"/{}/{}/{}/{}`{}/CA\".format(model, segi, chain, resn, resi)\n s3 = \"/{}/{}/{}/{}`{}/N\".format(... | [
0
] | [] | [] | [
"bioinformatics",
"pymol",
"python"
] | stackoverflow_0074214897_bioinformatics_pymol_python.txt |
Q:
How to convert multi-page pdf to single html file
I'm implementing poppler pdftohtml method to convert pdf to html. I'm trying to run the exec file via python.
import subprocess
subprocess.Popen([r"D:/poppler-0.68.0/bin/pdftohtml.exe" , 'name.pdf', 'name.html'])
Using the above code I'm getting my html file and ... | How to convert multi-page pdf to single html file | I'm implementing poppler pdftohtml method to convert pdf to html. I'm trying to run the exec file via python.
import subprocess
subprocess.Popen([r"D:/poppler-0.68.0/bin/pdftohtml.exe" , 'name.pdf', 'name.html'])
Using the above code I'm getting my html file and also the images(.jpg) of each and every page in pdf.
I ... | [
"According to their documentation there might be two options that could help you out with that:\n-i ignore images\nand\n-s generate single HTML that includes all pages\nIf these don't work, there's nothing else you could do.\n",
"Use -noframes, it will generate one file.\nAccording to help:\nUsage: pdftohtml [opt... | [
0,
0
] | [] | [] | [
"poppler",
"python"
] | stackoverflow_0055473203_poppler_python.txt |
Q:
How to subscribe to GCP Pub/Sub when running a server of Django?
I have a backend service using django, I need to subscribe a message queue hosted on GCP pub/sub
Here's the example code provided by Google:
https://cloud.google.com/pubsub/docs/pull
Implementing a function is easy,
but I will have to start the djang... | How to subscribe to GCP Pub/Sub when running a server of Django? | I have a backend service using django, I need to subscribe a message queue hosted on GCP pub/sub
Here's the example code provided by Google:
https://cloud.google.com/pubsub/docs/pull
Implementing a function is easy,
but I will have to start the django server via the command like:
python manage.py runserver
Or ASGI com... | [
"Add new process as below format in Django\ntaskApp/\n __init__.py\n models.py\n management/\n __init__.py\n commands/\n __init__.py\n task_process.py\n\nIn startup.sh add below command\n#!/bin/sh\ngunicorn --bind :8000 --workers 3 --worker-class uvicorn.workers.UvicornW... | [
1
] | [] | [] | [
"django",
"google_cloud_platform",
"google_cloud_pubsub",
"python"
] | stackoverflow_0066328787_django_google_cloud_platform_google_cloud_pubsub_python.txt |
Q:
I want to delete values from an interval of keys from a list of key value pair
I want to make a function to delete some values from an interval given by two keys from a list of key value pairs in Python.
I've tried a lot of things, I already googled it a lot. This is the list of key value pair:
[{"day": 1, "sum": ... | I want to delete values from an interval of keys from a list of key value pair | I want to make a function to delete some values from an interval given by two keys from a list of key value pairs in Python.
I've tried a lot of things, I already googled it a lot. This is the list of key value pair:
[{"day": 1, "sum": 25, "type": in}, {"day": 2, "sum": 55, "type": in}, {"day": 3, "sum": 154, "type": o... | [
"You should not try to modify a list or any other mutable object while enumerating it. Best practice is to create a new object - a list in this case.\nInput data adjusted to make it valid Python.\n_in = 0\n_out = 0\n\n_list = [{\"day\": 1, \"sum\": 25, \"type\": _in}, {\"day\": 2, \"sum\": 55, \"type\": _in}, {\"da... | [
3,
1,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074220341_dictionary_list_python.txt |
Q:
calculating daily average across 30 years for different variables
I'm working with a dataframe that has daily information (measured data) across 30 years for different variables. I am trying to groupby days of the year, and then find a mean across 30 years. How do I go about this? This is what the dataframe looks ... | calculating daily average across 30 years for different variables | I'm working with a dataframe that has daily information (measured data) across 30 years for different variables. I am trying to groupby days of the year, and then find a mean across 30 years. How do I go about this? This is what the dataframe looks like
I tried to groupby day after checking for type of YYYYMMDD (it's ... | [
"You can groupby with month and day:\ndf.index = pd.to_datetime(df.index)\n( df.groupby([df.index.month, df.index.day]).mean().reset_index().\n rename({'level_0':'month', 'level_1':'day'}, axis=1))\n\nor if you want to group them by the day of year, i.e. 1, 2, .. 365, set as_index=False:\ndf.groupb... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074220861_pandas_python.txt |
Q:
Django PermissionDenied return error 500 instead of 403
So, in my Django 4.0 project, I have a Class-Based View that inherits UserPassesTestMixin.
If the test_func returns False it throws a PermissionDenied exception which in its turn must return 403.html
But instead of 403, I'm getting a 500 server error.
I read ... | Django PermissionDenied return error 500 instead of 403 | So, in my Django 4.0 project, I have a Class-Based View that inherits UserPassesTestMixin.
If the test_func returns False it throws a PermissionDenied exception which in its turn must return 403.html
But instead of 403, I'm getting a 500 server error.
I read in Django docs that PermissionDenied must trigger the django.... | [
"The bug was due to using of my custom middleware that catches all unhandled exceptions and returns 500 errors (and logs them).\nSo I have just caught the PermissionDenied exception there and returned the right 403 error.Overdone a little with middleware. Thanks to all.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074220458_django_python.txt |
Q:
Regular expression to extract substrings in python pandas
I have a data frame column name "New" below
df = pd.DataFrame({'New' : ['emerald shines bright(happy)(ABCED ID - 1234556)', 'honey in the bread(ABCED ID - 123467890)','http/ABCED/id/234555', 'healing strenght(AxYBD ID -1234556)', 'this is just a text'],
'UI... | Regular expression to extract substrings in python pandas | I have a data frame column name "New" below
df = pd.DataFrame({'New' : ['emerald shines bright(happy)(ABCED ID - 1234556)', 'honey in the bread(ABCED ID - 123467890)','http/ABCED/id/234555', 'healing strenght(AxYBD ID -1234556)', 'this is just a text'],
'UI': ['AOT', 'BOT', 'LOV', 'HAP', 'NON']})
Now I want to extract... | [
"Probably not the most elegant answer, however, I think this does what you want it to do, based on the NEW criteria.\nimport re\n\ndf = pd.DataFrame({'New' : ['emerald shines bright(happy)(ABCED ID - 1234556)', 'honey in the bread(ABCED ID - 123467890)','http/ABCED/id/234555', 'healing strenght(AxYBD ID -1234556)',... | [
2,
1,
0
] | [
"r'[i,d,I,D]{2}.*?(\\d.*?)\\D' probably this one help\nEdited: /?\\(?(\\w{5}) ?/?[i,d,I,D]{2} it's looks like you need letters, not digits\n"
] | [
-1
] | [
"pandas",
"python",
"regex",
"substring"
] | stackoverflow_0074220370_pandas_python_regex_substring.txt |
Q:
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField'
After upgrading djangorestframework from djangorestframework==3.13.1 to djangorestframework==3.14.0 the code
from rest_framework.serializers import NullBooleanField
Throws
AttributeError: module 'rest_framework.serializers' h... | AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' | After upgrading djangorestframework from djangorestframework==3.13.1 to djangorestframework==3.14.0 the code
from rest_framework.serializers import NullBooleanField
Throws
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField'
Reading the release notes I don't see a deprecation. Wher... | [
"For what it's worth, there's a deprecation warning in the previous version, which also suggests a fix:\n\nThe NullBooleanField is deprecated and will be removed starting with 3.14. Instead use the BooleanField field and set allow_null=True which does the same thing.\n\n"
] | [
3
] | [] | [] | [
"django",
"django_rest_framework",
"drf_spectacular",
"python"
] | stackoverflow_0073823743_django_django_rest_framework_drf_spectacular_python.txt |
Q:
Parsing json using Python in Azure function app - cannot remove elements
I am trying to remove elements from a json doc. Here's the input json.
{
"start": {
"docId": "3723",
"data": {
"dId": null,
"innerprops": {
"pId": "4573",
"stat": {
... | Parsing json using Python in Azure function app - cannot remove elements | I am trying to remove elements from a json doc. Here's the input json.
{
"start": {
"docId": "3723",
"data": {
"dId": null,
"innerprops": {
"pId": "4573",
"stat": {
"statId": "7578",
"portaldata": [
... | [
"You can do with list comprehension,\nfor entry in data[\"start\"][\"data\"][\"innerprops\"][\"stat\"][\"portaldata\"]:\n entry[\"pairs\"] = [pair for pair in entry[\"pairs\"] if pair[\"id\"] == '1111']\n\nResult:\n{'start': {'data': {'dId': None,\n 'innerprops': {'pId': '4573',\n ... | [
0
] | [] | [] | [
"azure_functions",
"json",
"python"
] | stackoverflow_0074221102_azure_functions_json_python.txt |
Q:
How to filter based on friends of the logged in user?
I'm doing a leaderboard which it works when filtering from all users. But here I would like to filter based on the friends of the user.
This is how I get a list of friends :
users = self.request.user.friends
and this is my view :
class FriendsDayLeaderBoard(Li... | How to filter based on friends of the logged in user? | I'm doing a leaderboard which it works when filtering from all users. But here I would like to filter based on the friends of the user.
This is how I get a list of friends :
users = self.request.user.friends
and this is my view :
class FriendsDayLeaderBoard(ListAPIView):
"""
List friends Leaderboard based on ... | [
"If you want to filter UserLeaderBoardTracking only for friends of current user, if i understood your post, you can do like this:\nclass FriendsDayLeaderBoard(ListAPIView):\n \"\"\"\n List friends Leaderboard based on XP token by Day\n\n Get request\n \"\"\"\n serializer_class = UserLeaderboardSerial... | [
0
] | [] | [] | [
"django",
"leaderboard",
"python"
] | stackoverflow_0074219322_django_leaderboard_python.txt |
Q:
OpenCV error img is incompatible with cv::Mat
Just realized of a surprising thing when using the following code:
import cv2
import numpy as np
a = np.zeros((720, 1280, 2), dtype=np.uint8)
b = np.zeros((720, 1280), dtype=np.uint8)
cv2.circle(b, (100,100),3,1,-1) # works
cv2.circle(a[..., 0], (100,100),3,1,-1) ... | OpenCV error img is incompatible with cv::Mat | Just realized of a surprising thing when using the following code:
import cv2
import numpy as np
a = np.zeros((720, 1280, 2), dtype=np.uint8)
b = np.zeros((720, 1280), dtype=np.uint8)
cv2.circle(b, (100,100),3,1,-1) # works
cv2.circle(a[..., 0], (100,100),3,1,-1) # does not work
Calling exactly same function with... | [
"when translating between numpy arrays and OpenCV cv::Mat, OpenCV's bindings require the numpy array to be contiguous.\nNumpy slicing commonly produces non-contiguous arrays because it merely adjusts strides and offsets, yet still refers to the entire original data.\nThe simplest way to \"fix\" this is to make a co... | [
2
] | [] | [] | [
"numpy",
"opencv",
"python"
] | stackoverflow_0074219062_numpy_opencv_python.txt |
Q:
How to read a line from text file (file containing logs) and remove timestamp IF it's there?
I am writing an automated code that opens a text file and reads it line by line:
if __name__ == '__main__':
#Argument Required: Full directory of log file for processing
parser = ArgumentParser()
parser.add_a... | How to read a line from text file (file containing logs) and remove timestamp IF it's there? | I am writing an automated code that opens a text file and reads it line by line:
if __name__ == '__main__':
#Argument Required: Full directory of log file for processing
parser = ArgumentParser()
parser.add_argument("--logDestination", dest="logDest", help="Provide the directory of the log file")
args... | [
"I'm only just learning Python myself at the moment, so this might not be the best solution, but my first thought was a regular expression, something like this:\nimport re\n\n# other code...\n\nreTimestamp = r'\\d{2}\\/\\d{2}\\/\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}'\nwith open(logDestination) as f:\n for line in f:... | [
0
] | [] | [] | [
"automated_refactoring",
"automated_tests",
"automation",
"python",
"text_parsing"
] | stackoverflow_0074220968_automated_refactoring_automated_tests_automation_python_text_parsing.txt |
Q:
Import class from file of the same name
I often do this:
└─ mymodule
├─__init__.py
├─ MyClass1.py
...
└─ MyClass2.py
And each file contains a single class, named accordingly MyClass1, MyClass2.
I know, I know, not pythonic of me, but I believe that convention should not limit my possibilities.
But, I enco... | Import class from file of the same name | I often do this:
└─ mymodule
├─__init__.py
├─ MyClass1.py
...
└─ MyClass2.py
And each file contains a single class, named accordingly MyClass1, MyClass2.
I know, I know, not pythonic of me, but I believe that convention should not limit my possibilities.
But, I encounter problems that I can not solve on my own... | [
"You can import it like this:\nfrom mymodule.MyClass1 import MyClass1\n\n\n",
"In __init__.py:\nfrom .MyClass1 import MyClass1\nfrom .MyClass2 import MyClass2\n\nThen you can use your import:\nfrom mymodule import MyClass1\n\n"
] | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074221149_python.txt |
Q:
Getting NoReverseMatch while click the comment button
I was getting that same error while click the like button, But the error was solved..
again after creating comment view and its other staff I'm getting that error again...When I click the comment button then the error appears..I'm very new to Django,,, help me ... | Getting NoReverseMatch while click the comment button | I was getting that same error while click the like button, But the error was solved..
again after creating comment view and its other staff I'm getting that error again...When I click the comment button then the error appears..I'm very new to Django,,, help me please..
My project models.py, template page, urls.py, view... | [
"Your comment button is just a link, is it normal ? I think, you want to submit your form when you click on?\n<div>\n <h4>\n Comments:\n </h4>\n {% for comment in comments %}\n <div>\n {{ user }} <br>\n <h5>{{ comment }}</h5>\n </div>\n {% endfor %}\n <!-- <h6>Add your comm... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074221136_django_python.txt |
Q:
Push notification from python to android
I'm running some scripts and looking for an easy way to ping my phone once the script has finished running.
Doing some research on the web, I've seen ways of sending messages using Slack, Push bullet, twilio, email etc.
I am looking for recommendations for an easy way to ... | Push notification from python to android | I'm running some scripts and looking for an easy way to ping my phone once the script has finished running.
Doing some research on the web, I've seen ways of sending messages using Slack, Push bullet, twilio, email etc.
I am looking for recommendations for an easy way to send a ping/message from python to my phone.
... | [
"I have found a much easier way, but it doesn't works on Linux. Here is a link for more details.\nFirst you have to install notify_run:\npip install notify_run\n\nThen you have to register:\nnotify-run register\n\nIt will give you a QR code (on windows the QR code doesn't works) and a link, which will take you to a... | [
9,
9,
8,
4,
3,
0,
0
] | [] | [] | [
"push_notification",
"python"
] | stackoverflow_0049879993_push_notification_python.txt |
Q:
reading matrices with different sizes from a input file
I am trying to make a function that will recieve a input file containing matrices, then will store those matrices inside another matrix, the input file format will always be the same.
This is what I've tried:
with open("input.txt", "r") as file:
r = input... | reading matrices with different sizes from a input file | I am trying to make a function that will recieve a input file containing matrices, then will store those matrices inside another matrix, the input file format will always be the same.
This is what I've tried:
with open("input.txt", "r") as file:
r = input.read()
matrix = [[num for num in line] for line in r if ... | [
"You can do this.\nwith open(\"input.txt\", \"r\") as file:\n r = file.read()\n [line.split() for line in list(map(str.strip, filter(None, r)))]\n\nfilter to remove the '' values\nmap is used to apply a strip for each element in the list.\nOutput:\n[['3', '4'],\n ['4', '2', '3', '1'],\n ['2', '1', '0', '0'],\... | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074221141_list_python.txt |
Q:
Add part of line found after #solution to file
I have a script that puts the line that starts with #Solution 1 in a new file together with the name of the input file. But I want to add the piece belonging to Major from the input file. Can someone please help me to figure out how to get the piece of text?
The scrip... | Add part of line found after #solution to file | I have a script that puts the line that starts with #Solution 1 in a new file together with the name of the input file. But I want to add the piece belonging to Major from the input file. Can someone please help me to figure out how to get the piece of text?
The script now:
#!/usr/bin/env python3
import os
dr = "/hom... | [
"If you print out the line, you could use regular expression to replace text before printing the line.\nOn the other hand, if you know it always starts with a fixed number of chars, then it's easier and faster to edit the line manually.\nWith regex:\n# Importing regular expressions\nimport re\n\n# Setting up regex ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074221202_python.txt |
Q:
How to convert list to dictionary in Python?
I have the following list
['BILL FROM:', 'TestCorp', 'USA, NY 02123, Washington St.', 'New York, NY, 02123', 'United States', 'musicjohnliofficial@gmail.com', 'BILL TO:', 'Yao Min', 'LA, 2123, Los Angeles', 'new York, NY, 9803432', 'United States', 'yao123@mail.com', 'I... | How to convert list to dictionary in Python? | I have the following list
['BILL FROM:', 'TestCorp', 'USA, NY 02123, Washington St.', 'New York, NY, 02123', 'United States', 'musicjohnliofficial@gmail.com', 'BILL TO:', 'Yao Min', 'LA, 2123, Los Angeles', 'new York, NY, 9803432', 'United States', 'yao123@mail.com', 'INVOICE #', '01', 'INVOICE DATE', '2022-08-05', 'AM... | [
"You can do with zip,\ndict(zip(lst[::2], lst[1::2]))\n\nUsing islice,\nfrom itertools import islice\ndict(zip(islice(lst, 0, None, 2), islice(lst, 1, None, 2)))\n\n",
"I think that your code is correct for lists that have an even number of elements, so they can be converted to dicts; but you get the error when i... | [
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074221349_dictionary_list_python.txt |
Q:
How to decouple nodes and cores with MPI?
I have code currently using multiprocessing with joblib to distribute computations from a loop over multiple cores within one cluster node, like so:
from joblib import Parallel, delayed
def function():
return Parallel(n_jobs=28)(delayed(computation)() for _ in range(n_... | How to decouple nodes and cores with MPI? | I have code currently using multiprocessing with joblib to distribute computations from a loop over multiple cores within one cluster node, like so:
from joblib import Parallel, delayed
def function():
return Parallel(n_jobs=28)(delayed(computation)() for _ in range(n_iter))
save(function()) # save results to some ... | [
"If what I understood is correct, you need to launch one mpi process per node in 5 nodes and each process should be able to use all cores (28) with python multiprocessing.\nUsing this mapping should be sufficient:\nmpirun -np $np --map-by ppr:1:node #np is 5\n\nMPI will launch a process per node. Inside the node, p... | [
0
] | [] | [] | [
"cluster_computing",
"mpi",
"multiprocessing",
"parallel_processing",
"python"
] | stackoverflow_0074201860_cluster_computing_mpi_multiprocessing_parallel_processing_python.txt |
Q:
Pandas: Merging two df's with different amount of rows
I have two dataframes that both have a column that can have the same number/value in it. One 'small df with ~300 rows (which is my leading file) and 1 df with ~ 5000 rows. I want to merge on 1 column but I cannot get the same amount of rows when I print the da... | Pandas: Merging two df's with different amount of rows | I have two dataframes that both have a column that can have the same number/value in it. One 'small df with ~300 rows (which is my leading file) and 1 df with ~ 5000 rows. I want to merge on 1 column but I cannot get the same amount of rows when I print the data.
first (small) dataframe (left):
import pandas as pd
df1 ... | [
"Try dataframe.join you can specify how='left which is by default\nimport pandas as pd\ndf = pd.DataFrame({\"a\": [0,0,1,1,2,2,2,]})\ndf2 = pd.DataFrame({\"a\": [0, 1,2,3,4,5,6,7,8,9], \"b\": list(\"abcdefghij\")})\ndf.join(df2, on=\"a\", lsuffix=\"df_a\", rsuffix=\"df_b\")\n\n# output\n adf_a adf_b b\n0 0 0... | [
5,
1
] | [] | [] | [
"merge",
"pandas",
"python"
] | stackoverflow_0074221419_merge_pandas_python.txt |
Q:
Bad results using OpenCV with Yolov5 comparing with pure Yolov5
I'm tryting to recognize lego bricks from video cam using opencv. It performs extremely bad comparing with just running detect.py in Yolov5. Thus I made some experiments about just recognizing images, and I found using openCV still performs dramatical... | Bad results using OpenCV with Yolov5 comparing with pure Yolov5 | I'm tryting to recognize lego bricks from video cam using opencv. It performs extremely bad comparing with just running detect.py in Yolov5. Thus I made some experiments about just recognizing images, and I found using openCV still performs dramatically bad as well, is there any clue? Here are the experiments I did.
Th... | [
"Probably your model is trained with RGB images while opencv is using BGR format. Please try to convert the colour space accordingly. Example:\nimport torch\nimport cv2\n\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s')\n\n# read image and convert to RGB\nimg = cv2.imread('zidane.jpg')\nimg = cv2.cvtColor(i... | [
0
] | [] | [] | [
"object_recognition",
"opencv",
"python",
"pytorch",
"yolov5"
] | stackoverflow_0074209769_object_recognition_opencv_python_pytorch_yolov5.txt |
Q:
Creating a sql file using python
So i have a dataset looks like:
Col A
Col B
Col C
Nanana
Teacher
123456
Popopo
Student
232322
Cecece
Teacher
455433
Lalala
Student
231231
Poasls
Teacher
235433
Lilili
Teacher
723543
I wanted to create a .sql file that contains
SELECT function({1},{2},{3})
then, i wanted to ... | Creating a sql file using python | So i have a dataset looks like:
Col A
Col B
Col C
Nanana
Teacher
123456
Popopo
Student
232322
Cecece
Teacher
455433
Lalala
Student
231231
Poasls
Teacher
235433
Lilili
Teacher
723543
I wanted to create a .sql file that contains
SELECT function({1},{2},{3})
then, i wanted to divide it into 2 stateme... | [
"From your comment: \"The problem now that the second iteration start from 1 not from 3. so the file consist of repetitive data\"\nWhat you want is a step=2 in your range function, so your going 0,2,4.. and inside the loop your processing the values between. See range(start, stop, step) for help\nYour code (but not... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074218861_pandas_python.txt |
Q:
How to replace specific parts of string contain numbers with a matching dictionary?
I would like to replace specific parts of string containing numbers with a dictionary. Suppose I have a dictionary:
d = {7: 'mandat_dépôt', 46: 'battu', 79: 'alphabétisé', 127: 'escrime', 160: 'daara', 162: 'arrivée_foyer', 169: 'f... | How to replace specific parts of string contain numbers with a matching dictionary? | I would like to replace specific parts of string containing numbers with a dictionary. Suppose I have a dictionary:
d = {7: 'mandat_dépôt', 46: 'battu', 79: 'alphabétisé', 127: 'escrime', 160: 'daara', 162: 'arrivée_foyer', 169: 'fugue', 170: 'né_légitimement'}
I have these kinds of string:
s_1 = "7 ==> 127 #SUP: 41 #... | [
"I do not know if it is an effective way but here is my codes:\nold_s = [s_1, s_2, s_3, s_4, s_5]\nnew_s = []\n\nfor i in old_s:\n number, string = i.split('#SUP:')\n number = number.split(\"==>\")\n number = [r.strip() for r in number]\n number = [r.split(\",\") for r in number]\n text_number = []\n... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0074219450_dictionary_python_string.txt |
Q:
kubernetes python client: block and wait for child pods to dissappear when deleting deployment
I'm looking to use the Kubernetes python client to delete a deployment, but then block and wait until all of the associated pods are deleted as well. A lot of the examples I'm finding recommend using the watch function s... | kubernetes python client: block and wait for child pods to dissappear when deleting deployment | I'm looking to use the Kubernetes python client to delete a deployment, but then block and wait until all of the associated pods are deleted as well. A lot of the examples I'm finding recommend using the watch function something like follows.
try:
# try to delete if exists
AppsV1Api(api_client).delete_namespace... | [
"May be you can try this way and handle exceptions based your requirement\n def delete_deployment():\n \"\"\" Delete deployment \"\"\"\n while True:\n try:\n deployment = api_client.delete_namespaced_deployment(\n name=\"deployment_name\",\n ... | [
0,
0
] | [] | [] | [
"client",
"kubernetes",
"kubernetes_python_client",
"python"
] | stackoverflow_0071117916_client_kubernetes_kubernetes_python_client_python.txt |
Q:
Opening powershell from python
I would like to open a powershell from my python script, then launch another python script in this newly created powershell.
import subprocess
subprocess.call("start C:\\Windows\\System32\\WindowsPowerShell\\v1.0", shell=True)
# Here, I would like to write this in the new opened po... | Opening powershell from python | I would like to open a powershell from my python script, then launch another python script in this newly created powershell.
import subprocess
subprocess.call("start C:\\Windows\\System32\\WindowsPowerShell\\v1.0", shell=True)
# Here, I would like to write this in the new opened powershell : python ./hello_world.py (... | [
"Another alternative:\nimport subprocess\nsubprocess.run([\"powershell\", \"-Command\", \"python hello-world.py\"], capture_output=True, cwd=\"C:\\\\your\\\\path\")\n\nWill output:\nCompletedProcess(args=['powershell', '-Command', 'python hello-world.py'], returncode=0, stdout=b'hello world\\r\\n', stderr=b'')\n\nW... | [
1,
0,
0
] | [] | [] | [
"powershell",
"python",
"subprocess"
] | stackoverflow_0074221405_powershell_python_subprocess.txt |
Q:
Rolling windows in pandas based on a condition
I've a dataset which looks like:
column
0
0
1
2
2
I need to create windows, iterating over a list containing the window size.
The output should be
when window size = 1
dataset1
0
0
dataset2
1
dataset3
2
2
when window size = 2
dataset1
0
0
1
datas... | Rolling windows in pandas based on a condition | I've a dataset which looks like:
column
0
0
1
2
2
I need to create windows, iterating over a list containing the window size.
The output should be
when window size = 1
dataset1
0
0
dataset2
1
dataset3
2
2
when window size = 2
dataset1
0
0
1
... | [
"You can use:\nL = [g for k,g in df.groupby('Index')]\n\nn = 2\ndfs = [pd.concat(L[i:i+n]) for i in range(0, len(L)-n+1)]\n\nprint(dfs)\n\noutput:\n[ Index\n 0 0\n 1 0\n 2 1,\n Index\n 2 1\n 3 2\n 4 2]\n\nupdate: multiple windows\nwindows = [1,2,3]\ndfs = []\nfor window in windows... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074221332_pandas_python.txt |
Q:
Python Requests throwing SSLError
I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't kno... | Python Requests throwing SSLError | I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't know what Python requests is wanting? Whe... | [
"The problem you are having is caused by an untrusted SSL certificate.\nLike @dirk mentioned in a previous comment, the quickest fix is setting verify=False:\nrequests.get('https://example.com', verify=False)\n\nPlease note that this will cause the certificate not to be verified. This will expose your application t... | [
648,
131,
66,
63,
50,
37,
27,
20,
17,
14,
10,
8,
6,
5,
5,
4,
3,
3,
2,
1,
1,
1,
0,
0,
0,
0,
0
] | [
"This is just another way you can try to solve the issue.\nIf you put \"www.example.com\", requests shouts at you. If you put \"https://www.example.com\", you get this error. So if you DO NOT NEED https, you can avoid the error by changing \"https\" to \"http\". eg. \"http://www.example.com\"\nWARNING: Not using HT... | [
-2
] | [
"python",
"python_requests",
"ssl",
"urllib3"
] | stackoverflow_0010667960_python_python_requests_ssl_urllib3.txt |
Q:
Can no longer fold python dictionaries in VS Code
I used to be able to collapse (fold) python dictionaries just fine in my VS Code. Randomly I am not able to do that anymore. I can still fold classes and functions just fine, but dictionaries cannot fold, the arrow on the left hand side just isn't there. I've ch... | Can no longer fold python dictionaries in VS Code | I used to be able to collapse (fold) python dictionaries just fine in my VS Code. Randomly I am not able to do that anymore. I can still fold classes and functions just fine, but dictionaries cannot fold, the arrow on the left hand side just isn't there. I've checked my settings but I can't figure out what would've ... | [
"For me, it wasn't a problem with Pylance but rather with Jupyter[*] extensions.\nI disabled all my extensions and enabled them one by one. See that enabling the Python extension will not just enable Python extension. I disabled Jupyter related extensions and Pylance wasn't the problem.\n",
"It's caused by Pylanc... | [
9,
6,
2,
0,
0
] | [] | [] | [
"python",
"visual_studio_code",
"vscode_settings"
] | stackoverflow_0070704285_python_visual_studio_code_vscode_settings.txt |
Q:
Simple check for value in list not giving expected result
I'm hosting a script on Pythonanywhere and I have a list of companies and I'm doing a check to see if a company is present in this list. The list of companies is made up of two lists, the first being owner companies and the second being resellers.
([<Compan... | Simple check for value in list not giving expected result | I'm hosting a script on Pythonanywhere and I have a list of companies and I'm doing a check to see if a company is present in this list. The list of companies is made up of two lists, the first being owner companies and the second being resellers.
([<Company 10>, <Company 11>, <Company 12>, <Company 13>, <Company 16>, ... | [
"Your 'if' is checking only the first element of the list, so it will only find the first company.\nTurn\nif owner in company_lists[0]:\n\ninto\nif owner in company_lists:\n\n"
] | [
0
] | [] | [] | [
"python",
"pythonanywhere"
] | stackoverflow_0074221598_python_pythonanywhere.txt |
Q:
Getting error: TypeError: module() takes at most 2 arguments (3 given)
I started learning the MVC pattern and started writing code according to this pattern but I don't understand what is my mistake. When I try to run the program it shows me:
line 143, in <module>
class App(tkinter):
TypeError: module() takes ... | Getting error: TypeError: module() takes at most 2 arguments (3 given) | I started learning the MVC pattern and started writing code according to this pattern but I don't understand what is my mistake. When I try to run the program it shows me:
line 143, in <module>
class App(tkinter):
TypeError: module() takes at most 2 arguments (3 given)
I will attach below the whole code:
import tk... | [
"This is not an answer. I just want to show you what is look like. I will delete answer next 48-72 hrs. Btw, I do not used import zipFilele import crypt. Actually, you are missing something.\nclass App():\n def __init__(self, tkinter):\n tkinter.geometry('800x580')\n \n tkinter.resizable(wi... | [
0
] | [] | [] | [
"model_view_controller",
"python",
"tkinter"
] | stackoverflow_0074207634_model_view_controller_python_tkinter.txt |
Q:
How to add document for search in marqo
i recently started using the marqo library and i am trying to add document so that marqo can search and return the relevant part of the document but i keep getting error when i run the the code.
i used the
add_document()
method and i pass the document as a string for searc... | How to add document for search in marqo | i recently started using the marqo library and i am trying to add document so that marqo can search and return the relevant part of the document but i keep getting error when i run the the code.
i used the
add_document()
method and i pass the document as a string for search but it returns an error. Here is what my co... | [
"you are getting the error because the add_document() method takes a list of python dictionaries as an argument not a string, so you are to pass the document as a value to any key you assign to it. But it is advisable to add a title and also an id for later referencing. Here is what i mean;\nmq.index(\"my-first-ind... | [
2,
1
] | [] | [] | [
"artificial_intelligence",
"python",
"python_3.x"
] | stackoverflow_0074221408_artificial_intelligence_python_python_3.x.txt |
Q:
Why do I get '0' response and some error when I try to scrape this site with selenium?
Hi I'm trying to scrape an ecommerce store 'konga.com' with selenium but when I try to get all the elements with with common class name, I get '0' response and some error. here's my code
from selenium import webdriver
import ti... | Why do I get '0' response and some error when I try to scrape this site with selenium? | Hi I'm trying to scrape an ecommerce store 'konga.com' with selenium but when I try to get all the elements with with common class name, I get '0' response and some error. here's my code
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by... | [
"By.CLASS_NAME searches for one class at a time. This element you are looking for has two classes: bbe45_3oExY and _22339_3gQb9. Class names are separated by space inside the class attribute.\nSo in this case you can get the result you want using the command driver.find_elements(By.CLASS_NAME, 'bbe45_3oExY')\nAnd c... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074219798_python_selenium_selenium_webdriver.txt |
Q:
Pydantic how to access updated values for PrivateAttr
I have this class
from pydantic import BaseModel, PrivateAttr
class A(BaseModel):
_value: str = PrivateAttr()
def __init__(self):
self._value = "Initial Value"
super().__init__()
@property
def value(self):
return self.... | Pydantic how to access updated values for PrivateAttr | I have this class
from pydantic import BaseModel, PrivateAttr
class A(BaseModel):
_value: str = PrivateAttr()
def __init__(self):
self._value = "Initial Value"
super().__init__()
@property
def value(self):
return self._value
@value.setter
def value(self, some_value: ... | [
"TL;DR\nPrivate attributes are special and different from fields. If you want to properly assign a new value to a private attribute, you need to do it via regular attribute setting:\n ...\n def clone(self):\n obj = self.copy()\n obj._value = \"Updated value\"\n return obj\n\n\nLong story:... | [
1
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074211366_pydantic_python.txt |
Q:
Escape # symbol in jinja variable assignment
I want to assign a hex color code to a variable in a yaml that will get parsed with jinja2. However, string "#558dd5" evaluates to None because of the # symbol. Without it, it evaluates to "558dd5".
example yaml:
{% set colors = namespace() %}
{% set colors.blue = "#558... | Escape # symbol in jinja variable assignment | I want to assign a hex color code to a variable in a yaml that will get parsed with jinja2. However, string "#558dd5" evaluates to None because of the # symbol. Without it, it evaluates to "558dd5".
example yaml:
{% set colors = namespace() %}
{% set colors.blue = "#558dd5" %}
"colors":
"blue": {{colors.blue}}
One... | [
"The generated YAML will look like this:\n\"colors\":\n \"blue\": #558dd5\n\nThis makes #558dd5 a comment. To avoid this, surround the Jinja replacement command with quotes:\n{% set colors = namespace() %}\n{% set colors.blue = \"#558dd5\" %}\n\n\n\"colors\":\n \"blue\": \"{{colors.blue}}\"\n\nNow you'll get\n\"c... | [
2
] | [] | [] | [
"jinja2",
"python",
"python_3.x",
"yaml"
] | stackoverflow_0074211199_jinja2_python_python_3.x_yaml.txt |
Q:
How to remove empty String in pandas Dataframe
I know there have been a lot of questions around this topic but I didn't find any that described my problem. I have a data, with a specific column that looks like this:
`
ColumnA
['meeting', '', 'delete', 'download']
['error', 'meeting', '']
['','applicati... | How to remove empty String in pandas Dataframe | I know there have been a lot of questions around this topic but I didn't find any that described my problem. I have a data, with a specific column that looks like this:
`
ColumnA
['meeting', '', 'delete', 'download']
['error', 'meeting', '']
['','application', '']
The values of columnA are a string NOT a l... | [
"You can use ast.literal_eval:\nfrom ast import literal_eval\n\ndf['New'] = [str([s for s in literal_eval(x) if s!=''])\n for x in df['ColumnA']]\n\noutput:\n ColumnA New\n0 ['meeting', '', 'delete', 'download'] ['meeting', 'delete', 'down... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"string"
] | stackoverflow_0074221530_dataframe_pandas_python_string.txt |
Q:
My Get Api isn't working , I can't retrieve list from db as i inteded(Django)
This is the information in my db
This is my model
Serializers
@api_view(['GET', 'POST', 'DELETE'])
def student_list(request):
if request.method == 'GET':
student = Student.objects.all()
FirstName = request.GET.get('FirstName', N... | My Get Api isn't working , I can't retrieve list from db as i inteded(Django) | This is the information in my db
This is my model
Serializers
@api_view(['GET', 'POST', 'DELETE'])
def student_list(request):
if request.method == 'GET':
student = Student.objects.all()
FirstName = request.GET.get('FirstName', None)
if FirstName is not None:
student = student.filter(FirstName__icon... | [
"Try removing this portion of code:-\n if FirstName is not None:\n student = student.filter(FirstName__icontains=FirstName)\n\nYou are sending the request, without FirstName I guess, and then you are filtering the queryset.\n",
"Sorry for the bother everyone! I found out the reason for this now, and it'... | [
0,
0
] | [] | [] | [
"backend",
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074219667_backend_django_django_rest_framework_python.txt |
Q:
Extract the words that start with a vowel from a list input _list=[wood,old, apple,big,item, euphoria] using list comprehensions
Extract the words that start with a vowel from a
list input _list=[wood,old, apple,big,item, euphoria]
using list comprehensions.
Old
apple
item
euphoria
EXPECTED OUTPUT
['old','apple',... | Extract the words that start with a vowel from a list input _list=[wood,old, apple,big,item, euphoria] using list comprehensions | Extract the words that start with a vowel from a
list input _list=[wood,old, apple,big,item, euphoria]
using list comprehensions.
Old
apple
item
euphoria
EXPECTED OUTPUT
['old','apple','item','euphoria']
| [
"I think you are on the right track recognizing using that a list comprehension is appropriate for this task, consider trying the following:\n>>> input_list = ['wood', 'old', 'apple', 'big', 'item', 'euphoria']\n>>> vowels = {'a', 'e', 'i', 'o', 'u'}\n>>> output_list = [word for word in input_list if word and word[... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074221611_python.txt |
Q:
Update column depending if other column value is in list
Im working with a data set that needs some manual cleanup.
One thing that i need to do is assign a certain value in one column to some of my rows, if in another column, that row has a value that is present in a list ive defined.
So here a reduced example of ... | Update column depending if other column value is in list | Im working with a data set that needs some manual cleanup.
One thing that i need to do is assign a certain value in one column to some of my rows, if in another column, that row has a value that is present in a list ive defined.
So here a reduced example of what i want to do:
to_be_changed = ['b','e','a']
df = pd.Data... | [
"You could also use pandas loc (documentation), using the same isin() function:\nimport pandas as pd\n\nto_be_changed = ['b','e','a']\ndf = pd.DataFrame({'col1':[1,2,2,1,2],'col2':['a','b','c','d','e' ]})\n\ndf.loc[df['col2'].isin(to_be_changed), 'col1'] = 3\n\nproduces the expected output:\n col1 col2\n0 3 ... | [
2,
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074221506_dataframe_pandas_python.txt |
Q:
create a dataframe with a for bucle
I have created a function to be able to represent different indicators of an API. I want to create a dataframe for each indicator and then join them together. I would like to ask the way to be able to represent it without having to create for example 7 dataframes and then join t... | create a dataframe with a for bucle | I have created a function to be able to represent different indicators of an API. I want to create a dataframe for each indicator and then join them together. I would like to ask the way to be able to represent it without having to create for example 7 dataframes and then join them. I imagine that I can do it with a fo... | [
"If you put your desired indicators in a list, you can generate a complete dataframe using concat over a list comprehension:\nindicators = ['79', '71', '74', '86', '84', '85', '73']\n\nresult = pd.concat([generar_df_indicator(id) for id in indicators]).reset_index(drop=True)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"function",
"pandas",
"python"
] | stackoverflow_0074221696_dataframe_for_loop_function_pandas_python.txt |
Q:
No browsers version found for Chrome
I was using code which I took from internet for scraping amazon. I got first error of 'Maximum amount of retry reached' I read that need to modify useragent credentials in some places. I modified to ;
ua = UserAgent(use_cache_server=False,verify_ssl=False)
uag_random = ua.rando... | No browsers version found for Chrome | I was using code which I took from internet for scraping amazon. I got first error of 'Maximum amount of retry reached' I read that need to modify useragent credentials in some places. I modified to ;
ua = UserAgent(use_cache_server=False,verify_ssl=False)
uag_random = ua.random
header = {
'User-Agent': ua.chrome,... | [
"You should read the docs again because there are no ua.random.chrome\nso if you want its random for google chrome you could try this code\nua = UserAgent(use_cache_server=False,verify_ssl=False)\n\nheader = {\n 'User-Agent': ua['google chrome'],\n 'Accept-Language': 'en-US,en;q=0.9'\n}\n\n"
] | [
0
] | [] | [] | [
"python",
"scrape",
"user_agent"
] | stackoverflow_0074205940_python_scrape_user_agent.txt |
Q:
USB Device Release
I am currently working on PyUSB. As I am new to USB, I don’t know, how can I do the following.
I have successfully connected to my USB Device hardware from Python PyUSB. In the code I required to reset the USB Device hardware.
Which I did by sending a command to the hardware. Now after hardware ... | USB Device Release | I am currently working on PyUSB. As I am new to USB, I don’t know, how can I do the following.
I have successfully connected to my USB Device hardware from Python PyUSB. In the code I required to reset the USB Device hardware.
Which I did by sending a command to the hardware. Now after hardware reset, I want to release... | [
"my_device = usb.core.find(...)\n\n...\n# necessary to allow further claim_interface calls\n# (bulk read), generally not needed\nusb.util.dispose_resources(my_device)\n\n",
"#!/usr/bin/python\nfrom usb.core import find as finddev\ndev = finddev(idVendor=0x1234, idProduct=0x5678)\ndev.reset()\n\n",
"While the ... | [
5,
4,
0
] | [] | [] | [
"python",
"pyusb"
] | stackoverflow_0025617039_python_pyusb.txt |
Q:
Python multiprocessing.Queue.get throws OSError (Handle is closed)
I have a Python Singleton class which exposes an API put_msg_to_queue to users. This API puts a string message to queue. The Singleton Tester class creates a thread which gets the message and just prints it.
Complete code used is given below. This ... | Python multiprocessing.Queue.get throws OSError (Handle is closed) | I have a Python Singleton class which exposes an API put_msg_to_queue to users. This API puts a string message to queue. The Singleton Tester class creates a thread which gets the message and just prints it.
Complete code used is given below. This code was working fine with Python 3.9.12, but seems broken with Python 3... | [
"Your problem can be resolved if you do not use the call to atexit.register to do the closing of the queue but rather explicitly call it after all messages have been added:\n... # code omitted for brevity\n\ntester = Tester()\ntester.put_msg_to_queue(\"sample msg\")\ntester.close()\n\nBut you have so many timing de... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"python_multithreading",
"queue"
] | stackoverflow_0074217429_multiprocessing_python_python_multithreading_queue.txt |
Q:
Most efficent way to read and process a large file
I have a .txt file which has the following format:
1 a 0.01 0.03 0.01 ...
2 b 0.04 0.03 0.01 ...
which may contain any number of columns with additional numbers. I need to find the index of the maximum value in each row for a large (2.5 million) number of rows.
S... | Most efficent way to read and process a large file | I have a .txt file which has the following format:
1 a 0.01 0.03 0.01 ...
2 b 0.04 0.03 0.01 ...
which may contain any number of columns with additional numbers. I need to find the index of the maximum value in each row for a large (2.5 million) number of rows.
So far my approach was to preallocate an array and read t... | [
"Reading a text file line by line is very efficient and obviates the need to have the entire file content in memory.\nFor the purpose of demonstration I have created a text file with 2,500,000 lines. Each line contains ten pseudo-random floating point numbers.\nProcessing goes like this:\nfrom time import perf_coun... | [
0
] | [
"Does this help? I took it from a similar question and adapted it to your case.\ndef recordsFromFile(inputFile):\n for line in inputFile:\n yield line\n\ninputFile = open('test.txt')\nfor record in recordsFromFile(inputFile):\n # Do stuff\n\n"
] | [
-1
] | [
"data_processing",
"python"
] | stackoverflow_0074221082_data_processing_python.txt |
Q:
Matplotlib - The graph does not show in Pycharm
I just started learning matplotlib. The code I used is here below:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,6]
plt.plot([x, y])
The graph doesn't show up. It just gets stuck. Is there a way to fix it?
I am a beginner matplotlibber, so I'm just followin... | Matplotlib - The graph does not show in Pycharm | I just started learning matplotlib. The code I used is here below:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,6]
plt.plot([x, y])
The graph doesn't show up. It just gets stuck. Is there a way to fix it?
I am a beginner matplotlibber, so I'm just following a tutorial, but this doesn't work for me. I just ... | [
"You missing the:\nplt.show()\n\nSo your code become:\nimport matplotlib.pyplot as plt\n\nx = [1,2,3]\ny = [2,4,6]\n\nplt.plot([x, y])\nplt.show()\n\nOr, if you are using a Jupiter Notebook:\n%matplotlib inline\n\n"
] | [
1
] | [] | [] | [
"data_science",
"graph",
"matplotlib",
"plot",
"python"
] | stackoverflow_0074221787_data_science_graph_matplotlib_plot_python.txt |
Q:
Pipeline including several steps: StandardScaler(), RandomUnderSampler, Classifiers
I have the following code and showing the error TypeError: Last step of Pipeline should implement fit or be the string 'passthrough'. '[('sc', StandardScaler()), ('rus', RandomUnderSampler()), ('clf', LogisticRegression(max_iter=10... | Pipeline including several steps: StandardScaler(), RandomUnderSampler, Classifiers | I have the following code and showing the error TypeError: Last step of Pipeline should implement fit or be the string 'passthrough'. '[('sc', StandardScaler()), ('rus', RandomUnderSampler()), ('clf', LogisticRegression(max_iter=10000, multi_class='ovr', solver='sag'))]' (type <class 'list'>) doesn't
my code as follow:... | [
"the solution was:\nfor classifier in classifiers:\nmodel = Pipeline_imb( [('sc',StandardScaler()),('rus',RandomUnderSampler()),\n ('clf',classifier)])\nmodel.fit(X_train,y_train)\n\ni had to install:\nfrom imblearn.pipeline import make_pipeline as make_pipeline_imb\nfrom imblearn.pipe... | [
0
] | [] | [] | [
"imblearn",
"python",
"scikit_learn"
] | stackoverflow_0074221554_imblearn_python_scikit_learn.txt |
Q:
I have a function that is scheduled to run every hour. How can i pass an argument only the first time I run it?
I am creating an investing bot. Every hour it runs a function that makes predictions every hour. In order to test the bot, I give it a variable called balance = 1000. I want to only pass it the first tim... | I have a function that is scheduled to run every hour. How can i pass an argument only the first time I run it? | I am creating an investing bot. Every hour it runs a function that makes predictions every hour. In order to test the bot, I give it a variable called balance = 1000. I want to only pass it the first time I run it, because the following times the function is being called, the balance variable is changed (in order to se... | [
"As you say it won't work by declaring balance in the main() function.\nTry to make it global.\nIt's not the most elegant but the most immediate to try.\n\nbalance = 0\n\nschedule.every().hour.at(\":01\").do(main)\n\nwhile True:\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n schedule.... | [
0
] | [] | [] | [
"python",
"python_schedule"
] | stackoverflow_0074221713_python_python_schedule.txt |
Q:
How to use a new thread for a new window in pyqt5
I have a pyqt5 GUI and there are some functions i want to run in a list. One of the functions is to open a pop window(QDialog)self.openPassDialog but the loading sign on the cursor appears and the program crashes when i click on anthing.
I have used a thread to run... | How to use a new thread for a new window in pyqt5 | I have a pyqt5 GUI and there are some functions i want to run in a list. One of the functions is to open a pop window(QDialog)self.openPassDialog but the loading sign on the cursor appears and the program crashes when i click on anthing.
I have used a thread to run the call_va_funcs() function, without the pop up windo... | [
"You should not touch and especially not create any Qt-thingey from a new thread like that, instead you should use signals to communicate between them.\nfrom master thread make new signal and connect it:\nsignal.whatevername.connect(self.openPassDialog)\nmake sure the slave thread has the signal and from slave thre... | [
0
] | [] | [] | [
"pyqt5",
"python",
"python_3.x"
] | stackoverflow_0074219637_pyqt5_python_python_3.x.txt |
Q:
Removing duplicate elements by their attributes in python
Is there a nice way to remove elements from a list, by their attributes?
Example:
lis = [['element1', 12], ['element2', 2], ['element3', 12], ['element4', 36], ['element5', 12]]
And I want to get this list:
new_lis = [['element1', 12], ['element2', 2], [... | Removing duplicate elements by their attributes in python | Is there a nice way to remove elements from a list, by their attributes?
Example:
lis = [['element1', 12], ['element2', 2], ['element3', 12], ['element4', 36], ['element5', 12]]
And I want to get this list:
new_lis = [['element1', 12], ['element2', 2], ['element4', 36]]
I am looking for a short and elegant solution... | [
"The best way to do this is using simple generator function. The reason is that generator is lazy evaluated which means that it produces the item in the list on demand; saves a lot of memory for large list. You can then iterate the generator object and do something with the item\nDemo:\n>>> lis = [['element1', 12],... | [
4,
2,
0
] | [] | [] | [
"duplicates",
"list",
"python"
] | stackoverflow_0034630772_duplicates_list_python.txt |
Q:
Limit a single record in model for django app?
I want use a model to save the system setting for a django app, So I want to limit the model can only have one record, how to do the limit?
A:
Try this:
class MyModel(models.Model):
onefield = models.CharField('The field', max_length=100)
class MyModelAdmin(adm... | Limit a single record in model for django app? | I want use a model to save the system setting for a django app, So I want to limit the model can only have one record, how to do the limit?
| [
"Try this:\nclass MyModel(models.Model):\n onefield = models.CharField('The field', max_length=100)\n\nclass MyModelAdmin(admin.ModelAdmin):\n def has_add_permission(self, request):\n # if there's already an entry, do not allow adding\n count = MyModel.objects.all().count()\n if count == 0:\n retu... | [
14,
11,
10,
10,
2,
2,
0
] | [
"You can rewrite the save method on your model. Whenever the user wants to register a new record, you can check the existence then, either save the record or, reject the request.\nclass MyModel(models.Model):\n title = models.CharField(...)\n body = models.TextField(...)\n \n def save(self, *args, **kwa... | [
-1
] | [
"django",
"django_admin",
"django_models",
"python",
"python_3.x"
] | stackoverflow_0002106823_django_django_admin_django_models_python_python_3.x.txt |
Q:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Event->event, expression 'Tag' failed to locate a name ('Tag')
I am trying to use ORM with SQLAlchemy in Python. My current solution fails and throws an exception right in the moment the ORM is first used. I receive the following exception:
... | sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Event->event, expression 'Tag' failed to locate a name ('Tag') | I am trying to use ORM with SQLAlchemy in Python. My current solution fails and throws an exception right in the moment the ORM is first used. I receive the following exception:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Event->event, expression 'Tag' failed to locate a name ('Tag'). If t... | [
"I think you need to define a Base = declarative_base(), need to use in your models and associations.\nfrom sqlalchemy import Column, Integer, ForeignKey, String, DECIMAL, Text, DateTime, Table, create_engine\n from sqlalchemy.dialects.mssql import TINYINT\n from sqlalchemy.dialects.postgresql import UUID\n ... | [
1
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0074220890_orm_python_sqlalchemy.txt |
Q:
Splitting Dates in a Dataframe into 2 separate Dataframes
I have a dataframe where two of the columns Start and End are lists of dates. What I would like to do is create two separate dataframes where, for the first dataframe, the first value in the Start column matches the value in the End column, while for the se... | Splitting Dates in a Dataframe into 2 separate Dataframes | I have a dataframe where two of the columns Start and End are lists of dates. What I would like to do is create two separate dataframes where, for the first dataframe, the first value in the Start column matches the value in the End column, while for the second dataframe the second value in the Start column also matche... | [
"You can use:\ntmp_df = df.assign(Start=df['Start'].str.split(',')).explode('Start')\n\ndf1 = tmp_df.groupby(level=0).first()\ndf2 = tmp_df.groupby(level=0).last()\n\nNB. if you already have lists, you can skip the .assign(Start=df['Start'].str.split(',')).\noutput:\n# df1\n Name Start End\n0 AAA 2... | [
4,
1
] | [] | [] | [
"dataframe",
"date",
"datetime",
"pandas",
"python"
] | stackoverflow_0074221572_dataframe_date_datetime_pandas_python.txt |
Q:
Pandas Query Fails
Given the following CSV:
ID,Title,Created By,Created On,Estimate,Forecast,Priority,References,Section,Section Depth,Section Description,Suite,Suite ID,Type,Updated By,Updated On
C28045,test1,dsa,10/27/2022 1:56 AM,,,Highest,,primary,0,,Master,S378,Automated,test,10/27/2022 4:33 AM
C28060,test32,... | Pandas Query Fails | Given the following CSV:
ID,Title,Created By,Created On,Estimate,Forecast,Priority,References,Section,Section Depth,Section Description,Suite,Suite ID,Type,Updated By,Updated On
C28045,test1,dsa,10/27/2022 1:56 AM,,,Highest,,primary,0,,Master,S378,Automated,test,10/27/2022 4:33 AM
C28060,test32,dsa,10/27/2022 4:34 AM,,... | [
"It looks like you are missing a few quotes and should be using '=='\n# using query, filter for Section == 'primary' and Title == 'test32'\ndata.query(\"Section == 'primary' and Title == 'test32'\", inplace=True)\n\n",
"Does this solve your problem?\ndata = pd.read_csv(csvPath)\n\ndata=data[(data['Section']=='pri... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074221803_pandas_python.txt |
Q:
Python type hinting: Inherited class with different init
I can't figure out how to use type hint in Python when I have subclass with different parameters.
class VehicleBase:
def __init__(self, vehicle_type: str) -> None:
self.vehicle_type: str = vehicle_type
class Car(VehicleBase):
def __init__... | Python type hinting: Inherited class with different init | I can't figure out how to use type hint in Python when I have subclass with different parameters.
class VehicleBase:
def __init__(self, vehicle_type: str) -> None:
self.vehicle_type: str = vehicle_type
class Car(VehicleBase):
def __init__(self) -> None:
super().__init__(vehicle_type="Car")... | [
"This should be an error because VehicleBase expects a str, but I understand why you ask. You want to do e.g. RegisterVehicle(Car), right? You may want Callable[[], VehicleBase].\nFor the same reasons I mention here, it's unsafe more often than not to use Type/type in type hints. Callable is safer.\n"
] | [
0
] | [] | [] | [
"inheritance",
"mypy",
"pylance",
"python",
"typing"
] | stackoverflow_0074214535_inheritance_mypy_pylance_python_typing.txt |
Q:
pymongo sort dictionaries inside of an array by date
I want some of your knowledge in here.
What I'm trying to do, is to sort the dates (datetime) of the dictionaries (from the oldest to newest) which is inside of an array from my MongoDB database.
{"_id": {
"$oid": "63595cb35e81b89cb442087c",
"Carrots": [
{
"ta... | pymongo sort dictionaries inside of an array by date | I want some of your knowledge in here.
What I'm trying to do, is to sort the dates (datetime) of the dictionaries (from the oldest to newest) which is inside of an array from my MongoDB database.
{"_id": {
"$oid": "63595cb35e81b89cb442087c",
"Carrots": [
{
"task": "Plantation",
"date": "2022-01-16T00:00:00",
"inf... | [
"One option is to use $sortArray:\npipeline = [\n {\"$project\": {\n \"Carrots\": {\n \"$sortArray\": {\n \"input\": \"$Carrots\",\n \"sortBy\": {\"date\": 1}\n }\n }\n }\n }\n]\nf = mycol.aggregate(pipeline)\n\nSee how it works on the playground example\n"
] | [
1
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0074221863_mongodb_pymongo_python.txt |
Q:
- Python Issue: Working with an Array key-value inside a While statement, is overwritting the content even if different names are detected
Explanation:
I'm trying to do a Progress bar, where you can control it by updating some values on an Excel, and it shows the changes live in a .svg file.
Issue:
I've a loop tha... | - Python Issue: Working with an Array key-value inside a While statement, is overwritting the content even if different names are detected | Explanation:
I'm trying to do a Progress bar, where you can control it by updating some values on an Excel, and it shows the changes live in a .svg file.
Issue:
I've a loop that can repeat itself sometimes, but the names of the Listed key-value inside the Array are changed between 2 options.
The issue is that, even if ... | [
"At the end of the while loop declare _opacity = {}, we need to make that empty, else for each run it adds the value in it.\n",
"I did a Newbie miss that I didn't even noticed.\nThe code I passed was good, but a method I was calling, was hardcoded from previous tests, and I didn't noticed it.\nThe phase which I w... | [
0,
0
] | [] | [] | [
"arraylist",
"arrays",
"key_value",
"python",
"while_loop"
] | stackoverflow_0073981516_arraylist_arrays_key_value_python_while_loop.txt |
Q:
LightGBM 'class_weight' parameter: To use with Binary Classification or not?
When dealing with class imbalance issue, penalizing the majority class is a common practice that I have come across while building Machine Learning models. Hence, I often use class weights post re-sampling. LightGBM is one efficient decis... | LightGBM 'class_weight' parameter: To use with Binary Classification or not? | When dealing with class imbalance issue, penalizing the majority class is a common practice that I have come across while building Machine Learning models. Hence, I often use class weights post re-sampling. LightGBM is one efficient decision tree based framework that is believed to handle class imbalance well. So I am ... | [
"Documentation recommends alternative parameters:\n\nUse this parameter only for multi-class classification task; for binary classification task you may use is_unbalance or scale_pos_weight parameters.\n\nhttps://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html\n"
] | [
0
] | [] | [] | [
"classification",
"decision_tree",
"lightgbm",
"machine_learning",
"python"
] | stackoverflow_0061141374_classification_decision_tree_lightgbm_machine_learning_python.txt |
Q:
How can I fix a bug using modulo (%) in Python?
I am making a converting program in Python, and in this case it’s from feet to yards. I have having trouble with a specific line of code that is not showing an error message, yet refuses to actually work.
When I run the program and put the following numbers in the in... | How can I fix a bug using modulo (%) in Python? | I am making a converting program in Python, and in this case it’s from feet to yards. I have having trouble with a specific line of code that is not showing an error message, yet refuses to actually work.
When I run the program and put the following numbers in the input (3, 2, 4, 1) the Yards should be 8, and the feet ... | [
"This line is causing your problem:\nif ((firstFeet + secondFeet) % 3) > 2:\n\nThe remainder of division by three cannot be greater than 2, maybe you mean to see if three fits more than twice? Try division instead of modulo if that's the case.\n",
"Your test\nif ((firstFeet + secondFeet) % 3) > 2:\n\nwill always ... | [
0,
0,
0
] | [] | [] | [
"input",
"modulo",
"python"
] | stackoverflow_0074214112_input_modulo_python.txt |
Q:
Pine Script Plotshape() not stable (the shapes are moving up and down with the change in chart)
Normal when add the script to chart
Goes above the bar when moving a little vertically
plotshape(buy, "Buy", style=shape.labelup, color=color.green, location=location.belowbar, text="buy", textcolor=color.white, size ... | Pine Script Plotshape() not stable (the shapes are moving up and down with the change in chart) | Normal when add the script to chart
Goes above the bar when moving a little vertically
plotshape(buy, "Buy", style=shape.labelup, color=color.green, location=location.belowbar, text="buy", textcolor=color.white, size = size.normal)
plotshape(sell, "Sell", style=shape.labeldown, color=color.red, location=location.abo... | [
"I also encounter when using my script with other scripts(it is a non V5 script), the solution is hide other scripts and then back to normal\n"
] | [
0
] | [] | [] | [
"pine_script",
"pinescript_v5",
"python",
"tradingview_api"
] | stackoverflow_0071671078_pine_script_pinescript_v5_python_tradingview_api.txt |
Q:
pyarmor obfuscation on Mac (arwin.aarch64)
I'm trying to obfuscate a script using pyarmor (bought license) but I'm getting the following error:
is incompatible with target arch arm64 (has arch: x86_64)!
I've read the docs and I've found this part where it shows the default supported platforms that already come wit... | pyarmor obfuscation on Mac (arwin.aarch64) | I'm trying to obfuscate a script using pyarmor (bought license) but I'm getting the following error:
is incompatible with target arch arm64 (has arch: x86_64)!
I've read the docs and I've found this part where it shows the default supported platforms that already come with pyarmor + the other dynamic libraries that pya... | [
"Check out the --platform linux.x86_64 setting on obfuscate command. There is also one for mac.\nCheck here for the docs:https://pyarmor.readthedocs.io/en/latest/platforms.html?highlight=platform#standard-platform-names\n"
] | [
0
] | [] | [] | [
"obfuscation",
"pyarmor",
"python"
] | stackoverflow_0071356253_obfuscation_pyarmor_python.txt |
Q:
How to calculate difference among every item within a group?
Consider the following DataFrame:
team player metric_a metric_b
0 1 player1 15 25
1 1 player2 20 30
2 1 player3 21 12
3 2 player4 9 46
4 2 player5 39 5
How could we compute the (abs... | How to calculate difference among every item within a group? | Consider the following DataFrame:
team player metric_a metric_b
0 1 player1 15 25
1 1 player2 20 30
2 1 player3 21 12
3 2 player4 9 46
4 2 player5 39 5
How could we compute the (absolute) difference of every player with every other player of the s... | [
"Let's try something new...self merge the dataframe on team to create all possible combinations then calculate the diff by subtracting the columns from left and right dataframes\ns = df.reset_index()\ns = (\n s.merge(s, on='team')\n .query('index_y > index_x') # remove duplicate combinations\n .drop(colu... | [
2,
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074210531_dataframe_pandas_python.txt |
Q:
Is there a way to create a list of callbacks to be done in python?
I have a program with multiple sliders, and there is a function called slider.on_changed() that allows to check if the amplitude of the slider has changed.
Right now I have the following:
slider1.on_changed(update)
slider2.on_changed(update)
Howev... | Is there a way to create a list of callbacks to be done in python? | I have a program with multiple sliders, and there is a function called slider.on_changed() that allows to check if the amplitude of the slider has changed.
Right now I have the following:
slider1.on_changed(update)
slider2.on_changed(update)
However, I want to have n sliders. Is there a way to create a list of callbac... | [
"You can put your sliders in a list:\nsliders = [slider1, slider2, slider3, ...]\n\nAnd then call N times their function:\nfor i in range(N):\n sliders[i].on_changed(update)\n\n"
] | [
0
] | [] | [] | [
"callback",
"event_handling",
"matplotlib",
"python",
"slider"
] | stackoverflow_0074221943_callback_event_handling_matplotlib_python_slider.txt |
Q:
Python: How to overcome invalid argument of incorrect file path
I am attempting to write a Python script that captures a screenshot everytime the left mouse button is pressed. I am using this guide as a reference: https://pytutorial.com/python-capture-screenshot-mouse-clicked
My problem is coming from the file pat... | Python: How to overcome invalid argument of incorrect file path | I am attempting to write a Python script that captures a screenshot everytime the left mouse button is pressed. I am using this guide as a reference: https://pytutorial.com/python-capture-screenshot-mouse-clicked
My problem is coming from the file path. I am wanting the screenshots to be saved in the "Screenshoots" fol... | [
"The problem is with the filename you're creating using strftime():\n26-10-2022_22:12:52.jpg\n\nWindows filenames can't have a : in them, because : in a file path is the separator between a drive letter (e.g. C:) and a path. There is an exception to this to use a : as part of a feature called Alternative Data Strea... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074217097_python.txt |
Q:
Cumulative sum on grouped objects
I have a dataframe like the following:
df = pd.DataFrame(data)
conditions = [
(df['Opened'] <'2022-09-30') & (df['Opened'] > '2022-03-31'),
(df['Opened'] <'2022-03-31') & (df['Opened'] > '2021-10-31'),
(df['Opened'] <'2021-10-31') & (df['Opened'] > '2021-04-30'),
... | Cumulative sum on grouped objects | I have a dataframe like the following:
df = pd.DataFrame(data)
conditions = [
(df['Opened'] <'2022-09-30') & (df['Opened'] > '2022-03-31'),
(df['Opened'] <'2022-03-31') & (df['Opened'] > '2021-10-31'),
(df['Opened'] <'2021-10-31') & (df['Opened'] > '2021-04-30'),
(df['Opened'] <'2021-04-30') & (df['O... | [
"I suggest adding 'agg' method like:\ndf=df.groupby('SentMonth').agg('Amount': 'count')\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"group_by",
"python"
] | stackoverflow_0074220543_dataframe_group_by_python.txt |
Q:
How to only calculate the xp earned at frist try?
So the user can take some quiz and earn xp only at first try. From the second try on I only want to calculate how many correct answer scored but not xp will be earn.
My models:
class ClassAttempt(models.Model):
user = models.ForeignKey(to=User,on_delete= models... | How to only calculate the xp earned at frist try? | So the user can take some quiz and earn xp only at first try. From the second try on I only want to calculate how many correct answer scored but not xp will be earn.
My models:
class ClassAttempt(models.Model):
user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True)
related_class = models.Foreign... | [
"You can get the first object in table using first()\nMyModel.objects.first()\n\nso calculate the xp from this result\nor\nMyModel.objects.all()[:number_for_question_you_want]\n\nexample:\nMyModel.objects.all()[:5]\n\nalso you can use .values() or any other filter you want\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074221522_django_python.txt |
Q:
JSON schema validation, If there are additional keys they have to be of a specified name and type
I'm a beginner to json (I do not have a history with JS) and only recently I've met with the need for json schema and it's validation. The problem could be described as:
I have 5 keys (properties) in my json; A, B, C,... | JSON schema validation, If there are additional keys they have to be of a specified name and type | I'm a beginner to json (I do not have a history with JS) and only recently I've met with the need for json schema and it's validation. The problem could be described as:
I have 5 keys (properties) in my json; A, B, C, D, E, of which A, B and C are required, but D and E are not, specifically, every combination of D, E a... | [
"Instead of \"maxProperties\": 5 you could use \"additionalProperties\": False\nHere in code:\nimport json\nfrom jsonschema import Draft7Validator\n\nmy_schema = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"required\": [\n \"A\", \"B\", \"C\"\n ],\n \"properties\": {\n ... | [
0
] | [] | [] | [
"json",
"json_schema_validator",
"jsonschema",
"python"
] | stackoverflow_0074221998_json_json_schema_validator_jsonschema_python.txt |
Q:
Create a pivot table with yearly index for each value
I'm currently dealing with a worldbank dataset and I would like to pivot it to analyse it better.
Currently, it's in a form like this :
df = pd.DataFrame({'Country Name' : ['A','A','A','B','B','B','C','C','C'],'Indicator' : ['X','Y','Z','X','Y','Z','X','Y','Z']... | Create a pivot table with yearly index for each value | I'm currently dealing with a worldbank dataset and I would like to pivot it to analyse it better.
Currently, it's in a form like this :
df = pd.DataFrame({'Country Name' : ['A','A','A','B','B','B','C','C','C'],'Indicator' : ['X','Y','Z','X','Y','Z','X','Y','Z'],'2010' : [1,2,3,4,5,6,7,8,9],'2011' : [9,8,7,6,5,4,3,2,1]}... | [
"melt before pivot_table:\n(df.melt(['Country Name', 'Indicator'], var_name='Year')\n .pivot_table(index=['Country Name', 'Year'],\n columns='Indicator', values='value')\n)\n\nOr reshape with stack/unstack (requires unique values, unlike pivot_table):\n(df.set_index(['Country Name', 'Indicator'])\n... | [
1
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074222065_multi_index_pandas_python.txt |
Q:
Install gdcm without conda
I want to install gdcm on linux. Based on the instructions (https://anaconda.org/clinicalgraphics/gdcm), I have to use:
conda install -c clinicalgraphics gdcm
However, I can not use conda install because I should not use Anaconda for some reasons. So, how can I install gdcm?
A:
The pr... | Install gdcm without conda | I want to install gdcm on linux. Based on the instructions (https://anaconda.org/clinicalgraphics/gdcm), I have to use:
conda install -c clinicalgraphics gdcm
However, I can not use conda install because I should not use Anaconda for some reasons. So, how can I install gdcm?
| [
"The problem is that you've gone to the Anaconda page for gdcm, instead of to the project's homepage. Of course the Anaconda page tells you how to install it for Anaconda. But it's got a link to the homepage right there near the top:\nHome: https://sourceforge.net/p/gdcm/gdcm/\n\nIf you follow the link, the readme ... | [
2,
0,
0
] | [] | [] | [
"anaconda",
"installation",
"linux",
"python"
] | stackoverflow_0050957541_anaconda_installation_linux_python.txt |
Q:
Which seeds have to be set where to realize 100% reproducibility of training results in tensorflow?
In a general tensorflow setup like
model = construct_model()
with tf.Session() as sess:
train_model(sess)
Where construct_model() contains the model definition including random initialization of weights (tf.tru... | Which seeds have to be set where to realize 100% reproducibility of training results in tensorflow? | In a general tensorflow setup like
model = construct_model()
with tf.Session() as sess:
train_model(sess)
Where construct_model() contains the model definition including random initialization of weights (tf.truncated_normal) and train_model(sess) executes the training of the model -
Which seeds do I have to set wh... | [
"One possible reason is that when constructing the model, there are some code using numpy.random module. So maybe you can try to set the seed for numpy, too. \n",
"The best solution which works as of today with GPU is to install tensorflow-determinism with the following:\npip install tensorflow-determinism\n\nThe... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"random_seed",
"tensorflow"
] | stackoverflow_0042022950_python_random_seed_tensorflow.txt |
Q:
selecting some rows from Truth Table
I am using Truths class to generate a truth table :
https://github.com/tr3buchet/truths
However I could not enumerate all rows or extract rows with correct evaluation of expression? Is there a way to do that ?
I received this error :
AttributeError: 'Truths' object has no attri... | selecting some rows from Truth Table | I am using Truths class to generate a truth table :
https://github.com/tr3buchet/truths
However I could not enumerate all rows or extract rows with correct evaluation of expression? Is there a way to do that ?
I received this error :
AttributeError: 'Truths' object has no attribute 'rows'
thanks in advance
I can only g... | [
"A Truths object stores almost exclusively the information that is provided during initialization. That is: the base items, the phrases (optional) and the ints (also optional).\nThe only other things are:\n\na regex method (which is probably not what you are looking for) and\na list of base_conditions, which stores... | [
0
] | [] | [] | [
"enumerate",
"generate",
"logic",
"python",
"truthtable"
] | stackoverflow_0074195134_enumerate_generate_logic_python_truthtable.txt |
Q:
What is _, in python used before declaring variables?
I was reading an article(https://www.techgeekbuzz.com/blog/how-to-read-emails-in-python/) that describes how to read emails using python, now its using _, before declaring a variable here is the code:
#modules
import imaplib
import email
#credentials
username ... | What is _, in python used before declaring variables? | I was reading an article(https://www.techgeekbuzz.com/blog/how-to-read-emails-in-python/) that describes how to read emails using python, now its using _, before declaring a variable here is the code:
#modules
import imaplib
import email
#credentials
username ="codehundred100@gmail.com"
#generated app password
app_pa... | [
"I think your question is unclear as it seems to be asking about leading underscores in variable names but the example code you provide is a variable who's who name is just _.\nIn the case of the former, leading underscores in variable names (eg. _myVariable), according to PEP8 is meant to denote that variable shou... | [
1,
1
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0074210602_python_variables.txt |
Q:
Open Jupyter Notebook from a Drive Other than C Drive
I have a machine learning project in drive D. It contains python notebook files. But when I launch jupyter notebook through command prompt, it only shows directories inside drive C. How can I navigate to a drive other than C drive without changing jupyter noteb... | Open Jupyter Notebook from a Drive Other than C Drive | I have a machine learning project in drive D. It contains python notebook files. But when I launch jupyter notebook through command prompt, it only shows directories inside drive C. How can I navigate to a drive other than C drive without changing jupyter notebook startup path?. I'm using windows 10 operating system. A... | [
"You can launch it from any drive/location you want with the --notebook-dir option.\nFor example:\njupyter notebook --notebook-dir=D:/\n\n",
"Follow these steps:\n\nOpen Anaconda Prompt\nInsert this command,\njupyter notebook --notebook-dir=NameOfTheDrive:.\n\nAs Example for Drive D, jupyter notebook --notebook-d... | [
146,
35,
18,
9,
6,
5,
4,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0055078484_jupyter_notebook_python.txt |
Q:
Count number of transitions in each row of a Numpy array
I have a 2D boolean array
a=np.array([[True, False, True, False, True],[True , True, True , True, True], [True , True ,False, False ,False], [False, True , True, False, False], [True , True ,False, True, False]])
I would like to create a new array, pr... | Count number of transitions in each row of a Numpy array | I have a 2D boolean array
a=np.array([[True, False, True, False, True],[True , True, True , True, True], [True , True ,False, False ,False], [False, True , True, False, False], [True , True ,False, True, False]])
I would like to create a new array, providing count of True-False transitions in each row of this ar... | [
"Here is a possible solution:\nb = a.astype(int)\nc = (b[:, :-1] - b[:, 1:])\ncount = (c == 1).sum(axis=1)\n\nResult:\n>>> count\narray([2, 0, 1, 1, 2])\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074221832_numpy_python.txt |
Q:
Filter pandas frame based on example row with "wildcard" values
I have a dataframe and a filter I want to apply to the frame in the form of a series. The filtered dataframe should include all rows that match the filter. Where the filter has a "wildcard-value", defined in this case as NaN, everything is considered ... | Filter pandas frame based on example row with "wildcard" values | I have a dataframe and a filter I want to apply to the frame in the form of a series. The filtered dataframe should include all rows that match the filter. Where the filter has a "wildcard-value", defined in this case as NaN, everything is considered a match.
Below is my implementation of such a filter:
df: pandas.Data... | [
"You could try to use an inner join to keep only the relevant rows, like this example:\n# Remove indexes without condition\nf = f.dropna()\n\n# Move the series into a DataFrame (T needed to transpose)\nf_frame = f.to_frame().T\n\n# Perform inner join\nfiltered_df = df.merge(f_frame, how='inner', on=list(f_frame.col... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074220827_pandas_python.txt |
Q:
How to split a numpy array of integers, into chunks that have successive values with a difference below a threshold
I have the following numpy array with positive integers, in ascending order:
import numpy as np
arr = np.array([222, 225, 227, 228, 230, 232, 241, 243, 244, 245, 252, 253, 258])
I want to split it,... | How to split a numpy array of integers, into chunks that have successive values with a difference below a threshold | I have the following numpy array with positive integers, in ascending order:
import numpy as np
arr = np.array([222, 225, 227, 228, 230, 232, 241, 243, 244, 245, 252, 253, 258])
I want to split it, into parts, where at each part, each number has maximum difference of 2 from the next one.
So the following array should... | [
"You can compute the diff, get the indices of differences above threshold with flatnonzero, and split with array_split:\nthreshold = 2\n\nout = np.array_split(arr, np.flatnonzero(np.diff(arr)>threshold)+1)\n\noutput:\n[array([222]),\n array([225, 227, 228, 230, 232]),\n array([241, 243, 244, 245]),\n array([252, 25... | [
5
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074222179_numpy_python.txt |
Q:
KIX barcode in ZPL
I'm trying to print out an addresslabel on a Zebra (ZPL) printer. Since we are sending within the Netherlands, it is required to add a KIX barcode to our labels, so the equipment for sorting the documents can read the zipcode and housenumber. Our labels look a bit like this:
I can create a KIX ... | KIX barcode in ZPL | I'm trying to print out an addresslabel on a Zebra (ZPL) printer. Since we are sending within the Netherlands, it is required to add a KIX barcode to our labels, so the equipment for sorting the documents can read the zipcode and housenumber. Our labels look a bit like this:
I can create a KIX barcode in ZDesigner 2, ... | [
"Seems the barcode symbiology is not terribly complicated. You could probably make your own algorithm. It's just simple lines and spacing; not terribly complex.ZPL gives you the capability of making lines pretty easy. You can keep track of the character number, and add X pixels * character number for positioning. U... | [
0
] | [] | [] | [
"barcode",
"python",
"zebra_printers",
"zpl"
] | stackoverflow_0074207131_barcode_python_zebra_printers_zpl.txt |
Q:
Matplotlib line and bar in the same chart
I have a pandas dataframe with this easy structure:
Month
Energy
Percentage
Jan
10
0.5
Feb
11
0.6
March
13
0.71
April
15
0.73
May
18
0.81
June
20
0.85
July
24
0.91
August
28
0.93
September
24
0.81
November
17
0.71
December
15
0.6
And I want to plot the energy ... | Matplotlib line and bar in the same chart | I have a pandas dataframe with this easy structure:
Month
Energy
Percentage
Jan
10
0.5
Feb
11
0.6
March
13
0.71
April
15
0.73
May
18
0.81
June
20
0.85
July
24
0.91
August
28
0.93
September
24
0.81
November
17
0.71
December
15
0.6
And I want to plot the energy in bar and the percentaje in... | [
"The code below solves your problem. So basically using the twinx() function you are able to create the 2nd access on the same plot. I copied and pasted the data you provided in your question to an excel file named Book1.xlsx.\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_excel(\"Book1.xlsx\... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074221875_matplotlib_pandas_python.txt |
Q:
Django Rest Framework: TypeError: Object of type Facility is not JSON serializable
When i try to send a put request to my LeadUpdate Api Endpoint i receive the following error:
Django Rest Framework: TypeError: Object of type Facility is not JSON serializable
Can someone tell me why that is?
This serializer is ba... | Django Rest Framework: TypeError: Object of type Facility is not JSON serializable | When i try to send a put request to my LeadUpdate Api Endpoint i receive the following error:
Django Rest Framework: TypeError: Object of type Facility is not JSON serializable
Can someone tell me why that is?
This serializer is basically supposed to save assigned facilities within a lead when a lead gets updated and ... | [
"The issue is in the to_representation method for the serializer.\ndef to_representation(self, instance):\n representation = super().to_representation(instance)\n\n representation[\"scheduled_datetime\"] = instance.LeadFacilityAssociation.first().scheduled_datetime\n representation[\"assigned_f... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074221666_django_django_rest_framework_python.txt |
Q:
Read Excel file from python pandas
I am unable to read this type of excel file from pandas in python.
A:
Although cannot understand your situation best from picture.
Still recommend to Try to read file with following code might help, where you need to add extra parameters which will help to filter some unnecessa... | Read Excel file from python pandas | I am unable to read this type of excel file from pandas in python.
| [
"Although cannot understand your situation best from picture.\nStill recommend to Try to read file with following code might help, where you need to add extra parameters which will help to filter some unnecessary info.\npd.read_excel(full_path, sheet_name = 'Daily Report', skiprows = <rowsyouwnttoskip>, nrows= <yo... | [
0,
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074221757_excel_pandas_python.txt |
Q:
Scrapy - What to do when no downloadable file is found?
I am currently working on a scrapy program that has the availability to download files from the page I'm scraping from, the issue that I am currently running into is that some of the pages have a datasheet like this page - https://www.tyconsystems.com/rpms24-... | Scrapy - What to do when no downloadable file is found? | I am currently working on a scrapy program that has the availability to download files from the page I'm scraping from, the issue that I am currently running into is that some of the pages have a datasheet like this page - https://www.tyconsystems.com/rpms24-720-720 - while others do not like this page - https://www.ty... | [
"Two approaches are possible:\n1. Override get_media_requests\nOverride get_media_requests in your pipelines to check for the existence of URLs as follows:\nclass DownfilesPipeline(FilesPipeline):\n def get_media_requests(self, item, info):\n urls = ItemAdapter(item).get(self.files_urls_field, [])\n ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"scrapy",
"web_scraping"
] | stackoverflow_0074215604_python_python_3.x_scrapy_web_scraping.txt |
Q:
Splitting a text file into two different text files
I have a file called names62.txt and it contains 62 names. There is one name per each line, so it contains 62 lines.
I need to develop a Python program that writes the 80% of the names contained in names62.txt to a file called train.txt and 20% of the names to a ... | Splitting a text file into two different text files | I have a file called names62.txt and it contains 62 names. There is one name per each line, so it contains 62 lines.
I need to develop a Python program that writes the 80% of the names contained in names62.txt to a file called train.txt and 20% of the names to a second output file called test.txt.
How can I do that? Th... | [
"Try this code:\ntrain_filename = 'train.txt'\ntest_filename = 'test.txt'\ntrain = open(train_filename, 'w')\ntest = open(test_filename, 'w')\n\np1 = int(input(\"Insert a number for the percentage? \"))\nn = 0\nwith open('names62.txt') as f:\n for name in f:\n n += 1\n\nnum_name_in_train = (n * p1) / 100\... | [
0
] | [] | [] | [
"file",
"python",
"split"
] | stackoverflow_0074221694_file_python_split.txt |
Q:
Creating uniform random quaternion and multiplication of two quaternions
I have a python (NumPy) function which creates a uniform random quaternion. I would like to get two quaternion multiplication as 2-dimensional returned array from the same or an another function. The formula of quaternion multiplication in my... | Creating uniform random quaternion and multiplication of two quaternions | I have a python (NumPy) function which creates a uniform random quaternion. I would like to get two quaternion multiplication as 2-dimensional returned array from the same or an another function. The formula of quaternion multiplication in my recent case is Q1*Q2 and Q2*Q1. Here, Q1=(w0, x0, y0, z0) and Q2=(w1, x1, y1,... | [
"I know that the question is old but as I found it interesting, for future reference I herewith write an answer: if no special data type for quaternions is desirable, then a quaternion can be written as a tuple of a real number and a normal vector as an array of floats. Thus, mathematically, based on the process me... | [
1,
0,
0,
0,
0
] | [] | [] | [
"2d",
"numpy",
"python",
"quaternions"
] | stackoverflow_0038978441_2d_numpy_python_quaternions.txt |
Q:
Conditionally defining method of a class
I have a Config class. I would like it to have several methods, which depends on another variable of the class. This way I would only have to change one variable in the config class and then it would function differently.
I tried the following. When creating an instance I c... | Conditionally defining method of a class | I have a Config class. I would like it to have several methods, which depends on another variable of the class. This way I would only have to change one variable in the config class and then it would function differently.
I tried the following. When creating an instance I can access other_param, but the objective funct... | [
"Something like this should work for your problem:\nclass Config:\n\n def __init__(self, task: str):\n self.task = task\n if self.task == 'Task1':\n self.other_param = 1\n self.objective = lambda probs: probs[0]\n elif self.task == 'Task2':\n self.other_param... | [
0,
0,
0
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0074221842_class_methods_python.txt |
Q:
How do I make an input() detect if the user input is something other than a string?
I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It w... | How do I make an input() detect if the user input is something other than a string? | I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported char... | [
"Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.\nisalpha() returns True for strings with only alphabets.\nisalnum() returns True for strings with only alphabets and numbers and nothing else.\nisdigit() returns True for strings with only numbers.\nAlso your if-else state... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074222376_python.txt |
Q:
Unable to import LazyRegressor
I am unable to use LazyRegressor in my jupyter notebook.
After doing:
import lazypredict
from lazypredict.Supervised import LazyRegressor
I get this error:
---------------------------------------------------------------------------
OSError Tracebac... | Unable to import LazyRegressor | I am unable to use LazyRegressor in my jupyter notebook.
After doing:
import lazypredict
from lazypredict.Supervised import LazyRegressor
I get this error:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
/var/folde... | [
"Okay found the answer. These files were missing.\nconda install -c conda-forge xgboost\nconda install -c conda-forge lightgbm\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074209892_python.txt |
Q:
How to add list elements into dictionary
Let's say I have dict = {'a': 1, 'b': 2'} and I also have a list = ['a', 'b, 'c', 'd', 'e']. Goal is to add the list elements into the dictionary and print out the new dict values along with the sum of those values. Should look like:
2 a
3 b
1 c
1 d
1 e
Total number of item... | How to add list elements into dictionary | Let's say I have dict = {'a': 1, 'b': 2'} and I also have a list = ['a', 'b, 'c', 'd', 'e']. Goal is to add the list elements into the dictionary and print out the new dict values along with the sum of those values. Should look like:
2 a
3 b
1 c
1 d
1 e
Total number of items: 8
Instead I get:
1 a
2 b
1 c
1 d
1 e
Total... | [
"You just have to iterate the list and increment the count against the key if it is already there, otherwise set it to 1.\n>>> d = {'a': 1, 'b': 2}\n>>> l = ['a', 'b', 'c', 'd', 'e']\n>>> for item in l:\n... if item in d:\n... d[item] += 1\n... else:\n... d[item] = 1\n>>> d\n{'a': 2, 'c': 1,... | [
11,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"python_3.x"
] | stackoverflow_0030208044_dictionary_list_python_python_3.x.txt |
Q:
Efficient way to iteratively count entries between given dates
I have two dataframes.
Dataframe allocatedTimes collects the allocated time (for a given activity) for a person identified by an ID.
ID: id of the person
startTime: allocated slot start datetime
endTime: allocated slot end datetime
weekday: calculated ... | Efficient way to iteratively count entries between given dates | I have two dataframes.
Dataframe allocatedTimes collects the allocated time (for a given activity) for a person identified by an ID.
ID: id of the person
startTime: allocated slot start datetime
endTime: allocated slot end datetime
weekday: calculated corresponding weekday
Dataframe events collects the events associat... | [
"First, in both DataFrames, create a column with \"start_date\", then join both Dataframes on id and start_date.\nres_df = pd.merge(allocatedTimes, events, how='left', on=['id', 'start_date'])\n\nNow filter that DataFrame to only keep the rows where the event time is inside the allocated time's timeframe.\nalloc_ev... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074222108_pandas_python.txt |
Q:
compare two lists with multiple attributes regarding the first attribute of each entry
I'm struggeling at an implementation in python for the following probelm:
I have two lists which look similar to the once below:
list1 = [("aa",2),("bb",1),("cc",5),("dd",3),("ee",7)]
list2 = [("bb",3),("dd",1),("cc",2)]
Regard... | compare two lists with multiple attributes regarding the first attribute of each entry | I'm struggeling at an implementation in python for the following probelm:
I have two lists which look similar to the once below:
list1 = [("aa",2),("bb",1),("cc",5),("dd",3),("ee",7)]
list2 = [("bb",3),("dd",1),("cc",2)]
Regarding the first attribute of the lists - the String, the second list, list2, consists out of a... | [
"Assuming the string values in list2 are unique, you could make a set of them and then use a list comprehension over list1 to generate the required output, checking whether the string element is contained in the set:\nlist1 = [(\"aa\",2),(\"bb\",1),(\"cc\",5),(\"dd\",3),(\"ee\",7)]\nlist2 = [(\"bb\",3),(\"dd\",1),(... | [
1
] | [] | [] | [
"equals",
"for_loop",
"if_statement",
"list",
"python"
] | stackoverflow_0074222430_equals_for_loop_if_statement_list_python.txt |
Q:
why python modules used in power BI desktop not working in power BI service
I have a python visual code which is working when ran in power BI desktop.
but when i published the same to power BI service and try to run, its throwing "Modlue Not found" error.
What might be the reason and how to overcome this error.
I'... | why python modules used in power BI desktop not working in power BI service | I have a python visual code which is working when ran in power BI desktop.
but when i published the same to power BI service and try to run, its throwing "Modlue Not found" error.
What might be the reason and how to overcome this error.
I'm importing below modules in my script
import pandas as pd
import numpy as np
imp... | [
"The official documentation has a list of packages that are supported in the online service:\nPython packages that are supported in Power BI.\nYou can request support for a new package here:\nPower BI Ideas\n",
"\nwhat might be the reason\n\nBecause your code is run in a multi-tenant SaaS service and so must run ... | [
1,
0
] | [] | [] | [
"powerbi",
"powerbi_desktop",
"python"
] | stackoverflow_0074217658_powerbi_powerbi_desktop_python.txt |
Q:
How to create a bar plot of the number of unique values within each group
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
## the following is the data set
gm = pd.read_csv('https://raw.githubusercontent.com/gerberl/6G7V0026-2223/main/datasets/gapminder.tsv', sep='\t')
the command that ... | How to create a bar plot of the number of unique values within each group | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
## the following is the data set
gm = pd.read_csv('https://raw.githubusercontent.com/gerberl/6G7V0026-2223/main/datasets/gapminder.tsv', sep='\t')
the command that I have been using, which counts each country multiple times.
sns.countplot(x=gm... | [
"\nThe most direct way is to use pandas to get the number of unique countries for each continent, and then plot directly with pandas.DataFrame.plot.\n\npandas uses matplotlib as the default plotting backend, and seaborn is just an API for matplotlib.\n\n\nThis answer shows how to use pd.DataFrame.pivot_table to get... | [
0,
0
] | [] | [] | [
"bar_chart",
"matplotlib",
"pandas",
"python",
"seaborn"
] | stackoverflow_0074089205_bar_chart_matplotlib_pandas_python_seaborn.txt |
Q:
Locust class-picker mode auto reset statistic when ramping up users
currently I have started working with Locust. I follow the class-picker docs and practice with a simple test, but quickly realized that every time I increase the number of users during the test, Locust will reset the statistics table. Besides, Loc... | Locust class-picker mode auto reset statistic when ramping up users | currently I have started working with Locust. I follow the class-picker docs and practice with a simple test, but quickly realized that every time I increase the number of users during the test, Locust will reset the statistics table. Besides, Locust behevior of ramping up users is quite strange: instead of increasing ... | [
"The user class UI picker is designed to let you choose a user class to use for the test run. This means that user class will be used for the whole duration of the test. If you want to choose a different user class, you need to start a new test which results in the behavior you described: Locust stops all currently... | [
1
] | [] | [] | [
"load_testing",
"locust",
"python",
"webui"
] | stackoverflow_0074219230_load_testing_locust_python_webui.txt |
Q:
Check if a character is not in a string (pyt
password = "e"
if any(c in password for c in "abcd"):
print("yes")
I am trying to write a code that allows me to check if a character "e", is not included in "abcd".
However, the code above only prints yes if there's an occurrence in the password of a, b, c, or d. I... | Check if a character is not in a string (pyt | password = "e"
if any(c in password for c in "abcd"):
print("yes")
I am trying to write a code that allows me to check if a character "e", is not included in "abcd".
However, the code above only prints yes if there's an occurrence in the password of a, b, c, or d. I don't know how to change it to have: If there's a... | [
"any takes an iterable. It expects a True. Statement so you should use not in rather than in. Because if not in you want it to say True, not in.\nif any([c, if c not in 'abcd' for c in password]):\n print(\"yes\")\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074222329_python.txt |
Q:
Why do i keep gettig an error message o this code
this is an IBM skill lab code. try running it and keeps getting a error
pearson_coef, p_value = stats.pearsonr(df['city-mpg'], df['price'])
print("The Pearson Correlation Coefficient is", pearson_coef, " with a P-value of P = ", p_value)
error message
----------... | Why do i keep gettig an error message o this code | this is an IBM skill lab code. try running it and keeps getting a error
pearson_coef, p_value = stats.pearsonr(df['city-mpg'], df['price'])
print("The Pearson Correlation Coefficient is", pearson_coef, " with a P-value of P = ", p_value)
error message
-----------------------------------------------------------------... | [
"You have to import stats - which without knowing what package you're trying to use - I would assume is the stats package from scipy\nAdd the following line at the top of your cell or file\n# Import statistical package from Scipy\nfrom scipy import stats\n\n"
] | [
1
] | [] | [] | [
"data_science",
"pearson_correlation",
"python"
] | stackoverflow_0074222506_data_science_pearson_correlation_python.txt |
Q:
Concatenate multiple strings and dictionary values
I have this dictionary and a list of sequences in the input file. The dictionary keys represent an aminoacid and the value represents the vector for this aminoacid.
I am trying to get an output like this:
MNTFSQVWVFSDTPSRLPELMNGAQALANQ:0000000000100000000000000000... | Concatenate multiple strings and dictionary values | I have this dictionary and a list of sequences in the input file. The dictionary keys represent an aminoacid and the value represents the vector for this aminoacid.
I am trying to get an output like this:
MNTFSQVWVFSDTPSRLPELMNGAQALANQ:000000000010000000000000000000010000000000000000000000001000000010000000000000000000... | [
"You can remove '\\n' from the line:\nx = line.strip()\n\nor read lines without '\\n's:\nfor line in f.readlines():\n ...\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"list",
"python",
"python_3.x"
] | stackoverflow_0074222627_dictionary_list_python_python_3.x.txt |
Q:
Find all combinations of a list of numbers with a given sum
I have a list of numbers, e.g.
numbers = [1, 2, 3, 7, 7, 9, 10]
As you can see, numbers may appear more than once in this list.
I need to get all combinations of these numbers that have a given sum, e.g. 10.
The items in the combinations may not be rep... | Find all combinations of a list of numbers with a given sum | I have a list of numbers, e.g.
numbers = [1, 2, 3, 7, 7, 9, 10]
As you can see, numbers may appear more than once in this list.
I need to get all combinations of these numbers that have a given sum, e.g. 10.
The items in the combinations may not be repeated, but each item in numbers has to be treated uniquely, that ... | [
"You could use itertools to iterate through every combination of every possible size, and filter out everything that doesn't sum to 10:\nimport itertools\n\nnumbers = [1, 2, 3, 7, 7, 9, 10]\ntarget = 10\n\nresult = [seq for i in range(len(numbers), 0, -1)\n for seq in itertools.combinations(numbers, i)\n ... | [
38,
24,
22,
4,
2,
1
] | [] | [] | [
"algorithm",
"combinations",
"python",
"python_3.x",
"subset_sum"
] | stackoverflow_0034517540_algorithm_combinations_python_python_3.x_subset_sum.txt |
Q:
Error: sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'user_name'
Flask-SQLAlchemy Core
I'm getting an error while binding parameters to sql query.
In this I want to bind dynamic parameters fetched from POSTMAN and return query for that specific data pres... | Error: sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'user_name' | Flask-SQLAlchemy Core
I'm getting an error while binding parameters to sql query.
In this I want to bind dynamic parameters fetched from POSTMAN and return query for that specific data present in DB.
SQL query to be implemented:- SELECT id, user_name, password, email_address, dob, uid FROM user WHERE user_name = 'Prati... | [
"In this I was comparing salted password with simple plain text which didn't work for me, so I fetched data using the only username and then compared password using \"werkzeug.security import generate_password_hash,check_password_hash\".\nhttps://werkzeug.palletsprojects.com/en/2.2.x/utils/#werkzeug.security.check_... | [
1
] | [] | [] | [
"flask",
"python",
"sqlalchemy"
] | stackoverflow_0074140104_flask_python_sqlalchemy.txt |
Q:
Drawing Weighted Bipartite Graph using python
I am trying to make a weighted bipartite graph using a dataset. I have a dataset as below-
i=0
for a in attributes_n:
B.add_weighted_edges_from(
[(row['Country'], a, row[a]) for idx, row in df.iterrows() if row[a] > weight_l[i]],
weight='weight')
But I am g... | Drawing Weighted Bipartite Graph using python | I am trying to make a weighted bipartite graph using a dataset. I have a dataset as below-
i=0
for a in attributes_n:
B.add_weighted_edges_from(
[(row['Country'], a, row[a]) for idx, row in df.iterrows() if row[a] > weight_l[i]],
weight='weight')
But I am getting errors while checking
bipartite.sets(B)
Amb... | [
"Bipartitie sets are determined via graph colouring. This results in a unique solution for each component of your graph. However, if your graph consists of multiple components, then there are multiple ways in which sets for different components could be joined to produce the final output. The solution is hence ambi... | [
0
] | [] | [] | [
"bipartite",
"networkx",
"python",
"social_networking"
] | stackoverflow_0074222094_bipartite_networkx_python_social_networking.txt |
Q:
Boto3 S3 Multipart Download of a Large Byte Range
I have a set of 4GB files stored in S3 that I need to extract 1GB sections from. I know that I can accomplish this via a boto3 S3 ranged get request:
import boto3
s3 = boto3.client('s3')
bucket = ''
key = ''
start = 100_0000_000
end = 200_0000_000
response = s3.ge... | Boto3 S3 Multipart Download of a Large Byte Range | I have a set of 4GB files stored in S3 that I need to extract 1GB sections from. I know that I can accomplish this via a boto3 S3 ranged get request:
import boto3
s3 = boto3.client('s3')
bucket = ''
key = ''
start = 100_0000_000
end = 200_0000_000
response = s3.get_object(Bucket=bucket, Key=key, Range=f'bytes={start}-... | [
"I have come up with a working solution using a ThreadPoolExecutor, but I believe it can still be improved. The best approach I found was to set up a thread pool of s3_client.get_object calls that have the range parameter specified:\nimport math\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport boto3\n\n... | [
1
] | [] | [] | [
"amazon_ec2",
"amazon_s3",
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0074153775_amazon_ec2_amazon_s3_amazon_web_services_boto3_python.txt |
Q:
Creating image tiles (m*n) of original image using Python and Numpy
I am using numpy to create tiles of (224*224) from my 16-bit tiff image (13777*16004). I was able to crop/slice into equal tiles of 224*224 along the rows and columns. I ran into problems while trying to create new tiles shifting by half of the ti... | Creating image tiles (m*n) of original image using Python and Numpy | I am using numpy to create tiles of (224*224) from my 16-bit tiff image (13777*16004). I was able to crop/slice into equal tiles of 224*224 along the rows and columns. I ran into problems while trying to create new tiles shifting by half of the tile size... For instance: A rough algorithm of what i am trying to achieve... | [
"You went a little off while calculating the range of your for loop. The number of slices to be made, must be calculated using the offset between two slices, which is x0/2 in your case, I have simplified your code and defined some meaningful variables which you can configure to get desired tiles from a given image:... | [
9,
4,
1,
1,
0,
0
] | [] | [] | [
"image",
"numpy",
"opencv",
"python"
] | stackoverflow_0045950124_image_numpy_opencv_python.txt |
Q:
Get ping latency time value with Python
I'm trying to write a simple script to ping an adress and retrieve the latency time. I've seen several solutions online but it doesn't work on my end.
import subprocess
import re
p = subprocess.Popen(["ping.exe","8.8.8.8"], stdout = subprocess.PIPE)
ping = p.communicate()[0... | Get ping latency time value with Python | I'm trying to write a simple script to ping an adress and retrieve the latency time. I've seen several solutions online but it doesn't work on my end.
import subprocess
import re
p = subprocess.Popen(["ping.exe","8.8.8.8"], stdout = subprocess.PIPE)
ping = p.communicate()[0]
timestr = re.compile("temps=[0-9]+ms").fin... | [
"re.findall(r'temps=[0-9]+\\s*ms',str(ping)) solves my problem. I get the times with a combination of 0 to 9 of several numbers, \\s*ms tells that it can have 0 to several spaces before ms.\n"
] | [
0
] | [] | [] | [
"parsing",
"ping",
"python"
] | stackoverflow_0074222396_parsing_ping_python.txt |
Q:
Conditional assignment of tensor values in TensorFlow
I want to replicate the following numpy code in tensorflow. For example, I want to assign a 0 to all tensor indices that previously had a value of 1.
a = np.array([1, 2, 3, 1])
a[a==1] = 0
# a should be [0, 2, 3, 0]
If I write similar code in tensorflow I get... | Conditional assignment of tensor values in TensorFlow | I want to replicate the following numpy code in tensorflow. For example, I want to assign a 0 to all tensor indices that previously had a value of 1.
a = np.array([1, 2, 3, 1])
a[a==1] = 0
# a should be [0, 2, 3, 0]
If I write similar code in tensorflow I get the following error.
TypeError: 'Tensor' object does not s... | [
"Comparison operators such as greater than are available within TensorFlow API.\nHowever, there is nothing equivalent to the concise NumPy syntax when it comes to manipulating the tensors directly. You have to make use of individual comparison, where and assign operators to perform the same action.\nEquivalent code... | [
30,
3,
0
] | [] | [] | [
"numpy",
"python",
"tensorflow"
] | stackoverflow_0039045797_numpy_python_tensorflow.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.