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: Print 1..N² in NxN matrix, starting at bottom-right and zig-zag Given an input n, I want to print n lines with each n numbers such that the numbers 1 through n² are displayed in a zig-zag way, starting with 1 appearing at the bottom-right corner of the output matrix, and 2 at the end of the one-but-last row, ...et...
Print 1..N² in NxN matrix, starting at bottom-right and zig-zag
Given an input n, I want to print n lines with each n numbers such that the numbers 1 through n² are displayed in a zig-zag way, starting with 1 appearing at the bottom-right corner of the output matrix, and 2 at the end of the one-but-last row, ...etc. Examples: Given Input 3. Print: 9 4 3 8 5 2 7 6 1 Given Input 1. ...
[ "Your code explicitly performs x = 1 and then x = x + 1 in a loop. As you need the first column in reverse order, and there are n*n numbers to output, instead the first top-left value should be x = n * n and in the first column it should decrease like with x = x - 1. The next column should be filled from end to sta...
[ 0 ]
[]
[]
[ "algorithm", "arrays", "logic", "python" ]
stackoverflow_0074506321_algorithm_arrays_logic_python.txt
Q: Image Zoom Using SciPy - wrong dimensions The code from answer to this question produces an error for some values of zoom factor. As mentioned in comments by @kg_sYy, "The rounding in int(np.round(h * zoom_factor)) seems to sometimes cause the resulting image to be 1 pixel smaller than target. The calculation then...
Image Zoom Using SciPy - wrong dimensions
The code from answer to this question produces an error for some values of zoom factor. As mentioned in comments by @kg_sYy, "The rounding in int(np.round(h * zoom_factor)) seems to sometimes cause the resulting image to be 1 pixel smaller than target. The calculation then gets -1 as diff and you get image pixel size 1...
[ "Why it becomes a single pixel\nThe code you have linked in question makes the assumption that:\n\nout might still be slightly larger than img due to rounding, so trim off any extra pixels at the edges\n\nAnd then proceeds to do trimming without checking anything. The zoomed image becomes 1 pixel whenever out is ac...
[ 1 ]
[]
[]
[ "image", "numpy", "python", "scipy", "zooming" ]
stackoverflow_0074504538_image_numpy_python_scipy_zooming.txt
Q: Print the last longest string PYTHON I'm currently facing the problem of not being able to print the last longest string. Strings example: banica pizza kiufte The first and the third are same length, but I want the last longest string. def longest(list1): longest_list = max(len(elem) for elem in list1) re...
Print the last longest string PYTHON
I'm currently facing the problem of not being able to print the last longest string. Strings example: banica pizza kiufte The first and the third are same length, but I want the last longest string. def longest(list1): longest_list = max(len(elem) for elem in list1) return longest_list somelist=[] while True: ...
[ "I don`t know, what exactly you are trying to achieve, but as\nlongest_string = max(somelist, key=len)\n\ngives you the first element with max length, you can just reverse the list, and get the last:\nlongest_string = max(somelist[::-1], key=len)\n\n", "This will work as you want :\n def longest(list1):\n l...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074506325_python.txt
Q: Didn't able to locate send files button I am trying to locate a button that uploads a file and gets the ouput result by clicking the button on the page itself, I know how to upload file by send keys. The website is https://huggingface.co/spaces/vaibhavsharda/semantic_clustering My code is import csv import time fr...
Didn't able to locate send files button
I am trying to locate a button that uploads a file and gets the ouput result by clicking the button on the page itself, I know how to upload file by send keys. The website is https://huggingface.co/spaces/vaibhavsharda/semantic_clustering My code is import csv import time from selenium import webdriver import chromedri...
[ "Element you trying to click is inside an iframe, so you need first to switch into the iframe in order to access that element.\nThe following code works:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdr...
[ 1 ]
[]
[]
[ "iframe", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074505601_iframe_python_selenium_selenium_webdriver_xpath.txt
Q: How to web scrap this page and turn it into a csv file? My name is João, im a law student from Brazil and im new to this. Im trying to web scrape this page for a week to help me with the Undergraduate thesis and other researchers. I want make a csv file with all the results from a research in a court (this link). ...
How to web scrap this page and turn it into a csv file?
My name is João, im a law student from Brazil and im new to this. Im trying to web scrape this page for a week to help me with the Undergraduate thesis and other researchers. I want make a csv file with all the results from a research in a court (this link). As you can see in the link, there are 404 results (processo) ...
[ "There are better (albeit more complex) ways of obtaining that information, like scrapy, or an async solution. Nonetheless, here is one way of getting that information you're after, as well as saving it into a csv file. I only scraped the first 2 pages (20 results), you can increase the range if you wish:\nfrom bs4...
[ 1 ]
[]
[]
[ "google_colaboratory", "html", "python", "web_scraping" ]
stackoverflow_0074504534_google_colaboratory_html_python_web_scraping.txt
Q: Huggingface: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu I am confusing about my fine-tune model implemented by Huggingface model. I am able to train my model, but while I want to predict it, I always get this error. The most similar problem is this. My transformer...
Huggingface: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu
I am confusing about my fine-tune model implemented by Huggingface model. I am able to train my model, but while I want to predict it, I always get this error. The most similar problem is this. My transformers version is 4.24.0, but it didn't seem to help me. I also try this. Below is my code snippet. from transformers...
[ "I do get the idea from the comment. The way I solve this is I can still train my qModel on 'cuda', but if I want to do the prediction, I'll need to put my qModel to 'cpu'. So I modify my last few lines code to below:\nqTrainer.train()\n\nqModel = qModel.to('cpu') #put my model to cpu\n\nqp = pipeline('summarizatio...
[ 0 ]
[]
[]
[ "data_science", "huggingface_transformers", "python", "pytorch" ]
stackoverflow_0074497166_data_science_huggingface_transformers_python_pytorch.txt
Q: _append_dispatcher() missing 1 required positional argument: 'values' i'm getting this error how to resolve it I don't know why i'm getting this error A: np.append function gets 2 arguments. first argument is input array and second one is values. In mentioned problem, you didn't pass the second argument to np.ap...
_append_dispatcher() missing 1 required positional argument: 'values'
i'm getting this error how to resolve it I don't know why i'm getting this error
[ "np.append function gets 2 arguments. first argument is input array and second one is values. In mentioned problem, you didn't pass the second argument to np.append function.\ndetails in site\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074506538_jupyter_notebook_python.txt
Q: Spacy - AttributeError: 'getset_descriptor' object has no attribute 'setdefault' I am trying to run this main.py file but I have the following error that I don't understand: Traceback (most recent call last): File "/Users/tyler/Desktop/Working Folder/trending-stories/main.py", line 4, in <module> from news_p...
Spacy - AttributeError: 'getset_descriptor' object has no attribute 'setdefault'
I am trying to run this main.py file but I have the following error that I don't understand: Traceback (most recent call last): File "/Users/tyler/Desktop/Working Folder/trending-stories/main.py", line 4, in <module> from news_processor import NewsProcessor File "/Users/tyler/Desktop/Working Folder/trending-sto...
[ "Yes, It's because of your python version.\nyou can downgrade your python version to lower than 3.6 or upgrade your spaCy version to greater than 3.x.x\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "nlp", "nltk", "python", "spacy" ]
stackoverflow_0074506503_machine_learning_nlp_nltk_python_spacy.txt
Q: Error installing Streamlit on Python 3.11 Screenshot of the errorI am trying to install Streamlit on python 3.11 and I keep on getting this error. I found solutions saying to do pip install pyarrow, but it also gives a similar error. Failed to build wheel. A: Sorry, this should be a comment, but I am a new user ...
Error installing Streamlit on Python 3.11
Screenshot of the errorI am trying to install Streamlit on python 3.11 and I keep on getting this error. I found solutions saying to do pip install pyarrow, but it also gives a similar error. Failed to build wheel.
[ "Sorry, this should be a comment, but I am a new user and cannot do it yet. \"Streamlit\" currently doesn't officially support python 3.11. So, it is more or less a gray area.\nYou can also find this link useful: Installation error streamlit: Building wheel for pyarrow (pyproject.toml) ... error\n\"Streamlit curren...
[ 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074505468_python_streamlit.txt
Q: Why is mu square not stopping at the obstacle I created? import pygame import keyboard screen = pygame.display.set_mode((800,600)) screen.fill((255,255,255)) blue = (20,40,200) gray = (100,100,100) x=200 y=200 w=60 h=60 p=0 OL=0 vel=0.1 #variables def player(): pygame.draw.rect(screen,blue,pygame.Rect(p+x,p+y...
Why is mu square not stopping at the obstacle I created?
import pygame import keyboard screen = pygame.display.set_mode((800,600)) screen.fill((255,255,255)) blue = (20,40,200) gray = (100,100,100) x=200 y=200 w=60 h=60 p=0 OL=0 vel=0.1 #variables def player(): pygame.draw.rect(screen,blue,pygame.Rect(p+x,p+y,p+w,p+h)) def obst(): pygame.draw.rect(screen,gray,pygame...
[ "Read *How do I detect collision in pygame?. I suggest to use pygame.Rect objects and colliderect for the collision detection. Create pygame.Rect objects for the player and the obstacle:\nplayer_rect = pygame.Rect(200, 200, 60, 60)\nobstacle_rect = pygame.Rect(100, 100, 100, 10)\n\nTest for collision when the playe...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074505199_pygame_python.txt
Q: Python variables behave differently after the value 256 In Python 3.8.10 pit@pit-desktop:~$ python Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x1 = 256 >>> x2 = 256 >>> print(f'id(x1) = {id(x1)}, id(x2) = {id(x2)}')...
Python variables behave differently after the value 256
In Python 3.8.10 pit@pit-desktop:~$ python Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x1 = 256 >>> x2 = 256 >>> print(f'id(x1) = {id(x1)}, id(x2) = {id(x2)}') id(x1) = 9809408, id(x2) = 9809408 >>> print(f'x1 is x2 = {x...
[]
[]
[ "The IDs remain the same only as long as the specific object in memory referenced remains the same. With smaller numbers (less than 257?), it's more likely that they'll remain the cache. Try the same game using the number 42506, and you'll get the same False result as with 257, whereas when I did it with the number...
[ -1 ]
[ "integer", "python", "variables" ]
stackoverflow_0074506296_integer_python_variables.txt
Q: Deploying a python Flask application with Jenkins and executing it I am trying to do auto-deployment of a Python Flask application using Jenkins and then run it by using shell command on a Raspberry Pi server. Here are some background info, Before using Jenkins, my deployment and execution process was manual descr...
Deploying a python Flask application with Jenkins and executing it
I am trying to do auto-deployment of a Python Flask application using Jenkins and then run it by using shell command on a Raspberry Pi server. Here are some background info, Before using Jenkins, my deployment and execution process was manual described below: FTP to the directory where my Python scripts and Python ven...
[ "The simple and robust solution (in my opinion) is to use Supervisor which is available in Debian as supervisor package. It allows you do make a daemon from script like your app, it can spawn multiple processes, watch if app doesn't crash and if it does it can start it again.\nNote about virtualenv - you don't need...
[ 2, 0 ]
[]
[]
[ "flask", "jenkins", "linux", "python", "raspberry_pi" ]
stackoverflow_0060681521_flask_jenkins_linux_python_raspberry_pi.txt
Q: how to run bash code in a loop in google colab I am trying to run a loop that requires the bash command -- !python3 -m runner.player_1 but when I make it into loop: for player1 in range(0, 100, 1): !python3 -m "runner.player_" + str(player1) it doesn't work and returns the error: /bin/bash: -c: line 0: synta...
how to run bash code in a loop in google colab
I am trying to run a loop that requires the bash command -- !python3 -m runner.player_1 but when I make it into loop: for player1 in range(0, 100, 1): !python3 -m "runner.player_" + str(player1) it doesn't work and returns the error: /bin/bash: -c: line 0: syntax error near unexpected token `(' /bin/bash: -c: lin...
[ "A native Bash loop would look like\nfor i in {0..99}; do python3 -m runner.player_$i; done\n\nYou can replace the semicolons with newlines, and/or add a newline after do if you like. I'm guessing you will want it literally as a one-liner.\nThis seems like an XY problem, though; surely it would be better if whateve...
[ 1, 0 ]
[]
[]
[ "bash", "google_colaboratory", "loops", "python" ]
stackoverflow_0074506646_bash_google_colaboratory_loops_python.txt
Q: 'pygame.Surface' object has no attribute 'update' I get the message : 'pygame.Surface' object has no attribute 'update'. But as you can see, i have an update function in the code. wha did i wrong? I looked around but i didn't fina a simular question. class Createparticle: def __init__(self, xx, yy,img): ...
'pygame.Surface' object has no attribute 'update'
I get the message : 'pygame.Surface' object has no attribute 'update'. But as you can see, i have an update function in the code. wha did i wrong? I looked around but i didn't fina a simular question. class Createparticle: def __init__(self, xx, yy,img): self.x = xx self.y = yy self.img = im...
[ "The error is caused by i.update(). i is an element from self.particlelist. In your case self.particlelist is an image (pygame.Surface). A pygame.Surface object has no update method. Probably i should not be a pygame.Surface, but you add pygame.Surface objects to the list:\n\nself.particlelist.append(self.img)\n\n\...
[ 1, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074505581_pygame_python.txt
Q: Split dataframe into grouped chunks I would like to split a dataframe into chunks. I have created a function which is able to split a dataframe into equal size chunks however am unable to figure out how to split by groups. Each split of dataframe must include all instances of a grouping variable, I'd like flexibil...
Split dataframe into grouped chunks
I would like to split a dataframe into chunks. I have created a function which is able to split a dataframe into equal size chunks however am unable to figure out how to split by groups. Each split of dataframe must include all instances of a grouping variable, I'd like flexibility on how many groups could be included ...
[ "Works in Python 2 and 3:\ndf = pd.DataFrame(data=['a', 'a', 'b', 'c', 'a', 'a', 'b', 'v', 'v', 'f'], columns=['A']) \n\ndef iter_by_group(df, column, num_groups):\n groups = []\n for i, group in df.groupby(column):\n groups.append(group)\n if len(groups) == num_groups:\n yield pd.con...
[ 6, 2, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0051411506_pandas_python.txt
Q: fillna with a condition (time limitation) thanks for advance for checking the question. i got a group of data, there are a lot of missing values for the column "bond_yield". my first question had been solved, which requires me to fill na with previous data. my code is like this: #sort the data first by company and...
fillna with a condition (time limitation)
thanks for advance for checking the question. i got a group of data, there are a lot of missing values for the column "bond_yield". my first question had been solved, which requires me to fill na with previous data. my code is like this: #sort the data first by company and then by time df_dataset = df_dataset.sort_valu...
[ "Sorry, this should be a comment, but I cannot leave one yet. fillna has a keyword limit. I think it can do what you want.\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna\n" ]
[ 0 ]
[]
[]
[ "conditional_statements", "fillna", "pandas", "python" ]
stackoverflow_0074504721_conditional_statements_fillna_pandas_python.txt
Q: How to get all token allowances in ethereum in python? Is there a way to get all the approvals granted by an ethereum address along with the contract it granted permission to in python? I want to obtain them programatically instead of using token approval checker websites. Tried pulling the data using the requests...
How to get all token allowances in ethereum in python?
Is there a way to get all the approvals granted by an ethereum address along with the contract it granted permission to in python? I want to obtain them programatically instead of using token approval checker websites. Tried pulling the data using the requests made by websites like revoke.cash, but getting blocked ofte...
[ "You will need an indexed source in any case, whether your own or a hosted on e.g. ette.\nFrom there you can get all tokens the user holds, and then you would get the latest allowance allowance(address owner, address spender) → uint256 (which is standard for most ERC20 tokens) for every token.\nSome indexers (e.g e...
[ 1 ]
[]
[]
[ "ethereum", "python", "web3py" ]
stackoverflow_0074502208_ethereum_python_web3py.txt
Q: Create Pandas DataFrame from a string In order to test some functionality I would like to create a DataFrame from a string. Let's say my test data looks like: TESTDATA="""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """ What is the simplest way to read that data into a Pandas DataFrame? A: A simple way ...
Create Pandas DataFrame from a string
In order to test some functionality I would like to create a DataFrame from a string. Let's say my test data looks like: TESTDATA="""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """ What is the simplest way to read that data into a Pandas DataFrame?
[ "A simple way to do this is to use StringIO.StringIO (python2) or io.StringIO (python3) and pass that to the pandas.read_csv function. E.g:\nimport sys\nif sys.version_info[0] < 3: \n from StringIO import StringIO\nelse:\n from io import StringIO\n\nimport pandas as pd\n\nTESTDATA = StringIO(\"\"\"col1;col2;c...
[ 752, 46, 46, 24, 9, 4, 0 ]
[]
[]
[ "csv", "csv_import", "pandas", "python", "string" ]
stackoverflow_0022604564_csv_csv_import_pandas_python_string.txt
Q: Removing items in a list from a string I'm teaching myself Python and I have been stuck on this issue for a few days now. The idea is to ask a user to input a sentence and then ask them for 5 characters that they would like to remove from the sentence. For example the sentence input by the user is: user_string = "...
Removing items in a list from a string
I'm teaching myself Python and I have been stuck on this issue for a few days now. The idea is to ask a user to input a sentence and then ask them for 5 characters that they would like to remove from the sentence. For example the sentence input by the user is: user_string = "The quick brown fox jumps over the lazy dog"...
[ "The method user_string.strip(char) only removes leading and padding char, so you can't call it agin and again on the initial char\nHere's 2 ways :\nuser_string = \"The quick brown fox jumps over the lazy dog\"\nlst = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\n# either collect valid chars\nresult = \"\"\nfor c in user_...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074506772_python.txt
Q: list indices must be integers or slices, not str Django I m getting this error. I am new in django. I am trying so send mail with django. Tracke Back : response = self.process_exception_by_middleware(e, request) File "/home/bari/Desktop/email_send/env/lib/python3.6/site-packages/django/core/handlers/base.py",...
list indices must be integers or slices, not str Django
I m getting this error. I am new in django. I am trying so send mail with django. Tracke Back : response = self.process_exception_by_middleware(e, request) File "/home/bari/Desktop/email_send/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(r...
[ "According to Django documentation at this link\nform.changed_data returns the name of fields in the models where the data has changed provided that the initial form. As you don't have any initial parameters in your code I think it's a typo at.\nmessage_body = form.cleaned_data[\"message_body\"]\n\n", "try using ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0062221678_django_python.txt
Q: How can I have only one api value? everyone I started programming in python yesterday to create a project. This consists of taking data from an API using the "Requests" library So far I had no trouble getting familiar with the library, but I can't get results for what I'm specifically looking for. My idea is just ...
How can I have only one api value?
everyone I started programming in python yesterday to create a project. This consists of taking data from an API using the "Requests" library So far I had no trouble getting familiar with the library, but I can't get results for what I'm specifically looking for. My idea is just to get the name of the account. Here the...
[ "Unless API allows you to specify exactly what data to return (some does) then you got no control about the API behavior nor what data (and how) given endpoint returns. Publicly exposed API is all you can have in hand and sometimes you may get tons of useless data and there's basically nothing you can do about that...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074506807_python_python_requests.txt
Q: How to add rows to a dataframe when values are recursively dependent? I have a data frame with columns a and b df = pd.DataFrame(data = [[3, 6], [5, 10], [9, 18], [17, 34]], columns = ["a", "b"]) The structure of this data is as follows, if at denotes the value of column a at row t and the same for bt, then bt = 2...
How to add rows to a dataframe when values are recursively dependent?
I have a data frame with columns a and b df = pd.DataFrame(data = [[3, 6], [5, 10], [9, 18], [17, 34]], columns = ["a", "b"]) The structure of this data is as follows, if at denotes the value of column a at row t and the same for bt, then bt = 2 * at at = bt - 1 - 1 See how the values of a are determined by the previo...
[ "Here is my take on your interesting question, for instance with 3 as the value of a at row 0 and 10 as n:\nimport pandas as pd\n\nA = 3\nN = 10\n\ndfs = [pd.DataFrame(data=[[A, 2 * A]], columns=[\"a\", \"b\"])]\nfor _ in range(N - 1):\n dfs = dfs + [\n (dfs[-1].shift(-1, axis=1) - 1).pipe(\n l...
[ 1 ]
[]
[]
[ "data_analysis", "pandas", "python", "time_series" ]
stackoverflow_0074468502_data_analysis_pandas_python_time_series.txt
Q: Node mul_1 required broadcastable shapes As a reference / follow up to my question here:previously asked but no asnwers I could compile my model by refraining from creating model objects, adding additional dimension and specifying axis to concatenate on def make_model(input_shape, input_shape_feat): base_input...
Node mul_1 required broadcastable shapes
As a reference / follow up to my question here:previously asked but no asnwers I could compile my model by refraining from creating model objects, adding additional dimension and specifying axis to concatenate on def make_model(input_shape, input_shape_feat): base_input_layer = tf.keras.layers.Input(input_shape) ...
[ "I've figured it out.\nThe problem arises from the mismatch in dimensions of input (2D) and output (1D) as I have just a class label as output.\nThe solution is to flatten before final output layer\nZ = keras.layers.Flatten()(Z)\nZ = keras.layers.Dense(num_classes, activation=\"softmax\")(Z)\n\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074502240_keras_python_tensorflow.txt
Q: Is there a way to kill uvicorn cleanly? Is there a way to kill uvicorn cleanly? I.e., I can type ^C at it, if it is running in the foreground on a terminal. This causes the uvivorn process to die and all of the worker processes to be cleaned up. (I.e., they go away.) On the other hand, if uvicorn is running in the...
Is there a way to kill uvicorn cleanly?
Is there a way to kill uvicorn cleanly? I.e., I can type ^C at it, if it is running in the foreground on a terminal. This causes the uvivorn process to die and all of the worker processes to be cleaned up. (I.e., they go away.) On the other hand, if uvicorn is running in the background without a terminal, then I can't ...
[ "That's because you're running uvicorn as your only server. uvicorn is not a process manager and, as so, it does not manage its workers life cycle. That's why they recommend running uvicorn using gunicorn+UvicornWorker for production.\nThat said, you can kill the spawned workers and trigger it's shutdown using the ...
[ 12, 0 ]
[ "In my case uvicorn managed to spawn new processes while pgrep -P was killing old ones,\nso I decided to kill the whole process group at once, just like ^C does:\nPID=\"$(pgrep -f example:app)\"\nif [[ -n \"$PID\" ]]\nthen\n PGID=\"$(ps --no-headers -p $PID -o pgid)\"\n kill -SIGINT -- -${PGID// /}\nfi\n\nEac...
[ -1 ]
[ "fastapi", "python", "python_3.x", "uvicorn" ]
stackoverflow_0060424390_fastapi_python_python_3.x_uvicorn.txt
Q: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden while using local mode in AWS SageMaker trainer = PyTorch( entry_point="train.py", source_dir= "source_dir", # directory of your training script role=role, framework_version="1.5.0", py_ve...
botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden while using local mode in AWS SageMaker
trainer = PyTorch( entry_point="train.py", source_dir= "source_dir", # directory of your training script role=role, framework_version="1.5.0", py_version="py3", instance_type= "local", instance_count=1, output_path=output_path, hyperparameters = hyperparameters ) This code is runni...
[ "The fact that the code worked until a few days ago does not make the problem reproducible.\nAt this point, it is strictly dependent on the settings related to your AWS account.\nLooking at the error log, it appears that you do not have access permissions to the S3 bucket.\nLook at this question, it talks about thi...
[ 0, 0 ]
[]
[]
[ "amazon_sagemaker", "python", "pytorch" ]
stackoverflow_0074384817_amazon_sagemaker_python_pytorch.txt
Q: Use Flask path string to refer to variables I have the following Flask app. It renders a html page with a form for each cell of the dataframe and allows the user to edit the cells and post the form data. The app then updates the dataframe. ''' from flask import Flask, render_template, url_for, request, redirect im...
Use Flask path string to refer to variables
I have the following Flask app. It renders a html page with a form for each cell of the dataframe and allows the user to edit the cells and post the form data. The app then updates the dataframe. ''' from flask import Flask, render_template, url_for, request, redirect import pandas app = Flask(__name__) df_abc = pand...
[ "The answer is using globals() with globals()[name], as shown below, and explained in this answer https://stackoverflow.com/a/1373201\nfrom flask import Flask, render_template, url_for, request, redirect\nimport pandas\n\napp = Flask(__name__)\n\ndf_abc = pandas.read_excel('source1.xlsx')\ndf_xyz = pandas.read_exce...
[ 0 ]
[]
[]
[ "flask", "global", "path", "python", "variables" ]
stackoverflow_0074503379_flask_global_path_python_variables.txt
Q: cmake error 'the source does not appear to contain CMakeLists.txt' I'm installing opencv in ubuntu 16.04. After installing the necessary prerequisites I used the following command:- kvs@Hunter:~/opencv_contrib$ mkdir build kvs@Hunter:~/opencv_contrib$ cd build kvs@Hunter:~/opencv_contrib/build$ kvs@Hunter:~/openc...
cmake error 'the source does not appear to contain CMakeLists.txt'
I'm installing opencv in ubuntu 16.04. After installing the necessary prerequisites I used the following command:- kvs@Hunter:~/opencv_contrib$ mkdir build kvs@Hunter:~/opencv_contrib$ cd build kvs@Hunter:~/opencv_contrib/build$ kvs@Hunter:~/opencv_contrib/build$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREF...
[ "You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there. \n", "Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instea...
[ 43, 23, 8, 1, 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0046448682_opencv_python.txt
Q: Creating a submodel using textVectorization and Embedding layers in Keras throws: 'str' object has no attribute 'base_dtype' in Keras I'm making a multi-input Tensorflow NLP model using text and numerical data. To create this, I plan on making two submodels, one for text and the other for numerical data, and then ...
Creating a submodel using textVectorization and Embedding layers in Keras throws: 'str' object has no attribute 'base_dtype' in Keras
I'm making a multi-input Tensorflow NLP model using text and numerical data. To create this, I plan on making two submodels, one for text and the other for numerical data, and then concatenating their outputs into my main model. For the text submodel, I've been following the Keras guides for text vectorization and embe...
[ "Your text_vectorizer would be your first layer after your input layer. It is used like a normal layer and not like a dictionary.\nimport tensorflow as tf\ninputs = tf.keras.Input(shape=(1,), dtype=tf.string)\nx = text_vectorizer(inputs)\nx = tf.keras.layers.Flatten()(x)\noutputs = tf.keras.layers.Dense(1)(x)\nmode...
[ 0 ]
[]
[]
[ "deep_learning", "jupyter_notebook", "keras", "python", "tensorflow" ]
stackoverflow_0067292093_deep_learning_jupyter_notebook_keras_python_tensorflow.txt
Q: googleapiclient.errors.UnknownApiNameOrVersion: name: sheets version v4 I'm working with Google Sheets API and Pyinstaller. My code runs just fine on the IDE, but whenever i try to run it on a .exe created by Pyinstaller, it provides the following error:. I thought it could be a missing file or dependency but i te...
googleapiclient.errors.UnknownApiNameOrVersion: name: sheets version v4
I'm working with Google Sheets API and Pyinstaller. My code runs just fine on the IDE, but whenever i try to run it on a .exe created by Pyinstaller, it provides the following error:. I thought it could be a missing file or dependency but i tested it on other environments and the error persists. Any thoughts? It was su...
[ "If you used --onedir (One Directory) this should work fine.\nIf you want a (One file) option then this issue didn't have any solution until now (I made a good search)\n", "edit the file\n\n\\Lib\\site-packages\\googleapiclient\\discovery_cache_init_.py\n\nadd this line after line 26:\nOld:\nDISCOVERY_DOC_DIR = o...
[ 0, 0, 0 ]
[]
[]
[ "google_sheets", "pyinstaller", "python", "python_3.x" ]
stackoverflow_0074239135_google_sheets_pyinstaller_python_python_3.x.txt
Q: I'm trying to make it so my tkinter input field is first checked amongst a file and then if it's not there, is added I've tried to make a functioning sign up page, and whilst my input can be added to the file, I first want to make sure that the input of username does not already exist in the file. The function whi...
I'm trying to make it so my tkinter input field is first checked amongst a file and then if it's not there, is added
I've tried to make a functioning sign up page, and whilst my input can be added to the file, I first want to make sure that the input of username does not already exist in the file. The function which checks this is as follows: forename = forename_entry.get() surname = surname_entry.get() username = username_entry.get(...
[ "try if username in existent_username:\n" ]
[ 0 ]
[]
[]
[ "file_handling", "python", "tkinter" ]
stackoverflow_0074506924_file_handling_python_tkinter.txt
Q: How to setup a failure_hook to with send messages from telegram bot I'm new one in Dagster. Could you help me, please? I want to understand how to set up an etl process error notification through a telegram bot My code: from dagster import ( load_assets_from_package_module, asset, repository, defin...
How to setup a failure_hook to with send messages from telegram bot
I'm new one in Dagster. Could you help me, please? I want to understand how to set up an etl process error notification through a telegram bot My code: from dagster import ( load_assets_from_package_module, asset, repository, define_asset_job, ScheduleDefinition ) import pyodbc import pandas as pd ...
[ "Hooks are not yet implemented with the \"software defined assets\" you are using. You can upvote for the feature here : https://github.com/dagster-io/dagster/issues/8577\nYou have to imagine a workaround for the moment.\n" ]
[ 0 ]
[]
[]
[ "dagster", "python", "telegram_bot" ]
stackoverflow_0074442272_dagster_python_telegram_bot.txt
Q: What is the data type used by set in python internally? Interviewer asked me that what is the data type used by set internally in python and what is the time complexity of inserting value in set. I tried to search on google but I am not getting any specific answer in google search. Also, I tried to find the set cl...
What is the data type used by set in python internally?
Interviewer asked me that what is the data type used by set internally in python and what is the time complexity of inserting value in set. I tried to search on google but I am not getting any specific answer in google search. Also, I tried to find the set class to check data type used by set in python but not able to ...
[ "set as well as dict use hash table as internal data type. As described in the Python documentation:\n\"A set object is an unordered collection of distinct hashable objects\"\n", "Given that \"a set is a collection which is unordered, unchangeable, and unindexed\" and it can hold data of any type, you can guess t...
[ 2, 2 ]
[]
[]
[ "python", "python_3.x", "set" ]
stackoverflow_0074507123_python_python_3.x_set.txt
Q: call a time-sensitive fail-safe function I have a time-sensitive request, let's call it query_response. How to write the program so that, if query_response take less than 2 seconds then run take_action else run abort_action. def query_response(): print("Query Response") def take_action(): print("Take Action")...
call a time-sensitive fail-safe function
I have a time-sensitive request, let's call it query_response. How to write the program so that, if query_response take less than 2 seconds then run take_action else run abort_action. def query_response(): print("Query Response") def take_action(): print("Take Action") def abort_action(): print("Abort Action")...
[ "So basically what you can do is save the time that your function started at and subtract the start_time from the time that your function ended at. For example: if your query_response started 12:34 and ended 12:37, you would get an execution time of 3 minutes. Code:\nimport time\n\ndef query_response():\n start_ti...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074506988_python_python_3.x.txt
Q: Plotting Bar Chart with X, Y and Z axis in matplotlib I have below data, Am trying to plot bar chart in matplotlib using below code, pyplot.bar(gender, ward, width, color='orange') pyplot.bar(count, gender, width, color='tomato') Below is the result, My expectation is as below which is created in excel,...
Plotting Bar Chart with X, Y and Z axis in matplotlib
I have below data, Am trying to plot bar chart in matplotlib using below code, pyplot.bar(gender, ward, width, color='orange') pyplot.bar(count, gender, width, color='tomato') Below is the result, My expectation is as below which is created in excel, Any suggestion will be helpful to get the same in matplot...
[ "You could achieve that very easy with seaborn.barplot.\nimport seaborn as sns\nsns.barplot(data=df, x='Ward', y='Count', hue='Gender', palette=['orange', 'tomato']) #df is the dataframe you showed as example\n\n\nWithout seaborn, you could pivot your data before plotting it. Like this:\ndf.pivot(index='Ward', colu...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074507097_matplotlib_python.txt
Q: Uploading an image to a website with Playwright I'm trying to click the button upload an image to this website: https://prnt.sc/ But it seems like there is not even a [button], so can I even click anything? Is this even possible? Super confused. There's lots of documentation on how to do this with selenium, but no...
Uploading an image to a website with Playwright
I'm trying to click the button upload an image to this website: https://prnt.sc/ But it seems like there is not even a [button], so can I even click anything? Is this even possible? Super confused. There's lots of documentation on how to do this with selenium, but not much for Playwright unfortunately. from playwright....
[ "Just use set_input_files. Here is an example:\nfrom playwright.sync_api import sync_playwright\n\nwith sync_playwright() as p:\n browser = p.webkit.launch()\n page = browser.new_page()\n page.goto('https://prnt.sc/')\n # click on AGREE privacy\n page.click('button[mode=\"primary\"]')\n # set file...
[ 1 ]
[]
[]
[ "playwright", "python" ]
stackoverflow_0074506905_playwright_python.txt
Q: convert 2D list to dict where duplicate values to keys and rest of values to list As No import any library To Do This x=[['A',1],['B',2],['C',3]] y=[['A',100],['B',200],['C',300]] z=[['A',1000],['B',2000],['C',3000]] output must: {'A':[1,100,1000],'B':[2,200,2000],'C':[3,300,3000]} I tried : dic=dict(filter(lamb...
convert 2D list to dict where duplicate values to keys and rest of values to list
As No import any library To Do This x=[['A',1],['B',2],['C',3]] y=[['A',100],['B',200],['C',300]] z=[['A',1000],['B',2000],['C',3000]] output must: {'A':[1,100,1000],'B':[2,200,2000],'C':[3,300,3000]} I tried : dic=dict(filter(lambda i:i[0]==i[0],[x,y,z])) So As Data I need first duplicated value to key , and common...
[ "Try:\nx = [[\"A\", 1], [\"B\", 2], [\"C\", 3]]\ny = [[\"A\", 100], [\"B\", 200], [\"C\", 300]]\nz = [[\"A\", 1000], [\"B\", 2000], [\"C\", 3000]]\n\nout = {}\nfor l in (x, y, z):\n for a, b in l:\n out.setdefault(a, []).append(b)\n\nprint(out)\n\nPrints:\n{\"A\": [1, 100, 1000], \"B\": [2, 200, 2000], \"...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074507106_dictionary_list_python.txt
Q: Two-dimensional array in Python (stupid problem) It is so stupid. This code works N = int(input("Input the N: ")) MATRIX = [0] * N for i in range(N): MATRIX[i] = [0] * N print(MATRIX) print(" ") for i in range(N): for j in range(N): z = int(input(" ")) MATRIX[i][j] = z print(MATRIX) But...
Two-dimensional array in Python (stupid problem)
It is so stupid. This code works N = int(input("Input the N: ")) MATRIX = [0] * N for i in range(N): MATRIX[i] = [0] * N print(MATRIX) print(" ") for i in range(N): for j in range(N): z = int(input(" ")) MATRIX[i][j] = z print(MATRIX) But if I change 11 line. Instead of z = int(input(" ")), ...
[ "This error occurs when you have pressed the Enter key (without typing any integer value) when prompted for input, which means you have passed an empty string to the int() function.\n>>> int('')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for int() with ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074506837_python.txt
Q: How to find elements that match specific conditions selenium i want to crawl data in web, but i don't know how to get data from these tags i don't know how to get data from these tags. Please help me from selenium import webdriver import pandas as pd from selenium.webdriver.common.keys import Keys from selenium.we...
How to find elements that match specific conditions selenium
i want to crawl data in web, but i don't know how to get data from these tags i don't know how to get data from these tags. Please help me from selenium import webdriver import pandas as pd from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By browser = webdriver.Chrome(executable_...
[ "Maybe the following code will solve your issue?\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Ge...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074507129_python_selenium.txt
Q: How to get absolute file path of folder from user input in python? The input gets added at the end of path import os print("enter folder name") FolderName = input() flag = os.path.isabs(FolderName) if flag == False: path = os.path.abspath(FolderName) print("The absolute path is: " ,path) What am I doin...
How to get absolute file path of folder from user input in python? The input gets added at the end of path
import os print("enter folder name") FolderName = input() flag = os.path.isabs(FolderName) if flag == False: path = os.path.abspath(FolderName) print("The absolute path is: " ,path) What am I doing wrong here? Let's say the Folder name input is Neon. The code output gives C:\Users\Desktop\Codes\Neon\Neon I...
[ "The os.path.abspath function normalizes the users current working directory and the input argument and then merges them together.\nSo if your input is 'Neon' and your current working directory is C:\\Users\\Desktop\\Codes\\Neon, then the output is C:\\Users\\Desktop\\Neon\\Neon.\nLikewise if your input is fkdjfkjd...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074507067_python_python_3.x.txt
Q: How to subset a dataframe with given pairs or row indices and column labels? I am given a dataframe (df_path) below, where the index corresponds to the index of the dataframe (df_from) i want to copy values from, and the values represent the column of the dataframe I want to copy values from. **df_path** {0: {Time...
How to subset a dataframe with given pairs or row indices and column labels?
I am given a dataframe (df_path) below, where the index corresponds to the index of the dataframe (df_from) i want to copy values from, and the values represent the column of the dataframe I want to copy values from. **df_path** {0: {Timestamp('2017-04-05 10:18:02.095000'): 0, Timestamp('2017-04-05 10:35:03.740000'):...
[ "Here is another way to it which is, on my machine, twice as fast in average.\n# In your post, you do not provide `df_ticks_paths.index`,\n# so I make up one for demonstration purpose\n\ndf_ticks_paths_index = pd.DatetimeIndex(\n [\n \"2017-04-04 10:18:02.095000\",\n \"2017-04-05 10:35:03.740000\",...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074463725_pandas_python.txt
Q: Why is the value of i not increasing in the python code below? What should I do to increase it? Why is the value of i not increasing in the python code below? What should I do to increase it? i = 0 for z in analink2.iloc[i,[1]]: req = requests.get(z, headers = header) print(z) i += 1 analink2.head() O...
Why is the value of i not increasing in the python code below? What should I do to increase it?
Why is the value of i not increasing in the python code below? What should I do to increase it? i = 0 for z in analink2.iloc[i,[1]]: req = requests.get(z, headers = header) print(z) i += 1 analink2.head() Out[268]: section weblink 0 bilgisayar-table...
[ "If you want to iterate over values in weblink column you can use next example:\nfor url in analink2[\"weblink\"]:\n print(url)\n req = requests.get(url, headers=header)\n\n\nIf you want index value you can use for example .iterrows():\nfor idx, row in analink2.iterrows():\n print(idx, row['weblink'])\n ...
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "loops", "python", "python_requests" ]
stackoverflow_0074507236_dataframe_for_loop_loops_python_python_requests.txt
Q: Python insert image into Tkinter error I want to insert an image into my tkinter but I received error: TclError: image "pyimage7" doesn't exist. I am using WinPython-64-3.3.5.9. I tried "rozmery.gif" but didn't help. from tkinter import * from PIL import ImageTk, Image app_root = Tk() #...
Python insert image into Tkinter error
I want to insert an image into my tkinter but I received error: TclError: image "pyimage7" doesn't exist. I am using WinPython-64-3.3.5.9. I tried "rozmery.gif" but didn't help. from tkinter import * from PIL import ImageTk, Image app_root = Tk() #Setting it up img = ImageTk.PhotoImage(I...
[ "You should keep a reference to the image before placing it:\nimglabel = Label(app_root, image=img)\nimglabel.image = img\nimglabel.grid(row=1, column=1) \n\n", "I had the same error message. I restarted the kernel (Spyder) and it worked perfectly fine. I have this kind of issue sometimes where the code works jus...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0050174404_python_tkinter.txt
Q: Flask-SQLAlchemy db.create_all() raises RuntimeError working outside of application context I recently updated Flask-SQLAlchemy, and now db.create_all is raising RuntimeError: working outside of application context. How do I call create_all? from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Fl...
Flask-SQLAlchemy db.create_all() raises RuntimeError working outside of application context
I recently updated Flask-SQLAlchemy, and now db.create_all is raising RuntimeError: working outside of application context. How do I call create_all? from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///project.db' db = SQLAlchemy(app)...
[ "As of Flask-SQLAlchemy 3.0, all access to db.engine (and db.session) requires an active Flask application context. db.create_all uses db.engine, so it requires an app context.\nwith app.app_context():\n db.create_all()\n\nWhen Flask handles requests or runs CLI commands, a context is automatically pushed. You o...
[ 28, 1 ]
[ "I spent several hours trying to figure out this myself.\nHaving succeeded, I felt I should do a detail post by example.\ncreate a model.py with example code below:\nfrom flask_sqlalchemy import SQLAlchemy\nimport datetime\nfrom flask_marshmallow import Marshmallow\nfrom secret import path\n\ndatabase_path = path \...
[ -1 ]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0073961938_flask_flask_sqlalchemy_python.txt
Q: BYPASS captcha during exploration of website,using selenium i'm trying to use the search engine of a website, but captcha blocks me continuously. Is there any way to perform search? driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get("https://www.autodoc.pl/") query ='H317W01' driver.fin...
BYPASS captcha during exploration of website,using selenium
i'm trying to use the search engine of a website, but captcha blocks me continuously. Is there any way to perform search? driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get("https://www.autodoc.pl/") query ='H317W01' driver.find_element(By.ID, "search").send_keys(query) driver.find_element(B...
[ "Captchas are implemented to block bots. Selenium is a bot.\nBypassing captchas is practically impossible, unless you control the website containing the captcha.\n", "You would need to load the picture data as per Download image with selenium python and analyze it with some OCR software (e.g. for Python, there's ...
[ 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074498062_python_selenium.txt
Q: Drf class based view how to manage method calls I have been working on FBV in Django and am now trying out CBV. I have created a basic crud application Views.py class UserViews(APIView): permission_classes = [IsViewOnly | IsManager | IsAdmin | IsStaff] def get_objects(self, user_id): #query def post(self, req...
Drf class based view how to manage method calls
I have been working on FBV in Django and am now trying out CBV. I have created a basic crud application Views.py class UserViews(APIView): permission_classes = [IsViewOnly | IsManager | IsAdmin | IsStaff] def get_objects(self, user_id): #query def post(self, request): #create code def get(self, request...
[ "You can use the @api_view decorator with function-based views, In order to set a specific permission on a specific method in the APIView class.\n@permission_classes([IsManager, ])\ndef delete(self, request):\n # your code.\n\nNote: when you set new permission classes via the class attribute or decorators you're...
[ 0 ]
[]
[]
[ "django", "django_class_based_views", "django_rest_framework", "django_views", "python" ]
stackoverflow_0074507179_django_django_class_based_views_django_rest_framework_django_views_python.txt
Q: Generate logs as the function's caller Is there a way to log messages as if they originated from the current function's caller? I have a very simple global logging facility that gets initialized by means of __main__ as logformat = '%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d - %(message)s' logging...
Generate logs as the function's caller
Is there a way to log messages as if they originated from the current function's caller? I have a very simple global logging facility that gets initialized by means of __main__ as logformat = '%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d - %(message)s' logging.basicConfig(format=logformat, level=logleve...
[ "There is logger.findCaller which seems to be purposefully designed for this, I can't deduce from the docs how it's supposed to be used, though.\nMore or less. This is indeed the way a logger finds the caller it should use in its message, but user code has no access to this method.\nBut the doc for logger.debug des...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074507284_python.txt
Q: how can I update one field in Django rest framework in abstract user model how can I update one field in the Django rest framework in the abstract user model can someone help me I want to Update device_id in my abstract user model I want to only update device_id dield without updating other field and I do not know...
how can I update one field in Django rest framework in abstract user model
how can I update one field in the Django rest framework in the abstract user model can someone help me I want to Update device_id in my abstract user model I want to only update device_id dield without updating other field and I do not know I have to create another view or not or I should add update to serializers here...
[ "you could create a view a like this(ref)\nfrom django.views.generic.edit import UpdateView\nfrom myapp.models import Author\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\nclass UserUpdateView(UpdateView):\n model = User\n fields = ['device_id']\n \n\n" ]
[ 0 ]
[]
[]
[ "abstract_class", "django", "django_rest_framework", "python" ]
stackoverflow_0074507168_abstract_class_django_django_rest_framework_python.txt
Q: Why does XOR not produce the expected result 3**2==9 ^ 3-2==4 False True ^ False TRUE Why is the result of first line False while it should be True? A: Because the operator ^ has more priority than == and the operation 9 ^ 3 has priority A: It returns False because of operation priority. The priority of ^...
Why does XOR not produce the expected result
3**2==9 ^ 3-2==4 False True ^ False TRUE Why is the result of first line False while it should be True?
[ "Because the operator ^ has more priority than == and the operation 9 ^ 3 has priority\n", "It returns False because of operation priority.\nThe priority of ^ is more than priority of ==\nYou can see the priority of operations in this Link\n" ]
[ 0, 0 ]
[]
[]
[ "difference", "google_colaboratory", "python", "try_catch", "xor" ]
stackoverflow_0074454972_difference_google_colaboratory_python_try_catch_xor.txt
Q: Convert BufferedImage.TYPE_INT_ARGB to CV_8UC3 with JavaCV I've been working on something similiar to OpenTrack in Java. I have working example with Demo Video opened with FFMpegGrabber but now I'm trying to implement it with PS3 Eye Webcam. I'm using JavaCV and I've tried to get CL-Eye SDK but now it is impossibl...
Convert BufferedImage.TYPE_INT_ARGB to CV_8UC3 with JavaCV
I've been working on something similiar to OpenTrack in Java. I have working example with Demo Video opened with FFMpegGrabber but now I'm trying to implement it with PS3 Eye Webcam. I'm using JavaCV and I've tried to get CL-Eye SDK but now it is impossible to register at their site what is needed to get DLL Library fo...
[ "Ok, the solutions was seriously easier than I've expected (even though I thought I've tried this method).\npublic Frame grab() {\n int frame_w = ps3eye.getResolution().w;\n int frame_h = ps3eye.getResolution().h;\n BufferedImage frame = new BufferedImage(frame_w, frame_h, BufferedImage.TYPE_3BYTE_BGR);\n ...
[ 1 ]
[]
[]
[ "c++", "java", "javacv", "opencv", "python" ]
stackoverflow_0074503116_c++_java_javacv_opencv_python.txt
Q: Matching Whole Dictionary Keys in String using List Comprehension I have a dictionary called cc_dict and am trying to use list comprehension to iterate over each key to find a match in a string called new_string. The line below works but it also matches keys that are part of whole words. I want to match whole word...
Matching Whole Dictionary Keys in String using List Comprehension
I have a dictionary called cc_dict and am trying to use list comprehension to iterate over each key to find a match in a string called new_string. The line below works but it also matches keys that are part of whole words. I want to match whole words only. So, for example, the key "test" is matched in the string "text ...
[ "If I understand correctly, you can split your match string into words using split:\n[te for key, te in cc_dict.items() if key in new_string.split()]\n\n", "You can try the following,\nThis method will use regex to determine if the whole string that you are looking for is available in the string that you are sear...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074476930_python.txt
Q: replace all floats in df with corresponding index name I want to replace all values in my df that are float (excluding nans), with the name of the index of the corresponding row. I have this: index1 10.0 190.6 index2 17.9 NaN ind...
replace all floats in df with corresponding index name
I want to replace all values in my df that are float (excluding nans), with the name of the index of the corresponding row. I have this: index1 10.0 190.6 index2 17.9 NaN index3 NaN 8.0 index4 ...
[ "Technically, np.nan is also float. If you want to replace non-null values with the index values, you can use df.where:\noutput = df.where(df.isna(), df.index.tolist())\n\nOutput:\n 1 2\n0 \nindex1 index1 index1\nindex2 index2 NaN\nindex3 NaN index3\nindex4 index4 index4\n\n", "if you w...
[ 2, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074506980_numpy_pandas_python.txt
Q: Set xticks visible in when plotting using pandas Consider the following snippet import numpy as np import pandas as pd from matplotlib import pyplot as plt data = np.random.rand(10,5) cols = ["a","b","c","d","e"] df = pd.DataFrame(data=data, columns = cols) df.index.name="Time (s)" fig,axes = plt.subplots(3,2,sh...
Set xticks visible in when plotting using pandas
Consider the following snippet import numpy as np import pandas as pd from matplotlib import pyplot as plt data = np.random.rand(10,5) cols = ["a","b","c","d","e"] df = pd.DataFrame(data=data, columns = cols) df.index.name="Time (s)" fig,axes = plt.subplots(3,2,sharex=True, squeeze=False) axes = axes.T.flat axes[5].r...
[ "You need to turn off sharing x properties by setting sharex=False (which is the default value by the way in matplotlib.pyplot.subplots):\nReplace this:\nfig,axes = plt.subplots(3,2,sharex=True, squeeze=False)\n\nBy this:\nfig,axes = plt.subplots(3,2, squeeze=False)\n\n# Output:\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074507451_matplotlib_pandas_python.txt
Q: How to write data of type DataFrame using asksaveasfile dialog I am trying to save my data from an input csv file and write it to another csv file. I know how to write the dataFile using the to_csv method and using a pre-determined file to write into(output.csv). How do I do it via asksaveasfile dialog method. Any...
How to write data of type DataFrame using asksaveasfile dialog
I am trying to save my data from an input csv file and write it to another csv file. I know how to write the dataFile using the to_csv method and using a pre-determined file to write into(output.csv). How do I do it via asksaveasfile dialog method. Any help is appreciated. import csv import pandas as pd import os impor...
[ "Nevermind I fixed the problem already. \nimport csv\n import pandas as pd\n import os\n import tkinter as tk\n from tkinter import filedialog\n\n root = tk.Tk()\n root.withdraw()\n file_path = filedialog.askopenfilename() \n dataFile=pd.read_csv(file_path,usecols=['Name','Email','Gender']...
[ 6, 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0047453050_csv_pandas_python.txt
Q: Getting {"errorMessage": "'httpMethod'", "errorType": "KeyError" Using Lambda function to Get and post request. While testing it gives error {"errorMessage": "'httpMethod'", "errorType": "KeyError", "requestId": "435e6811-acc5-4bc7-b009-377bc6178bb8", "stackTrace": [" File "/var/task/lambda_function.py", line 11,...
Getting {"errorMessage": "'httpMethod'", "errorType": "KeyError"
Using Lambda function to Get and post request. While testing it gives error {"errorMessage": "'httpMethod'", "errorType": "KeyError", "requestId": "435e6811-acc5-4bc7-b009-377bc6178bb8", "stackTrace": [" File "/var/task/lambda_function.py", line 11, in lambda_handler\n if event['httpMethod'] == 'GET':\n"]} : dynamo...
[ "This error happens before you even read from DynamoDB.\nYou are getting a key error while trying to parse the event object. Have a look at your event object and ensure the path of the values your are trying to resolve from it are correct.\nIf that fails, share the value of event here and we can guide you better.\n...
[ 1, 0, 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "aws_lambda", "boto3", "python" ]
stackoverflow_0074506245_amazon_dynamodb_amazon_web_services_aws_lambda_boto3_python.txt
Q: Replace numpy columns when indexing backwards I'm using advanced indexing on the numpy arrays but find that my columns do not swap but instead they're replaced. For example: test_array = np.array([ [1, 2, 3, 4, 5] , [5, 4, 3, 2, 1] , [5, 2, 2, 2, 1] , [1, 2, 2, 1, 1] ]) zeros = np.repeat( np.zeros((1, 5)) , 2, axi...
Replace numpy columns when indexing backwards
I'm using advanced indexing on the numpy arrays but find that my columns do not swap but instead they're replaced. For example: test_array = np.array([ [1, 2, 3, 4, 5] , [5, 4, 3, 2, 1] , [5, 2, 2, 2, 1] , [1, 2, 2, 1, 1] ]) zeros = np.repeat( np.zeros((1, 5)) , 2, axis=0) swap_array = np.vstack([test_array, zeros]) s...
[ "They are indeed replaced, because there is no assignment stating that the last two columns should contain the first two. To do this, you can use the comma operator (or tuple unpacking), which evaluates all expressions on the right-hand side, before any assignment is made. There are pitfalls with this approach, so ...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074507482_arrays_numpy_python.txt
Q: how to mock `await asyncio.Future()`? I want to write a asyncio main function in pytest: async def main(host, port): log.debug('starting websockets server...') async with websockets.serve(myserver, host, port): await asyncio.Future() # run forever async def test_main(): with patch('websocket...
how to mock `await asyncio.Future()`?
I want to write a asyncio main function in pytest: async def main(host, port): log.debug('starting websockets server...') async with websockets.serve(myserver, host, port): await asyncio.Future() # run forever async def test_main(): with patch('websockets.legacy.server.Serve') as mock_serve: ...
[ "The problem is that it that you dont patch the Future. Try debugging it with a breakpoint on await asyncio.Future() and you will see that type(asyncio.Future) is not a mock. But if you patch using with patch('asyncio.Future') as mock_future: and try the same thing, you will get type(asyncio.Future) is unittest.moc...
[ 1 ]
[]
[]
[ "pytest", "python", "python_asyncio" ]
stackoverflow_0074470798_pytest_python_python_asyncio.txt
Q: Why did the Seq2SeqTrainer not stop when the EarlyStoppingCallback criteria is met? When trying to use EarlyStopping for Seq2SeqTrainer, e.g. patience was set to 1 and threshold 1.0: training_args = Seq2SeqTrainingArguments( output_dir='./', num_train_epochs=3, per_device_train_batch_size=4, per_de...
Why did the Seq2SeqTrainer not stop when the EarlyStoppingCallback criteria is met?
When trying to use EarlyStopping for Seq2SeqTrainer, e.g. patience was set to 1 and threshold 1.0: training_args = Seq2SeqTrainingArguments( output_dir='./', num_train_epochs=3, per_device_train_batch_size=4, per_device_eval_batch_size=4, logging_steps=1, save_steps=5, eval_steps=1, max_...
[ "As discussed in the comments in the question, the unexpected behavior of eval_steps going beyond the early stopping is because of the save_state being set at 5.\ntraining_args = Seq2SeqTrainingArguments(\n ...,\n logging_steps=1,\n save_steps=5,\n eval_steps=1,\n max_steps=10,\n evaluation_strate...
[ 0, 0 ]
[]
[]
[ "encoder_decoder", "huggingface_transformers", "python", "pytorch", "seq2seq" ]
stackoverflow_0074394999_encoder_decoder_huggingface_transformers_python_pytorch_seq2seq.txt
Q: Python - Having trouble assigning value into new col based on data from another cell I have data that looks like; ID File 1 this_file_whatever.ext1 2 this_whatever.ext2 3 this_is_ok_pooh.ext3 I am trying to get the extension and put the key from a dict in a new col based on the extension in File. ...
Python - Having trouble assigning value into new col based on data from another cell
I have data that looks like; ID File 1 this_file_whatever.ext1 2 this_whatever.ext2 3 this_is_ok_pooh.ext3 I am trying to get the extension and put the key from a dict in a new col based on the extension in File. def create_filegroups(row): filegroup_dict = { 'GroupA': 'ext1', 'G...
[ "I believe you need pandas.Series.map after extracting the file extension from the column File.\nTry this:\ndf['COL3']= (\n df['File']\n .str.extract(r'\\w+\\.(\\w+)', expand=False)\n .map({k:v for v,k in filegroup_dict.items()})\n )\n\n# Output :\npri...
[ 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074507547_dictionary_pandas_python.txt
Q: How to use numpy to add a value by iterating the other values from another array? I have 2 arrays. I want to access just the first index of array1 and add it to the values of array2. How can I use Numpy for this? I apologize as I cannot phrase my question correctly. Here is an updated example: 10 + 1 + 2 + 3 + 4 +...
How to use numpy to add a value by iterating the other values from another array?
I have 2 arrays. I want to access just the first index of array1 and add it to the values of array2. How can I use Numpy for this? I apologize as I cannot phrase my question correctly. Here is an updated example: 10 + 1 + 2 + 3 + 4 + 5 which results to 25. array1 = [10,11,12] array2 = [1,2,3,4,5] I would like to stor...
[ "You don't need numpy, just with for loop, code could look like this :\narray1 = [10, 11, 12]\narray2 = [1, 2, 3, 4, 5]\ns = 0\nsumArray = []\nfor i in range(0, len(array1)):\n s += array1[i]\n for j in range(0, len(array2)):\n s += array2[j]\n sumArray.append(s)\n s = 0\nprint(sumArray)\n# in on...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074507529_numpy_python.txt
Q: String center-align in python How can I make center-align in the following poem using python "She Walks in Beauty BY LORD BYRON (GEORGE GORDON) She walks in beauty, like the night Of cloudless climes and starry skies; And all that’s best of dark and bright Meet in her aspect and her eyes; Thus mellowed to that ten...
String center-align in python
How can I make center-align in the following poem using python "She Walks in Beauty BY LORD BYRON (GEORGE GORDON) She walks in beauty, like the night Of cloudless climes and starry skies; And all that’s best of dark and bright Meet in her aspect and her eyes; Thus mellowed to that tender light Which heaven to gaudy day...
[ "\nSplit the line into individual lines using splitlines().\nFind the size of your terminal with os.get_terminal_size().\nIterate though lines and print the lines using .center() and pass column size.\n\nimport os\n\ncolumn, row = os.get_terminal_size()\nx = \"She Walks in Beauty\\nBY LORD BYRON (GEORGE GORDON)\\nS...
[ 0 ]
[]
[]
[ "center_align", "python", "python_3.x", "string", "text_alignment" ]
stackoverflow_0074507599_center_align_python_python_3.x_string_text_alignment.txt
Q: What is the expected value of a coin-toss that doubles in value if heads and why is it different in practice? Here's the thought experiment: say I have a coin that is worth 1$. Everytime I toss it, if it lands on head, it will double in value. If it lands on tail, it will be forever stuck with the latest value. Wh...
What is the expected value of a coin-toss that doubles in value if heads and why is it different in practice?
Here's the thought experiment: say I have a coin that is worth 1$. Everytime I toss it, if it lands on head, it will double in value. If it lands on tail, it will be forever stuck with the latest value. What is the expected final value of the coin? Here is how I am thinking about it: ExpectedValue = 1 * 0.5 + (1 * 2) *...
[ "The average value of the process over infinitely many trials is infinite. However, you did not perform infinitely many trials; you only performed 10,000,000, which falls short of infinity by approximately infinity.\nSuppose we have a fair coin. In four flips, the average number of heads that come up is two. So, I ...
[ 1 ]
[]
[]
[ "math", "probability", "python", "statistics" ]
stackoverflow_0074505811_math_probability_python_statistics.txt
Q: Can't make Angle object in Manim, is the class deprecated or am I missing something? Pretty new to Manim and trying to make an Angle object like it says on the documentation: https://docs.manim.community/en/stable/reference/manim.mobject.geometry.line.Angle.html?highlight=angle#manim.mobject.geometry.line.Angle.fr...
Can't make Angle object in Manim, is the class deprecated or am I missing something?
Pretty new to Manim and trying to make an Angle object like it says on the documentation: https://docs.manim.community/en/stable/reference/manim.mobject.geometry.line.Angle.html?highlight=angle#manim.mobject.geometry.line.Angle.from_three_points But getting the following error: NameError: name 'Angle' is not defined H...
[ "The community maintained version (\"Manim\") is different from Grant's version (\"ManimGL\" / \"manimlib\"). In ManimGL, there is no Angle mobject.\nSee here for more information: https://docs.manim.community/en/stable/faq/installation.html#why-are-there-different-versions-of-manim\n" ]
[ 0 ]
[]
[]
[ "manim", "python" ]
stackoverflow_0074505177_manim_python.txt
Q: Upgrading Python 3.7 to 3.9 on macOS Big Sur I'm trying to upgrade Python 3.7 to 3.9 on macOS Big Sur. I'm also trying to avoid losing packages that were installed on Python 3.7 and reinstalling them again on Python 3.9 I tried using brew install python3 brew update && brew upgrade python which yielded Already up...
Upgrading Python 3.7 to 3.9 on macOS Big Sur
I'm trying to upgrade Python 3.7 to 3.9 on macOS Big Sur. I'm also trying to avoid losing packages that were installed on Python 3.7 and reinstalling them again on Python 3.9 I tried using brew install python3 brew update && brew upgrade python which yielded Already up-to-date. Warning: python3 3.9.1_7 already install...
[ "I fixed this frustrating error by first removing the Python 3.7 manually, by deleting it from the Applications folder and then uninstalling Python 3.9 using brew uninstall python3\nNext, I downloaded and installed the latest Python from here and it worked!\nTo save all the installed packages by generating a requir...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0066004178_python.txt
Q: How to pass my access and secret keys properly for GlueContext? I have a glue notebook from which I am trying to read a specific file from a different AWS account. When I try to run a spark session and read it. The code works perfectly and I get the spark df but when I try to use glueContext.create_dynamic_frame()...
How to pass my access and secret keys properly for GlueContext?
I have a glue notebook from which I am trying to read a specific file from a different AWS account. When I try to run a spark session and read it. The code works perfectly and I get the spark df but when I try to use glueContext.create_dynamic_frame() I get an Access Denied error. This is what my code looks like so far...
[ "You should avoid typing your actual creds in the code itself. Rather use a role that can access your services.\nFor S3 update the s3 bucket policy in the other account which would allow the job to read the data and also add IAM policy to job's account to read data from S3 in other account.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_glue", "python" ]
stackoverflow_0074493513_amazon_s3_amazon_web_services_aws_glue_python.txt
Q: How to clear the Entry widget after a button is pressed in Tkinter? I'm trying to clear the Entry widget after the user presses a button using Tkinter. I tried using ent.delete(0, END), but I got an error saying that strings don't have the attribute delete. Here is my code, where I'm getting error on real.delete(...
How to clear the Entry widget after a button is pressed in Tkinter?
I'm trying to clear the Entry widget after the user presses a button using Tkinter. I tried using ent.delete(0, END), but I got an error saying that strings don't have the attribute delete. Here is my code, where I'm getting error on real.delete(0, END): secret = randrange(1,100) print(secret) def res(real, secret): ...
[ "After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the \"Clear text\" button is pushed:\nimport tkinter as tk\n\nclass App(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, ...
[ 93, 18, 5, 4, 1, 0, 0, 0, 0, 0, 0 ]
[ "if none of the above is working you can use this->\nidAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)\nfor e.g. -> \nid assigned is = en then\nen.delete(first =0, last =100) \n", "Try with this:\nimport os\nos.system('clear')\n\n" ]
[ -2, -8 ]
[ "python", "tkinter", "user_interface", "widget" ]
stackoverflow_0002260235_python_tkinter_user_interface_widget.txt
Q: Viewing the full output of an xarray DataArray in plain text I am trying to view the full output of print(MyDataArray) instead of the shortened version which displays array([[[[[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ..., 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [0.00000000e+...
Viewing the full output of an xarray DataArray in plain text
I am trying to view the full output of print(MyDataArray) instead of the shortened version which displays array([[[[[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ..., 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ..., 0.00000000e+00...
[ "I just solved my own question, I'm posting this information if somebody also encounters this problem. My solution is a workaround\nnew_numpy_ndarray = existing_xarray_DataArray.to_numpy()\nnp.set_printoptions(threshold=np.Inf)\nprint(new_numpy_array)\n\nthis allows you to then view your array in full.\nThank you t...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python", "python_xarray" ]
stackoverflow_0074507619_numpy_pandas_python_python_xarray.txt
Q: INSERT to MYSQL throwing error due to apostrophe sql ="""INSERT INTO birthday(team, birthday) VALUES ('Norway', {"2020-01-01": "Ram's BDay"}));""" Above sql statement throws an error while inserting. ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds...
INSERT to MYSQL throwing error due to apostrophe
sql ="""INSERT INTO birthday(team, birthday) VALUES ('Norway', {"2020-01-01": "Ram's BDay"}));""" Above sql statement throws an error while inserting. ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server ver Based on manual attempts I ...
[ "you must put the hole JSON String in quotes an escape them in the string\nsql =\"\"\"INSERT INTO birthday(team, birthday)\n VALUES ('Norway', \"{\\\"2020-01-01\\\": \\\"Ram's BDay\\\"}\" );\"\"\"\n\nor you use single quotes then you must escape them in the string\nsql =\"\"\"INSERT INTO birthday(tea...
[ 0 ]
[ "You have a syntax mistake\nsql ='\"\"\"INSERT INTO birthday(team, birthday)\n VALUES (\\'Norway\\', {\"2020-01-01\": \"Ram\\'s BDay\"}));\"\"\"'\n\nIf you are using more apostrophe be sure to add \\ so it will not read\n" ]
[ -1 ]
[ "mysql", "python" ]
stackoverflow_0074507605_mysql_python.txt
Q: python - bag of words I want to create a very simple bag of words based on multiple Excel-files (300). DummyDoc1 = "This is a testdoc DummyDoc2 = "This is also a testdoc, the second one" ... I can import all the files and I also can do a simple wordcount (dict) for each file. What I don't get is how to combine tho...
python - bag of words
I want to create a very simple bag of words based on multiple Excel-files (300). DummyDoc1 = "This is a testdoc DummyDoc2 = "This is also a testdoc, the second one" ... I can import all the files and I also can do a simple wordcount (dict) for each file. What I don't get is how to combine those two in a matrix that loo...
[ "\nGet all those excel files into one directory\nIterate over all files in that directory\nUse the code from your wordcount to count words in every file\n\nUse this source to export into excel format\nimport os\n\ntotal = dict()\ndirectory = \"YOUR DIRECTORY HERE\"\nfor filename in os.listdir(directory):\n d = di...
[ 0 ]
[]
[]
[ "dataframe", "python", "word_count" ]
stackoverflow_0074507711_dataframe_python_word_count.txt
Q: Can a cython subclass access private attributes of its cython superclass? Other cython classes? I'm building cython extended types, and I've always been bothered that I had to make class attributes public for other extended types to be able to see them. But now than I'm also making subclasses I've even more surpri...
Can a cython subclass access private attributes of its cython superclass? Other cython classes?
I'm building cython extended types, and I've always been bothered that I had to make class attributes public for other extended types to be able to see them. But now than I'm also making subclasses I've even more surprised. The following code @cython.cclass class Base: base_attrib = cython.declare(cython.double, 0....
[ "So several issues where at play here:\nThe compiler errors were due to the attribute declaration including a value. Leaving them just like base_attrib = cython.declare(cython.double) removed the warning and the values where initialized to 0 automatically all the same.\nThe other issue was that the object produced ...
[ 0 ]
[]
[]
[ "attributes", "cython", "python", "subclass" ]
stackoverflow_0074500553_attributes_cython_python_subclass.txt
Q: How to write conditionals across multiple columns in dataframe? I have the following pandas dataframe: I am trying to write some conditional python statements, where if we have issue_status of 10 or 40 AND market_phase of 0 AND tade_state of (which is what we have in all of the cases in the above screenshot). T...
How to write conditionals across multiple columns in dataframe?
I have the following pandas dataframe: I am trying to write some conditional python statements, where if we have issue_status of 10 or 40 AND market_phase of 0 AND tade_state of (which is what we have in all of the cases in the above screenshot). Then I want to call a function called resolve_collision_mp(...). Can I...
[ "You can use .apply() with the relevant conditions,\ndf['new_col'] = df.apply(lambda row: resolve_collision_mp_10(row) if (row['issue_status'] == 10 and row['market_phase'] == 0 and row['tade_state'] = '') else None, axis=1)\n\ndf['new_col'] = df.apply(lambda row: resolve_collision_mp_40(row) if (row['issue_status'...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074507462_dataframe_pandas_python.txt
Q: How can I check the value of a DNS TXT record for a host? I'm looking to verify domain ownership via a script, specifically a Python script, and would like know how to lookup the value of a DNS TXT entry. I know there are services and websites out there for this, but I would like to do it with a script. A: This ...
How can I check the value of a DNS TXT record for a host?
I'm looking to verify domain ownership via a script, specifically a Python script, and would like know how to lookup the value of a DNS TXT entry. I know there are services and websites out there for this, but I would like to do it with a script.
[ "This is easy using dnspython. Here is an example:\nimport dns.resolver\nprint dns.resolver.resolve(\"aaa.asdflkjsadf.notatallsuspicio.us\",\"TXT\").response.answer[0][-1].strings[0]\n\nThis gives the following output:\nPnCcKpPiGlLfApDbDoEcBbPjIfBnLpFaAaObAaAaMhNgNbIfPbHkMiEfPpGgJfOcPnLdDjBeHkOjFjIbPbIoKhIjHfJlAhAh...
[ 23, 6, 0, 0 ]
[ "Something like this should work to at least get the value for the URL, I used google.com for the example.\nimport pycurl\nimport StringIO\nurl = \"whatsmyip.us/dns_txt.php?host=google.com\"\nc = pycurl.Curl()\nc.setopt(pycurl.URL, url)\nc.setopt(pycurl.HTTPHEADER, [\"Accept:\"])\ntxtcurl = StringIO.StringIO()\nc.s...
[ -7 ]
[ "dns", "python" ]
stackoverflow_0011705946_dns_python.txt
Q: Can't use int(input())'s x = int(input()) y = int(input()) z = int(input()) print(x, y, z) When I input y an error shows up: ValueError: invalid literal for int() with base 10: '' I didn't know what to try so I just messed around and when I did the following it somehow worked x = int(input()) print(x) y = int(in...
Can't use int(input())'s
x = int(input()) y = int(input()) z = int(input()) print(x, y, z) When I input y an error shows up: ValueError: invalid literal for int() with base 10: '' I didn't know what to try so I just messed around and when I did the following it somehow worked x = int(input()) print(x) y = int(input()) print(y) z = int(inpu...
[ "There's nothing inherently wrong with what you're doing, you can pass the result of input() into int():\n>>> x = int(input())\n123\n>>> type(x)\n<class 'int'>\n>>> x\n123\n\nThe error that you're getting indicates that you're passing something which isn't a number into int().\n>>> int(\"hello\")\nTraceback (most r...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074507804_python.txt
Q: Unable to install tables (Python, OS X) - could not find a local HDF5 installation I keep having an error ERROR:: Could not find a local HDF5 installation when I'm installing tables in Python: pip install tables I've downloaded and installed http://continuum.io/downloads but it didn't help. What else can I try ...
Unable to install tables (Python, OS X) - could not find a local HDF5 installation
I keep having an error ERROR:: Could not find a local HDF5 installation when I'm installing tables in Python: pip install tables I've downloaded and installed http://continuum.io/downloads but it didn't help. What else can I try to solve it?
[ "If you are using the anaconda distribution you can just do:\n$ conda install pytables\n\nIf you need to install from pip and already have the HDF5 libraries installed you can do:\n$ HDF5_DIR=/path/to/hdf5 pip install tables\n\nE.g. you could install HDF5 with conda and still install pytables using the method above...
[ 7, 1, 0 ]
[]
[]
[ "hdf5", "macos", "python" ]
stackoverflow_0028733625_hdf5_macos_python.txt
Q: Buffer.from(, 'hex') equivalent in Python I have a typescript library that I need to translate into Python. I am using the library bs58 in Typescript and its equivalent base58 library in python. My problem is coming when I try to replicate this: const decodedTxHash = Buffer.from('34cc2932f90774851410a536e3db2c2e6...
Buffer.from(, 'hex') equivalent in Python
I have a typescript library that I need to translate into Python. I am using the library bs58 in Typescript and its equivalent base58 library in python. My problem is coming when I try to replicate this: const decodedTxHash = Buffer.from('34cc2932f90774851410a536e3db2c2e61266a1587fbc15e7e9c79b41631ac74', 'hex') ...
[ "According to your title you're only asking on how to convert hex into bytes which can simply be archived by bytes.fromhex(\"<some hex in here>\").\nA full working example for your code will be:\nimport base58\nraw_bytes = bytes.fromhex(\"34cc2932f90774851410a536e3db2c2e61266a1587fbc15e7e9c79b41631ac74\")\nb58_enco...
[ 0 ]
[]
[]
[ "base58", "hex", "javascript", "python", "typescript" ]
stackoverflow_0074507836_base58_hex_javascript_python_typescript.txt
Q: How to get the real number after a string in a file I have files that contain both strings and floats. I am interested in finding the floats after a specific string. Any help in writing such a function that reads the file look for that specific string and returns the float after it will be much appreciated. Thanks...
How to get the real number after a string in a file
I have files that contain both strings and floats. I am interested in finding the floats after a specific string. Any help in writing such a function that reads the file look for that specific string and returns the float after it will be much appreciated. Thanks An example of a file is lines = """aaaaaaaaaaaaaaa bbbb...
[ "You can use regex\n(-?\\d+\\.?\\d*)\n\n\nimport re\n\nlines = \"\"\"aaaaaaaaaaaaaaa bbbbbbbbbbbbbbb cccccccccc\nqq vvv rrr ssssa 22.6\nzzzzx bbbb 12.0\nxxxxxxxxxx -1.099\nzzzz bbb nnn 33.5\nxxxxxxxxxx 1.099\"\"\"\n\nstr_to_search = \"xxxxxxxxxx\"\nnum = re.findall(fr\"(?m)^{str_to_search}\\s+(-?\\d+\\.?\\d*)\", ...
[ 3, 2, 1 ]
[]
[]
[ "file", "python", "string", "txt" ]
stackoverflow_0074507864_file_python_string_txt.txt
Q: Adding a field to a list of dictionaries based on another field value I have list of dictionary in the form of [{'a': '2.1', 'z': 'apple', 'aa': 'banana'}, {'a': '4.7', 'z': 'apple', 'aa': 'banana'}, {'a': '1.6', 'z': 'apple', 'aa': 'orange'}] I am looking to add another field to each dictionary whose value depen...
Adding a field to a list of dictionaries based on another field value
I have list of dictionary in the form of [{'a': '2.1', 'z': 'apple', 'aa': 'banana'}, {'a': '4.7', 'z': 'apple', 'aa': 'banana'}, {'a': '1.6', 'z': 'apple', 'aa': 'orange'}] I am looking to add another field to each dictionary whose value depends on value of another field and the final list should look like [{'a': '2....
[ "I feel there is a misunderstanding about what are those \"one-liners\".\nI, myself, proudly exhibit one of those from times to times, in answer to some questions.\nBut, in reality, it is not the fact that they fit on 1 line that makes them \"pythonesque\". But the fact that they are expression, not instruction. Th...
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074507769_dictionary_python.txt
Q: How to get last Thursday date of next month and next of next month using python I want to get Date on Last Thursday of next month and next of next month. Currently able to get Date of last thursday on current month. Code: import datetime dt = datetime.datetime.today() def lastThurs_currentmonth(dt): currDate, ...
How to get last Thursday date of next month and next of next month using python
I want to get Date on Last Thursday of next month and next of next month. Currently able to get Date of last thursday on current month. Code: import datetime dt = datetime.datetime.today() def lastThurs_currentmonth(dt): currDate, currMth, currYr = dt, dt.month, dt.year for i in range(31): if currDate.m...
[ "One way is to add months less one day from the start of the current month and then subtract back to the last Thursday. Thursdays are isoweekday 4, so it's a case of subtracting off the right number of days. Unfortunately timedelta doesn't allow months, so the dateutil library is also needed for my solution.\nimp...
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074507551_datetime_python.txt
Q: Attempt to connect to postgresql silently stops the program I am trying to connect to postgresql using pyside2. But, when I try to call the open method, the program stops running without showing any error. This is my code: from PySide2.QtSql import QSqlDatabase, QSqlQuery from PySide2.QtWidgets import QApplication...
Attempt to connect to postgresql silently stops the program
I am trying to connect to postgresql using pyside2. But, when I try to call the open method, the program stops running without showing any error. This is my code: from PySide2.QtSql import QSqlDatabase, QSqlQuery from PySide2.QtWidgets import QApplication app = QApplication([]) db = QSqlDatabase.addDatabase("QPSQL") ...
[ "I can not believe it. The problem was that it was not setting the port correctly. Now that I put the port right, it works perfect xD\nI don't know why it took me so long to notice.\n db.setPort(myport)\n\n" ]
[ 0 ]
[]
[]
[ "postgresql", "pyside2", "python", "qt" ]
stackoverflow_0074507874_postgresql_pyside2_python_qt.txt
Q: Using Regex to combine lines start with quotation marks I would like to combine two lines with only one line feed \n, and sometime the next line starts with a quotation mark. I am trying use this code to combine them, with \" to find quotation marks, comb_nextline = re.sub(r'(?<=[^\.][A-Za-z,-])\n[ ]*(?=[a-zA-Z0...
Using Regex to combine lines start with quotation marks
I would like to combine two lines with only one line feed \n, and sometime the next line starts with a quotation mark. I am trying use this code to combine them, with \" to find quotation marks, comb_nextline = re.sub(r'(?<=[^\.][A-Za-z,-])\n[ ]*(?=[a-zA-Z0-9\(\"])', ' ', txt) but it doesn't work with the line start...
[ "You can also match optional spaces before matching the newline\n(?<=[^.][A-Za-z,-]) *\\n *(?=[a-zA-Z0-9(\\\"])\n\nRegex demo | Python demo\nOr matching all spaces without newlines using a negated character class [^\\S\\n]\n(?<=[^.][A-Za-z,-])[^\\S\\n]*\\n[^\\S\\n]*(?=[a-zA-Z0-9(\\\"])\n\nRegex demo\nimport re\n\nt...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074507967_python_regex.txt
Q: How to create table dynamically from user input? I am creating a wishlist app using Tkinter and sqlite3. I want the user to be able to create tables in database by imputing names. For that I connected a button to this function: def create_table(table_name): connection = sql.connect(f'{directory}\main.sqlite') ...
How to create table dynamically from user input?
I am creating a wishlist app using Tkinter and sqlite3. I want the user to be able to create tables in database by imputing names. For that I connected a button to this function: def create_table(table_name): connection = sql.connect(f'{directory}\main.sqlite') cursor = connection.cursor() cursor.execu...
[ "Nope, this cannot be done. A table name cannot act as a dynamic parameter from SQLite's point of view. You will need to do something like this:\nf'CREATE TABLE {table_name} (name TEXT, price REAL, url TEXT)'\n\nBut first you will need to validate the user input for table_name. Which shouldn't be a problem if you w...
[ 1 ]
[]
[]
[ "python", "sqlite", "string", "string_formatting" ]
stackoverflow_0074507946_python_sqlite_string_string_formatting.txt
Q: I have different age groups data and different months, How can I convert it to Annually in Python? df = pd.read_csv('1410001701eng.csv') df.head() df['date'] = pd.to_datetime(df['Age group']) df['year'] = pd.DatetimeIndex(df['date']).year monthly_year_avg = df.groupby('year')['VALUE'].mean() print(monthly_year_avg...
I have different age groups data and different months, How can I convert it to Annually in Python?
df = pd.read_csv('1410001701eng.csv') df.head() df['date'] = pd.to_datetime(df['Age group']) df['year'] = pd.DatetimeIndex(df['date']).year monthly_year_avg = df.groupby('year')['VALUE'].mean() print(monthly_year_avg) This is my code. Could you please tell me or give me a hint or show me the website has similar quest...
[ "This should give you a new pandas dataframe with the yearly mean. Note that the if statement has a subtract by 1 on the timestep to account for no December column for 2022.\nnew_df = pd.DataFrame() #create empty pandas dataframe\ntime_step = 12 #years\nfor i in np.arange(0, len(df.columns), time_step):\n new_he...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074505669_dataframe_pandas_python.txt
Q: import requests giving "Traceback (most recent call last):", Issue with python version or environment? during my slow coding progress, I just found out that probably I have some issue with environment variables and I am little bit confused with it. I am using python 3.6 in Pycharm tool and it seems, that I have bo...
import requests giving "Traceback (most recent call last):", Issue with python version or environment?
during my slow coding progress, I just found out that probably I have some issue with environment variables and I am little bit confused with it. I am using python 3.6 in Pycharm tool and it seems, that I have both versions of python installed: Controller$ python2 -V Python 2.7.17 Controller$ python3 -V Python 3.10.5 ...
[ "Ok, I finally found the solution via this reddit link:\nhttps://www.reddit.com/r/learnpython/comments/tzja94/comment/i4022j7/\nAs I had a similar symptoms as in the case guy had, I went through the path from the error and did these changes in the \"selectors.py\" file.\n# from collections.abc import namedtuple, Ma...
[ 0 ]
[]
[]
[ "environment_variables", "python", "python_import", "request" ]
stackoverflow_0074500969_environment_variables_python_python_import_request.txt
Q: Ho to filter keys and values from a python dictionary based on conditions? I have python dictionary with the below items : > ... > {'HostName': 'DEMOBDDBX00100.demo', 'BackupStatus': 'SUCCESS'} > {'HostName': 'DEMOBDDBX00200.demo', 'BackupStatus': 'SUCCESS'} > {'HostName': 'DEMOBDDBX10101.demo', 'Backu...
Ho to filter keys and values from a python dictionary based on conditions?
I have python dictionary with the below items : > ... > {'HostName': 'DEMOBDDBX00100.demo', 'BackupStatus': 'SUCCESS'} > {'HostName': 'DEMOBDDBX00200.demo', 'BackupStatus': 'SUCCESS'} > {'HostName': 'DEMOBDDBX10101.demo', 'BackupStatus': 'FAILURE'} > {'HostName': 'DEMOBDDBX10102.demo', 'BackupStatus': '...
[ "This does not look like a dictionary but a list of dictionaries.\nIf that's the case, it seems you want to obtain a sub-list with only those elements (dictionaries) that have BackupStatus equal to FAILURE. So you could do something like this:\nrecs = [\n {'HostName': 'DEMOBDDBX00100.demo', 'BackupStatus': 'SUCC...
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074507998_dictionary_python.txt
Q: Install Google Maps 4.7 on Conda Environment I would like to to install the latest Google Maps (Version 4.7 as of today) in a conda environment. The question is, how to do it in the configuration file (The YAML file) which defines the environment without using the command line I tried looking for the latest versio...
Install Google Maps 4.7 on Conda Environment
I would like to to install the latest Google Maps (Version 4.7 as of today) in a conda environment. The question is, how to do it in the configuration file (The YAML file) which defines the environment without using the command line I tried looking for the latest version of Google Maps on conda-forge. Yet it is of the ...
[ "By looking at the answer for Using Pip to install packages to Anaconda Environment you may do something like:\nname: YourName\nchannels:\n - conda-forge\ndependencies:\n - python=3.11\n - numpy\n - scipy\n - pip\n - pip:\n - googlemaps==4.7\n\n" ]
[ 1 ]
[]
[]
[ "conda", "environment", "google_maps", "python" ]
stackoverflow_0074507990_conda_environment_google_maps_python.txt
Q: use min & max functions on objects list so I have a list of objects that I made and every object has the var y. so I want to use the min function to find the lowest y of them without creating a new list of this var or use loops. from random import randint class Dot(): def __init__(self, x=randint(-100, 100), ...
use min & max functions on objects list
so I have a list of objects that I made and every object has the var y. so I want to use the min function to find the lowest y of them without creating a new list of this var or use loops. from random import randint class Dot(): def __init__(self, x=randint(-100, 100), y=randint(-100, 100)): self.x, self.y...
[ "Try to use key= parameter of min():\nfrom random import randint\n\n\nclass Dot:\n def __init__(self, x=None, y=None):\n if x is None:\n x = randint(-100, 100)\n\n if y is None:\n y = randint(-100, 100)\n\n self.x, self.y = x, y\n\n\n\nd1, d2, d3, d4, d5 = Dot(), Dot(),...
[ 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074508103_list_python_python_3.x.txt
Q: How to add a new line to the string that I input to Python input()? I ask user for some input using s = input('enter something: ') Then I save it to a text file. I want my user to be able to input new lines using '\n'. For example, if user input "hello\nbye", and I use file.write(s) to save the text, I want my te...
How to add a new line to the string that I input to Python input()?
I ask user for some input using s = input('enter something: ') Then I save it to a text file. I want my user to be able to input new lines using '\n'. For example, if user input "hello\nbye", and I use file.write(s) to save the text, I want my text file to be: hello bye But just typing in '\n' does not seen to work. ...
[ "Since python's input can't turn \\n into newline characters, you may need to do the conversion yourself:\ns = input('enter something: ') #e.g \"hello\\nworld\"\ns = s.replace('\\\\n', '\\n') # turns literal '\\n' text into newline characters\n...\nfile.write(s)\n\nNow, s will have newlines instead of \\n and will ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074508092_python.txt
Q: create a tag at top of xml file using python I have xml file named 'test.xml' like below format <final_output> <career_profile> <output> <Template OriginalSentence="1" SentenceID="1" RecordID="0"> <Employer Type="String"><Value>HCL TECHNOLOGY LTD</Value></Employer> ...
create a tag at top of xml file using python
I have xml file named 'test.xml' like below format <final_output> <career_profile> <output> <Template OriginalSentence="1" SentenceID="1" RecordID="0"> <Employer Type="String"><Value>HCL TECHNOLOGY LTD</Value></Employer> <duration><Value>JAN 2018 to till date</Val...
[ "If you want to use xml package then the simple solution will be\nfrom xml.etree import ElementTree\n\nxml_input = \"input.xml\"\nxml_output = \"output.xml\"\n\ntree_input = ElementTree.parse(xml_input)\nroot = tree_input.getroot()\n\n# add new tag\nnew_root = ElementTree.Element(\"final_file\")\nnew_root.insert(0,...
[ 0 ]
[]
[]
[ "python", "python_3.x", "xml" ]
stackoverflow_0074507942_python_python_3.x_xml.txt
Q: How to properly import libraries that I downloaded via pip or conda? I am trying to use "matplotlib" for a project and when importing it I get: "matplotlib.pyplot not resolved from source", then I tried to import pandas and I got something similar, how can I fix this? I am using WSL, and I am in a virtual environm...
How to properly import libraries that I downloaded via pip or conda?
I am trying to use "matplotlib" for a project and when importing it I get: "matplotlib.pyplot not resolved from source", then I tried to import pandas and I got something similar, how can I fix this? I am using WSL, and I am in a virtual environment that I created in conda. I want to use some libraries but they are not...
[ "Maybe you are not connected to the correct conda env in visual studio code.\nYou could check that by pressing \" CTRL SHIFT P\" Then press on Select Interpreter and select your created environment.\nTo check if matplotlib was installed in the correct environment you could try the following:\n\nopen anaconda shell\...
[ 1 ]
[]
[]
[ "conda", "matplotlib", "pandas", "python", "windows_subsystem_for_linux" ]
stackoverflow_0074501112_conda_matplotlib_pandas_python_windows_subsystem_for_linux.txt
Q: Append a nested dictionary to a dictionary in python I'm trying to append a nested dictionary to a dictionary, I have searched the internet and couldn't find an answer. I tried Colors = {} a = {"1:1":{255,1,2}} b = {"2:1":{1,255,2}} Colors.update(a) Colors.update(b) print(Colors) It prints {'1:1': {1, 2, 255}, ...
Append a nested dictionary to a dictionary in python
I'm trying to append a nested dictionary to a dictionary, I have searched the internet and couldn't find an answer. I tried Colors = {} a = {"1:1":{255,1,2}} b = {"2:1":{1,255,2}} Colors.update(a) Colors.update(b) print(Colors) It prints {'1:1': {1, 2, 255}, '2:1': {1, 2, 255}} Instead of {'1:1': {255,1,2}, '2:1':...
[ "The reason the values don't keep their order is because you're using sets and not lists. Unlike lists, sets are unordered (you can read more here).\nTo fix your issue, you can use lists instead (note the {} turned into []:\nColors = {}\n\na = {\"1:1\":[255,1,2]}\nb = {\"2:1\":[1,255,2]}\nColors.update(a)\nColors.u...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074508125_dictionary_python.txt
Q: Enabling CAFFE2 while building pytorch from source on Windows command prompt So, I was doing a model train up using Yolo7 on Windows platform and C:\Users\LENOVO>python train.py --weights yolov7.pt --data "data/custom.yaml" --workers 4 --batch-size 4 --img 416 --cfg cfg/training/yolov7.yaml --name yolov7 --hyp da...
Enabling CAFFE2 while building pytorch from source on Windows command prompt
So, I was doing a model train up using Yolo7 on Windows platform and C:\Users\LENOVO>python train.py --weights yolov7.pt --data "data/custom.yaml" --workers 4 --batch-size 4 --img 416 --cfg cfg/training/yolov7.yaml --name yolov7 --hyp data/hyp.scratch.p5.yaml After running the above command the below stack trace of e...
[ "I have solved the issue but setting BUILD_CAFFE2=1 on the command prompt before installing pytorch, with the following code.\nset BUILD_CAFFE2=1\n\n" ]
[ 0 ]
[]
[]
[ "caffe2", "python", "pytorch" ]
stackoverflow_0074492524_caffe2_python_pytorch.txt
Q: Comparing contents in the given tuples I've two python class 'tuples' and and i want to compare contents on both of them and get only which is only in 'deactivated' tuple for eg., deactivated = ((34, 'abcd'), (250, 'def'), (350, 'xyz')) schedules = ((34, 'abcd'), (250, 'def')) to_deactivate = () in here, i want t...
Comparing contents in the given tuples
I've two python class 'tuples' and and i want to compare contents on both of them and get only which is only in 'deactivated' tuple for eg., deactivated = ((34, 'abcd'), (250, 'def'), (350, 'xyz')) schedules = ((34, 'abcd'), (250, 'def')) to_deactivate = () in here, i want to push (350, 'xyz') which is not in schedule...
[ "Are you sure you those variables should be tuples?\nBecause tuples are immutable. In their essence, you are not supposed to add or remove things from them. It looks like those variables are intended to be collections to which you add or remove things. Which is not possible with tuples.\nFor example, sets, since yo...
[ 2, 0, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074507765_python_tuples.txt
Q: Factory_boy not creating different User objects Django I am new to Factory_boy with Django. After spending some time I understood how to create a factory for User model. I am using the default user model and following is my factory. I am using Faker for randomness import factory from . import models from django.c...
Factory_boy not creating different User objects Django
I am new to Factory_boy with Django. After spending some time I understood how to create a factory for User model. I am using the default user model and following is my factory. I am using Faker for randomness import factory from . import models from django.contrib.auth.models import User from faker import Faker from ...
[ "You are defining class attributes for your factory, which get evaluated only when the class is defined. email = first_name+\".\"+last_name+\"@gmail.com\" will be evaluated once, not each time you call UserFactory.create(), hence the unique constraint errors. The usual solution to this is to instead define instance...
[ 2, 0, 0 ]
[]
[]
[ "django", "factory_boy", "python" ]
stackoverflow_0042709008_django_factory_boy_python.txt
Q: How can I scroll a web page using selenium webdriver in python? I am currently using selenium webdriver to parse through facebook user friends page and extract all ids from the AJAX script. But I need to scroll down to get all the friends. How can I scroll down in Selenium. I am using python. A: You can use driv...
How can I scroll a web page using selenium webdriver in python?
I am currently using selenium webdriver to parse through facebook user friends page and extract all ids from the AJAX script. But I need to scroll down to get all the friends. How can I scroll down in Selenium. I am using python.
[ "You can use\ndriver.execute_script(\"window.scrollTo(0, Y)\") \n\nwhere Y is the height (on a fullhd monitor it's 1080). (Thanks to @lukeis)\nYou can also use\ndriver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\nto scroll to the bottom of the page.\nIf you want to scroll to a page with in...
[ 417, 101, 60, 28, 23, 16, 12, 8, 8, 8, 8, 8, 7, 6, 6, 3, 3, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "automated_tests", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0020986631_automated_tests_python_selenium_selenium_webdriver.txt
Q: Redirecting a python code output to a file and rotating it every day I want to write a shell script that executes a python script and redirects its output with a timestamp to a different log file every day. The python script should run forever without stopping, it prints small text to the terminal every 10 seconds...
Redirecting a python code output to a file and rotating it every day
I want to write a shell script that executes a python script and redirects its output with a timestamp to a different log file every day. The python script should run forever without stopping, it prints small text to the terminal every 10 seconds. Here is how far I have come: filename="log-$(date +%Y-%m-%d).log" python...
[ "Rather than controlling log files externally, I would recommend using TimedRotatingFileHandler instead.\nExample:\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\n\nlog = logging.getLogger(__name__)\n\ndef init_file_handler(log_path, logger=None):\n handler = TimedRotatingFileHandler(log_...
[ 0 ]
[]
[]
[ "logging", "python", "rotation", "shell", "ubuntu" ]
stackoverflow_0074507894_logging_python_rotation_shell_ubuntu.txt
Q: How can I improve my stock lookup code to run in under 5 minutes? I have a list of stock symbols, for which I need to extract financial data. I wrote a function to get all data I need (see below). I tested it on 35 stocks, it took me 9 min to run. The real dataset has more than 600 stock symbols, which would take ...
How can I improve my stock lookup code to run in under 5 minutes?
I have a list of stock symbols, for which I need to extract financial data. I wrote a function to get all data I need (see below). I tested it on 35 stocks, it took me 9 min to run. The real dataset has more than 600 stock symbols, which would take hours of running. Can you review my code and advise on how to make it r...
[ "I know this post is pretty old, but I just came across it now. Check out the 'yfinance' library. There's all kinds of stuff available over there!!\nimport pandas_datareader as web\nimport pandas as pd\n \ndf = web.DataReader('AAPL', data_source='yahoo', start='2011-01-01', end='2021-01-12')\ndf.head()\n\nimport yf...
[ 1 ]
[]
[]
[ "performance", "python", "yahoo_finance", "yfinance" ]
stackoverflow_0073940353_performance_python_yahoo_finance_yfinance.txt
Q: Cannot pass Twitter authorization I am absolutely brand new to coding (about 11 days) and I was told to post my question here since I cannot solve my problem despite countless attempts. I am using Python and Jupyter notebook (it is required that I use this) I have a config file named config.txt where all my keys a...
Cannot pass Twitter authorization
I am absolutely brand new to coding (about 11 days) and I was told to post my question here since I cannot solve my problem despite countless attempts. I am using Python and Jupyter notebook (it is required that I use this) I have a config file named config.txt where all my keys and tokens are located and I am able to ...
[ "You are not passing your api_key and api_secret.\nThis:\nauth = OAuthHandler(\"API_key\", \"API_secret\")\nshould be this:\nauth = OAuthHandler(api_key, api_secret)\n" ]
[ 0 ]
[]
[]
[ "authentication", "jupyter_notebook", "python", "twitter", "twitter_oauth" ]
stackoverflow_0074507641_authentication_jupyter_notebook_python_twitter_twitter_oauth.txt
Q: How to click on a button on a webpage and iterate through contents after clicking on button using python selenium I am using Python Selenium to web scrape from https://finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL but I want to scrape the Quarterly data instead of the Annual after clicking on the "Quarterly" b...
How to click on a button on a webpage and iterate through contents after clicking on button using python selenium
I am using Python Selenium to web scrape from https://finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL but I want to scrape the Quarterly data instead of the Annual after clicking on the "Quarterly" button on the top right. This is my code so far: def readQuarterlyBSData(ticker): url = 'https://finance.yahoo.com/q...
[ "\nsoup = BeautifulSoup(driver.page_source, 'lxml')\n\nYou don't need to pass your driver.page_source to BS4, use Selenium itself to extract the data using driver.find_element function.\nHere is the doc on that: https://selenium-python.readthedocs.io/locating-elements.html\nAlso, you are not waiting for the page so...
[ 1, 0 ]
[]
[]
[ "onclick", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0073725603_onclick_python_selenium_selenium_webdriver_web_scraping.txt
Q: Python yahoo finance data optimitzation I've found a code here pretty good to retrieve some data I need (Python yahoo finance error market_cap=int(data.get_quote_yahoo(str)['marketCap']) TypeError: 'int' object is not callable): tickers=["AAPL","GOOG","RY","HPQ"] # Get market cap (not really necessary for you) m...
Python yahoo finance data optimitzation
I've found a code here pretty good to retrieve some data I need (Python yahoo finance error market_cap=int(data.get_quote_yahoo(str)['marketCap']) TypeError: 'int' object is not callable): tickers=["AAPL","GOOG","RY","HPQ"] # Get market cap (not really necessary for you) market_cap_data = web.get_quote_yahoo(tickers)...
[ "Using the set, you can get all the items that can be retrieved by the ticker for the initial set, and using the union set, you can also add in a list, so you can get all the item names that have a value in the issue you want to retrieve.\nimport pandas_datareader as web\nimport pandas as pd\n\ntickers = [\"AAPL\",...
[ 0, 0 ]
[]
[]
[ "python", "yahoo_finance" ]
stackoverflow_0074263159_python_yahoo_finance.txt
Q: aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host stackoverflow.com:443 ssl:default [Connect call failed ('151.101.193.69', 443)] here is my code: import asyncio from aiohttp import ClientSession async def main(): url = "https://stackoverflow.com/" async with ClientSession() as sessi...
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host stackoverflow.com:443 ssl:default [Connect call failed ('151.101.193.69', 443)]
here is my code: import asyncio from aiohttp import ClientSession async def main(): url = "https://stackoverflow.com/" async with ClientSession() as session: async with session.get(url) as resp: print(resp.status) asyncio.run(main()) if I run it on my computer, everything works, but if ...
[ "first solution\nReferring to the help from the forum, I added trust_env = True when creating the client and now everything works.\nExplanation:\nFree accounts on PythonAnywhere must use a proxy to connect to the public internet, but aiohttp, by default, does not connect to a proxy accessible from an environment va...
[ 22, 10, 3, 1, 1 ]
[ "I just solved what could have been a 3 hour problem in 5 mins by changing all https to http. If it's possible, don't use https. I had an issue where another library (playwright) could not use the selector event loop, I would have had to separate process to use aiohttp. Better yet, switch libraries, httpx is an oka...
[ -5 ]
[ "aiohttp", "python", "python_3.x", "python_asyncio", "pythonanywhere" ]
stackoverflow_0063347818_aiohttp_python_python_3.x_python_asyncio_pythonanywhere.txt
Q: Keep rows according to condition in Pandas I am looking for a code to find rows that matches a condition and keep those rows. In the image example, I wish to keep all the apples with amt1 => 5 and amt2 < 5. I also want to keep the bananas with amt1 => 1 and amt2 < 5 (highlighted red in image). There are many other...
Keep rows according to condition in Pandas
I am looking for a code to find rows that matches a condition and keep those rows. In the image example, I wish to keep all the apples with amt1 => 5 and amt2 < 5. I also want to keep the bananas with amt1 => 1 and amt2 < 5 (highlighted red in image). There are many other fruits in the list that I have to filter for (m...
[ "I am not quite sure I understand your requirements because I don't understand how the conditions for the rows to keep are formulated.\nOne thing you can use to combine multiple criteria for selecting data is the query method of the dataframe:\nimport pandas as pd\n\ndf = pd.DataFrame([\n ['Apple', 5, 1],\n [...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074508189_dataframe_pandas_python.txt