content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python Requests returning 404
Essentially what is happening is that the library requests will only return 404, no matter what and I can't seem to understand why and I've probably spent too much time on this now.
I'm wondering whether it is a requests issue or mine at this point and would appreciate some insight.
I... | Python Requests returning 404 | Essentially what is happening is that the library requests will only return 404, no matter what and I can't seem to understand why and I've probably spent too much time on this now.
I'm wondering whether it is a requests issue or mine at this point and would appreciate some insight.
I'm attempting to GET some job detai... | [
"I solved this by using httpauth and managed to get it working.\n"
] | [
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074359020_python_python_requests.txt |
Q:
Is it possible to use python.locals() with numba?
I'm working on a python function that dynamically creates and uses variables. When i try to speed it up with numba I get this error message:
'numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Untyped global name 'locals': Can... | Is it possible to use python.locals() with numba? | I'm working on a python function that dynamically creates and uses variables. When i try to speed it up with numba I get this error message:
'numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Untyped global name 'locals': Cannot determine Numba type of <class 'builtin_function_or... | [
"Solution with dictonary instead of locals()\nimport numba\n\n@numba.njit\ndef dynamic_dict():\n my_dict = {}\n for i in range(6, 9):\n key = f\"my_key_{i}\"\n value = i\n my_dict[key] = value\n\n for i in range(6, 9):\n yield my_dict[f\"my_key_{i}\"] + 2\n\nprint(list(dynamic_d... | [
0
] | [] | [] | [
"dynamic_variables",
"local_variables",
"numba",
"python"
] | stackoverflow_0074348482_dynamic_variables_local_variables_numba_python.txt |
Q:
png images to one pdf in python
I have a list of .png images. I need to convert all of them into one pdf, 9 images per page , but not to place them one after another vertically, but fill in all the width, and only then continue to next row.
Amount of pictures can be different each time (12, ... 15)
I have tried f... | png images to one pdf in python | I have a list of .png images. I need to convert all of them into one pdf, 9 images per page , but not to place them one after another vertically, but fill in all the width, and only then continue to next row.
Amount of pictures can be different each time (12, ... 15)
I have tried fpdf
from fpdf import FPDF
list_of_im... | [
"Just place each image at required coordinates using FPDF:\npdf.image(image, x=50, y=100, w=sizew, h=sizeh)\n\nMore info on FPDF documentation: image\n",
"This is the code which converts a list of images into a pdf. You can also keep a for loop instead of image_1, image_2 etc as below.\nfrom PIL import Image\n\ni... | [
8,
0,
0
] | [] | [] | [
"fpdf",
"pdf",
"png",
"python"
] | stackoverflow_0040906463_fpdf_pdf_png_python.txt |
Q:
what does the __file__ variable mean/do?
import os
A = os.path.join(os.path.dirname(__file__), '..')
B = os.path.dirname(os.path.realpath(__file__))
C = os.path.abspath(os.path.dirname(__file__))
I usually just hard-wire these with the actual path. But there is a reason for these statements that determine pat... | what does the __file__ variable mean/do? | import os
A = os.path.join(os.path.dirname(__file__), '..')
B = os.path.dirname(os.path.realpath(__file__))
C = os.path.abspath(os.path.dirname(__file__))
I usually just hard-wire these with the actual path. But there is a reason for these statements that determine path at runtime, and I would really like to under... | [
"When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.\nTaking your examples one at a time:\nA = os.path.join(os.path.dirname(__file__), '..')\n# A is the parent directory of the directory where progr... | [
256,
81,
25,
21,
16,
1
] | [] | [] | [
"python",
"self_reference"
] | stackoverflow_0009271464_python_self_reference.txt |
Q:
read position based txt
I have a txt file that I read into a list of strings in which each item of the list is a data sample of 3 variables (A,B,C)
txt = [
'001 0198110',
'0020130198110',
'0030132198110',
]
A separate support dataframe that looks like this
df = pd.DataFrame(data=[[1,3,"A"],[4,3,"... | read position based txt | I have a txt file that I read into a list of strings in which each item of the list is a data sample of 3 variables (A,B,C)
txt = [
'001 0198110',
'0020130198110',
'0030132198110',
]
A separate support dataframe that looks like this
df = pd.DataFrame(data=[[1,3,"A"],[4,3,"B"],[7,6,"C"]],columns=["Posi... | [
"Try pd.read_fwf:\nfrom io import StringIO\n\ntxt = [\"001 198110\", \"0020130198110\", \"0030132198110\"]\n\ndf = pd.DataFrame(\n data=[[1, 3, \"A\"], [4, 4, \"B\"], [7, 6, \"C\"]],\n columns=[\"Position\", \"Lenght\", \"Name\"],\n)\n\n\nx = pd.read_fwf(\n StringIO(\"\\n\".join(txt)),\n widths=df.Le... | [
1,
0
] | [] | [] | [
"parsing",
"python",
"txt"
] | stackoverflow_0074359496_parsing_python_txt.txt |
Q:
count groups of values with aggregated value
I have a dataset like this one:
DateTime
Value
2022-01-01 11:03:45
0
2022-01-01 11:03:50
40
2022-01-01 11:03:55
50
2022-01-01 11:04:00
60
2022-01-01 11:04:05
5
2022-01-01 11:04:10
4
2022-01-01 11:04:15
3
2022-01-01 11:04:20
0
2022-01-01 11:04:25
0
2022-01-01 ... | count groups of values with aggregated value | I have a dataset like this one:
DateTime
Value
2022-01-01 11:03:45
0
2022-01-01 11:03:50
40
2022-01-01 11:03:55
50
2022-01-01 11:04:00
60
2022-01-01 11:04:05
5
2022-01-01 11:04:10
4
2022-01-01 11:04:15
3
2022-01-01 11:04:20
0
2022-01-01 11:04:25
0
2022-01-01 11:04:30
40
2022-01-01 11:04:35
5... | [
"For GroupId greate groups by consecutive values greater like 10 and aggregate cumulative sum by GroupBy.cumsum, then per dates and GroupId get maximal and minimal datetime and subtract, last add 5 seconds because sample every 5 seconds:\ndf['DateTime'] = pd.to_datetime(df['DateTime'])\ns = df['Value'].gt(10)\ndat... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074359900_pandas_python.txt |
Q:
RFID authentication
I'm using an RFID tag and I have written auth1 on the tag. I want to use it as an authentication tag. So if you scan the tag and the content of the tag is the same as the variable auth1 you get a return 'Access Granted'. And if the content of the tag isn't the same as the variable auth1 it retu... | RFID authentication | I'm using an RFID tag and I have written auth1 on the tag. I want to use it as an authentication tag. So if you scan the tag and the content of the tag is the same as the variable auth1 you get a return 'Access Granted'. And if the content of the tag isn't the same as the variable auth1 it returns 'Access Denied'.
Belo... | [
"You are comparing the text on the tag to the variable auth1, which has a value of \"Acces Granted\"\nauth1 = 'Access Granted'\nif text == auth1:\n\n-> if text == \"Access Granted\"\n\nSo if your tag has \"auth1\" on it, you should compare to that.\nif text == \"auth1\":\n\n"
] | [
0
] | [] | [] | [
"python",
"rfid"
] | stackoverflow_0074359972_python_rfid.txt |
Q:
How to count number of rows dropped in a pandas dataframe
How do I print the number of rows dropped while executing the following code in python:
df.dropna(inplace = True)
A:
Use:
np.random.seed(2022)
df = pd.DataFrame(np.random.choice([0,np.nan, 1], size=(10, 3)))
print (df)
0 1 2
0 NaN 0.0 NaN
... | How to count number of rows dropped in a pandas dataframe | How do I print the number of rows dropped while executing the following code in python:
df.dropna(inplace = True)
| [
"Use:\nnp.random.seed(2022) \ndf = pd.DataFrame(np.random.choice([0,np.nan, 1], size=(10, 3)))\nprint (df)\n 0 1 2\n0 NaN 0.0 NaN\n1 0.0 NaN NaN\n2 0.0 0.0 1.0\n3 0.0 0.0 NaN\n4 NaN NaN 1.0\n5 1.0 0.0 0.0\n6 1.0 0.0 1.0\n7 NaN 0.0 1.0\n8 1.0 1.0 NaN\n9 1.0 0.0 NaN\n\nYou can ... | [
0,
0
] | [] | [] | [
"count",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074359778_count_dataframe_pandas_python.txt |
Q:
Find presence of a pair in 2d python list
I have a python list as follows:-
['cat', 'doc_1.txt']
['cat', 'doc_4.txt']
['dog', 'doc_5.txt']
['mouse', 'doc_6.txt']
['horse', 'doc_7.txt']
I need to quickly find out boolean answer to queries like
"Does cat exist in doc_1.txt" answer = yes
"Does mouse exist in ... | Find presence of a pair in 2d python list | I have a python list as follows:-
['cat', 'doc_1.txt']
['cat', 'doc_4.txt']
['dog', 'doc_5.txt']
['mouse', 'doc_6.txt']
['horse', 'doc_7.txt']
I need to quickly find out boolean answer to queries like
"Does cat exist in doc_1.txt" answer = yes
"Does mouse exist in doc_1.txt" answer = no
I have implemented it t... | [
"Use the Python keyword in to check if item q is in a list L with q in L which returns True if it is:\n# I have a python list as follows:-\nL = [\n['cat', 'doc_1.txt'], \n['cat', 'doc_4.txt'], \n['dog', 'doc_5.txt'], \n['mouse', 'doc_6.txt'], \n['horse', 'doc_7.txt'],\n] \n# I need to quickly find out boolean answe... | [
1
] | [
"If you have:\nlst = [['cat', 'doc1.txt'], ['dog', 'doc2.txt']]\n\nThen it's simple:\nbools = [l[0] in open(l[1], 'r').read().split() for l in lst]\nprint(bools)\n\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0074359816_list_python.txt |
Q:
I cant get my python discord bot polling command to send. All the other response commands work, so im not sure why the poll wont send
Here is my code
@bot.command("poll")
async def poll(ctx, *args):
# poll command:
# !poll event_name event_date
event_name = args[0]
event_date = args[1]
# retrie... | I cant get my python discord bot polling command to send. All the other response commands work, so im not sure why the poll wont send | Here is my code
@bot.command("poll")
async def poll(ctx, *args):
# poll command:
# !poll event_name event_date
event_name = args[0]
event_date = args[1]
# retrieving the 'events' channel
# sending the poll
message = await ctx.send(f"@everyone Will you come to the **{event_name}** event the *... | [
"https://media.discordapp.net/attachments/1019539306777415712/1039502797420376074/25f07d49ecf5de59.png\nu need to give arg and it work, but u will get unkonwn emoji error , beacuse u don't use \\ in unicode\n\n await message.add_reaction('U00002705')\n\n\nuse ('\\U00002705')\n"
] | [
0
] | [] | [] | [
"ctx",
"discord.py",
"python"
] | stackoverflow_0074351642_ctx_discord.py_python.txt |
Q:
Flask/Dash application running as a service in windows must be restarted every day to include the current day's date. How to solve the problem?
I have this Flask/Dash application that I deployed as a service running in the background and it works fine. I use a datepicker (calendar) in the application to choose the... | Flask/Dash application running as a service in windows must be restarted every day to include the current day's date. How to solve the problem? | I have this Flask/Dash application that I deployed as a service running in the background and it works fine. I use a datepicker (calendar) in the application to choose the date for which the data will be fetched and processed. However, the date of today is being grayed (deactivated) every day until I restart the servic... | [
"Eventually, I solved the issue as recommended by @coralvanda by setting the initial value as None, then doing the checking and updating inside a callback function.\ndcc.DatePickerSingle(id='previ_date',\n min_date_allowed=datetime.date(2022, 5, 10),\n max_date_allowed=None,\n initial_visible_month=None,\n... | [
1
] | [] | [] | [
"flask",
"plotly_dash",
"python",
"windows_services"
] | stackoverflow_0074331959_flask_plotly_dash_python_windows_services.txt |
Q:
How to align text in table cells using Borb
I am creating PDF document using borb and try to align text within table cells.
from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import SingleColumnLayout
from borb.pdf import Paragraph
from borb.pdf import PDF
from borb.pdf import Alignment
from bo... | How to align text in table cells using Borb | I am creating PDF document using borb and try to align text within table cells.
from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import SingleColumnLayout
from borb.pdf import Paragraph
from borb.pdf import PDF
from borb.pdf import Alignment
from borb.pdf import TableCell
from borb.pdf import Flex... | [
"disclaimer: I am the author of borb\nYou are experiencing the difference between the horizontal_alignment of a LayoutElement and the text_alignment of said element.\nWhen performing layout on a text-carrying LayoutElement, the logic is roughly the following:\n\nHow wide is this text going to be? That will be the w... | [
0
] | [] | [] | [
"borb",
"pdf",
"python"
] | stackoverflow_0074305426_borb_pdf_python.txt |
Q:
Combining multiple perspectiveTransforms into one transform with opencv
I have an application that has two perspective transforms obtained from two findHomography calls that get applied in succession to a set of points (python):
pts = np.float32([ [758,141],[769,141],[769,146],[758,146] ]).reshape(-1,1,2)
pts2 = c... | Combining multiple perspectiveTransforms into one transform with opencv | I have an application that has two perspective transforms obtained from two findHomography calls that get applied in succession to a set of points (python):
pts = np.float32([ [758,141],[769,141],[769,146],[758,146] ]).reshape(-1,1,2)
pts2 = cv2.perspectiveTransform(pts, trackingM)
dst = cv2.perspectiveTransform(pts2, ... | [
"Let us say, we have a series of Perspective Transformation as follows. Let tij be the perspective transform matrix from image_i to image_j\nimage_1 -- t12 --> image_2 -- t23 --> .... -- tN-1N --> image_N\nThe point p1 in image_1 would be transformed to point p2 in image_2 as p2 = t12.p1\nThe point p2 in image_2 wo... | [
1,
0,
0
] | [] | [] | [
"image_processing",
"numpy",
"opencv",
"python"
] | stackoverflow_0048454055_image_processing_numpy_opencv_python.txt |
Q:
How to fix the error "QObject::moveToThread:" in opencv in python?
I am using opencv2 in python with the code
import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL)
cv2.imshow("output",im)
cv2.resizeWindow('output', 400,400)
cv2.waitKey(0)
cv2.destroyAllWindows()
I have the error as
QObject::moveToThread... | How to fix the error "QObject::moveToThread:" in opencv in python? | I am using opencv2 in python with the code
import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL)
cv2.imshow("output",im)
cv2.resizeWindow('output', 400,400)
cv2.waitKey(0)
cv2.destroyAllWindows()
I have the error as
QObject::moveToThread: Current thread (0x1d2c9cf0) is not the object's thread (0x1d347b20).
C... | [
"I got same problem, it was from opencv-python version problem for me.\nMy Linux machine's environment is as following:\n$ cat /etc/lsb-release \n...\nDISTRIB_DESCRIPTION=\"Ubuntu 18.04.5 LTS\"\n$ date\nTue Aug 11 11:43:16 KST 2020\n$ python --version\nPython 3.7.8\n$ pip list|grep Qt\nPyQt5 5.15.0\n... | [
29,
18,
10,
7,
4,
3,
3,
3,
2,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"The answer of @Mateen works great if you have Ubuntu version 17 and above. For Ubuntu 16, it's better to compile from sources your opencv python. As @Varun mentioned, follow the opencv tutorial. However, to successfully compile opencv with python 3 I have to add some flags in cmake command:\n\ncmake -DCMAKE_BUILD_... | [
-1,
-1,
-1,
-1,
-1,
-1,
-1
] | [
"opencv",
"python",
"qt"
] | stackoverflow_0046449850_opencv_python_qt.txt |
Q:
Why is my file not being recorded in JSON
news_dict[article_id] = {
"article_date_timestamp": article_date_timestamp,
"article_title": article_title,
"article_url": article_url,
"article_desc": article_desc
}
with open("news_dict.txt", 'w') as file:
json.dump(news_dict,... | Why is my file not being recorded in JSON | news_dict[article_id] = {
"article_date_timestamp": article_date_timestamp,
"article_title": article_title,
"article_url": article_url,
"article_desc": article_desc
}
with open("news_dict.txt", 'w') as file:
json.dump(news_dict, file, indent=4, ensure_ascii=False)
The json ... | [
"I've made simple solution which works based on your snippet. You can try with this. To your code I've added default=str in json_dump()\nimport json\nfrom datetime import datetime\nnews_dict = {}\n\narticle_id = 1\narticle_date_timestamp = datetime.now()\narticle_title = \"Title\"\narticle_url = \"http://example.co... | [
0
] | [] | [] | [
"json",
"python",
"save"
] | stackoverflow_0074360095_json_python_save.txt |
Q:
What is "if cv2.waitKey(20) & 0xFF ==27:"
if cv2.waitKey(20) & 0xFF ==27:
Can anybody tell me the working of this this code in python
A:
The waitKey() function waits for the specified millisecond and then returns the code for the key pressed or -1 if no key was pressed.
https://stackoverflow.com/a/67356778/142... | What is "if cv2.waitKey(20) & 0xFF ==27:" | if cv2.waitKey(20) & 0xFF ==27:
Can anybody tell me the working of this this code in python
| [
"The waitKey() function waits for the specified millisecond and then returns the code for the key pressed or -1 if no key was pressed.\nhttps://stackoverflow.com/a/67356778/14237825\n"
] | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074360004_opencv_python.txt |
Q:
How can I calculate time correctly?
*Here is my code *
I want get ühole number
from time import time
import math
start=time()
total_time= 30
while time!=0:
move=input('Chess move:')
if move !='off':
print(start)
remaining_time=math.floor(total_time-start)
print('Remaninig time:',remaining_ti... | How can I calculate time correctly? | *Here is my code *
I want get ühole number
from time import time
import math
start=time()
total_time= 30
while time!=0:
move=input('Chess move:')
if move !='off':
print(start)
remaining_time=math.floor(total_time-start)
print('Remaninig time:',remaining_time)
else:
end=time()
... | [
"Python time.time() returns time since January 1, 1970. Not since start of the program\n\nhttps://docs.python.org/3/library/time.html#time.time\nhttps://docs.python.org/3/library/time.html#epoch\n\nIt is better to compare difference between current time and start_time\nfrom time import time\nimport math\nstart=time... | [
0,
0
] | [] | [] | [
"line",
"python",
"python_mode"
] | stackoverflow_0074360228_line_python_python_mode.txt |
Q:
Discord.py / display messages of a specific user?
I need to display in the chat using the bot the last 10-20 messages of a certain user that he wrote on the entire server (in any channel). How can I do that?
used
messages = []
async for message in ctx.channel.history(limit=100):
if message.author.id ==... | Discord.py / display messages of a specific user? | I need to display in the chat using the bot the last 10-20 messages of a certain user that he wrote on the entire server (in any channel). How can I do that?
used
messages = []
async for message in ctx.channel.history(limit=100):
if message.author.id == member:
messages += [message]
understood ... | [] | [] | [
"Hi for an entire server can be quite heavy but this will give you last 100 messages from a channel, you can set limit=None to get all mesages in a channel\n messages = [message async for message in channel.history(limit=100) if message.author.id == member]\n\nFor the server, you could iterate through all the chann... | [
-2
] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074338672_bots_discord_discord.py_python.txt |
Q:
Why does dividing an np.array behave differently from dividing an array element directly
I'm trying to normalize an uint8 np.array by dividing it by 255.0.
When I divide the array by 255.0 the dtype of it's element changes to float64.
When I only divide the element itself by 255.0, the elements dtype stays uint8... | Why does dividing an np.array behave differently from dividing an array element directly | I'm trying to normalize an uint8 np.array by dividing it by 255.0.
When I divide the array by 255.0 the dtype of it's element changes to float64.
When I only divide the element itself by 255.0, the elements dtype stays uint8.
Why does the division behave differently here?
In the example below, I was expecting two si... | [
"Float division is always 64-bit float. When you do it for a single element, it will convert it back to the type of the array (int8 in your case). If do it for the whole array, it will change the type of the array to the result type.\nYou can can use python's integer division (//). [However, it will result in pure ... | [
0
] | [] | [] | [
"numpy_ndarray",
"python"
] | stackoverflow_0074360189_numpy_ndarray_python.txt |
Q:
python simplify warning message
I'm getting this (three) runtime warnings, every time I run my code.
/usr/local/lib/python3.8/dist-packages/scipy/interpolate/_fitpack_impl.py:977: RuntimeWarning: No more knots can be added because the additional knot would
coincide with an old one. Probable cause: s too small or t... | python simplify warning message | I'm getting this (three) runtime warnings, every time I run my code.
/usr/local/lib/python3.8/dist-packages/scipy/interpolate/_fitpack_impl.py:977: RuntimeWarning: No more knots can be added because the additional knot would
coincide with an old one. Probable cause: s too small or too large
a weight to an inaccurate da... | [
"According to warnings docs\n\nThe printing of warning messages is done by calling showwarning(),\nwhich may be overridden; the default implementation of this function\nformats the message by calling formatwarning(), which is also\navailable for use by custom implementations.\n\nwhich mean you might assign own func... | [
2
] | [] | [] | [
"python",
"suppress_warnings"
] | stackoverflow_0074360147_python_suppress_warnings.txt |
Q:
Get percentage of occurrence of each value for certain columns
I have a df with many questions, each in a separate column. The rows are answers to those questions, which are on a scale of 1-5.:
q1 q2 q3 q4 q5
4 5 2 5 2
4 5 5 5 5
1 4 5 4 5
3 1 4 1 4
4 3 2 3 2
2 4 3 ... | Get percentage of occurrence of each value for certain columns | I have a df with many questions, each in a separate column. The rows are answers to those questions, which are on a scale of 1-5.:
q1 q2 q3 q4 q5
4 5 2 5 2
4 5 5 5 5
1 4 5 4 5
3 1 4 1 4
4 3 2 3 2
2 4 3 4 3
I would like to see, for each question, what percentage did e... | [
"You can use:\ndf.apply(lambda s: s.value_counts(normalize=True)).T.fillna(0).round(2)\n\noutput:\n 1 2 3 4 5\nq1 0.17 0.17 0.17 0.50 0.00\nq2 0.17 0.00 0.17 0.33 0.33\nq3 0.00 0.33 0.17 0.17 0.33\nq4 0.17 0.00 0.17 0.33 0.33\nq5 0.00 0.33 0.17 0.17 0.33\n\n"
] | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074360397_pandas_python.txt |
Q:
Colouring the boundary of same-colored block of pixels
I've got an image with 5 different colors; in this case, randomly generated:
w, h = 40, 27
img = Image.new("RGB", (w,h))
pixels = img.load()
available_colors = {
'r': (255, 13, 18),
'b': (72, 64, 255),
'y': (236, 236, 1),
'p': (208, 1, 239),
... | Colouring the boundary of same-colored block of pixels | I've got an image with 5 different colors; in this case, randomly generated:
w, h = 40, 27
img = Image.new("RGB", (w,h))
pixels = img.load()
available_colors = {
'r': (255, 13, 18),
'b': (72, 64, 255),
'y': (236, 236, 1),
'p': (208, 1, 239),
'g': (37, 252, 32),
}
for i in range(w):
for j in rang... | [
"I am not 100% certain exactly where you want to get to with this, so I \"did some things\" and you can pick and choose techniques that are useful to you. Each little block of code does one specific thing and creates an output image of that phase of processing.\nI mixed up PIL and OpenCV by doing things the way the... | [
3
] | [] | [] | [
"image_processing",
"opencv",
"python",
"python_imaging_library"
] | stackoverflow_0074353966_image_processing_opencv_python_python_imaging_library.txt |
Q:
How can I change timestamp to readable date in pandas when I have mixed timestamp formats
I have a column with different timestamp formats as shown below. I want to convert the date column to readable date. Since the timestamp units are mixed, I find other converted properly while others default to 1970. Is there ... | How can I change timestamp to readable date in pandas when I have mixed timestamp formats | I have a column with different timestamp formats as shown below. I want to convert the date column to readable date. Since the timestamp units are mixed, I find other converted properly while others default to 1970. Is there a way I can convert them together or convert them to a unix timestamp unit before converting to... | [
"Idea is replace values with missing values if not possible convert to datetimes and then use Series.fillna:\ndf['newdate'] = (pd.to_datetime(df['date'], unit='ms', errors='coerce')\n .fillna(pd.to_datetime(df['date'], errors='coerce')))\n\nprint (df)\n date ne... | [
1
] | [] | [] | [
"dataframe",
"date",
"pandas",
"python",
"timestamp"
] | stackoverflow_0074360400_dataframe_date_pandas_python_timestamp.txt |
Q:
A good method for comparing each row in dataframe to each row in another dataframe?
I'm currently in need for a better method for doing some calculations in a quite tedious fashion. And I'd like to change that, due to some of the dataframes that will be processed can have a large size.
I would like to do some comp... | A good method for comparing each row in dataframe to each row in another dataframe? | I'm currently in need for a better method for doing some calculations in a quite tedious fashion. And I'd like to change that, due to some of the dataframes that will be processed can have a large size.
I would like to do some comparisons for each row in one dataframe to each row in another dataframe. This by nature sc... | [
"merge cross get cartesian product:\ndf1.merge(df2, how='cross')\n\noutput:\n value_x value_y\n0 1 3\n1 1 4\n2 2 3\n3 2 4\n\nthen apply your func:\ndf1.merge(df2, how='cross').apply(lambda x: func(x['value_x'], x['value_y']), axis=1)\n\n\nexample \nfunc : f(x, y) = xy\ndf1.merge(d... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074360203_pandas_python.txt |
Q:
Organizing a (6000,2) np array into 2-D grid
I am having difficulties organizing or sorting a np array into 2-D Bins. I essentially have a 6000 by 2 datapoint array. I want to sort the array acording to it's x and y values (axis 1) over a 2-D plot ranging on either axis from 0 to 1. Meaning ultimately I need the c... | Organizing a (6000,2) np array into 2-D grid | I am having difficulties organizing or sorting a np array into 2-D Bins. I essentially have a 6000 by 2 datapoint array. I want to sort the array acording to it's x and y values (axis 1) over a 2-D plot ranging on either axis from 0 to 1. Meaning ultimately I need the counts of datapoints that land in the specific bin ... | [
"So originally I was looking into using seaborn as seaborn can easily plot heatmaps and would then have used the values per grid to calc the std. However the organizing and sorting was my main issue. Using np.histogram2d was the key. I had previously only thought about 1D histograms, which in this case would'nt wor... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"seaborn",
"sorting"
] | stackoverflow_0074340025_arrays_numpy_python_seaborn_sorting.txt |
Q:
How to create a sparse binary matrix from a dictionary in python
I have a .tsv file from which I've created a pyhton dictionary where the keys are all the movie_id and the values are the features (every movie has a different number of features).
Here's an example of my dictionary:
Goal to achieve:
From this dicti... | How to create a sparse binary matrix from a dictionary in python | I have a .tsv file from which I've created a pyhton dictionary where the keys are all the movie_id and the values are the features (every movie has a different number of features).
Here's an example of my dictionary:
Goal to achieve:
From this dictionary I want to create an item-features sparse matrix to use for a rec... | [
"Based on this answer, you can do the following with few lines of code:\nimport pandas as pd\n\nid_to_features = {\n 880: [18, 23, 854, 98475, 20],\n 152: [1, 578, 18, 654, 23, 5, 11],\n 6654: [2088]\n}\n\ndf = pd.DataFrame({\"features\": list(id_to_features.values())})\nmatrix = df['features'].apply(pd.va... | [
1,
1
] | [] | [] | [
"dictionary",
"key_value",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0074278780_dictionary_key_value_python_scipy_sparse_matrix.txt |
Q:
Combining dataframes with differing dates column
I have a dataset of hourly prices where I have produced a dataframe that contains the minimum price from the previous day using:
df_min = df_hour_0[['Price_REG1', 'Price_REG2', 'Price_REG3',
'Price_REG4']].between_time('00:00', '23:00').resample('d... | Combining dataframes with differing dates column | I have a dataset of hourly prices where I have produced a dataframe that contains the minimum price from the previous day using:
df_min = df_hour_0[['Price_REG1', 'Price_REG2', 'Price_REG3',
'Price_REG4']].between_time('00:00', '23:00').resample('d').min()
This gives me:
Price_... | [
"One option could be to normalize to the date:\ndfs = [df_hour_0, df_min, df_max]\npd.concat([d.set_axis(d.index.normalize()) for d in dfs], axis=1)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074360488_pandas_python.txt |
Q:
Scrape data that changes every time an "li" option is selected - Python Selenium
I'm trying to scrape data from that site https://www.pais.co.il/info/Thank-to.aspx (Ignore the hebrew).
I need to click on any of these options from the first dropdown menu
click on that button
and scrape these numbers
I do know ho... | Scrape data that changes every time an "li" option is selected - Python Selenium | I'm trying to scrape data from that site https://www.pais.co.il/info/Thank-to.aspx (Ignore the hebrew).
I need to click on any of these options from the first dropdown menu
click on that button
and scrape these numbers
I do know how to scrape the numbers/ click or select buttons but I can't figure out how to iterati... | [
"The data you need is loaded with js so you can use Selenium to get the list of cities.\nHere is one possible solution:\nimport csv\nimport requests\nfrom typing import Union, Any\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfro... | [
1
] | [] | [] | [
"html",
"python",
"screen_scraping",
"selenium",
"web_scraping"
] | stackoverflow_0074339310_html_python_screen_scraping_selenium_web_scraping.txt |
Q:
how can I create a nested dictionary with use a same key in list of dictionaries
I have this dictionary:
data=[{'first': '0', 'last': 'hg01', 'pay': 0},
{'first': '0', 'last': 'hg75', 'pay': 15},
{'first': '0', 'last': 'hg0', 'pay': 1},
{'first': '0', 'last': 'hg9', 'pay': 13},
{'first': '0', 'last': 'hg0', 'p... | how can I create a nested dictionary with use a same key in list of dictionaries | I have this dictionary:
data=[{'first': '0', 'last': 'hg01', 'pay': 0},
{'first': '0', 'last': 'hg75', 'pay': 15},
{'first': '0', 'last': 'hg0', 'pay': 1},
{'first': '0', 'last': 'hg9', 'pay': 13},
{'first': '0', 'last': 'hg0', 'pay': 0},
{'first': '0', 'last': 'hg', 'pay': 13},
{'first': '0', 'last': 'hg76', 'pa... | [
"Try itertools.groupby and dict comprehension\nfrom itertools import groupby\n{k:{v1['last']: {'first': v1['first']} for v1 in v} for k,v in groupby(sorted(data, key=lambda x: x[\"pay\"]), key=lambda x: x[\"pay\"])}\n\n#output\n{0: {'hg01': {'first': '0'}, 'hg0': {'first': '0'}, 'hg76': {'first': '0'}},\n 1: {'hg0'... | [
2,
2,
2
] | [] | [] | [
"dictionary",
"dictionary_comprehension",
"list_comprehension",
"python"
] | stackoverflow_0074360439_dictionary_dictionary_comprehension_list_comprehension_python.txt |
Q:
List to list dictionary (Python optimization)
I'm trying to convert a list of lists of strings (that represents a tic-tac-toe game) to a list of lists of integers, so that I can perform calculations.
These are the possible inputs:
A = ['X', 'O', '#']
And these the corresponding integers:
B = [1, 0, 99]
So overal... | List to list dictionary (Python optimization) | I'm trying to convert a list of lists of strings (that represents a tic-tac-toe game) to a list of lists of integers, so that I can perform calculations.
These are the possible inputs:
A = ['X', 'O', '#']
And these the corresponding integers:
B = [1, 0, 99]
So overall it would do the following:
[['X', 'O', 'O'], ['O'... | [
"Consider creating a mapping dictionary and using a nested list comprehension:\n>>> mapping = {'X': 1, 'O': 0, '#': 99}\n>>> raw_board = [['X', 'O', 'O'], ['O', 'X', 'O'], ['O', '#', 'X']]\n>>> value_board = [[mapping[c] for c in row] for row in raw_board]\n>>> value_board\n[[1, 0, 0], [0, 1, 0], [0, 99, 1]]\n\n",
... | [
5,
3,
0
] | [] | [] | [
"arrays",
"dictionary",
"optimization",
"performance",
"python"
] | stackoverflow_0074360464_arrays_dictionary_optimization_performance_python.txt |
Q:
What does `free_raw_data` do in `lightgbm.Dataset()`?
I've read the docs and an explanation on the FAQ. But the former is just a tautology and the latter explains things with self. as if I would be regularly using Dataset in my own classes. Usually, I load up a dataset and use it to train my models, so never need ... | What does `free_raw_data` do in `lightgbm.Dataset()`? | I've read the docs and an explanation on the FAQ. But the former is just a tautology and the latter explains things with self. as if I would be regularly using Dataset in my own classes. Usually, I load up a dataset and use it to train my models, so never need to use self. anywhere. I am a beginner though.
Where does t... | [
"Combining the comments into an answer.\nWhen talking about memory and variables, free means delete. So, it deletes the raw data which leaves just the lightgbm.Dataset object in memory.\n"
] | [
0
] | [] | [] | [
"lightgbm",
"python"
] | stackoverflow_0066639306_lightgbm_python.txt |
Q:
PermissionError: [WinError 5] Access is denied in Python
import shutil
def create_dir(path):
if not os.path.exists(path):
os.mkdir(path)
else:
shutil.rmtree(path)
when I run this code it gives me permission error, even though I have access to that directory.
Also, I use Windows and I have... | PermissionError: [WinError 5] Access is denied in Python | import shutil
def create_dir(path):
if not os.path.exists(path):
os.mkdir(path)
else:
shutil.rmtree(path)
when I run this code it gives me permission error, even though I have access to that directory.
Also, I use Windows and I have tried running as administrator
| [
"Check if the folder is not Read-Only.\nOr you can also run command:\nimport os\nos.system('whoami')\n\nIt will show you which user is currently registered as launching user.\n",
"Try with ignore_errors=True,\nimport shutil\n\ndef create_dir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n el... | [
0,
0
] | [] | [] | [
"permission_denied",
"python",
"python_3.x",
"shutil"
] | stackoverflow_0074360379_permission_denied_python_python_3.x_shutil.txt |
Q:
How to compare 2 Ordered Dictionaries and create a new Ordered one with differences? (Python 3.7)
I'm struggling on how to generate a "Differences" Ordered-Dictionary containing the Different and also New values appearing on a "Modified" Ordered-Dictionary after comparing with a "Reference" Ordered-Dictionary.
EXA... | How to compare 2 Ordered Dictionaries and create a new Ordered one with differences? (Python 3.7) | I'm struggling on how to generate a "Differences" Ordered-Dictionary containing the Different and also New values appearing on a "Modified" Ordered-Dictionary after comparing with a "Reference" Ordered-Dictionary.
EXAMPLE:
#python
from collections import OrderedDict
ref_d = OrderedDict() # REFERENCE Ordered Dictionar... | [
"You cannot make two comparisons at the same time. You need two separate checks:\nfor key, value in mod_d.items():\n if key not in ref_d:\n dif_d.update({key: value})\n else:\n if value != ref_d[key]:\n dif_d.update({key: value})\n\n",
"copied you code and worked for me:\n$ python t... | [
3,
0
] | [] | [] | [
"array_difference",
"comparison",
"ordereddictionary",
"python"
] | stackoverflow_0074360336_array_difference_comparison_ordereddictionary_python.txt |
Q:
edit, modify for loops in list comprehension
I want to create 2 same subgraphs it works when I do it in this manner
for _ in range(2):
for neighbor in graph.adj[i]:
print(graph.subgraph(neighbor))
but when I do it in a list comprehension
print([graph.subgraph(neighbor) for neighbor in graph.adj[i] for... | edit, modify for loops in list comprehension | I want to create 2 same subgraphs it works when I do it in this manner
for _ in range(2):
for neighbor in graph.adj[i]:
print(graph.subgraph(neighbor))
but when I do it in a list comprehension
print([graph.subgraph(neighbor) for neighbor in graph.adj[i] for _ in range(2)])
it gives me
[<networkx.classes.g... | [
"It's simply because you have put a pair of square brackets inside the print method. Remove them to get it working.\nCode:\nprint(graph.subgraph(neighbor) for neighbor in graph.adj[i] for _ in range(2))\n\nHoping an acceptance!\n"
] | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074335700_networkx_python.txt |
Q:
How can I register kedro data catalog programmatically in Kedro 0.18?
For various reasons (mainly ability to dynamically construct file paths) I like to define the data catalog programatically, and not use yaml file to define datasets e.g.
DataCatalog(
{"products": ParquetDataSet(filepath=f{PREFIX}/products.pa... | How can I register kedro data catalog programmatically in Kedro 0.18? | For various reasons (mainly ability to dynamically construct file paths) I like to define the data catalog programatically, and not use yaml file to define datasets e.g.
DataCatalog(
{"products": ParquetDataSet(filepath=f{PREFIX}/products.parquet")
...
})
In kedro 0.17 there was an easy way to register the catal... | [
"Not sure if this is the precise functionality that you're looking for, but I've been programmatically adding datasets by using a combination of after_context_created and after_catalog_created hooks.\nJust create an \"add\" method for the dataset that you require and use the docs to see what args are needed. In the... | [
1
] | [] | [] | [
"kedro",
"python"
] | stackoverflow_0074357203_kedro_python.txt |
Q:
See if object from one dataframe appears in other dataframe, when one has numbers added (e.g. string, string1)
I have two dataframes with actor names (their types are object) that look like the following:
df = pd.DataFrame({Actors: [Christian Bale, Ben Kingsley, Halley Bailey, Aaron Paul, etc...]
df2 = pd.read_csv... | See if object from one dataframe appears in other dataframe, when one has numbers added (e.g. string, string1) | I have two dataframes with actor names (their types are object) that look like the following:
df = pd.DataFrame({Actors: [Christian Bale, Ben Kingsley, Halley Bailey, Aaron Paul, etc...]
df2 = pd.read_csv({id: [Halley Bailey - 1998, Coco Jones – 1998, etc...]
Normally I would use the following code to find if one it... | [
"You can extract the actor names from df2['id'] and check if df['Actors'] is in it:\ndf.assign(indf=df['Actors'].isin(df2['id'].str.extract('(.*)(?=\\s[-–])',\n expand=False)).astype(int))\n\noutput:\n Actors indf\n0 Christian Bale 0\n1 Ben Kingsley 0\n2 Hall... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074360622_dataframe_pandas_python.txt |
Q:
Lazy Method for Reading Big File in Python?
I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to yield these pieces ?
I would love to have a... | Lazy Method for Reading Big File in Python? | I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to yield these pieces ?
I would love to have a lazy method.
| [
"To write a lazy function, just use yield:\ndef read_in_chunks(file_object, chunk_size=1024):\n \"\"\"Lazy function (generator) to read a file piece by piece.\n Default chunk size: 1k.\"\"\"\n while True:\n data = file_object.read(chunk_size)\n if not data:\n break\n yield d... | [
532,
47,
43,
41,
13,
10,
7,
4,
2,
1,
0
] | [
"you can use following code.\nfile_obj = open('big_file') \n\nopen() returns a file object\nthen use os.stat for getting size\nfile_size = os.stat('big_file').st_size\n\nfor i in range( file_size/1024):\n print file_obj.read(1024)\n\n"
] | [
-2
] | [
"file_io",
"generator",
"python"
] | stackoverflow_0000519633_file_io_generator_python.txt |
Q:
How to autoload venv/bin/activate in vscode on mac
I have django project folder with venv environment.
when opening vscode it has terminal opened in vscode.
Is there a way that I don't have to venv/bin/activate all the time when opening the project folder?
A:
Edit (credit to @XJOJIX) from the comment in this ans... | How to autoload venv/bin/activate in vscode on mac | I have django project folder with venv environment.
when opening vscode it has terminal opened in vscode.
Is there a way that I don't have to venv/bin/activate all the time when opening the project folder?
| [
"Edit (credit to @XJOJIX) from the comment in this answer. This will active the virtual environment without having to close or open terminals. A Python file still needs to be selected to load the Python extension.\nAdd this parameter in VS Code to \"launch.json\" or \".code-workspace\"\n \"settings\": {\n ... | [
3,
0,
0,
0
] | [] | [] | [
"macos",
"python",
"python_3.x",
"python_venv",
"visual_studio_code"
] | stackoverflow_0065250276_macos_python_python_3.x_python_venv_visual_studio_code.txt |
Q:
Hide certain class methods depending on load criteria
I have a class which I use to handle three types of data structures.
In this class I have many plotting methods, which depends on which type of data is loaded into the class.
Is there a way for me to hide the methods not belonging to the data structure loaded, ... | Hide certain class methods depending on load criteria | I have a class which I use to handle three types of data structures.
In this class I have many plotting methods, which depends on which type of data is loaded into the class.
Is there a way for me to hide the methods not belonging to the data structure loaded, when looking at the class attributes?
Example:
class data_r... | [
"My approach to this depend on how \"different\" your various data structures are:\nV1:\nNot so different, e.g, nested list vs numpy array. In this case I would advise you to write different data load functions, which always convert the data to a common format, e.g.:\ndef load_list_data(self, data):\n # reads a ... | [
1,
0,
0
] | [] | [] | [
"class",
"function",
"methods",
"python"
] | stackoverflow_0074360493_class_function_methods_python.txt |
Q:
ModuleNotFoundError but the module name exists in one of the directories in sys.path
The issue
I've pip installed a library called disagree which installed and upgraded without any issues, confirming that the latest version had been successfully installed.
When running import disagree I get the error:
Traceback (m... | ModuleNotFoundError but the module name exists in one of the directories in sys.path | The issue
I've pip installed a library called disagree which installed and upgraded without any issues, confirming that the latest version had been successfully installed.
When running import disagree I get the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No modul... | [
"I have the same issue here. This solution below worked for me.\nFirst of all, check the version of python that you have (must be between python3.8 and 3.10 (included). No python3.7 and python3.11 as I understand.\nTo check it do this in your notebook/python:\nimport sys\nprint(sys.version)\n\nIf it matches with th... | [
1
] | [] | [] | [
"package",
"path",
"python",
"sys"
] | stackoverflow_0072669551_package_path_python_sys.txt |
Q:
Azure ML error: NotImplementedError: Linux distribution debian 11. does not have automatic support
I am trying to train my model as an Azure ML job.
I train my model as a Docker container. However I keep getting this error when executing the Azure ML job:
Warning: Falling back to use azure cli login credentials.
I... | Azure ML error: NotImplementedError: Linux distribution debian 11. does not have automatic support | I am trying to train my model as an Azure ML job.
I train my model as a Docker container. However I keep getting this error when executing the Azure ML job:
Warning: Falling back to use azure cli login credentials.
If you run your code in unattended mode, i.e., where you can't give a user input, then we recommend to us... | [
"Debian is not supportive of all the .net versions. Debian 11 will function with .Net core 3.1, and .Net 6.\nThe following versions of .NET are no longer supported:\n• .NET 5\n• .NET Core 3.0\n• .NET Core 2.2\n• .NET Core 2.1\n• .NET Core 2.0\nBefore installing .Net, run the commands which are mentioned b... | [
0
] | [] | [] | [
".net_core",
"azure",
"azure_machine_learning_studio",
"python"
] | stackoverflow_0074181670_.net_core_azure_azure_machine_learning_studio_python.txt |
Q:
Get runs from Experiment with specific Property in Azure Machine Learning
I wish to get runs from my experience where I can filter from a specific item inside it.
From my Experience object, I get a generator containing all my azureml.PipelineRun
experiment.get_runs(type="azureml.PipelineRun")
In the official docu... | Get runs from Experiment with specific Property in Azure Machine Learning | I wish to get runs from my experience where I can filter from a specific item inside it.
From my Experience object, I get a generator containing all my azureml.PipelineRun
experiment.get_runs(type="azureml.PipelineRun")
In the official documentation it is said we can add some type of filtering on the properties of the... | [
"we need to perform the nested dictionary to get the properties of the pipeline using Run.\nUse the following code block to get the details of the pipleline.\nfor run in experiment.get_runs(type=\"azureml.PipelineRun\", properties={\"azureml.git.branch\": \"my_branch\"}):\n print(run)\n\nto get the below code b... | [
0
] | [] | [] | [
"azure_machine_learning_service",
"azure_machine_learning_studio",
"python"
] | stackoverflow_0074196402_azure_machine_learning_service_azure_machine_learning_studio_python.txt |
Q:
Getting concrete attribute within a HTML span tag
My problem:
I'm using beautiful SOAP in Python, and i want to know how do i get the concrete attribute such as "data-hk".
My code at the moment:
The output of the code is km/L, but i want the data about HK. How do i specifically select the right attribute within ... | Getting concrete attribute within a HTML span tag | My problem:
I'm using beautiful SOAP in Python, and i want to know how do i get the concrete attribute such as "data-hk".
My code at the moment:
The output of the code is km/L, but i want the data about HK. How do i specifically select the right attribute within the span?
Many thanks in advance.
I tried the above cod... | [
"Try this:\nHK = cars.find(\"span\", class_=\"variableDataColumn\")[\"data-hk\"]\n\n"
] | [
-1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074360655_beautifulsoup_html_python_web_scraping.txt |
Q:
Azure ML - Retrieve an AutoMLStep model and use for inference
I am currently trying to use the AutoMLStep to train a machine learning model, register it in the workspace, and use it for inference as a deserialized model.
My current project folder/file structure is the following:
project/
│
├── src/
│
... | Azure ML - Retrieve an AutoMLStep model and use for inference | I am currently trying to use the AutoMLStep to train a machine learning model, register it in the workspace, and use it for inference as a deserialized model.
My current project folder/file structure is the following:
project/
│
├── src/
│
├──data_prep.py
├──register_model.py
├── ... | [
"The way to import the pickle files for different models to retrieve the best model based on the metrics is different. We need to download entire set of metrics and model files and update those in the datastore.\nUse the path of the downloaded metric files and use them for inference.\nUsing run ID need to download ... | [
0
] | [] | [] | [
"azure_auto_ml",
"azure_machine_learning_service",
"azureml_python_sdk",
"python"
] | stackoverflow_0074034688_azure_auto_ml_azure_machine_learning_service_azureml_python_sdk_python.txt |
Q:
How to add the key of a dictionary to dataframe of value is in range of a dictionary value in python
A sample df is shown below:
df=pd.DataFrame({'Price':[10,8,7,6,10,12,11,11,7,9], 'Group':['apple','apple','apple','apple','apple','berry','berry','berry','berry','berry']})
Price
Group
10
apple
8
apple
7
apple
... | How to add the key of a dictionary to dataframe of value is in range of a dictionary value in python | A sample df is shown below:
df=pd.DataFrame({'Price':[10,8,7,6,10,12,11,11,7,9], 'Group':['apple','apple','apple','apple','apple','berry','berry','berry','berry','berry']})
Price
Group
10
apple
8
apple
7
apple
6
apple
10
apple
12
berry
11
berry
11
berry
7
berry
9
berry
Nested dictionaries... | [
"With df the DataFrame and\nD = {\n \"apple\":{'A':[9, 10], 'B':[6, 8], 'C':[3,5]},\n \"berry\":{'A':[11, 12], 'B':[6, 9]}\n}\n\nTry:\ndf[\"cat\"] = df[[\"Price\", \"Group\"]].apply(lambda x: next(k for k,v in D[x[1]].items() if v[0] <= x[0] <= v[1] ), axis = 1)\n\nprint(df)\n\nOutput:\nPrice Group cat\n ... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074018012_dictionary_python.txt |
Q:
Pytorch giving runtimeerror can't be cast to the desired output type Long
The following code is giving runtimeerror "result type Float can't be cast to the desired output type Long".
I already tried to do the following:
FROM:
torch.div(self.indices_buf, vocab_size, out=self.beams_buf)
TO:
torch.div(self.indices_bu... | Pytorch giving runtimeerror can't be cast to the desired output type Long | The following code is giving runtimeerror "result type Float can't be cast to the desired output type Long".
I already tried to do the following:
FROM:
torch.div(self.indices_buf, vocab_size, out=self.beams_buf)
TO:
torch.div(self.indices_buf, vocab_size, out=self.beams_buf).type_as(torch.LongTensor)
Problematic code:
... | [
"maybe you can try this\nself.beams_buf = self.indices_buf // vocab_size\n"
] | [
0
] | [] | [] | [
"deep_learning",
"fairseq",
"python",
"pytorch",
"tensor"
] | stackoverflow_0070807597_deep_learning_fairseq_python_pytorch_tensor.txt |
Q:
Can't connect to database after Python and SQLAlchemy updates
I have an SQLite database in a virtual environment using Python 3.10, Flask 2.1.3 and Flask-SQLAlchemy 2.5.1 (depending on Flask-SQLAlchemy 1.4.40). I wanted to try Python build 3.11 for the improved error log so I can configure a new interpreter in PyC... | Can't connect to database after Python and SQLAlchemy updates | I have an SQLite database in a virtual environment using Python 3.10, Flask 2.1.3 and Flask-SQLAlchemy 2.5.1 (depending on Flask-SQLAlchemy 1.4.40). I wanted to try Python build 3.11 for the improved error log so I can configure a new interpreter in PyCharm to which I switch and if it didn't work to simply switch back.... | [
"The reason for the discrepancy is the SQLALCHEMY_Database_URI. FLASK-SQLAlchemy changed the file location when configuring a sqlite-database with a relative path:\n\nConfiguring SQLite with a relative path is relative to app.instance_path instead of app.root_path. The instance folder is created if necessary\n\nDet... | [
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python",
"sqlite"
] | stackoverflow_0074352935_flask_flask_sqlalchemy_python_sqlite.txt |
Q:
how to print values till ':' of a column
I have a column in a dataset as Variant Description. This column typically has values as
Variant Description
XS00463-06:CE:LEGACY
XS00464-04:CE:LEGACY
D9822-17:NONCE:STERILIZATION LOCATION CHANGE
D9822-18:NONCE:STERILIZATION LOCATION CHANGE
D9822-19:NONCE:STERI... | how to print values till ':' of a column | I have a column in a dataset as Variant Description. This column typically has values as
Variant Description
XS00463-06:CE:LEGACY
XS00464-04:CE:LEGACY
D9822-17:NONCE:STERILIZATION LOCATION CHANGE
D9822-18:NONCE:STERILIZATION LOCATION CHANGE
D9822-19:NONCE:STERILIZATION LOCATION CHANGE
I wish to ge... | [
"I would use str.extract:\ndf['Variant Description'] = df['Variant Description'].str.extract('([^:]+)')\n\nOr with str.replace (probably less efficient):\ndf['Variant Description'] = df['Variant Description'].str.replace(':.*', '', regex=True)\n\nNB. Another option would be df['Variant Description'].str.split(':', ... | [
0
] | [] | [] | [
"dataframe",
"multiple_columns",
"pandas",
"python",
"sorting"
] | stackoverflow_0074360970_dataframe_multiple_columns_pandas_python_sorting.txt |
Q:
pycups module for CUPS prinitng
I am using the python cups module to list the available destinations. And everything work perfectly. I've installed the pycups using sudo apt-get install pycups.
import cups
conn = cups.Connection()
printers = conn.getPrinters()
for p in printers:
print(p)
print(printers[p]... | pycups module for CUPS prinitng | I am using the python cups module to list the available destinations. And everything work perfectly. I've installed the pycups using sudo apt-get install pycups.
import cups
conn = cups.Connection()
printers = conn.getPrinters()
for p in printers:
print(p)
print(printers[p],["device-uri"])
The problem is that... | [
"I ran into the same problem. There is one example in their github and that's all I could find. You should probably poke around with a python debugger to learn how the library works.\n",
"You can use built-in help function in python interpreter:\n>>> import cups\n>>> help(cups)\n# shows auto-generated documentati... | [
1,
1,
0
] | [] | [] | [
"cups",
"documentation",
"python"
] | stackoverflow_0072057061_cups_documentation_python.txt |
Q:
get locator from a hover element
I want to get the locator of this element (5,126,
601) but seem cant get it normally.
I think it will have to hover the mouse to the element and try to get the xpath but still I cant hover my mouse into it because it an SVG element . Any one know a way to get the locator properly?
... | get locator from a hover element | I want to get the locator of this element (5,126,
601) but seem cant get it normally.
I think it will have to hover the mouse to the element and try to get the xpath but still I cant hover my mouse into it because it an SVG element . Any one know a way to get the locator properly?
here is the link to the website: https... | [
"Well, this element is updated only by hovering over the chart.\nThis is the unique XPath locator for this element:\n\"//*[name()='text']//*[name()='tspan' and(contains(@style,'bold'))]\"\n\nThe entire Selenium command can be:\ntotal_text = driver.find_element(By.XPATH, \"//*[name()='text']//*[name()='tspan' and(c... | [
2,
1
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074355834_css_selectors_python_selenium_selenium_webdriver_xpath.txt |
Q:
Having trouble getting next page in Scrapy
I am learning to use scrapy and am building a simple crawler to reinforce what I am learning, and am attempting to get the next page link but am having trouble. Can anyone point me in the right direction of getting the next page link, which is located in the a of the fina... | Having trouble getting next page in Scrapy | I am learning to use scrapy and am building a simple crawler to reinforce what I am learning, and am attempting to get the next page link but am having trouble. Can anyone point me in the right direction of getting the next page link, which is located in the a of the final li
The pagination div is as follows:
<div clas... | [
"Since it's the last li on the list we can use this to out advantage.\ncss:\nIn [1]: response.css('div.pagination li:last-child a::attr(href)').get()\nOut[1]: './viewforum.php?f=399&start=120'\n\nxpath:\nIn [2]: response.xpath('//div[contains(@class, \"pagination\")]//li[last()]/a/@href').get()\nOut[2]: './viewforu... | [
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler",
"web_scraping"
] | stackoverflow_0074358741_python_scrapy_web_crawler_web_scraping.txt |
Q:
select values from a list after a matching condition
I've a list of data and want to get values after a matching keyword from another list and append it to a dictionary. it should run until the next keyword is matched and added to a new dictionary.
a = ['Experience',
'Software Engineer',
'EY',
'Sep 2018 - Prese... | select values from a list after a matching condition | I've a list of data and want to get values after a matching keyword from another list and append it to a dictionary. it should run until the next keyword is matched and added to a new dictionary.
a = ['Experience',
'Software Engineer',
'EY',
'Sep 2018 - Present',
'Education',
'xyz College',
'Bachelor of Technolog... | [
"One way using a loop (assuming you have unique keys):\nB = set(b)\nc = {}\nkey = None\nfor s in a:\n if s in B:\n key = s\n c[key] = []\n elif key is not None:\n c[key].append(s)\nprint(c)\n\nOutput:\n{'Experience': ['Software Engineer', 'EY', 'Sep 2018 - Present'],\n 'Education': ['xyz ... | [
0,
0,
0,
0
] | [] | [] | [
"list",
"python",
"while_loop"
] | stackoverflow_0074360842_list_python_while_loop.txt |
Q:
How can i use pd.concat' to join all columns at once instead of calling `frame.insert` many times?
I have to create a new dataframe in which each column is determined by a function which has two arguments. The problem is that for each column the function needs a different argument which is given by the number of t... | How can i use pd.concat' to join all columns at once instead of calling `frame.insert` many times? | I have to create a new dataframe in which each column is determined by a function which has two arguments. The problem is that for each column the function needs a different argument which is given by the number of the column.
There are about 6k rows and 200 columns in the dataframe:
The function that defines each colu... | [
"you should create all dataframes in a list or generator then call pd.concat on the list or generator to create a new dataframe with all the dataframe columns in it, instead of doing it once for each column.\nthe following uses a generator to be memory efficient.\nresults = (phiNT(M,i) for i in range(1,len(M.column... | [
1
] | [] | [] | [
"dataframe",
"performance",
"python"
] | stackoverflow_0074360872_dataframe_performance_python.txt |
Q:
How do i edit django-machina forum template and styling
I am using django-machina for forum in my app. I want to change the template and also style on my own. I did that by copying all the templates of its to my template directory and copied style(machina.board_theme.min.css) to my static folder. Is this a best wa... | How do i edit django-machina forum template and styling | I am using django-machina for forum in my app. I want to change the template and also style on my own. I did that by copying all the templates of its to my template directory and copied style(machina.board_theme.min.css) to my static folder. Is this a best way if i want to edit the style and template? Also if i want to... | [
"In the static folder of your project there is a css file. Just change it (although it's min, so its hard to find what you're looking for). \nPS: I tried, but nothing was happening. So go to the installation folder of machina, \nC:\\Python27\\Lib\\site-packages\\machina\\static\\machina\\build\\css\n",
"To overri... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"python",
"python_3.x"
] | stackoverflow_0039587819_django_django_templates_python_python_3.x.txt |
Q:
Comparing different degrees of fitting curves on a dataset
I have a data set including two columns (X,y) and 40 rows and I want to fit different degrees of curves on them and plot the fitted curve in each degree and also report the MSE, bias and variance.
I have tried some different ways to do that but I couldn't ... | Comparing different degrees of fitting curves on a dataset | I have a data set including two columns (X,y) and 40 rows and I want to fit different degrees of curves on them and plot the fitted curve in each degree and also report the MSE, bias and variance.
I have tried some different ways to do that but I couldn't get to do.
this is the last code that I've wrote:
error_list=[]
... | [
"All you will need to do is reshape your X using X.reshape(-1,1) seeing as how you only have a single feature. This works if it is already a numpy array, otherwise you will need to do something like np.array(X).reshape(-1, 1).\nso your final code could look something like this\nerror_list=[]\nbias_list=[]\nvariance... | [
1
] | [] | [] | [
"non_linear_regression",
"python"
] | stackoverflow_0074361023_non_linear_regression_python.txt |
Q:
Pandas read byte string from csv
I have a pandas dataframe which has byte strings as elements in a column:
E.g. b'hey'.
When I write this dataframe to a csv and read if afterwards, pandas will return a
string with the following form "b'hey'".
This is a problem, because when calling tf.data.Dataset.from_tensor_slic... | Pandas read byte string from csv | I have a pandas dataframe which has byte strings as elements in a column:
E.g. b'hey'.
When I write this dataframe to a csv and read if afterwards, pandas will return a
string with the following form "b'hey'".
This is a problem, because when calling tf.data.Dataset.from_tensor_slices
the string will be casted to a byte... | [
"The solution is to apply ast.literal_eval first before decode with 'utf-8'.\nTo read and convert whole column with byte string:\nimport pandas as pd\nimport ast\ndf = pd.read_csv(<YOUR_DATA_FILE>, sep='\\t')\ndf['text'].apply(ast.literal_eval) # assume the column is named with 'text'\ndf['text'] = df['text'].apply... | [
0
] | [] | [] | [
"dtype",
"pandas",
"python",
"tensorflow",
"types"
] | stackoverflow_0069948363_dtype_pandas_python_tensorflow_types.txt |
Q:
NCBI Blast not running
I am trying to run online ncbi blast on python.
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import SeqIO
record = SeqIO.read(r"C:\Users\loops\Downloads\biopy_resources\Section1\Chap8\buccal_swab.unmapped1.fasta",format="fasta")
handle = NCBIWWW.qblast("blastn","nt... | NCBI Blast not running | I am trying to run online ncbi blast on python.
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import SeqIO
record = SeqIO.read(r"C:\Users\loops\Downloads\biopy_resources\Section1\Chap8\buccal_swab.unmapped1.fasta",format="fasta")
handle = NCBIWWW.qblast("blastn","nt",record.seq)
blast_records... | [
"if there is no error, maybe there is not result because the e-value if above the threshold? you could disable the if condition\nOR\nmight relate to this problem of running slow within python eventually:\nNCBIWWW.qblast parsing xml files\n"
] | [
0
] | [] | [] | [
"biopython",
"blast",
"ncbi",
"python"
] | stackoverflow_0074360808_biopython_blast_ncbi_python.txt |
Q:
scraping when there is on-click
Hi I'm trying to scrape pdf files from this website.
I tried using beautiful soup and also lxml. But I get empty lists. Please let me know where I'm mistaking. There is also one on-click button.
my code.
r= requests.get('http://www.italgiure.giustizia.it/sncass/')
soup = BeautifulS... | scraping when there is on-click | Hi I'm trying to scrape pdf files from this website.
I tried using beautiful soup and also lxml. But I get empty lists. Please let me know where I'm mistaking. There is also one on-click button.
my code.
r= requests.get('http://www.italgiure.giustizia.it/sncass/')
soup = BeautifulSoup(r.text, 'html.parser')
pdf_list ... | [
"The files come from a POST request and you need to mimic it to get the files.\nFor example:\nimport urllib.parse\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074360647_beautifulsoup_python_web_scraping.txt |
Q:
Python Pandas Error tokenizing data
I'm trying to use pandas to manipulate a .csv file but I get this error:
pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12
I have tried to read the pandas docs, but found nothing.
My code is simple:
path = 'GOOG Key Ratios.csv'
#p... | Python Pandas Error tokenizing data | I'm trying to use pandas to manipulate a .csv file but I get this error:
pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12
I have tried to read the pandas docs, but found nothing.
My code is simple:
path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_cs... | [
"you could also try;\ndata = pd.read_csv('file1.csv', on_bad_lines='skip')\n\nDo note that this will cause the offending lines to be skipped.\nEdit\nFor Pandas < 1.3.0 try\ndata = pd.read_csv(\"file1.csv\", error_bad_lines=False)\n\nas per pandas API reference.\n",
"It might be an issue with\n\nthe delimiters in ... | [
900,
192,
64,
57,
44,
40,
26,
17,
14,
14,
13,
8,
8,
8,
6,
6,
6,
5,
4,
4,
4,
4,
3,
3,
3,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [
"try: pandas.read_csv(path, sep = ',' ,header=None)\n"
] | [
-1
] | [
"csv",
"pandas",
"python"
] | stackoverflow_0018039057_csv_pandas_python.txt |
Q:
How to run duplex communication using python sockets
I have 3 Raspberry Pi's, all on the same LAN doing stuff that is monitored by Python and I want them to talk to each other, and to my PC. Sockets seem like the way to go, but the examples are so simplistic. Here's the issue I am stuck on - the listen and receive... | How to run duplex communication using python sockets | I have 3 Raspberry Pi's, all on the same LAN doing stuff that is monitored by Python and I want them to talk to each other, and to my PC. Sockets seem like the way to go, but the examples are so simplistic. Here's the issue I am stuck on - the listen and receive processes are all blocking, unless you set a timeout, in ... | [
"You can handle multiple sockets in a single process using I/O multiplexing. This is usually done using calls such as epoll(), poll() or select(). These calls monitor multiple sockets and return when one or more sockets have data available for reading. Or are ready to write data to. In many cases this is more conve... | [
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0074361006_python_sockets.txt |
Q:
How to create a data frame from different Text files
I was working on a project where I have to scrape the some text files from a source. I completed this task and I have 140 text file.
This is one of the text file I have scraped.
I am trying to create a dataframe where I should have one row for each text file. S... | How to create a data frame from different Text files | I was working on a project where I have to scrape the some text files from a source. I completed this task and I have 140 text file.
This is one of the text file I have scraped.
I am trying to create a dataframe where I should have one row for each text file. So I wrote the below code:-
import pandas as pd
import os
... | [
"I'm not shure why you need pd.read_csv() for this. Try it with pure python:\nresult = pd.DataFrame(columns=['Samplename', 'data'])\nfor file in textfiles:\n with open(file) as f:\n data = f.read()\n result = pd.concat([result, pd.DataFrame({'Samplename' : file, 'data': data}, index=[0])], axis=0, igno... | [
1
] | [] | [] | [
"dataframe",
"operating_system",
"pandas",
"python"
] | stackoverflow_0074361051_dataframe_operating_system_pandas_python.txt |
Q:
Selenium python program freezes at get() function
A simple python program freezes on the get() function of the selenium driver and does not return.
Please find below the written code:
self.browser = webdriver.Ie("IEDriver\\IEDriverServer.exe")
self.browser.get(<url_in_quotes>)
print('here')... | Selenium python program freezes at get() function | A simple python program freezes on the get() function of the selenium driver and does not return.
Please find below the written code:
self.browser = webdriver.Ie("IEDriver\\IEDriverServer.exe")
self.browser.get(<url_in_quotes>)
print('here') ##does not print
self.browser.find_element_by_... | [
"As suggested by Pcalkins, I made the necessary configuration changes in IE settings and the python code worked.\nPlease refer to the link below for recommended settings:\nhttps://www.selenium.dev/documentation/ie_driver_server/\n"
] | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_iedriver"
] | stackoverflow_0074266894_python_selenium_selenium_iedriver.txt |
Q:
Create new column by using a list comprehension with two 'for' loops in Pandas DataFrame
I have the following dataframe
df=pd.DataFrame({'col1': ['aaaa', 'aabb', 'bbcc', 'ccdd'],
'col2': ['ab12', 'cd15', 'kf25', 'zx78']})
df
col1 col2
0 aaaa ab12
1 aabb cd15
2 bbcc kf25
3 ccdd zx78
... | Create new column by using a list comprehension with two 'for' loops in Pandas DataFrame | I have the following dataframe
df=pd.DataFrame({'col1': ['aaaa', 'aabb', 'bbcc', 'ccdd'],
'col2': ['ab12', 'cd15', 'kf25', 'zx78']})
df
col1 col2
0 aaaa ab12
1 aabb cd15
2 bbcc kf25
3 ccdd zx78
I want to create 'col3' based on 'col1' and 'col2', I want to get:
df
col1 col2 col3... | [
"Use simple slicing with the str accessor, and concatenation:\ndf['col3'] = df['col1'].str[:2] + '-' + df['col2'].str[2:4]\n\nOr, if you want the last two characters of col2:\ndf['col3'] = df['col1'].str[:2] + '-' + df['col2'].str[-2:]\n\nOutput:\n col1 col2 col3\n0 aaaa ab12 aa-12\n1 aabb cd15 aa-15\n2 ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074361279_dataframe_pandas_python.txt |
Q:
How come queries aren't being added to Django's db.connection.queries in tests?
I'm trying to capture the queries which my code submits to the database by examining the contents of django.db.connection.queries. For some reason though, after all the automatically produced setup queries are logged, no further queri... | How come queries aren't being added to Django's db.connection.queries in tests? | I'm trying to capture the queries which my code submits to the database by examining the contents of django.db.connection.queries. For some reason though, after all the automatically produced setup queries are logged, no further queries are logged from my own code. The following test case demonstrates the behavior.
f... | [
"You have to explicitly set DEBUG. For example, see the sample usage section for these tests in the django documentation:\n# Set up.\n# The test runner sets settings.DEBUG to False, but we want to gather queries\n# so we'll set it to True here and reset it at the end of the test suite.\n>>> from django.conf import... | [
9,
5,
5,
0
] | [] | [] | [
"django",
"python",
"sql",
"testing"
] | stackoverflow_0003663319_django_python_sql_testing.txt |
Q:
How to fix gTTS Unable to find token python error
Im trying to create a virtual assistant but I cant get the gTTS working (google text to speech) working and I cant seem to fix it
import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS
def speak(text):
tts = gTTS(text = te... | How to fix gTTS Unable to find token python error | Im trying to create a virtual assistant but I cant get the gTTS working (google text to speech) working and I cant seem to fix it
import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS
def speak(text):
tts = gTTS(text = text, lang="en")
filename = "voice.mp3"
tts.save(... | [
"I had the same error, until I upgrade gTTS-token\npip install gTTS-token --upgrade\n\nAnd let me tell you as well that I have a Windows machine in which I run a Linux terminal. In that case I couldn't make it work (Nevertheless try it if this is your case).\nHope it works!\n",
"There was an ISSUE with gtts depen... | [
0,
0,
0
] | [] | [] | [
"google_text_to_speech",
"gtts",
"python",
"python_3.x"
] | stackoverflow_0064760579_google_text_to_speech_gtts_python_python_3.x.txt |
Q:
RuntimeWarning: coroutine 'Loop._loop' was never awaited Process exited with status 1
i have a RuntimeWarning error in my code it will help me if you could tell me what to fix,
btw this is discord.py
code :
`
@tasks.loop(minutes=2)
async def rated():
channel = bot.get_channel(95... | RuntimeWarning: coroutine 'Loop._loop' was never awaited Process exited with status 1 | i have a RuntimeWarning error in my code it will help me if you could tell me what to fix,
btw this is discord.py
code :
`
@tasks.loop(minutes=2)
async def rated():
channel = bot.get_channel(954343331889025035)
messages = await channel.history(limit=10).flatten()
... | [
"You need create/get loop and run it with asyncio:\nhttps://docs.python.org/3/library/asyncio-eventloop.html\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074361068_discord_discord.py_python.txt |
Q:
get columns from key words + count occurences
I have a problem to solve. I need to create new columns from given key_words list and sum their occurrence in data frame.
key_words = ['apple', 'animal', 'everyone']
input data frame:
id
description
xx
1
Apple is a healthy fruit. Everyone should eat it.
..
2
Lion is... | get columns from key words + count occurences | I have a problem to solve. I need to create new columns from given key_words list and sum their occurrence in data frame.
key_words = ['apple', 'animal', 'everyone']
input data frame:
id
description
xx
1
Apple is a healthy fruit. Everyone should eat it.
..
2
Lion is a denagerous animal.
..
3
Everyone likes ... | [
"This will work for you\nkey_words = ['apple', 'animal', 'everyone']\nfor key in key_words:\n df[key] = df['description'].str.lower().str.count(key)\n\n",
"keys = ['apple', 'animal', 'everyone']\ndf['apple'], df['animal'], df['everyone'] = (\n zip(*list([len(re.findall(f'(?i){k}', r)) for k in keys] for r in... | [
2,
0
] | [] | [] | [
"dataframe",
"list",
"python"
] | stackoverflow_0074360839_dataframe_list_python.txt |
Q:
How can I get the len of nontype
Hello guys I'm trying to write a program that generate a random password then cracks is it but I'm getting the error object of type 'NoneType' has no len()
from random import choice
from string import ascii_lowercase
def nrndprint(n):
k=(''.join(choice(ascii_lowercase) for i in... | How can I get the len of nontype | Hello guys I'm trying to write a program that generate a random password then cracks is it but I'm getting the error object of type 'NoneType' has no len()
from random import choice
from string import ascii_lowercase
def nrndprint(n):
k=(''.join(choice(ascii_lowercase) for i in range(n))) #.join
print(k)
nrndpri... | [
"You can't calculate the length of NoneType.\nYour function nrndprint() doesn't return anything. Adding return k will solve your problem.\n",
"NoneType doesn't have len() method so it's raising an error.\nYou are assinging passwd = nrndprint(4) and then passing the passwd variable to crack_pass, but since your fu... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074361302_python.txt |
Q:
Pandas Rolling Gradient - Improving/Reducing Computation Time
I am calculating the rolling slope or gradient of a column in a pandas data frame with a datetime index and looking for suggestions to reduce computation time over the current approach using .rolling and .apply (detailed below).
You have additional requ... | Pandas Rolling Gradient - Improving/Reducing Computation Time | I am calculating the rolling slope or gradient of a column in a pandas data frame with a datetime index and looking for suggestions to reduce computation time over the current approach using .rolling and .apply (detailed below).
You have additional requirements which are the minimum number of observations to include in... | [
"Okay, here is are my first results (managed to get a ~7x improvement). However, I'm pretty sure that if you assume no nans, you can get a ~100x to 1000x speed improvement, but that's for another time. -- update, see the edit below\nProfiling the get_slope function reveals the 3 bottlenecks:\nLine # Hits ... | [
2,
1,
0
] | [] | [] | [
"pandas",
"performance",
"python"
] | stackoverflow_0067997826_pandas_performance_python.txt |
Q:
model.get_weights() vs model.trainable_variables Tensorflow
model.get_weights() and model.trainable_variables in Tensorflow seems to be returning same values in different data types. Former returns list of arrays and latter array of tensors. (If I am not mistaken)
Please, explain in which context is better to use ... | model.get_weights() vs model.trainable_variables Tensorflow | model.get_weights() and model.trainable_variables in Tensorflow seems to be returning same values in different data types. Former returns list of arrays and latter array of tensors. (If I am not mistaken)
Please, explain in which context is better to use each?
Also, I was trying to compare them but had no luck, if poss... | [
"model.get_weights():\n\nIt returns the current weights of the layer, as NumPy arrays.\nThis function returns a list of NumPy arrays containing both trainable and non-trainable weight values associated with this layer, which may then be used to load state into similarly parameterized layers.\n\nmodel.trainable_vari... | [
1
] | [] | [] | [
"data_science",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0067553616_data_science_machine_learning_python_tensorflow.txt |
Q:
Efficient way to set all empty lists in column to None in Pandas
In pandas, it is possible to do the following:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 99919 entries, 0 to 99918
Data columns (total 47 columns):
# Column Non-Null Count Dtype
--- ------ ... | Efficient way to set all empty lists in column to None in Pandas | In pandas, it is possible to do the following:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 99919 entries, 0 to 99918
Data columns (total 47 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 reason ... | [
"The syntax should be:\ndf.loc[df['reasons'].str.len() == 0, 'reasons'] = None\n\nThe correct use of loc is loc[row, col], not loc[:, (row, col)]\ndf.loc[:, (X, Y)] can be used if you have a MultiIndex (see below for an example), but this is not the case here.\ndf = pd.DataFrame(None, index=range(2),\n ... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074361351_dataframe_pandas_python.txt |
Q:
Is there a way to install pytest on wingide?
I know this might seem like a dumb question but is there a way to install pytest on wingide as I am in need.
I have tried looking for tutorials and getting help but I can't seem to figure out.
A:
You should be able to install it using pip:
pip install pytest
or:
pyth... | Is there a way to install pytest on wingide? | I know this might seem like a dumb question but is there a way to install pytest on wingide as I am in need.
I have tried looking for tutorials and getting help but I can't seem to figure out.
| [
"You should be able to install it using pip:\npip install pytest\n\nor:\npython -m pip install pytest\n\nYou do have to make sure you're using the right pip or python, to match the one that you are using in Wing. If you have Wing Pro you can also use the Packages tool in the Tools menu to install pytest. Use Inst... | [
1
] | [] | [] | [
"pytest",
"python",
"wing_ide"
] | stackoverflow_0074355322_pytest_python_wing_ide.txt |
Q:
How can i create timer or contdown in python?
Is there any function or way that I can greate timer in python?
For example:you have 5 seconds to slove this question or maybe to calculate total time for solving this question
The simple one countdown:
A:
Here is your code:
import time
run = int(input(""))
if run:
... | How can i create timer or contdown in python? | Is there any function or way that I can greate timer in python?
For example:you have 5 seconds to slove this question or maybe to calculate total time for solving this question
The simple one countdown:
| [
"Here is your code:\nimport time\nrun = int(input(\"\"))\nif run:\n for i in range(1, run+1):\n time.sleep(1)\n print(i)\n\n"
] | [
0
] | [] | [] | [
"python",
"python_module",
"timer"
] | stackoverflow_0074361484_python_python_module_timer.txt |
Q:
Convert JSON IPython notebook (.ipynb) to .py file
How do you convert an IPython notebook file (json with .ipynb extension) into a regular .py module?
A:
From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would se... | Convert JSON IPython notebook (.ipynb) to .py file | How do you convert an IPython notebook file (json with .ipynb extension) into a regular .py module?
| [
"From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.\n\nAnother option would be to use nbconvert from the command line:\njupyter nbconvert --to script 'my-notebook.ipynb'\n\nHave a l... | [
152,
38,
30,
13,
4,
4,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"ipython",
"jupyter_notebook",
"nbconvert",
"python"
] | stackoverflow_0037797709_ipython_jupyter_notebook_nbconvert_python.txt |
Q:
How to run an exponential function with sympy.Symbol?
I am trying to plot a Piecewise Defined Function in Python. I have figured out how to get it to plot, however, one of the formulas in the Piecewise reads: 4e^(0.1x)sin(2x) X E [−10,-]
I tried including the Exponential function of it (e^(0.1x)) but it gives me t... | How to run an exponential function with sympy.Symbol? | I am trying to plot a Piecewise Defined Function in Python. I have figured out how to get it to plot, however, one of the formulas in the Piecewise reads: 4e^(0.1x)sin(2x) X E [−10,-]
I tried including the Exponential function of it (e^(0.1x)) but it gives me the following error:
TypeError: Cannot convert expression to... | [
"You cannot mix functions from math and sympy. Look at what you did:\nf1 = 4*sp.pi*math.exp(0.1*x)*sp.sin(2*sp.pi*x)\n\nHere you used the math.exp into a symbolic expression. You need to use Sympy's exponential function:\nf1 = 4*sp.pi*sp.exp(0.1*x)*sp.sin(2*sp.pi*x)\n\n"
] | [
0
] | [] | [] | [
"exponential",
"plot",
"python",
"sympy"
] | stackoverflow_0074360032_exponential_plot_python_sympy.txt |
Q:
How to send powershell command to pc through usb with python?
I'm making an rpi based terminal in python and I want to run a powershell command on my computer. How can I send a command to a usb device
A:
You could run socat on your Windows PC to read from serial and execute whatever you receive - if you like big... | How to send powershell command to pc through usb with python? | I'm making an rpi based terminal in python and I want to run a powershell command on my computer. How can I send a command to a usb device
| [
"You could run socat on your Windows PC to read from serial and execute whatever you receive - if you like big security holes Try adding socat tag to attract the right folk if that's an option.\nOr you could run a Python script that sits in a loop reading from serial and then using subprocess.run() to execute the c... | [
0
] | [] | [] | [
"linux",
"powershell",
"python",
"windows"
] | stackoverflow_0074360724_linux_powershell_python_windows.txt |
Q:
Position of cursor rectangle in QTextEdit (PySide6)
I need to get absolute cursor position (in pixels) in QTextEdit.
I try
from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self.text_edit = QtWidgets.QTextEdit(... | Position of cursor rectangle in QTextEdit (PySide6) | I need to get absolute cursor position (in pixels) in QTextEdit.
I try
from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self.text_edit = QtWidgets.QTextEdit(self)
self.text_edit.setGeometry(10, 10, 100, 100... | [
"There are two basic problems with your code. Firstly, from the documentation (my emphasis)...\n\nreturns a rectangle (in viewport coordinates) that includes the\ncursor.\n\nSo the print statement should be...\nprint(self.text_edit.viewport().mapToGlobal(self.text_edit.cursorRect(self.cursor).topLeft()))\n\nSecond... | [
0
] | [] | [] | [
"pyside6",
"python",
"qt",
"qtextcursor",
"qtextedit"
] | stackoverflow_0074361020_pyside6_python_qt_qtextcursor_qtextedit.txt |
Q:
tkinter .after() second and minute
hey guys i have a problem im making a timer in tkinter but i cant use time.sleep() so i use .after() and i have new problem,I made an entry that I want the entry number to be * 60 and after the set time, a text will be written that says >> time is over! ,but then, how should tha... | tkinter .after() second and minute | hey guys i have a problem im making a timer in tkinter but i cant use time.sleep() so i use .after() and i have new problem,I made an entry that I want the entry number to be * 60 and after the set time, a text will be written that says >> time is over! ,but then, how should that 60 be converted into seconds? my code:... | [
"The after command takes input in milliseconds, so multiply it by 1000 to convert it to seconds.\nAdditionally, I just made a small example that displays the countdown for you as the clock ticks down:\n# Usually it is a good idea to refrain from importing everything from the tkinter\n# package, as to not pollute yo... | [
3,
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0074361523_python_tkinter_tkinter_entry.txt |
Q:
Trouble converting code from VBA to Python
I am having issues converting this code from VBA to python, it's a function that needs to be converted to python instead of VBA
Function NC(SPL, pond) As Single
Dim A As Single
Dim B As Single
Dim I As Integer
Dim SPL1(8) As Single
B = 0
If p... | Trouble converting code from VBA to Python | I am having issues converting this code from VBA to python, it's a function that needs to be converted to python instead of VBA
Function NC(SPL, pond) As Single
Dim A As Single
Dim B As Single
Dim I As Integer
Dim SPL1(8) As Single
B = 0
If pond = "A" Then
SPL1(1) = SPL(1) + 26.222... | [
"Python is dynamically typed and 0 base indexed. Also by convention lower-case variable names are used. So your code would be something along the lines of:\ndef nc(spl, pond):\n \n spl1 =[0.0 for _ in range(8))]\n \n b = 0.0\n \n if pond == 'A':\n spl1[0] = spl[0] + 26.228\n #and so ... | [
0
] | [] | [] | [
"excel",
"for_loop",
"if_statement",
"python",
"vba"
] | stackoverflow_0074361157_excel_for_loop_if_statement_python_vba.txt |
Q:
Why is multiprocess running outside of the target function?
I have this code:
import multiprocessing
with open('pairs.txt') as f:
pairs = f.read().splitlines()
print(pairs)
def worker(pairtxt):
print(pairtxt)
if __name__ == '__main__':
jobs = []
for i in pairs:
p = multiprocessing.Proces... | Why is multiprocess running outside of the target function? | I have this code:
import multiprocessing
with open('pairs.txt') as f:
pairs = f.read().splitlines()
print(pairs)
def worker(pairtxt):
print(pairtxt)
if __name__ == '__main__':
jobs = []
for i in pairs:
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.sta... | [
"Try moving the with open and print(pairs) statements into your if __name__ == '__main__' block. \nI suspect that python is running the full script every time the subprocess is called, as it wants to ensure that all of the dependencies are met (imports and such) for the function that you hand it. By having running ... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0045651900_python.txt |
Q:
How to create a spark DataFrame from Nested JSON structure
I'm trying to load data from the ExactOnline API into a spark DataFrame. Data comes out of the API in a very ugly format. I have multiple lines of valid JSON objects in one JSON file. One line of JSON looks as follows:
{
"d": {
"results": [
... | How to create a spark DataFrame from Nested JSON structure | I'm trying to load data from the ExactOnline API into a spark DataFrame. Data comes out of the API in a very ugly format. I have multiple lines of valid JSON objects in one JSON file. One line of JSON looks as follows:
{
"d": {
"results": [
{
"__metadata": {
"... | [
"you can directly read JSON files in spark with spark.read.json(), but use the multiLine option as a single JSON is spread across multiple lines. then use inline sql function to explode and create new columns using the struct fields inside the array.\njson_sdf = spark.read.option(\"multiLine\", \"true\").json(\n ... | [
2,
1
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"json",
"pyspark",
"python"
] | stackoverflow_0074361544_apache_spark_apache_spark_sql_json_pyspark_python.txt |
Q:
is there a way to solve higher power nonlinear equations using sympy
im new to python and sympy , but I'm trying to use sympy to solve equations of high powers which i cannot manually do .The code I'm using worked for lower powers but for this specific equation ,the code runs but the output is an empty list [].I... | is there a way to solve higher power nonlinear equations using sympy | im new to python and sympy , but I'm trying to use sympy to solve equations of high powers which i cannot manually do .The code I'm using worked for lower powers but for this specific equation ,the code runs but the output is an empty list [].Is there a way to fix this ?
I tried running it without setting y to be pos... | [
"You can use nsolve but you would have to provide an initial guess. For example:\n# solve eq for y, with an initial guess of y=2\nnsolve(eq, y, 2)\n# out: 2.0002640101498\n\nSince this is a relatively easy equation, you can use plot to find a proper initial guess:\nplot(eq.rewrite(Add))\n\n"
] | [
1
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074361587_python_sympy.txt |
Q:
Bulk indexing in elasticsearch 8.x : 'Action/metadata line [1] contains an unknown parameter [_type]'
I have been trying to do a bulk index in the elasticsearch 8.x using this:
from elasticsearch.helpers import bulk as bulk_indexer
success, failed = bulk_indexer(self.es_client, actions, stats_only=True, chunk_siz... | Bulk indexing in elasticsearch 8.x : 'Action/metadata line [1] contains an unknown parameter [_type]' | I have been trying to do a bulk index in the elasticsearch 8.x using this:
from elasticsearch.helpers import bulk as bulk_indexer
success, failed = bulk_indexer(self.es_client, actions, stats_only=True, chunk_size=900)
Apparently i am seeing :
RuntimeError: elasticsearch.BadRequestError: BadRequestError(400, 'illegal... | [
"There must be a _type in the action command line that shouldn't be there anymore. If those records have been stored in Kafka in earlier versions of ES and you're replaying them, or if the client application still produces those action records with the same logic, then you either need to change that producing logic... | [
0
] | [] | [] | [
"elasticsearch",
"elasticsearch_py",
"full_text_search",
"python"
] | stackoverflow_0074360987_elasticsearch_elasticsearch_py_full_text_search_python.txt |
Q:
Trying to retrieve data from the Anbima API
I'm trying to automate a process in which i have to download some brazilian fund quotes from Anbima (Brazil regulator). I have been able to work around the first steps to retrieve the access token but i don't know how to use the token in order to make requests. Here is t... | Trying to retrieve data from the Anbima API | I'm trying to automate a process in which i have to download some brazilian fund quotes from Anbima (Brazil regulator). I have been able to work around the first steps to retrieve the access token but i don't know how to use the token in order to make requests. Here is the tutorial website https://developers.anbima.com... | [
"I was having the same problem, but today I could advance. I believe you need to adjust some parameters in the header.\nFollows the piece of code I developed.\nfrom bs4 import BeautifulSoup\n\nimport requests\n\nPRODUCTION_URL = 'https://api.anbima.com.br'\nSANDBOX_URL = 'https://api-sandbox.anbima.com.br'\nAPI_URL... | [
0,
0
] | [] | [] | [
"api",
"python",
"request"
] | stackoverflow_0068210942_api_python_request.txt |
Q:
Pythpn select records from a sql table only from last hour
I want to get the records from last 5 minutes. I am currently using this code, which I got from this site:
select sum(valueint) from clienttest where date <= "2022-11-04 12:00" and date >= "2022-11-04 11:00"
and its working fine in mysql, now i want to do... | Pythpn select records from a sql table only from last hour | I want to get the records from last 5 minutes. I am currently using this code, which I got from this site:
select sum(valueint) from clienttest where date <= "2022-11-04 12:00" and date >= "2022-11-04 11:00"
and its working fine in mysql, now i want to do the same and this data on the terminal on pycharm with python b... | [
"read = (\"\"\"select * from clienttest where timestamp >= timestamp(date_sub(now(), interval 5 minute))\"\"\")\n\nmycursor.execute(read)\n\nfor row in read:\n print(row)\n\ni forget to interact with the DB, still no data shown..\n"
] | [
0
] | [] | [] | [
"mysql",
"pandas",
"python"
] | stackoverflow_0074361694_mysql_pandas_python.txt |
Q:
How can I plot a line with markers for separate categories in a relplot?
Using Seaborn I would like to plot both SBP and DBP columns as below.
To achieve this, I use:
plt.style.use('ggplot')
g = sns.relplot(data=r_29, x="DATE_TIME", y="SBP", col="VISIT", col_wrap=2, facet_kws={'sharey': False, 'sharex': False}, a... | How can I plot a line with markers for separate categories in a relplot? | Using Seaborn I would like to plot both SBP and DBP columns as below.
To achieve this, I use:
plt.style.use('ggplot')
g = sns.relplot(data=r_29, x="DATE_TIME", y="SBP", col="VISIT", col_wrap=2, facet_kws={'sharey': False, 'sharex': False}, aspect=2, marker='o')
g = sns.relplot(data=r_29, x="DATE_TIME", y="DBP", col="V... | [
"\nYou can use FacetGrid to render plots in a way that is shown in your first figure.\n\nThen, use set_axis_labels option to change name of the x- and y- axis.\n\n\n# LINE PLOT\ng = sns.FacetGrid(r_29, col=\"VISIT\", sharex=False, sharey=False,aspect=2,col_wrap=2,legend_out=True) # 2 columns, legend is outside of p... | [
1
] | [] | [] | [
"facet_grid",
"pandas",
"python",
"relplot",
"seaborn"
] | stackoverflow_0074233215_facet_grid_pandas_python_relplot_seaborn.txt |
Q:
Changing the key in a counter form an integer to a string
Please is there a way to change the key in a counter from an interger to a string?
Counter({0: 335251, 1: 31430})
A:
I am assuming that Counter comes from collections module. If yes, Counter is just a subclass of dict which means that all dict methods are... | Changing the key in a counter form an integer to a string | Please is there a way to change the key in a counter from an interger to a string?
Counter({0: 335251, 1: 31430})
| [
"I am assuming that Counter comes from collections module. If yes, Counter is just a subclass of dict which means that all dict methods are available in Counter class as well.\n>>> from collections import Counter\n>>>\n>>> c = Counter({0: 335251, 1: 31430})\n>>> {str(key): value for key, value in c.items()}\n{'0': ... | [
1
] | [] | [] | [
"counter",
"dictionary",
"python"
] | stackoverflow_0074361771_counter_dictionary_python.txt |
Q:
How to calculate rolling cumulative product on Pandas DataFrame
I have a time series of returns, rolling beta, and rolling alpha in a pandas DataFrame. How can I calculate a rolling annualized alpha for the alpha column of the DataFrame? (I want to do the equivalent to =PRODUCT(1+[trailing 12 months])-1 in excel... | How to calculate rolling cumulative product on Pandas DataFrame | I have a time series of returns, rolling beta, and rolling alpha in a pandas DataFrame. How can I calculate a rolling annualized alpha for the alpha column of the DataFrame? (I want to do the equivalent to =PRODUCT(1+[trailing 12 months])-1 in excel)
SPX Index BBOEGEUS Index Beta Alpha
2006-07-31 ... | [
"rolling_apply has been dropped in pandas and replaced by more versatile\nwindow methods (e.g. rolling() etc.)\n# Both agg and apply will give you the same answer\n(1+df).rolling(window=12).agg(np.prod) - 1\n# BUT apply(raw=True) will be much FASTER!\n(1+df).rolling(window=12).apply(np.prod, raw=True) - 1\n\n",
"... | [
25,
22,
7,
0
] | [
"rolling_apply is deprecated, so this works best:\n\n(1 + df).cumprod() - 1\n\n"
] | [
-2
] | [
"finance",
"pandas",
"python",
"time_series"
] | stackoverflow_0015295434_finance_pandas_python_time_series.txt |
Q:
Print dictionary value having a letter '
Sorry for the basic question. But I cannot find a solution of this problem.
I'd like to print dictionary value at the Django terminal.
Here, I have a dictionary
c={'code': '12'}
I just want to print 12 at the terminal
But when I enter
print(c.values()) in the terminal,
noth... | Print dictionary value having a letter ' | Sorry for the basic question. But I cannot find a solution of this problem.
I'd like to print dictionary value at the Django terminal.
Here, I have a dictionary
c={'code': '12'}
I just want to print 12 at the terminal
But when I enter
print(c.values()) in the terminal,
nothing appears.
I think the latter ' is the probl... | [
"print(c[\"code\"])\n\nThe c variable is a dictionary, \"code\" is a key and 12 is a value.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074361778_django_python.txt |
Q:
How to transform th function into decorator in Django?
I have the fucntion header which values I need to put into 3 urls, I don't want to request the values in every view and render the context, because it takes some lines. How can I make the decorator?
def acc_profile(request):
refferals, balance= header(requ... | How to transform th function into decorator in Django? | I have the fucntion header which values I need to put into 3 urls, I don't want to request the values in every view and render the context, because it takes some lines. How can I make the decorator?
def acc_profile(request):
refferals, balance= header(request)
context = {'refferals':refferals,'balance':balance}... | [
"You can create decorator like this\ndef acc_profile(request, referrals,balance):\n context = {'refferals':refferals,'balance':balance}\n return render(request, 'accounts/profile.html')\n\ndef header(func):\n def fun(request, *args, **kwargs):\n user_id = request.user.id\n refferals = Customer.objects.... | [
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0074361603_django_django_views_python.txt |
Q:
how to schedule task with python using Schedule?
Right now i am trying to do a reminder in python with scheduler. I used the schedule.every().tuesday.at("21:35").do(reminder) method but i want users to input the day and time instead of setting in coding. is there a way to do so?
coding:
remind = input("What should... | how to schedule task with python using Schedule? | Right now i am trying to do a reminder in python with scheduler. I used the schedule.every().tuesday.at("21:35").do(reminder) method but i want users to input the day and time instead of setting in coding. is there a way to do so?
coding:
remind = input("What should i remind about?")
DAY = input("Which Day?")
Time = i... | [
"user_input = input(\"Enter a date\")\n# do whatever you want with the input\nprint(user_input)\n\nYou should consider extracting the day and the time from the input. It depends on how you want them.\n"
] | [
0
] | [] | [] | [
"days",
"pycharm",
"python",
"reminders",
"time"
] | stackoverflow_0074361759_days_pycharm_python_reminders_time.txt |
Q:
Problem with plotting multiple functions with a for loop in matplotlib
I am using a for loop to plot a curve for each parameter-value (k) - this works just fine for all the negative k-values, but when the loop reaches the k values = 0 or greater, the lambdify function seems to collapse and I get an error stating t... | Problem with plotting multiple functions with a for loop in matplotlib | I am using a for loop to plot a curve for each parameter-value (k) - this works just fine for all the negative k-values, but when the loop reaches the k values = 0 or greater, the lambdify function seems to collapse and I get an error stating the dimensions of x and y are not equal.
This is my code:
import sympy as sym... | [
"The problem is that when y=0, then 2*x**3*y**n/(((2*n)**2+x**2)**(3/2)) will be 0, hence R will be zero. When you lambdify it and pass in a numpy array, it will return the scalar value 0. We need to take into account this fact. Note that in the following code block I also optimize for speed: only one symbolic addi... | [
0,
0
] | [] | [] | [
"lambdify",
"matplotlib",
"numpy",
"python",
"sympy"
] | stackoverflow_0074361048_lambdify_matplotlib_numpy_python_sympy.txt |
Q:
Python - Trying to backup a network switch using Paramiko, not receiving the expected output
I've been trying to create a script that would back up our switches from a CSV file.
I'm using Paramiko to SSH into a switch and run "show run", but for some reason the only output I'm receiving is the name of the switch.
... | Python - Trying to backup a network switch using Paramiko, not receiving the expected output | I've been trying to create a script that would back up our switches from a CSV file.
I'm using Paramiko to SSH into a switch and run "show run", but for some reason the only output I'm receiving is the name of the switch.
import pandas
import paramiko
# Connection info
USERNAME = "username"
PW = "password"
PORT = 22... | [
"As @MarinPrikryl pointed, the devices I was trying to connect do not support the \"exec\" channel.\nHere's how I managed to do it using the shell:\nimport pandas\nimport paramiko\nfrom time import sleep\n\n# Connection info\nUSERNAME = \"username\"\nPW = \"password\"\nPORT = 22\nssh = paramiko.SSHClient()\nssh.set... | [
0
] | [] | [] | [
"paramiko",
"python",
"ssh",
"switching"
] | stackoverflow_0074356744_paramiko_python_ssh_switching.txt |
Q:
(pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'mysql' ([Errno -3] Temporary failure in name resolution
I am trying to Dockerize a FastAPI app that uses MYSQL and Seleniun.
I am having issues with connecting MYSQL with the FASTAPI app in the Docker.
I have tried to establish connection wit... | (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'mysql' ([Errno -3] Temporary failure in name resolution | I am trying to Dockerize a FastAPI app that uses MYSQL and Seleniun.
I am having issues with connecting MYSQL with the FASTAPI app in the Docker.
I have tried to establish connection with MYSQL container using MYSQL Workbench which worked well using 'localhost' as the host. However, when I try to run the fastapi contai... | [
"Your app container declares networks: [selenium]. The mysql container doesn't have a networks: block at all, so Compose automatically inserts networks: [default]. Since the two containers aren't on the same Docker network they can't communicate with each other, and one of the ways you see that is with the DNS-re... | [
1
] | [] | [] | [
"docker",
"fastapi",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0074361490_docker_fastapi_mysql_python_sqlalchemy.txt |
Q:
pandas data rows part merge
I have created a dataframe with pandas.
There are more than 1000 rows
I want to merge rows of overlapping columns among them.
For convenience, there are example screenshots made in Excel.
I want to make that form in PYTHON.
I want to make the above data like below
A:
This should be as... | pandas data rows part merge | I have created a dataframe with pandas.
There are more than 1000 rows
I want to merge rows of overlapping columns among them.
For convenience, there are example screenshots made in Excel.
I want to make that form in PYTHON.
I want to make the above data like below
| [
"This should be as simple as setting the index.\ndf = df.set_index('Symbol', append=True).swaplevel(0,1)\nOutput should be as desired.\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074361872_pandas_python.txt |
Q:
How to find partial word matches in 2 pandas dataframes?
Sorry if this is a similar question, I tried to find one that could answer my specific use-case but I only found ones that give exact matches between dataframes.
I have 2 pandas data frames of descriptions:
df1:
Description
i had lunch
going to the airport
b... | How to find partial word matches in 2 pandas dataframes? | Sorry if this is a similar question, I tried to find one that could answer my specific use-case but I only found ones that give exact matches between dataframes.
I have 2 pandas data frames of descriptions:
df1:
Description
i had lunch
going to the airport
buying a suitcase
df2:
Description
buying lunch
airport travel... | [
"globally\nTo match globally (any row of df1 with any row of df2), you can use:\nimport re\nregex = '|'.join(map(re.escape, df1['Description'].str.split().explode().unique()))\n\nout = df2[df2['Description'].str.contains(fr'\\b({regex})\\b')]\n\nTo count:\ndf2['Description'].str.contains(fr'\\b({regex})\\b').sum()\... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074361692_pandas_python.txt |
Q:
How to declare multiple variables with type annotation syntax in Python?
As far as I know, now we can declare variables using type annotation syntax in Python 3.6 as following code.
def printInt():
a: int = 0
b: int = 1
c: int = 2
print(a, b, c)
What I want to do is declaring variables a, b, c in ... | How to declare multiple variables with type annotation syntax in Python? | As far as I know, now we can declare variables using type annotation syntax in Python 3.6 as following code.
def printInt():
a: int = 0
b: int = 1
c: int = 2
print(a, b, c)
What I want to do is declaring variables a, b, c in one line.
I tried a, b, c: int, but it returns error.
Also a: int=0, b: int=1... | [
"If you really want to use annotation then\nyou can do this in this form:-\na: int;b: int;c: int\na,b,c = range(3)\nprint(a,b,c) #As output 0 1 2\n\n",
" a: int = 0; b: int = 1; c: int = 2\n\nwould actually work.\nIf you are looking for a way to avoid repeating int all times, I am afraid you cannot as of Python 3... | [
6,
5,
0
] | [
"Python is completely object oriented, and not \"statically typed\". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.\na,b,c=0,1,2\n\nOr the following maybe what you are looking for\ndef magic(a: str, b: str) -> int:\n light = a.find(b)\n re... | [
-7
] | [
"mypy",
"python",
"python_3.x"
] | stackoverflow_0048860385_mypy_python_python_3.x.txt |
Q:
How to exctract text from a PDF and manipulate it (python)
Hi i used to following code to exctract the text(as a string) from the following insurance contract:
import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceMana... | How to exctract text from a PDF and manipulate it (python) | Hi i used to following code to exctract the text(as a string) from the following insurance contract:
import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
def extract_text_by_... | [
"disclaimer: I am the author of borb, the library used in this answer\nI describe a scenario similar to yours in the examples repository of the library. For the sake of completeness I'll repeat the answer here.\n#!chapter_005/src/snippet_008.py\nimport typing\nfrom decimal import Decimal\n\nfrom borb.pdf.canvas.geo... | [
0
] | [] | [] | [
"pdf",
"pdfminer",
"python",
"string",
"text"
] | stackoverflow_0074295846_pdf_pdfminer_python_string_text.txt |
Q:
EntwicklerHeld Transposition Cipher
I'm trying to improve my coding skills on entwicklerheld.de
and right now I'm trying to solve the transposition cipher challenge:
We consider a cipher in which the plaintext is written downward and diagonally in successive columns. The number of rows or rails is given. When rea... | EntwicklerHeld Transposition Cipher | I'm trying to improve my coding skills on entwicklerheld.de
and right now I'm trying to solve the transposition cipher challenge:
We consider a cipher in which the plaintext is written downward and diagonally in successive columns. The number of rows or rails is given. When reaching the lowest rail, we traverse diagon... | [
"You could first define a generator that gives the mapping for each index to the index where the character has to be taken from during encryption. But this generator would not need to get the plain text input, just the length of it. As this generator just produces the indices, it can be used to decrypt as well.\nIt... | [
0
] | [] | [] | [
"algorithm",
"decoding",
"encoding",
"python"
] | stackoverflow_0074357317_algorithm_decoding_encoding_python.txt |
Q:
How to find the value of a dictionary when a dictionary variable is put in a list and random is run
In Python, when a dictionary variable is put in a list and randomized, is there a way to get only the key or values? I know I need to use key() to get the value of key, but I need to use a dictionary variable.key, i... | How to find the value of a dictionary when a dictionary variable is put in a list and random is run | In Python, when a dictionary variable is put in a list and randomized, is there a way to get only the key or values? I know I need to use key() to get the value of key, but I need to use a dictionary variable.key, is there a way?
import random
SPADE_A = {'SPADE':'CARD','A':'NUM'}
HEART_A = {'HEART':'CARD','A':'NUM'}
C... | [
"It's better to ask \"What's the correct way of doing this?\" rather than \"How can I do this the wrong way?\"\nYou have figured out something fundamental is wrong - your data structure doesn't fit the problem. What would work better, given what you've shown, is a list.\nFor a deck of cards there's several use case... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074361115_dictionary_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.