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: getting data from the backend django models I am working on a project pastly the i used sql querys, but change in the django models the models i used are for the members table class Members(models.Model): name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) phoneNo = mod...
getting data from the backend django models
I am working on a project pastly the i used sql querys, but change in the django models the models i used are for the members table class Members(models.Model): name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) phoneNo = models.CharField(unique=True, max_length = 50) c...
[ "Pass all fields you need in .values() like:\nBills.objects.filter(cash = False).values('purchasedPerson', 'name', 'address', 'phoneNo').annotate(...)\n\nAnother choice is skipping the .values() part:\nBills.objects.filter(cash = False).annotate(...)\n\n\nNote: all() is not required in your case.\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074590177_django_python.txt
Q: Execute function specifically on CPU in Jax I have a function that will basically instantiate a huge array and do other things. I am running my code on TPUs so basically my memory is limited. How can I execute my function specifically on the CPU? If I do: y = jax.device_put(my_function(), device=jax.devices("cpu")...
Execute function specifically on CPU in Jax
I have a function that will basically instantiate a huge array and do other things. I am running my code on TPUs so basically my memory is limited. How can I execute my function specifically on the CPU? If I do: y = jax.device_put(my_function(), device=jax.devices("cpu")[0]) I guess that my_function() is first execute...
[ "I'm going to make a guess here. I can't run it either so you may have to fiddle with it\nwith jax.default_device(jax.devices(\"cpu\")[0]):\n y = my_function()\n\nSee the docs here and here.\n", "To directly specify the device on which a function should be executed, use the device argument of jax.jit. For exam...
[ 0, 0 ]
[]
[]
[ "cpu", "jax", "memory", "python", "tpu" ]
stackoverflow_0074537026_cpu_jax_memory_python_tpu.txt
Q: Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed I am encountering the error Forbidden (403) CSRF verification failed when trying to login into the Django Admin after updating the version of Django. Also, there were no changes in the settings of Django. The error ca...
Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed
I am encountering the error Forbidden (403) CSRF verification failed when trying to login into the Django Admin after updating the version of Django. Also, there were no changes in the settings of Django. The error can be seen in the below image:
[ "I Already posted it on https://shriekdj.hashnode.dev/unable-to-login-django-admin-after-update-giving-error-forbidden-403-csrf-verification-failed-request-aborted.\nThis Issue can happen suddenly after updating to the newer version Of Django.\nDetails\n\nDjango Project Foundation team made some changes in security...
[ 0, 0 ]
[]
[]
[ "django", "django_admin", "django_forms", "python", "python_3.x" ]
stackoverflow_0071857585_django_django_admin_django_forms_python_python_3.x.txt
Q: How to update marker positions in a scatter mapbox? I'm trying to display live location data on a mapbox scatter plot. In order to mimic new data received from the server the callback moves all points every 3 seconds: import plotly.express as px from dash import Dash, html, dcc from dash.dependencies import Input,...
How to update marker positions in a scatter mapbox?
I'm trying to display live location data on a mapbox scatter plot. In order to mimic new data received from the server the callback moves all points every 3 seconds: import plotly.express as px from dash import Dash, html, dcc from dash.dependencies import Input, Output px.set_mapbox_access_token(open(".mapbox_token")...
[ "I found a work around by having two callbacks.\nmy html looks like this dbc.Col > dcc.Graph(figure = fig)\n@app.callback(\n Output('graph-id','figure'),\n\n Input('control-id', 'n_clicks')\n)\ndef update_func(scatter_map_fig):\n return go.Figure\n\nThe second callback returns a new graph component with th...
[ 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074567159_plotly_dash_python.txt
Q: Flask change the server header I've made a simple flask application: Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 host:google.be HTTP/1.0 404 NOT FOUND Content-Type: text/html Content-Length: 233 Server: Werkzeug/0.9.6 Python/2.7.6 Date: Mon, 08 Dec 2014 19:15:43 GMT <!DOC...
Flask change the server header
I've made a simple flask application: Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 host:google.be HTTP/1.0 404 NOT FOUND Content-Type: text/html Content-Length: 233 Server: Werkzeug/0.9.6 Python/2.7.6 Date: Mon, 08 Dec 2014 19:15:43 GMT <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3...
[ "You can use Flask's make_response method to add or modify headers.\nfrom flask import make_response\n\n@app.route('/index')\ndef index():\n resp = make_response(\"Hello, World!\")\n resp.headers['server'] = 'ASD'\n return resp\n\n", "@bcarroll's answer works but it will bypass other processes defined in...
[ 13, 8, 5, 3, 0, 0 ]
[]
[]
[ "flask", "python", "werkzeug" ]
stackoverflow_0027365298_flask_python_werkzeug.txt
Q: Remove elements from a list based on a condition in Python, problem: loop removes only the first instance For each element in my list I'd like to check: if it includes 'strategies available for player', or is it equal to '\n' If yes, the element should be removed. I've written a loop to iterate over the list. It...
Remove elements from a list based on a condition in Python, problem: loop removes only the first instance
For each element in my list I'd like to check: if it includes 'strategies available for player', or is it equal to '\n' If yes, the element should be removed. I've written a loop to iterate over the list. It removes the first instance of 'strategies availbale for player' just fine but totally ignores the second one. ...
[ "I would suggest to create another list using list comprehension and applying conditions accordingly:\nel = [x for x in a_list if not 'strategies available for' in x or x != '\\n']\n\nBut, if you wish to remove the elements from the current list and without creating a new one, you SHOULD iterate from the end whenev...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074590287_list_python.txt
Q: Update table in SQLite based on other table I have two tables, A and B. Due to wrongly specified loop I need to delete some rows from table A (25k rows). The tables looks as follows: CREATE TABLE "A" ( "tournament" INTEGER, "year" INTEGER, "course" INTEGER, "round" INTEGER, "hole" INTEG...
Update table in SQLite based on other table
I have two tables, A and B. Due to wrongly specified loop I need to delete some rows from table A (25k rows). The tables looks as follows: CREATE TABLE "A" ( "tournament" INTEGER, "year" INTEGER, "course" INTEGER, "round" INTEGER, "hole" INTEGER, "front" INTEGER, "side" INTEGER, ...
[ "The simplest way to get all the Rx values from table B is with UNION in a CTE.\nThen use NOT IN in the DELETE statement to delete all rows of table A with a course that does not exist in the CTE:\nWITH cte AS (\n SELECT R1 FROM B \n UNION \n SELECT R2 FROM B \n UNION \n SELECT R3 FROM B \n UNION \n SELECT R...
[ 1 ]
[]
[]
[ "common_table_expression", "python", "sql", "sql_delete", "sqlite" ]
stackoverflow_0074590084_common_table_expression_python_sql_sql_delete_sqlite.txt
Q: Given rows and cols, print a list of all seats in a theater Sample input: 2 3 Expected output: 1A 1B 1C 2A 2B 2C Current code: num_rows = int(input()) num_cols = int(input()) k='A' for i in range(num_rows): for j in range(num_cols): print(f'{i+1}{k}',end=' ') k = chr(ord(k)+1) Current outp...
Given rows and cols, print a list of all seats in a theater
Sample input: 2 3 Expected output: 1A 1B 1C 2A 2B 2C Current code: num_rows = int(input()) num_cols = int(input()) k='A' for i in range(num_rows): for j in range(num_cols): print(f'{i+1}{k}',end=' ') k = chr(ord(k)+1) Current output: 1A 1B 1C 2D 2E 2F The letter does not start again at "A" for...
[ "It looks like you have misplaced the k='A' line. The rest seems to be correct.\nnum_rows = int(input())\nnum_cols = int(input())\n\nfor i in range(num_rows):\n k='A'\n for j in range(num_cols):\n print(f'{i+1}{k}',end=' ')\n k = chr(ord(k)+1)\n\nFor your input this would output\n1A 1B 1C 2A 2B ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074590316_python.txt
Q: GROUP By in Django ORM for page in Django Admin I'm not very long in Django, sorry for the probably stupid question. But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution. My Models: class Offer(models.Model): seller = models.ForeignKey()<..> # oth...
GROUP By in Django ORM for page in Django Admin
I'm not very long in Django, sorry for the probably stupid question. But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution. My Models: class Offer(models.Model): seller = models.ForeignKey()<..> # other fields class OfferViewCount(models.Model): of...
[ "you should use the Django group by like below\ndef get_queryset(self, request):\n qs = OfferViewCount.objects.values(\"offer\")\n .annotate(count=Count(\"offer\")).distinct().order_by(\"count\")\n return qs\n\n", "You can use below queryset for group by query\nfrom django.db.models import Count\n\ndef g...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "django_queryset", "python" ]
stackoverflow_0074575988_django_django_admin_django_models_django_queryset_python.txt
Q: How to measure objects in different planes with OpenCv and a single camera I'm working on a project where I need to track markers placed in a person. The person will be walking on a treadmill. I will use a single camera for each side. I already calibrated the cameras, but now I'm trying to understand how to solve ...
How to measure objects in different planes with OpenCv and a single camera
I'm working on a project where I need to track markers placed in a person. The person will be walking on a treadmill. I will use a single camera for each side. I already calibrated the cameras, but now I'm trying to understand how to solve a problem. The problem is: the person will be walking and consequently the plane...
[ "If the treadmill is always the same, you might use it as a \"calibration object\" to fix scale. Build (or find online) a 3d model for it, position it on the image in a 3d modeling tool (e.g. Blender), then work out, e.g., the position of its \"walk plane\" w.r.t. the camera.\n" ]
[ 0 ]
[]
[]
[ "computer_vision", "opencv", "python" ]
stackoverflow_0074563856_computer_vision_opencv_python.txt
Q: Is there a way in Django where the superadmin can create normal users and the users gets an email with the credentials that was created for them? I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety. I am using the default Django admin panel, where ...
Is there a way in Django where the superadmin can create normal users and the users gets an email with the credentials that was created for them?
I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety. I am using the default Django admin panel, where I have logged in with a super admin I created. The app doesn't have a sign up view so only the admin will be able to create new users. The normal users...
[ "You can use create Admin actions that sends emails utilizing the send_email function when an account is created.\nAdmin Actions - https://docs.djangoproject.com/en/3.2/ref/contrib/admin/actions/\nsend_email - https://docs.djangoproject.com/en/4.1/topics/email/\n" ]
[ 1 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074586852_django_django_rest_framework_python.txt
Q: How to add date stamps on the images using Python library to create noise in the image How to add date stamps on the image frames using Python library to create noise in the image I tried the below but would like to know how to add it as part of the image frame from datetime import datetime datetime.now().strftime...
How to add date stamps on the images using Python library to create noise in the image
How to add date stamps on the image frames using Python library to create noise in the image I tried the below but would like to know how to add it as part of the image frame from datetime import datetime datetime.now().strftime('%Y-%m-%d %H:%M:%S') import pandas as pd print(pd.datetime.now())
[ "From this article, you can understand how add watermark on image.\nI modified code from that website to add timestamp as watermark using python Pillow library.\n\n\nfrom datetime import datetime\nfrom PIL import Image, ImageDraw, ImageFont\nim = Image.open('image.jpg')\nwidth, height = im.size\ndraw = ImageDraw.Dr...
[ 0 ]
[]
[]
[ "autoencoder", "deep_learning", "python" ]
stackoverflow_0074590071_autoencoder_deep_learning_python.txt
Q: Is there any good command to get pixel's gray value (in this case I'm working on a gray image) I found img.getpixel((i,j))[0] that works well, but I want to pick the gray value of pixels that have less gray value than T (T go grom 0 to 255). I tried the code below but it didn't work as I expected. #create a list t...
Is there any good command to get pixel's gray value (in this case I'm working on a gray image)
I found img.getpixel((i,j))[0] that works well, but I want to pick the gray value of pixels that have less gray value than T (T go grom 0 to 255). I tried the code below but it didn't work as I expected. #create a list to store results for each loop: J={} #picking gray value of pixels: totalgrayvalue=0 for i in range (...
[ "Giving the complete answer would be no fun for you, so here are some thoughts and a little animation.\nUsing Python for loops with images is really not very advisable, they are slow and error-prone. Try to favour vectorised code like Numpy or OpenCV in general.\nimport cv2\nimport numpy as np\n\n# Load image\nim =...
[ 2 ]
[]
[]
[ "image_processing", "image_segmentation", "python", "python_imaging_library", "variance" ]
stackoverflow_0074582777_image_processing_image_segmentation_python_python_imaging_library_variance.txt
Q: Change values in a kivy storage Can someone tell me how to change a value in a kivy storage (JsonStore) ? Here is an example of what I have : from kivy.storage.jsonstore import JsonStore store = JsonStore("Test.json") store["MyDict"] = {"0":"H", "1":"A", "2":"Y"} print(store["MyDict"]) store["MyDict"]["1"] = "E...
Change values in a kivy storage
Can someone tell me how to change a value in a kivy storage (JsonStore) ? Here is an example of what I have : from kivy.storage.jsonstore import JsonStore store = JsonStore("Test.json") store["MyDict"] = {"0":"H", "1":"A", "2":"Y"} print(store["MyDict"]) store["MyDict"]["1"] = "E" print(store["MyDict"]) This code w...
[ "you cannot directly do this because that store object is not a dictionary.\nhowever, you can store your whole dictionary as one item in the store.\nIn this example, entry is a Python dict. According to the kivy.storage documentation, the storage objects have put(), get(), exists(), delete() and find() methods. T...
[ 1 ]
[]
[]
[ "kivy", "python", "storage" ]
stackoverflow_0074589758_kivy_python_storage.txt
Q: TypeError: translation() got an unexpected keyword argument 'codeset' I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" mes...
TypeError: translation() got an unexpected keyword argument 'codeset'
I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" message. I've run back the video like 20 times to see if I've missed anything,...
[ "I've also been following Mosh's Python course, ran into the same problem, came here for answers and then did some more research on my own.\nI'm a total beginner, I might me wrong, but in the tutorial, Mosh makes us install django 2.1 instead of the current version of django. The error \"translation() got an unexpe...
[ 0, 0 ]
[]
[]
[ "django", "manage.py", "python" ]
stackoverflow_0074406706_django_manage.py_python.txt
Q: How to merge 2 dataframe rows in a new dataframe row with pandas? I have 2 variables (dataframes) one is 47 colums wide and the other is 87, they are DF2 and DF2. Then I have a variable (dataframe) called full_data. Df1 and DF2 are two different subset of data I want to merge together once I find 2 rows are equal....
How to merge 2 dataframe rows in a new dataframe row with pandas?
I have 2 variables (dataframes) one is 47 colums wide and the other is 87, they are DF2 and DF2. Then I have a variable (dataframe) called full_data. Df1 and DF2 are two different subset of data I want to merge together once I find 2 rows are equal. I am doing everything I want so far besides appending the right value ...
[ "In the end I solved my problem. Probably I was not clear enough but my question but what was happening when concatenating is that I was getting duplicated or multiple rows when the expected result was getting a single row concatenation.\nThe issues was found to be with the indexing. Indexing had to be reset becaus...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074586298_dataframe_pandas_python.txt
Q: Local file upload progress bar in console using Python I need to upload a file and show its stats to the user (as it shows on the console). Didn't find any library for this, the function can be as simple as showing the uploaded percentage (uploaded/filesize*100) and showing the uploaded size (20/50MB) with the upl...
Local file upload progress bar in console using Python
I need to upload a file and show its stats to the user (as it shows on the console). Didn't find any library for this, the function can be as simple as showing the uploaded percentage (uploaded/filesize*100) and showing the uploaded size (20/50MB) with the upload speed and ETA. There's a nice library named alive-progre...
[ "You could use the sys lib.\nUsing stdout & flush (more details here).\nimport sys, time\n\nlenght_bar = 50\n\nsys.stdout.write(\"Loading : |%s|\" % (\" \" * lenght_bar))\nsys.stdout.write(\"\\b\" * (lenght_bar+1)) #use backspace\n\nfor i in range(lenght_bar):\n sys.stdout.write(\"▒\")\n sys.stdout.flush()\n ...
[ 1, 0, 0, 0 ]
[]
[]
[ "pathlib", "progress_bar", "python", "python_3.x", "sys" ]
stackoverflow_0071160646_pathlib_progress_bar_python_python_3.x_sys.txt
Q: How to remove all balise in text python I want to extract data from a tag to simply retrieve the text. Unfortunately I can't extract just the text, I always have links in this one. Is it possible to remove all of the <img> and <a href> tags from my text? <div class="xxx" data-handler="xxx">its a good day <a class=...
How to remove all balise in text python
I want to extract data from a tag to simply retrieve the text. Unfortunately I can't extract just the text, I always have links in this one. Is it possible to remove all of the <img> and <a href> tags from my text? <div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// ...
[ "Try to do this\nimport requests\nfrom bs4 import BeautifulSoup\n\n#response = requests.get('your url')\n\nhtml = BeautifulSoup('''<div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a> \n</div>''', 'html.parser')\n\nsoup = html.find_all(class_='...
[ 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074589261_beautifulsoup_python_python_3.x_web_scraping.txt
Q: pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid (caused by "auth.SignUp") When I want to si...
pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid
pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid (caused by "auth.SignUp") When I want to sign up it says confirmation code is invalid but I didn't even input the confirmation code. I've been searching for a long time and I asked eve...
[ "Take confirmation code as input, then pass it in code.\nclient = Client(f\"sessions/{phone}\", api_id, api_hash)\n\nclient.connect()\n\nsent_code = client.send_code(phone)\n\ncode = input(\"Enter the code : \")\n\nsigned_in = client.sign_in(phone, sent_code.phone_code_hash, code)\n\n" ]
[ 0 ]
[]
[]
[ "pyrogram", "python", "telegram" ]
stackoverflow_0073910395_pyrogram_python_telegram.txt
Q: Selenium python driver doesn't click or press the key for the button all the times I'm using selenium to get to YouTube and write something on the search bar and then press the button or press the enter key. Both clicking or pressing a key does sometimes work, but sometimes it does not. I tried to wait with WebDri...
Selenium python driver doesn't click or press the key for the button all the times
I'm using selenium to get to YouTube and write something on the search bar and then press the button or press the enter key. Both clicking or pressing a key does sometimes work, but sometimes it does not. I tried to wait with WebDriverWait, and I even changed the waiting time from 10 to 20 seconds, but it didn't make a...
[ "To make this working you need to click the search field input first, then add a short delay and then send the Keys.ENTER or click search-icon-legacy element.\nSo, this is not your fault, this is how YouTube webpage works. You may even call it a kind of bug. But since this webpage it built for human users it works ...
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_testing", "webdriverwait" ]
stackoverflow_0074590398_python_selenium_selenium_webdriver_web_testing_webdriverwait.txt
Q: Comparing dictionary of list of dictionary/nested dictionary There are two dict main and input, I want to validate the "input" such that all the keys in the list of dictionary and nested dictionary (if present/all keys are optional) matches that of the main if not the wrong/different key should be returned as the ...
Comparing dictionary of list of dictionary/nested dictionary
There are two dict main and input, I want to validate the "input" such that all the keys in the list of dictionary and nested dictionary (if present/all keys are optional) matches that of the main if not the wrong/different key should be returned as the output. main = "app":[{ "name": str, "info": [ { ...
[ "The schema module does exactly this.\nYou can catch SchemaUnexpectedTypeError to see which data doesn't match your pattern.\nAlso, make sure you don't use the word input as a variable name, as it's the name of a built-in function.\n", "keys = []\ndef print_dict(d):\n if type(d) == dict:\n for val in d....
[ 1, 0, 0 ]
[]
[]
[ "comparison", "dictionary", "list", "python", "recursion" ]
stackoverflow_0074531927_comparison_dictionary_list_python_recursion.txt
Q: How to make an application from two python programs? I have two python programs which one of them connects to a bluetooth device(socket package), it receives and saves data from device, and another one read the stored data and draw a real time plot. I should make one application from these two programs. I tried to...
How to make an application from two python programs?
I have two python programs which one of them connects to a bluetooth device(socket package), it receives and saves data from device, and another one read the stored data and draw a real time plot. I should make one application from these two programs. I tried to mix these two python programs, but since bluetooth should...
[ "Install threaded:\npip install threaded\n\nCreate a new python file:\nfrom threading import Thread\n\ndef runFile1(): import file1\ndef runFile2(): import file2\n\nThread(target=runFile1).start()\nrunFile2()\n\nRun the new python file.\n", "It can be done with threading. To do communication between the threaded...
[ 0, 0 ]
[]
[]
[ "kivy", "multithreading", "python", "sockets" ]
stackoverflow_0074588784_kivy_multithreading_python_sockets.txt
Q: mini-batch gradient descent, loss doesn't improve and accuracy very low I’m trying to implement mini-batch gradient descent on the popular iris dataset, but somehow I don’t manage to get the accuracy of the model above 75-80%. Also the loss does not decrease and is rather stuck at around 0.45, even when I set the ...
mini-batch gradient descent, loss doesn't improve and accuracy very low
I’m trying to implement mini-batch gradient descent on the popular iris dataset, but somehow I don’t manage to get the accuracy of the model above 75-80%. Also the loss does not decrease and is rather stuck at around 0.45, even when I set the number of iterations to 10000. Something im missing here ? class NeuralNetwor...
[ "you didn't provide enough data and code to reproduce the problem. I wrote a complete and working code to train your model on the IRIS dataset.\nImports and Classes.\nimport torch\nfrom torch import nn\nimport pandas as pd\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import train_...
[ 1 ]
[]
[]
[ "gradient", "iris_dataset", "mini_batch", "python", "pytorch" ]
stackoverflow_0074589556_gradient_iris_dataset_mini_batch_python_pytorch.txt
Q: transpose function of numpy I am new to numpy and python and I am trying to understand the usage of transpose function of numpy. The code below works fine but I am still not be able to understand the effect of transpose function and also the use of the arguments inside it. It would be great help if someone can exp...
transpose function of numpy
I am new to numpy and python and I am trying to understand the usage of transpose function of numpy. The code below works fine but I am still not be able to understand the effect of transpose function and also the use of the arguments inside it. It would be great help if someone can explain the usage and effect of tran...
[ "Here's an attempt to visually explain for a 3d-array. I hope it'll help you better understand what's happening:\na=np.arange(24).reshape(2,4,3)\n\n# array([[[ 0, 1, 2],\n# [ 3, 4, 5],\n# [ 6, 7, 8],\n# [ 9, 10, 11]],\n#\n# [[12, 13, 14],\n# [15, 16, 17],\n# [18,...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074586389_numpy_python.txt
Q: Match by "," ",[" or "]," second alternative is not working I have the regex: (?:,)(?![^[]*\])|(?:,\[)(?![^[]*\])|(?:\],)(?![^[]*\]) which is supposed to find all of the , ,[ or ], in a string however the second or statement (?:,\[)(?![^[]*\]) does not work but the other two do. input : file,[test],10,10,[som...
Match by "," ",[" or "]," second alternative is not working
I have the regex: (?:,)(?![^[]*\])|(?:,\[)(?![^[]*\])|(?:\],)(?![^[]*\]) which is supposed to find all of the , ,[ or ], in a string however the second or statement (?:,\[)(?![^[]*\]) does not work but the other two do. input : file,[test],10,10,[something],[something else] desired output: file test 10 10 somethin...
[ "It depends on the order in your pattern. You noticed correctly that the expressions consume the part of the strings that they match and that there exist special expressions to hold them from consuming parts of the string. However, if you use such expression, you might end up with some remaining characters:\nimport...
[ 0 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074366543_python_python_re_regex.txt
Q: How to hide/show password with Custom Tkinter? Can't find any info about how to make password visible or hide with Custom Tkinter. import tkinter as tk import customtkinter def toggle_password(): if txt.cget('show') == '': txt.config(show='*') else: txt.config(show='') root = tk.Tk() root...
How to hide/show password with Custom Tkinter?
Can't find any info about how to make password visible or hide with Custom Tkinter. import tkinter as tk import customtkinter def toggle_password(): if txt.cget('show') == '': txt.config(show='*') else: txt.config(show='') root = tk.Tk() root.geometry("200x200") txt = customtkinter.CTkEntry(r...
[ "The show method isn't directly supported by the CtkEntry widget. You will need to configure the Entry widget that is internal to the CtkEntry widget.\ndef toggle_password():\n if txt.entry.cget('show') == '':\n txt.entry.config(show='*')\n else:\n txt.entry.config(show='')\n\n" ]
[ 0 ]
[]
[]
[ "customtkinter", "passwords", "python", "tkinter" ]
stackoverflow_0074590427_customtkinter_passwords_python_tkinter.txt
Q: python - the scope of variables inside "main" function This is my first post here, so please give me some constructive criticism (not too much). My initial intent was to receive inputs from the user, and save them into variables to later user in other functions (in other modules). This is a simplified version of w...
python - the scope of variables inside "main" function
This is my first post here, so please give me some constructive criticism (not too much). My initial intent was to receive inputs from the user, and save them into variables to later user in other functions (in other modules). This is a simplified version of what i am trying to do: i tried both with and without the "gl...
[ "You need to call the function in order to acces the function value.\ndef main():\n global inputfile\n\n inputfile = \"a\"\n\nif __name__ == \"__main__\":\n main()\n print(inputfile)\n\nGives #\na\n\n" ]
[ 2 ]
[]
[]
[ "defined", "global", "program_entry_point", "python", "scope" ]
stackoverflow_0074590613_defined_global_program_entry_point_python_scope.txt
Q: Parse every element in a Dataframe I have a Dataframe of some 3700 rows. I used if loop and gave my conditions. The code got executed but i'm only getting one element. I want the to check whole Dataframe and print all elements within my conditions. for i in df: i=0 div = "Divergence spotted at " ...
Parse every element in a Dataframe
I have a Dataframe of some 3700 rows. I used if loop and gave my conditions. The code got executed but i'm only getting one element. I want the to check whole Dataframe and print all elements within my conditions. for i in df: i=0 div = "Divergence spotted at " if (df.High[i] < df.High[i+1]) and (d...
[ "You are using break, this stops at the first divergence.\nYou would rather need:\nout = []\nfor i in range(len(df)-1):\n div = \"Divergence spotted at \"\n \n if (df.High[i] < df.High[i+1]) and (df.RSI[i] > df.RSI[i+1]) :\n \n out.append(f'{div}{i}')\n if (df.High[i] > df.High[i+1]) and (...
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "if_statement", "loops", "python" ]
stackoverflow_0074590622_dataframe_for_loop_if_statement_loops_python.txt
Q: Storing parquet file in redis I want to know how I would store a parquet file as it is binary data in redis via python? Background is, that I want check the fastest way of serving a parquet file of small size over the network. I believe object storage like s3 or any file system is slower. So it comes down to the f...
Storing parquet file in redis
I want to know how I would store a parquet file as it is binary data in redis via python? Background is, that I want check the fastest way of serving a parquet file of small size over the network. I believe object storage like s3 or any file system is slower. So it comes down to the fastest way of serving binary data o...
[ "Okay found it myself:\n\nUse python Pandas to write as bytes into memory\nbytes_data = df.to_parquet()\n\nNow having the compressed parquet format as bytes in memory one can send it to redis\nset(\"key\", bytes_data)\n\n\n" ]
[ 0 ]
[]
[]
[ "parquet", "pyarrow", "python", "redis" ]
stackoverflow_0074584407_parquet_pyarrow_python_redis.txt
Q: MultiIndex pandas dataframe and writing to Google Sheets using gspread-pandas Starting with the following dictionary: test_dict = {'header1_1': {'header2_1': {'header3_1': {'header4_1': ['322.5', 330.0, -0.28], 'header4_2': ['322.5', 332.5, -0.26]}, 'header3_2': {'header4_1': ['285.0', 277.5, -0.09], 'h...
MultiIndex pandas dataframe and writing to Google Sheets using gspread-pandas
Starting with the following dictionary: test_dict = {'header1_1': {'header2_1': {'header3_1': {'header4_1': ['322.5', 330.0, -0.28], 'header4_2': ['322.5', 332.5, -0.26]}, 'header3_2': {'header4_1': ['285.0', 277.5, -0.09], 'header4_2': ['287.5', 277.5, -0.12]}}, 'header2_2': {'header3_1': {'header4_1': ['...
[ "Issue #1\nYour columns are numbers (not strings). You can see it by:\nprint(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n\nUse numbers in df.rename() as follows:\ndf = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype=...
[ 1, 0 ]
[]
[]
[ "gspread", "pandas", "python" ]
stackoverflow_0074564252_gspread_pandas_python.txt
Q: How to get partial cumulative sums (of positive and negative numbers) in an array? I have an array with positive and negative numbers and want to do a cumulative sum of numbers of the same sign until the next number carries an opposite sign. It starts again at 0. Maybe better explained with a sample. Here is the o...
How to get partial cumulative sums (of positive and negative numbers) in an array?
I have an array with positive and negative numbers and want to do a cumulative sum of numbers of the same sign until the next number carries an opposite sign. It starts again at 0. Maybe better explained with a sample. Here is the original array: np.array([0.2, 0.5, 1.3, 0.6, -0.3, -1.1, 0.2, -2.0, 0.7, 1.1, 0.0, -1.2]...
[ "One vectorial option:\na = np.array([0.2, 0.5, 1.3, 0.6, -0.3, -1.1, 0.2, -2.0, 0.7, 1.1, 0.0, -1.2])\n\ncs = np.cumsum(a)\nidx = np.nonzero(np.r_[np.diff(a>0), True])\nout = np.zeros_like(a)\n\nout[idx] = np.diff(np.r_[0, cs[idx]])\n\nOutput:\narray([ 0. , 0. , 0. , 2.6, 0. , -1.4, 0.2, -2. , 0. , 1.8, 0....
[ 2 ]
[]
[]
[ "arrays", "cumulative_sum", "numpy", "python", "sum" ]
stackoverflow_0074590529_arrays_cumulative_sum_numpy_python_sum.txt
Q: How can I insert the numbers of the 3D matrix into 2D matrix? Suppose that A is a three-dimensional matrix like the following: A = [np.zeros((3, 8)) for _ in range(20)] and B is a two-dimensional matrix that has 60 rows and 8 columns containing numbers. What should I do if I want to put numbers from matrix B into...
How can I insert the numbers of the 3D matrix into 2D matrix?
Suppose that A is a three-dimensional matrix like the following: A = [np.zeros((3, 8)) for _ in range(20)] and B is a two-dimensional matrix that has 60 rows and 8 columns containing numbers. What should I do if I want to put numbers from matrix B into matrix A and use a loop to write code? A[0][0] = B[0] A[0][1] = B...
[ "I hope I've understood your question right. You can use .flat + indexing:\nA = [np.zeros((3, 8)) for _ in range(20)]\nB = np.arange(60 * 8).reshape(60, 8)\n\nfor i, subl in enumerate(A):\n subl.flat[:] = B.flat[i * 3 * 8 :]\n\nprint(*A, sep=\"\\n\\n\")\n\nPrints:\n[[ 0. 1. 2. 3. 4. 5. 6. 7.]\n [ 8. 9. 1...
[ 0 ]
[]
[]
[ "arrays", "for_loop", "loops", "matrix", "python" ]
stackoverflow_0074588839_arrays_for_loop_loops_matrix_python.txt
Q: Grid from left to right I am having troubles putting a grid of images starting from the top right corner. I am trying to do the Python Crash Course Sideway shooter project, so I tried creating a grid from the top right corner. I can create one column in the top right corner, but when I try to write a code to creat...
Grid from left to right
I am having troubles putting a grid of images starting from the top right corner. I am trying to do the Python Crash Course Sideway shooter project, so I tried creating a grid from the top right corner. I can create one column in the top right corner, but when I try to write a code to create multiple columns going towa...
[ "current_x starts at alien_width. So you need to step the current_x coordinate from left to right. And you have to current_x to new_alien.x and new_alien.rect.x:\nalien_width, alien_height = alien.rect.size\n\n# from left to right\nwhile current_x < self.settings.width - alien_width:\n \n # from top to bottom...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074590634_pygame_python.txt
Q: ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark' I'm trying to run stable diffusion on my local pc. It's a macbook pro m1. Even though I did follow every single step, I keep getting an import error. What might possibly be the reason and how may I fix it? ImportError: cannot import name 'Waterm...
ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark'
I'm trying to run stable diffusion on my local pc. It's a macbook pro m1. Even though I did follow every single step, I keep getting an import error. What might possibly be the reason and how may I fix it? ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark' I was referring an online tutorial so I did ...
[ "If you look in the txt2img.py script it references https://github.com/ShieldMnt/invisible-watermark\nInstall with pip install invisible-watermark\n", "It seems they forgot to add it into requirements.txt or smt like that.\nIf you continue getting the error after invisible-watermark installation, change the line ...
[ 1, 0 ]
[]
[]
[ "importerror", "python", "python_import", "stable_diffusion", "watermark" ]
stackoverflow_0074524544_importerror_python_python_import_stable_diffusion_watermark.txt
Q: Scipy linear programming doesn't give the correct answer I am trying to solve the following problem using Scipy. However, it doesn't produce the correct result. r is the only decision variable that we have. Since the equation (2) doesn't follow the Scipy's required format of Ab <= ub I modified to the following f...
Scipy linear programming doesn't give the correct answer
I am trying to solve the following problem using Scipy. However, it doesn't produce the correct result. r is the only decision variable that we have. Since the equation (2) doesn't follow the Scipy's required format of Ab <= ub I modified to the following form. Following is my implemented code: # Objective function d...
[ "Your problem does not have a unique solution. Both the Scipy and CPLEX solutions are equivalent in that they have the same OF value. Here's a verification:\nS_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, ...
[ 1, 0 ]
[]
[]
[ "linear_programming", "python", "scipy" ]
stackoverflow_0074585512_linear_programming_python_scipy.txt
Q: Trying to add a progress bar as my python program runs I am a beginner writing a Python code, where the computer generates a random number between 1 and 10, 1 and 100, 1 and 1000, 1 and 10000, 1 and 100000 and so on. The computer itself will guess the random number a number of times (a user input number), and ever...
Trying to add a progress bar as my python program runs
I am a beginner writing a Python code, where the computer generates a random number between 1 and 10, 1 and 100, 1 and 1000, 1 and 10000, 1 and 100000 and so on. The computer itself will guess the random number a number of times (a user input number), and every time there is a count of how many times the computer took ...
[ "You can define the following progress_bar function, which you will call from wherever you want to monitor the advancement in you code:\nimport colorama\ndef progress_bar(progress, total, color=colorama.Fore.YELLOW):\n percent = 100 * (progress / float(total))\n bar = '█' * int(percent) + '-' * (100 - int(per...
[ 0, 0, 0 ]
[]
[]
[ "for_loop", "progress_bar", "python" ]
stackoverflow_0074536225_for_loop_progress_bar_python.txt
Q: How do I use nested lists properly in that context I need to create a memory game in Python. I need to print a 5x4 (4 rows, 5 elements in a line) field in the console and the fields should have names like a1, b1, c1... in the next row a2, b2, c2 etc. We've already got a list of symbols, which should be used in the...
How do I use nested lists properly in that context
I need to create a memory game in Python. I need to print a 5x4 (4 rows, 5 elements in a line) field in the console and the fields should have names like a1, b1, c1... in the next row a2, b2, c2 etc. We've already got a list of symbols, which should be used in the game (list1). One of the instructions we have is to cre...
[ "Instead of using fields, translate the reference to two indices; one for the row, the other the column. Your nested list appears to use a list of rows, and each nested list is a list of cards at each column. It could be that your nested list actually encodes columns and that each nested list holds cards at each r...
[ 2, 1 ]
[]
[]
[ "function", "nested_lists", "printing", "python" ]
stackoverflow_0074590616_function_nested_lists_printing_python.txt
Q: how to enter elements using "input" EDIT: Command lista = [int(i) for i in input("Podaj Liczby: ").split(",")] still doesn't sort. When I try to enter numbers, it does not sort them for me Even if i use "," still doesn't sort. Here's code: lista = [int(i) for i in input("Podaj Liczby: ").split(",")] def sortowani...
how to enter elements using "input"
EDIT: Command lista = [int(i) for i in input("Podaj Liczby: ").split(",")] still doesn't sort. When I try to enter numbers, it does not sort them for me Even if i use "," still doesn't sort. Here's code: lista = [int(i) for i in input("Podaj Liczby: ").split(",")] def sortowaniebabelkowe(): n = len(lista) zm...
[ "i think you have to use\nlista[l],lista[l+1]=lista[l+1],lista[l]\n\ninsead of\nlista[l],lista[l+1]==lista[l+1],lista[l]\n\nto swap the values.\n", "I modified above code in to this form\nlista = [int(i) for i in input(\"Podaj Liczby: \").split(\",\")]\ndef sortowaniebabelkowe():\n n = len(lista)\n while ...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.11" ]
stackoverflow_0074590255_python_python_3.11.txt
Q: Recursively generate LaTeX expression for continued fractions for a given python list I am trying to generate LaTeX string expression for continued fractions in Jupyter Notebook. for example, a given Python list x=[1,2,3,4,5] can be written as continued fraction: Structure expression to generate this LaTeX fracti...
Recursively generate LaTeX expression for continued fractions for a given python list
I am trying to generate LaTeX string expression for continued fractions in Jupyter Notebook. for example, a given Python list x=[1,2,3,4,5] can be written as continued fraction: Structure expression to generate this LaTeX fraction is \\frac{Numerator}{Denominator} With Non-recursive code : from IPython.display import ...
[ "We can define the function nest_frac_N taking x as an additional argument:\ndef nest_frac_N(previous_expr, numerator_expr1, denominator_expr2, x):\n \n temp_frac=str(x[len(x)-1]-1) +\"+ \\\\frac{\"+str(numerator_expr1)+\"}{\"+str(x[len(x)-1])+\"}\"\n \n for i in reversed(x[:len(x)-2]):\n \n ...
[ 0 ]
[]
[]
[ "continued_fractions", "jupyter_notebook", "latex", "mathjax", "python" ]
stackoverflow_0074590234_continued_fractions_jupyter_notebook_latex_mathjax_python.txt
Q: how to return value inside a dictionary which is changed by a radio button I created a dictionary with two keys, when selecting one of the keys, the dictionary items are updated, the problem is that I am not returning the selected value within the updated list. for example, when selecting 'male', and then 'Execute...
how to return value inside a dictionary which is changed by a radio button
I created a dictionary with two keys, when selecting one of the keys, the dictionary items are updated, the problem is that I am not returning the selected value within the updated list. for example, when selecting 'male', and then 'Executed', I would like to receive 'Executed' as a value import PySimpleGUI as sg gene...
[ "There's programming logic issue in the event loop, it will be better for all the cases starts with the event decision, not the value(s) decision. In your code, the case for the event GENERATE will be never executed after any one of the Radio element clicked.\nimport PySimpleGUI as sg\n\ngenero = {\n 'male': ['R...
[ 0 ]
[]
[]
[ "dictionary", "pysimplegui", "python" ]
stackoverflow_0074589814_dictionary_pysimplegui_python.txt
Q: Calculate a date difference between two dates in a series of a dataframe by ID? Sorry if my question is simple i'm starting(so thank you for your help and understanding) I am trying to get a date discrepancy by 'identifier' A B C D in the DF example. Using Python how can i add a column to establish the delta betw...
Calculate a date difference between two dates in a series of a dataframe by ID?
Sorry if my question is simple i'm starting(so thank you for your help and understanding) I am trying to get a date discrepancy by 'identifier' A B C D in the DF example. Using Python how can i add a column to establish the delta between each contract knowing that a person can have only one contract as he can have 10 ...
[ "You mean something like:\ndf['new_col'] = df['header1'] - df['header2']\n\nFor timedeltas use:\nimport numpy as np\ndf['diff_days'] = (df['end_date'] - df['start_date']) / np.timedelta64(1, 'D')\n\nD stands for timediffernce in days. Use \"W\", \"M\", \"Y\" for weeks, months or years.\n" ]
[ 0 ]
[]
[]
[ "dataiku", "python", "timedelta" ]
stackoverflow_0074590883_dataiku_python_timedelta.txt
Q: Python: How to specify type hints of a function that returns an attribute of a class with generic types? import typing as typ T = typ.TypeVar("T") class Foo(typ.Generic[T]): """The generic class.""" def __init__(self, var: T): self.var = var def var_getter(foo_obj: ??) -> ??: """Var getter."...
Python: How to specify type hints of a function that returns an attribute of a class with generic types?
import typing as typ T = typ.TypeVar("T") class Foo(typ.Generic[T]): """The generic class.""" def __init__(self, var: T): self.var = var def var_getter(foo_obj: ??) -> ??: """Var getter.""" return foo_obj.var These are the test cases that should be satisfied: class Bar(Foo[str]): pass ...
[ "from typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\nclass Foo(Generic[T]):\n var: T\n\n def __init__(self, var: T):\n self.var = var\n\nclass Bar(Foo[str]):\n pass\n\nclass Baz(Foo[int]):\n pass\n\ndef var_getter(foo_obj: Foo[T]) -> T:\n return foo_obj.var\n\nreveal_type(var_getter(B...
[ 1 ]
[]
[]
[ "python", "type_hinting" ]
stackoverflow_0074590269_python_type_hinting.txt
Q: How can I return a context from views.py in different html files in Django? So, I have a method called 'room' in my views.py file. I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well. How can I do that? Views.py def room(request): ...
How can I return a context from views.py in different html files in Django?
So, I have a method called 'room' in my views.py file. I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well. How can I do that? Views.py def room(request): rooms = Rooms.objects.all() photos = RoomImage.objects.all() context = ...
[ "\nI can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well.\n\nJust pass Rooms.objects.all() also in that view which renders the index.html template.\nBelow is an example.\ndef index(request):\n rooms = Rooms.objects.all()\n photos ...
[ 2, 2 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0074589771_django_django_templates_django_views_python.txt
Q: How can I automatically detect if a colum is categorical? I want to find a category of a pandas column. I can get the type but I'm struggling to figure out categories. titanic_df = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv') #ID datatype def idDataTypes(inputDataFrame): ...
How can I automatically detect if a colum is categorical?
I want to find a category of a pandas column. I can get the type but I'm struggling to figure out categories. titanic_df = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv') #ID datatype def idDataTypes(inputDataFrame): columnTypesDict = {} import numpy as np import numbe...
[ "Here's the bug in your code:\nproposedCategory = list(set(cols) - set(num_cols))\n\nEverything other than the numeric columns are to become categories.\n\nThere is no right way to do this either, since whether a column is categorical is best decided manually with knowledge of the data the column contains. You are ...
[ 1, 0 ]
[]
[]
[ "algorithm", "pandas", "python" ]
stackoverflow_0059384802_algorithm_pandas_python.txt
Q: Disable Tensorflow debugging information By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not Python errors. I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally I tensorflow/stream_executor/dso_loade...
Disable Tensorflow debugging information
By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not Python errors. I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library lib...
[ "You can disable all debugging logs using os.environ :\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nimport tensorflow as tf\n\nTested on tf 0.12 and 1.0\nIn details, \n0 = all messages are logged (default behavior)\n1 = INFO messages are not printed\n2 = INFO and WARNING messages are not printed\n3 = INFO...
[ 386, 235, 55, 20, 13, 12, 11, 11, 6, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0035911252_python_tensorflow.txt
Q: Copying only non-relation attributes django/python I am copying a model object to another, but I want that it doesn’t copy the relations For example, assume you have a model like this: class Dish(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) categ...
Copying only non-relation attributes django/python
I am copying a model object to another, but I want that it doesn’t copy the relations For example, assume you have a model like this: class Dish(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) category = models.ForeignKey(Category, on_delete=models.CASCA...
[ "I assume in your serializer you don't want to explicitly define which field to serialize. Otherwise you could do the following:\nclass Dish_Serializer(serializers.ModelSerializer):\n class Meta:\n model = Dish\n fields = ['id','name', 'description']\n\nYou probably can define these fields dynamica...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_serializer", "python" ]
stackoverflow_0074590516_django_django_models_django_rest_framework_django_serializer_python.txt
Q: how to download youtube video in the highest quality available This code works perfectly, but I don't want the lowest quality. I want the highest one. When I tried changing the video = youtube. streams.first() to video = youtube.streams.last() I encountered a problem where the video that I downloaded was just a bl...
how to download youtube video in the highest quality available
This code works perfectly, but I don't want the lowest quality. I want the highest one. When I tried changing the video = youtube. streams.first() to video = youtube.streams.last() I encountered a problem where the video that I downloaded was just a black screen with the audio playing in the background. from tkinter im...
[ "Try To Use\n\nget_highest_resolution()\n\nInstant Of Contact With Streams\nThis Func. Returns Highest Progressive Quality : )\nMay Be Checking The Documentation Will Help You Next Time : )\n", "There are two types of streams\n1- Dynamic Adaptive Streaming over HTTP (DASH): save audio and video on the different t...
[ 2, 0, 0 ]
[]
[]
[ "python", "python_3.x", "pytube", "youtube" ]
stackoverflow_0065802599_python_python_3.x_pytube_youtube.txt
Q: How to find stat (min, max, quantile, etc) of a list without using pandas.series? I have a variable list of elements. I want to be able to find, count mean std min 25% 50% 75% max . I know I can use pandas.Series.describe(). However, I have a restriction that I cannot use pandas for the specific problem. Is there ...
How to find stat (min, max, quantile, etc) of a list without using pandas.series?
I have a variable list of elements. I want to be able to find, count mean std min 25% 50% 75% max . I know I can use pandas.Series.describe(). However, I have a restriction that I cannot use pandas for the specific problem. Is there any built in function/package that will give me the same output? Thanks.
[ "As mentioned in the comments count, min, and max are all built in so you can simply call count(your_list), max(your_list), min(your_list).\nI would recommend using libraries such as Pandas, Numpy etc. if you can. If you are restricted only to the standard library you can also take a look at the statistics module.\...
[ 3 ]
[]
[]
[ "max", "min", "percentile", "python", "stat" ]
stackoverflow_0074590410_max_min_percentile_python_stat.txt
Q: is there a better way to get the data form beautiful soup query? I am trying to extract the m/z data for different ions from "https://www.lipidmaps.org/databases/lmsd/LMFA08040013". I can get access to the ions and thier data, however to extract the formula and m/z, I am thinking to convert it to a string and the ...
is there a better way to get the data form beautiful soup query?
I am trying to extract the m/z data for different ions from "https://www.lipidmaps.org/databases/lmsd/LMFA08040013". I can get access to the ions and thier data, however to extract the formula and m/z, I am thinking to convert it to a string and the use striping tool to extract it. Is thier another way using beautifuls...
[ "Not sure what you mean by more elegant but if all you want is the first option with the given ion value you can get the output you want this way:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.lipidmaps.org/databases/lmsd/LMFA08040013\"\nsoup = (\n BeautifulSoup(requests.get(url).text, \...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074590759_beautifulsoup_python.txt
Q: How to separate elements of a line having multiple delimiters via Python? date Mon Jan 4 15:59:21.129 2021 base hex timestamps absolute no internal events logged // version 13.0.0 //545285.973861 previous log file: Myfile_0.asc // Measurement UUID: 4520e127-a0b6-48d2-9e23-2588160af285 545333.620639 LoggingS...
How to separate elements of a line having multiple delimiters via Python?
date Mon Jan 4 15:59:21.129 2021 base hex timestamps absolute no internal events logged // version 13.0.0 //545285.973861 previous log file: Myfile_0.asc // Measurement UUID: 4520e127-a0b6-48d2-9e23-2588160af285 545333.620639 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:17.4,34.72,12,0.01058,11...
[ "I hope I've understood your question well. You can check if there's LoggingString := inside the line and if is, split the string:\nimport pandas as pd\n\nout = []\nwith open(\"your_file.txt\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if \"LoggingString :=\" in line:\n first_quote ...
[ 1 ]
[]
[]
[ "arrays", "export_to_csv", "file", "numpy", "python" ]
stackoverflow_0074589537_arrays_export_to_csv_file_numpy_python.txt
Q: How to get the value of a selected treeview item? I've looked at several posts regarding this and they've done the following -The output i get is blank -The output i get is the id, which is practically useless unless somebody can show me how to manipulate it -No output at all i just want to be able to click an ite...
How to get the value of a selected treeview item?
I've looked at several posts regarding this and they've done the following -The output i get is blank -The output i get is the id, which is practically useless unless somebody can show me how to manipulate it -No output at all i just want to be able to click an item in treeview, and instantly be given the text i just c...
[ "You can get a list of the selected items with the selection method of the widget. It will return a list of item ids. You can use the item method to get information about each item.\nFor example:\nimport tkinter as tk\nfrom tkinter import ttk\n\nclass App:\n def __init__(self):\n self.root = tk.Tk()\n ...
[ 12, 0, 0 ]
[]
[]
[ "python", "python_2.7", "python_3.x", "tkinter", "treeview" ]
stackoverflow_0034849035_python_python_2.7_python_3.x_tkinter_treeview.txt
Q: Shipping Python interpreter with C++ project Problem description: I have a Visual Studio 2022 C++ project that involves live python script interpretation. Naturally, I need a valid Python installation to do this. However, I intend to ship this as an application, so I'd like to have a localized Python installation,...
Shipping Python interpreter with C++ project
Problem description: I have a Visual Studio 2022 C++ project that involves live python script interpretation. Naturally, I need a valid Python installation to do this. However, I intend to ship this as an application, so I'd like to have a localized Python installation, to avoid consumer-side installation, but that doe...
[ "To embed python into your application, you need two things:\nInitialize isolated python\nThis will not let user's system interfere with your app.\nhttps://docs.python.org/3/c-api/init_config.html#init-isolated-conf\nDeploy python stuff with your application\nOn windows, you need:\n\nPython DLL (python311.dll).\nPy...
[ 1 ]
[]
[]
[ "c++", "python", "python_install", "visual_studio_2022" ]
stackoverflow_0074590755_c++_python_python_install_visual_studio_2022.txt
Q: AttributeError: 'Player' object has no attribute 'pos' I'm following a tutorial on youtube on how to make a doom type game in python. And I'm at a point where finished Raycasting and implementing 3D environment. But when I wanted to test the progress an attribute error occurred. Here is the terminals response: Fil...
AttributeError: 'Player' object has no attribute 'pos'
I'm following a tutorial on youtube on how to make a doom type game in python. And I'm at a point where finished Raycasting and implementing 3D environment. But when I wanted to test the progress an attribute error occurred. Here is the terminals response: File "d:\School Documents\SMGS\PDM\PyDom\raycasting.py", line 1...
[ "You need to indent the pos and map_pos properties, which are currently just dangling functions on the module - not a part of the Player class.\nclass Player:\n @property\n def pos(self):\n return self.x, self.y\n\n @property\n def map_pos(self):\n return int(self.x), int(self.y)\n \n ...
[ 0 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0074591155_attributeerror_python.txt
Q: Checking if certain phrases are on a website with python I've written a function that is ment to check if a phrase is in a certain website, however, it is always telling me that it isn't in the website even when it is. I'm relativly new to webscraping so any help would be appreciated. def check_availability(url,ph...
Checking if certain phrases are on a website with python
I've written a function that is ment to check if a phrase is in a certain website, however, it is always telling me that it isn't in the website even when it is. I'm relativly new to webscraping so any help would be appreciated. def check_availability(url,phrase): global log try: # page = urllib.request...
[ "Modified function:\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef url_contains(url, phrase):\n soup = BeautifulSoup(requests.get(url).content, 'html.parser')\n return phrase in soup.get_text()\n\nExample:\nurl = 'https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss'\n\n>>> url_contains(url, 'Princeps m...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074590288_python_web_scraping.txt
Q: if-else statement not working correctly in python for loop I have a block of code that I am iterating through a dictionary looking for keywords found and the number of times each is found. The if statement works and returns the expected output if keywords are found. However, the else statement is not working when ...
if-else statement not working correctly in python for loop
I have a block of code that I am iterating through a dictionary looking for keywords found and the number of times each is found. The if statement works and returns the expected output if keywords are found. However, the else statement is not working when no keywords are found it should return "No keywords found". This...
[ " for key in kw_found.keys():\n\nThe above line will go through each element of kw_found.keys(), binding them to key.\n if key in kw_found.keys():\n\nThis asks if the thing we're looking at from kw_found.keys() is in kw_found.keys() - which, yes, it is.\n width = max(len(x) for x in key)\n ...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "if_statement", "python" ]
stackoverflow_0074553450_dictionary_if_statement_python.txt
Q: Python function for taking formatted input from user similar to scanf() in 'C' I was wondering if there is a function in Python to take formatted input from user similar to taking the input from user in 'C' using scanf() and format strings such as %d, %lf, etc. Hypothetical example in which scanf() returns a list:...
Python function for taking formatted input from user similar to scanf() in 'C'
I was wondering if there is a function in Python to take formatted input from user similar to taking the input from user in 'C' using scanf() and format strings such as %d, %lf, etc. Hypothetical example in which scanf() returns a list: input_date_list = scanf("%d-%d-%d") # User enters "1969-04-20" input_time_list = sc...
[ "What the Standard Library provides\nThere is no direct scanf(3) equivalent in the standard library. The documentation for the re module suggests itself as a replacement, providing this explanation:\n\nPython does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though a...
[ 2, 1, 1 ]
[ "in Python 2, you can use input() or raw_input()\ns = input() // gets int value \n\nk = raw_input() // gets string value\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0041725535_python.txt
Q: How to concatenate multiple json as dict in pandas? I have two json files that I would like to concatenate into one. Is there any approach to combine these json? json1 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 }...
How to concatenate multiple json as dict in pandas?
I have two json files that I would like to concatenate into one. Is there any approach to combine these json? json1 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 }, "105911": { "name": "Avatar - Yotian Frontliner",...
[ "Try:\nimport pandas as pd\n\njson1 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05,\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"...
[ 2, 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074590923_json_pandas_python.txt
Q: Changing the value of values after a particular index along one axis in a 3D numpy array I have a 3d array of format given below. The below is the one sample of the 3D array, like it , it contain more than 1000. sample shape of the 3D array is (1000 x 10 x 5) The image contain one element (10 x 5) I want to change...
Changing the value of values after a particular index along one axis in a 3D numpy array
I have a 3d array of format given below. The below is the one sample of the 3D array, like it , it contain more than 1000. sample shape of the 3D array is (1000 x 10 x 5) The image contain one element (10 x 5) I want to change the value to 0 after the 3rd one on the last value check the figure below desired I want to c...
[ "import numpy as np\n\n# Your array here:\narr = np.arange(50000).reshape(1000, 10, 5)\n\n# Solution:\narr[:, 3:, -1] = 0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "multidimensional_array", "numpy", "python", "vectorization" ]
stackoverflow_0074591237_dataframe_multidimensional_array_numpy_python_vectorization.txt
Q: Numpy Sort 3D Array of Coordinates I got a 3D array of rects' coordinates from CRAFT text detector that looks like this. arr = np.array( [ [ [13.715625, 149.62498], [68.99374, 149.62498], [68.99374, 162.50937], [13.715625, 162.50937], ], [...
Numpy Sort 3D Array of Coordinates
I got a 3D array of rects' coordinates from CRAFT text detector that looks like this. arr = np.array( [ [ [13.715625, 149.62498], [68.99374, 149.62498], [68.99374, 162.50937], [13.715625, 162.50937], ], [ [22.44375, 96.84062], ...
[ "\nwhich means that we sort the texts by using the y coordinate of the\ntop-left point of each rect's and only sort by x if there are same y\ncoordinates?\n\nWouldn't the following give you the desired result?\n arr = sorted(arr, key=lambda x: (x[0][1], x[0][0]))\n\nThen you can add arr = np.array(arr) to get a num...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074591019_numpy_python.txt
Q: Extracting from List What I have coded students = ['Rose', 'Dorothy', 'Sophia', 'Blanch'] for i in range(len(students)): print('Hey',students[i],',please input the folowing grades:') weightAvg = [] discussionGrade = int(input('What was your discussion grade?: ')) # prompt grade 1 quizGrade = int(i...
Extracting from List
What I have coded students = ['Rose', 'Dorothy', 'Sophia', 'Blanch'] for i in range(len(students)): print('Hey',students[i],',please input the folowing grades:') weightAvg = [] discussionGrade = int(input('What was your discussion grade?: ')) # prompt grade 1 quizGrade = int(input('What was your quiz g...
[ "You need to store the averages outside the loop, to be able to have all of them once ended\nPut the pairs (avg, student) in the loop, and at the end use max function, as we put the average value in the tuple, the items will be compared by that, if we had add (student, avg), we would have had the max in term of lex...
[ 2 ]
[]
[]
[ "function", "indexing", "list", "python", "weighted_average" ]
stackoverflow_0074591222_function_indexing_list_python_weighted_average.txt
Q: BeautifulSoup select_all does not work with data-testid attribute I am trying to scrape the current prices from the search result page of Booking.com such as: https://www.booking.com/searchresults.ja.html?lang=ja&dest_id=6411914&dest_type=hotel&checkin=2022-12-22&checkout=2022-12-23&group_adults=4&no_rooms=1&group...
BeautifulSoup select_all does not work with data-testid attribute
I am trying to scrape the current prices from the search result page of Booking.com such as: https://www.booking.com/searchresults.ja.html?lang=ja&dest_id=6411914&dest_type=hotel&checkin=2022-12-22&checkout=2022-12-23&group_adults=4&no_rooms=1&group_children=0&sb_travel_purpose=leisure As you can see, each property's i...
[ "The tag that you are looking for isn't in the soup object.\nHere is the soup for the first hotel from your URL, which is Cup of Tea Ensemble\n<div class=\"bui-carousel__item\" data-bui-ref=\"carousel-item\" data-lp-ga-click=\"hotel-group-3:click:4\">\n <div class=\"hotel-card__default bui-card bui-card--m...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074591178_beautifulsoup_python.txt
Q: Commas between numbers in Python or Django hi this is my code for Percentage for the price of a product: def get_discounted_malile_price(self): result = int(self.price - (self.price * (self.discount / 100))) round_result = round(result, 3) return round_result and this is my result: i have add , for r...
Commas between numbers in Python or Django
hi this is my code for Percentage for the price of a product: def get_discounted_malile_price(self): result = int(self.price - (self.price * (self.discount / 100))) round_result = round(result, 3) return round_result and this is my result: i have add , for result number ,for example(1936000 -> 193.600.0) ...
[ "Are you looking for this? https://stackoverflow.com/a/10742904/17320013\nvalue = 123456789\nprint(f'{value:,}') # 123,456,789\n\nIf yes, your code should be\ndef get_discounted_malile_price(self) -> str:\n result = int(self.price - (self.price * (self.discount / 100)))\n round_result = f'{round(result, 3):,}...
[ 0 ]
[]
[]
[ "python", "web" ]
stackoverflow_0074591105_python_web.txt
Q: Changing the colour of tkinter menubar I have the following code, what I'm trying to do is change the color the the menubar to be the same as my window. I have tried what you see below, adding to bg="#20232A" to menubar but this seems to have no affect.. My Question: The below image is the window (albeit a snippe...
Changing the colour of tkinter menubar
I have the following code, what I'm trying to do is change the color the the menubar to be the same as my window. I have tried what you see below, adding to bg="#20232A" to menubar but this seems to have no affect.. My Question: The below image is the window (albeit a snippet of the window), it showcases both the menu...
[ "You cannot change the color of the menubar on Windows or OSX. It might be possible on some window managers on linux, though I don't know for certain. \nThe reason is that the menubar is drawn using native widgets that aren't managed by tkinter, so you're limited to what the platform allows. \n", "On Linux it is ...
[ 9, 2, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0049088785_python_tkinter.txt
Q: How to scrap publication date from news? I have a scraper of headlines, but I want a publication date also. That's my code: news = [] url = 1 while url != 100: website = f"https://www.newscientist.com/subject/space/page/{url}" r = requests.get( website, headers={ "User-Agent":...
How to scrap publication date from news?
I have a scraper of headlines, but I want a publication date also. That's my code: news = [] url = 1 while url != 100: website = f"https://www.newscientist.com/subject/space/page/{url}" r = requests.get( website, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv...
[ "There are different options, simplest one in my opinion is to uses their RSS-Feed:\nimport pandas as pd\npd.read_xml('https://www.newscientist.com/subject/space/feed/', xpath='*/item')\n\n\n\n\n\n\ntitle\nlink\npubDate\ndescription\nguid\n{http://search.yahoo.com/mrss/}thumbnail\n\n\n\n\n0\nBluewalker 3 satellite ...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074590801_beautifulsoup_python_web_scraping.txt
Q: How to draw grid lines behind matplotlib bar graph x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue') plt.xticks(range(len(y)), x, size='small') plt.savefig('/home/user/graphimages/foo2.png') plt.clo...
How to draw grid lines behind matplotlib bar graph
x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue') plt.xticks(range(len(y)), x, size='small') plt.savefig('/home/user/graphimages/foo2.png') plt.close() I want to draw grid lines (of x & y) behind the ba...
[ "To add a grid you simply need to add\nax.grid()\nIf you want the grid to be behind the bars then add \nax.grid(zorder=0)\nax.bar(range(len(y)), y, width=0.3, align='center', color='skyblue', zorder=3)\n\nThe important part is that the zorder of the bars is greater than grid. Experimenting it seems zorder=3 is the ...
[ 113, 15, 1, 0 ]
[ "ax.grid(zorder=0) Woud work. But First Place the Bar and then Place the Grid.Not the orther way.\nax = df.plot.bar(x='Index', y='Values', rot=90)\nax.grid(zorder=0)\n\nI took some currency Correlation with Year and Sorted it as my Data Frame df, and below is the result of the code run. \n\n" ]
[ -2 ]
[ "matplotlib", "python" ]
stackoverflow_0023357798_matplotlib_python.txt
Q: Rendering issues in FrozenLake-v1 environment I am using the FrozenLake-v1 gym environment for testing q-table algorithms. When I use the default map size 4x4 and call the env.render() function, I see the image as shown: [] But when I call the same env.render() function for map size 8x8, I see no such results! The...
Rendering issues in FrozenLake-v1 environment
I am using the FrozenLake-v1 gym environment for testing q-table algorithms. When I use the default map size 4x4 and call the env.render() function, I see the image as shown: [] But when I call the same env.render() function for map size 8x8, I see no such results! The code runs fine with no error message, but the rend...
[ "Ran into the same problem. I was able to fix it by passing in render_mode=\"human\". For example\nenv = gym.make(\"FrozenLake-v1\", map_name=\"8x8\", render_mode=\"human\")\n\nThis worked on my own custom maps in addition to the built in ones.\n" ]
[ 0 ]
[]
[]
[ "openai", "openai_gym", "python", "render" ]
stackoverflow_0071334309_openai_openai_gym_python_render.txt
Q: Sort with custom function I can sort a 2D-array in Javascript like the following: const a = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]] a.sort((a,b) => { if (a[0] != b[0]) { return a[0] - b[0] } else { return b[1] - a[1] * 2 + 3 } }) How to perform the same task in Python? A: ...
Sort with custom function
I can sort a 2D-array in Javascript like the following: const a = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]] a.sort((a,b) => { if (a[0] != b[0]) { return a[0] - b[0] } else { return b[1] - a[1] * 2 + 3 } }) How to perform the same task in Python?
[ "x = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]]\n>>> sorted(x)\n[[-25, 1], [-1, 5], [3, 2], [12, 1], [12, 3]]\n\nIf you wanted to customize the order, e.g. order by b, a (for each [a, b] sublist):\n>>> sorted(x, key=lambda ab: ab[::-1])\n[[-25, 1], [12, 1], [3, 2], [12, 3], [-1, 5]]\n\nHowever, in your JavaScrip...
[ 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0074591136_python_sorting.txt
Q: how to check if a number is a power of base b? In python, how can you check if a number n is an exact power of base b? Note: it needs to be generalized to any base which is given as a parameter. Here is what I got: Assume n and base are integers > 0. import math def is_power(n,base): return math.log(n,base) ==...
how to check if a number is a power of base b?
In python, how can you check if a number n is an exact power of base b? Note: it needs to be generalized to any base which is given as a parameter. Here is what I got: Assume n and base are integers > 0. import math def is_power(n,base): return math.log(n,base) == base**n
[ "First, assuming you have a specific logarithm operator (many languages provide logarithms to base 10 or base e only), logab can be calculated as logxb / logxa (where x is obviously a base that your language provides).\nPython goes one better since it can work out the logarithm for an arbitrary base without that tr...
[ 10, 5, 0, 0 ]
[ ">>>(math.log(int(num),int(base))).is_integer()\nThis will return a boolean value either true or false. This should work fine. Hope it helps\n" ]
[ -1 ]
[ "logarithm", "python" ]
stackoverflow_0015352593_logarithm_python.txt
Q: How to specify a directory for "spark.sparkContext.textFile()"? I have downloaded the following code rating.py to see if my Spark working correctly. from pyspark import SparkConf, SparkContext import collections conf = SparkConf().setMaster("local").setAppName("RatingsHistogram") sc = SparkContext(conf = conf) l...
How to specify a directory for "spark.sparkContext.textFile()"?
I have downloaded the following code rating.py to see if my Spark working correctly. from pyspark import SparkConf, SparkContext import collections conf = SparkConf().setMaster("local").setAppName("RatingsHistogram") sc = SparkContext(conf = conf) lines = sc.textFile("file:///SparkCourse/ml-100k/u.data") ratings = li...
[ "In windows you have to escape \"\\\"\nTry:\nlines = sc.textFile(\"C:\\\\SparkCourse\\\\ml-100k\\\\u.data\")\n\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "directory", "pyspark", "python", "windows_10" ]
stackoverflow_0074576551_apache_spark_directory_pyspark_python_windows_10.txt
Q: if else condition in pandas with multiple column as arguements I have a df like so: import pandas as pd df = pd.DataFrame({"code": [sp,wh,sp], "qty": [20, 30, 10]}) I want to create a new column based on data from the two columns with the value the new column as the same as an existing column if a condition is me...
if else condition in pandas with multiple column as arguements
I have a df like so: import pandas as pd df = pd.DataFrame({"code": [sp,wh,sp], "qty": [20, 30, 10]}) I want to create a new column based on data from the two columns with the value the new column as the same as an existing column if a condition is met. This is what I’ve tried: df['out'] = df.apply(lambda x: x['qty'])...
[ "You can use numpy's where:\nimport numpy as np\ndf['out'] = np.where(df['code']=='sp', df['qty'], 0)\n\n", "here is one way to do it using mask\n# mask the qty as zero when code is not 'sp'\n\ndf['out']=df['qty'].mask(df['code'].ne('sp'), 0)\ndf\n\ncode qty out\n0 sp 20 20\n1 wh 30 0\n2 sp 10 ...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074591165_dataframe_pandas_python.txt
Q: How to move all items one item forward in a list I'm trying to do the following (consider this list): ['Hello, 'Hi', 'Nice', Cool'] I would like to change 'Hi' to 'Love' But, I wouldn't want it to stay that way: ['Hello, 'Love', 'Nice', Cool'] I'm trying to get ahead of the others, even cropping the last one, ge...
How to move all items one item forward in a list
I'm trying to do the following (consider this list): ['Hello, 'Hi', 'Nice', Cool'] I would like to change 'Hi' to 'Love' But, I wouldn't want it to stay that way: ['Hello, 'Love', 'Nice', Cool'] I'm trying to get ahead of the others, even cropping the last one, getting like this: ['Hello, 'Love', 'Hi', Nice'] Note t...
[ "old_list = ['Hello', 'Hi', 'Nice', 'Cool']\nnew_item_index = 1\nnew_item = 'Love'\n\nnew_list = old_list[0:new_item_index] + [new_item] + old_list[new_item_index+1:]\nprint(old_list)\nprint(new_list)\n\n['Hello', 'Hi', 'Nice', 'Cool']\n['Hello', 'Love', 'Hi', 'Nice']\n\n", "You can insert the item into the desir...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074591309_list_python.txt
Q: For loop using Pandas dataframe to predict price doesn't append I'm currently using a TensorFlow model that I've made to predict the X next prices for a curve using a for loop that calls the append() fonction of the pandas dataframe. The model is a time series one so at each loop I calculate the "next date" uing t...
For loop using Pandas dataframe to predict price doesn't append
I'm currently using a TensorFlow model that I've made to predict the X next prices for a curve using a for loop that calls the append() fonction of the pandas dataframe. The model is a time series one so at each loop I calculate the "next date" uing the last dataframe row and I calculate the predicted price using the l...
[ "Try changing:\nlast_data.append([nextdate, pred_price])\n\nto:\nlast_data = last_data.append([nextdate, pred_price])\n\nor:\nlast_data = pd.concat([nextdate, pred_price])\n\n", "Thank you a lot @9769953 !\nThe append fonction didn't worked as the list.append() fonction from Python as he said, the solution was as...
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "tensorflow" ]
stackoverflow_0074590893_dataframe_jupyter_notebook_pandas_python_tensorflow.txt
Q: How to correct the count number after groupby? I am trying to get a dataframe which has Date and Section to count the items in each Section per hour. I use the following: new_df = df.groupby([pd.Grouper(key='Date',freq='H'),'Section']).agg(PPT=('Section','count')).reset_index() The problem is that the count does ...
How to correct the count number after groupby?
I am trying to get a dataframe which has Date and Section to count the items in each Section per hour. I use the following: new_df = df.groupby([pd.Grouper(key='Date',freq='H'),'Section']).agg(PPT=('Section','count')).reset_index() The problem is that the count does not take into account the 0 values. I have tried so ...
[ "I found the answer in another thread: I added\n.unstack(fill_value=0).stack().reset_index()\n\n" ]
[ 1 ]
[]
[]
[ "aggregate", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074586456_aggregate_dataframe_group_by_pandas_python.txt
Q: TKinter weird behavior using grid location manager with arguments row=0, column=0 I'm using two frames to organize my main frame into two subframes. One subframe is one the left and it contains a few buttons and a label. The subframe on the right contains a treeview. The items in the left_frame don't show up when ...
TKinter weird behavior using grid location manager with arguments row=0, column=0
I'm using two frames to organize my main frame into two subframes. One subframe is one the left and it contains a few buttons and a label. The subframe on the right contains a treeview. The items in the left_frame don't show up when I use the arguments row=0, column=0 as show in the example below. class MainFrame(ttk.F...
[ "It is most likely because you did not specify the parent of left_frame and right_frame, so they will be children of root window, not instance of MainFrame.\nIf instance of MainFrame or other frame is also a child of root window and put in row 0 and column 0 as well, it may overlap/cover left_frame.\nSet the parent...
[ 2 ]
[]
[]
[ "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0074591158_python_tkinter_ttk_user_interface.txt
Q: How to locate a block with certain text using python selenium With selenium in python, I want to collect data about a user called "GrahamDumpleton" on the website below: https://github.com/GrahamDumpleton/wrapt/graphs/contributors And this is the block I want to locate with the user name "GrahamDumpleton": How to...
How to locate a block with certain text using python selenium
With selenium in python, I want to collect data about a user called "GrahamDumpleton" on the website below: https://github.com/GrahamDumpleton/wrapt/graphs/contributors And this is the block I want to locate with the user name "GrahamDumpleton": How to locate this block using selenium? Thank you.
[ "This can be clearly done with XPath since XPath is the only approach supporting locating elements based on their text content.\nSo, that user block element can be located with the following XPath:\n//li[contains(@class,'contrib-person')][contains(.,'Graham')]\n\nIn case you want only the header part of that block ...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "xpath" ]
stackoverflow_0074591353_python_selenium_selenium_webdriver_web_scraping_xpath.txt
Q: How to sum random.choices? I have a list of songs: my_favorite_songs = [ ['Waste a Moment', 3.03], ['New Salvation', 4.02], ['Staying\' Alive', 3.40], ['Out of Touch', 3.03], ['A Sorta Fairytale', 5.28], ['Easy', 4.15], ['Beautiful Day', 4.04], ['Nowhere to Run', 2.58], ['In Thi...
How to sum random.choices?
I have a list of songs: my_favorite_songs = [ ['Waste a Moment', 3.03], ['New Salvation', 4.02], ['Staying\' Alive', 3.40], ['Out of Touch', 3.03], ['A Sorta Fairytale', 5.28], ['Easy', 4.15], ['Beautiful Day', 4.04], ['Nowhere to Run', 2.58], ['In This World', 4.02], My task is to ...
[ "Try\nsum([x[1] for x in random.choices(my_favorite_songs, k=3)])\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074591489_python.txt
Q: Take random samples from the data with different number each time I have a pandas dataframe that I want to randomly pick samples from it. The first time I want to pick 10, then 20, 30, 40, and 50 random samples (without replacment). I'm trying to do it with a for loop, altough I don't know how good this is cause a...
Take random samples from the data with different number each time
I have a pandas dataframe that I want to randomly pick samples from it. The first time I want to pick 10, then 20, 30, 40, and 50 random samples (without replacment). I'm trying to do it with a for loop, altough I don't know how good this is cause a list can't contain data frames, right? (my coding is better with R and...
[ "You could do that using radint method for choosing random element from the list number:\nimport random \nnumber = [10,20,30,40,50]\nsample = []\nfor i in range(len(number)):\n sample.append(data.sample(n = number[random.randint(0, len(number)-1]))\n\nUpdate:\nAssuming you have this dataframe for Movies Ratin...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "random" ]
stackoverflow_0074591439_pandas_python_random.txt
Q: ModuleNotFoundError with a python requests library Is anyone else receiving a moduleNotFoundError with their requests library? Not sure why this is happening. The library is installed as well which is even more confusing. import csv from datetime import datetime import requests from bs4 import BeautifulSoup and ...
ModuleNotFoundError with a python requests library
Is anyone else receiving a moduleNotFoundError with their requests library? Not sure why this is happening. The library is installed as well which is even more confusing. import csv from datetime import datetime import requests from bs4 import BeautifulSoup and the resulting error was this: ----------------------...
[ "Most likely, you don't have the requests module installed. Run the following command:\npip install requests to install the package.\n", "corrected the error by referencing this question (i didnt see it when I first searched)\nrunning sudo pip3 install requests and it recognized the library now.\n" ]
[ 0, 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0074584661_pip_python_python_3.x.txt
Q: How to round Matrix elements in sympy? As we know from sympy import * x = sin(pi/4) y = sin(pi/5) A = Matrix([x, y]) print(x) print(A.evalf()) displays sqrt(2)/2 Matrix([[0.707106781186548], [0.587785252292473]]) So print(round(x.evalf(), 3)) print(round(y.evalf(), 3)) displays 0.707 0.588 But how can we ro...
How to round Matrix elements in sympy?
As we know from sympy import * x = sin(pi/4) y = sin(pi/5) A = Matrix([x, y]) print(x) print(A.evalf()) displays sqrt(2)/2 Matrix([[0.707106781186548], [0.587785252292473]]) So print(round(x.evalf(), 3)) print(round(y.evalf(), 3)) displays 0.707 0.588 But how can we round all the elements in a Matrix in a terse ...
[ "Why you do not use method evalf with args like evalf(3)?\nfrom sympy import *\n\nx = sin(pi/4)\ny = sin(pi/5)\n\nA = Matrix([x, y])\n\nprint(x)\nprint(A.evalf(3))\n\nOutput\nsqrt(2)/2\nMatrix([[0.707], [0.588]])\n\n", "This works for me\n# Z is a matrix\nfrom functools import partial\n\nround3 = partial(round, n...
[ 3, 1, 0 ]
[]
[]
[ "python", "rounding", "sympy" ]
stackoverflow_0053844884_python_rounding_sympy.txt
Q: Find values of specific parameters from XML I have tried this approach but it doesn't work for me. I want to get the releaseDate value from the below xml <Product prodID="bed" lang="en"> <ProductState stateType="Published" stateDateTime="2019-04" testDate="2019-04" releaseDate="2019"/> I have tried the below cod...
Find values of specific parameters from XML
I have tried this approach but it doesn't work for me. I want to get the releaseDate value from the below xml <Product prodID="bed" lang="en"> <ProductState stateType="Published" stateDateTime="2019-04" testDate="2019-04" releaseDate="2019"/> I have tried the below code: from pathlib import Path import os import temp...
[ "Listing [Python.Docs]: xml.etree.ElementTree - The ElementTree XML API.\nConsidering this exact XML blob, there are 2 errors in your code:\n\nThe root node is Product node, so if you search for (other) Product sub-nodes it won't find anything\n\nreleaseDate is an attribute (not a tag) so it doesn't belong in the p...
[ 1, 0 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0074401612_python_xml_xml_parsing.txt
Q: Linked list implementation in python issue I have been trying to implement a linked-list in python.Any call of a variable inside a function in Python is by default call by reference.I have this code: For the list_node: class list_node: def __init__(self,obj,next_listnode): self.obj = obj self....
Linked list implementation in python issue
I have been trying to implement a linked-list in python.Any call of a variable inside a function in Python is by default call by reference.I have this code: For the list_node: class list_node: def __init__(self,obj,next_listnode): self.obj = obj self.next_listnode = next_listnode For the linked_l...
[ "If you add one more node to your list, the problem becomes a bit more clear:\nA = list_node(\"John\",None)\nB = list_node(\"Mike\",None)\nC = list_node(\"Biff\",None)\nliste = linked_list(A)\nliste.add_node(B)\nliste.add_node(C)\n\nliste.print_linkedlist()\n\nThis prints \"John\" and \"Mike\" -- so the problem isn...
[ 1 ]
[]
[]
[ "class", "linked_list", "pass_by_reference", "python" ]
stackoverflow_0074591485_class_linked_list_pass_by_reference_python.txt
Q: How to plot a vertical thermal plot in Matplotlib? Hi Anyone has an idea about how to plot this kind of thermal plot in python?. I tried to search any sample plot like this, but didn't find. Highly appreciate if someone can help me to draw a graph like this. This image I got from the internet. I want to plot somet...
How to plot a vertical thermal plot in Matplotlib?
Hi Anyone has an idea about how to plot this kind of thermal plot in python?. I tried to search any sample plot like this, but didn't find. Highly appreciate if someone can help me to draw a graph like this. This image I got from the internet. I want to plot something same like this
[ "FROM\n\nTO\n\n\n3 weeks later…\nProbably the OP resorted to display their time dependent temperature field with, surprise! a heat map, so that, notwithstanding the fact that SO is not a code writing service, I feel free to answer their question.\nFirst and above all, this is an exercise, to represent this type of ...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python", "seaborn" ]
stackoverflow_0074356558_matplotlib_plot_python_seaborn.txt
Q: I want to create custom signup form and add extra fields in Django default user model I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city. from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from dja...
I want to create custom signup form and add extra fields in Django default user model
I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city. from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCr...
[ "Because, you are adding additional fields to the default user model. First you have to\n-Create a Custom User Model by using AbstractUser\nThen\n-Create a Custom Form for UserCreationForm\nYou can search google for:\nExtend-existing-user-model-in-django\n" ]
[ 0 ]
[]
[]
[ "django", "forms", "model", "python" ]
stackoverflow_0074591257_django_forms_model_python.txt
Q: how to return user email on google api, python ive been trying to use google sheets api for a project and for this project it requires the users email to be compaired to a list of emails in the sheets and only return the rows with the users email in. so if the google sheets as A _______________________ B personA@g...
how to return user email on google api, python
ive been trying to use google sheets api for a project and for this project it requires the users email to be compaired to a list of emails in the sheets and only return the rows with the users email in. so if the google sheets as A _______________________ B personA@gmail.com ___apples personB@gmail.con ___ bananas per...
[ "This is going to depend a bit on what scope you authorized the user with. Assuming that you authorized them with one of the drive scopes.\nYou can go though the google drive api the about.get method this will return the email address of the currently authenticated user.\n\"kind\": \"drive#about\",\n \"user\": {\...
[ 0 ]
[]
[]
[ "email", "google_api", "python", "python_3.10" ]
stackoverflow_0074591548_email_google_api_python_python_3.10.txt
Q: compare two list and set zero for not exist value I want to compare lst2 with lst and set zero for value who is not exist lst = ['IDP','Remote.CMD.Shell','log4j'] lst2 = ['IDP'] I want output like this in for example loop { IDP:1, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remo...
compare two list and set zero for not exist value
I want to compare lst2 with lst and set zero for value who is not exist lst = ['IDP','Remote.CMD.Shell','log4j'] lst2 = ['IDP'] I want output like this in for example loop { IDP:1, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } I would be glad if anyone ca...
[ "Here is how i can achieve this\nfirst you can create a new dictionary and then manipulate the data inside\nlst = ['IDP','Remote.CMD.Shell','log4j']\n\nlst2 = ['IDP']\n\nresult = {}\n\nfor i in lst:\n result[i] = 0\n\n# if one of result keys is in lst2, set the value to 1\nfor i in lst2:\n if i in result:\n ...
[ 0, 0 ]
[]
[]
[ "compare", "list", "python", "python_3.x" ]
stackoverflow_0074591397_compare_list_python_python_3.x.txt
Q: How to make a grid of the size a rows x b columns from a list containing exactly a*b items? Python grid, list, matrix? How do I make a 3x5 grid out of a list containing 15 items/strings? I have a list containing 15 symbols but it could very well also just be a list such as mylist = list(range(15)), that I want to ...
How to make a grid of the size a rows x b columns from a list containing exactly a*b items? Python grid, list, matrix?
How do I make a 3x5 grid out of a list containing 15 items/strings? I have a list containing 15 symbols but it could very well also just be a list such as mylist = list(range(15)), that I want to portray in a grid with 3 rows and columns. How does that work without importing another module? I've been playing around wit...
[ "A mxn Grid? There are multiple ways to do it. Print for every n elements.\nmylist = list(range(15))\n\nn = 5\nchunks = (mylist[i:i+n] for i in range(0, len(mylist), n))\nfor chunk in chunks:\n print(*chunk)\n\nGives 3x5\n0 1 2 3 4\n5 6 7 8 9\n10 11 12 13 14\n\nMethod 2\nIf you want more cosmetic then yo...
[ 0 ]
[]
[]
[ "field", "grid", "list", "matrix", "python" ]
stackoverflow_0074591109_field_grid_list_matrix_python.txt
Q: Difficulty decoding image with base64 library I'm having trouble decoding an image when I import it from another file. I have four .py files to make two buttons. In the first, on line 21, the button works and brings the image, in the second, on line 28, which is imported from another file, it appears as a button b...
Difficulty decoding image with base64 library
I'm having trouble decoding an image when I import it from another file. I have four .py files to make two buttons. In the first, on line 21, the button works and brings the image, in the second, on line 28, which is imported from another file, it appears as a button but without an image. How can I resolve this? lab.py...
[ "It is because there is no variable referencing the instance of Botoes(), so it will be garbage collected (so as the image inside it).\nJust use a variable to store the instance of Botoes():\nclass Janela(Images):\n def __init__(self) -> None:\n self.images_base64()\n self.tamJanela()\n\n def ta...
[ 0 ]
[]
[]
[ "base64", "python", "tkinter" ]
stackoverflow_0074589749_base64_python_tkinter.txt
Q: I am getting TypeError: Person() takes no arguments I have 2 underscores for init class Person: def __int__(self, name): self.name = name def talk(self): print('talk') john = Person("John Smith") print(john.name) john.talk() what could be the problem?
I am getting TypeError: Person() takes no arguments I have 2 underscores for init
class Person: def __int__(self, name): self.name = name def talk(self): print('talk') john = Person("John Smith") print(john.name) john.talk() what could be the problem?
[]
[]
[ "You have wrote __int__, and not __init__\n" ]
[ -1 ]
[ "pycharm", "python" ]
stackoverflow_0074591587_pycharm_python.txt
Q: making a sort algorithm but it works only sometimes trying to make a basic sorting algorithm that slowly puts one number from list1 to list2. it should be lowest to highest. i do know there are better sorting algorithm but i want to make my own shitty own list1 = [3,1,2,8,4,73,6,9,14,12,6712,23,76,111,312,42] list...
making a sort algorithm but it works only sometimes
trying to make a basic sorting algorithm that slowly puts one number from list1 to list2. it should be lowest to highest. i do know there are better sorting algorithm but i want to make my own shitty own list1 = [3,1,2,8,4,73,6,9,14,12,6712,23,76,111,312,42] list2 = [-1] w = 0 for i in range(len(list1)): while w !...
[ "\nnot sure about the error aswell but it probally has to do with a\nnumber being in list2 at the very start\n\nThe first item in list2 is not your problem. The issue is that you are at times making two insertions to your list (check code block under condition elif list1[w] < list2[w]:), but evaluating the loop con...
[ 1 ]
[]
[]
[ "algorithm", "python", "sorting" ]
stackoverflow_0074591342_algorithm_python_sorting.txt
Q: NotFoundError using BERT Preprocessing from TFHub I'm trying to use the pre-trained BERT models on TensorFlow Hub to do some simple NLP. I'm on a 2021 MacBook Pro (Apple Silicon) with Python 3.9.13 and TensorFlow v2.9.2. However, preprocessing any amount of text returns a "NotFoundError" that I can't seem to resol...
NotFoundError using BERT Preprocessing from TFHub
I'm trying to use the pre-trained BERT models on TensorFlow Hub to do some simple NLP. I'm on a 2021 MacBook Pro (Apple Silicon) with Python 3.9.13 and TensorFlow v2.9.2. However, preprocessing any amount of text returns a "NotFoundError" that I can't seem to resolve. The link to the preprocessing model is here: (https...
[ "Update: While using BERT preprocessing from TFHub, Tensorflow and tensorflow_text versions should be same so please make sure that installed both versions are same. It happens because you're using latest version for tensorflow_text but you're using other versions for python and tensorflow but there is internal dep...
[ 0 ]
[]
[]
[ "bert_language_model", "data_preprocessing", "python", "tensorflow", "tensorflow_hub" ]
stackoverflow_0074554805_bert_language_model_data_preprocessing_python_tensorflow_tensorflow_hub.txt
Q: Passing a list of strings to from python/ctypes to C function expecting char ** I have a C function which expects a list \0 terminated strings as input: void external_C( int length , const char ** string_list) { // Inspect the content of string_list - but not modify it. } From python (with ctypes) I would li...
Passing a list of strings to from python/ctypes to C function expecting char **
I have a C function which expects a list \0 terminated strings as input: void external_C( int length , const char ** string_list) { // Inspect the content of string_list - but not modify it. } From python (with ctypes) I would like to call this function based on a list of python strings: def call_c( string_list )...
[ "def call_c(L):\n arr = (ctypes.c_char_p * len(L))()\n arr[:] = L\n lib.external_C(len(L), arr)\n\n", "Thank you very much; that worked like charm. I also did an alternative variation like this:\ndef call_c( L ):\n arr = (ctypes.c_char_p * (len(L) + 1))()\n arr[:-1] = L\n arr[ len(L) ] = None\n ...
[ 26, 6, 5, 1, 0 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0003494598_c_ctypes_python.txt
Q: how do I keep track of a minimum across recursion calls I am trying my way around practising recursion and I want to find the minimum ways to generate a sum with given coins. I did figure out a way to do using a global variable but I've heard it's not really optimal to do it this way This is my code minres = 10000...
how do I keep track of a minimum across recursion calls
I am trying my way around practising recursion and I want to find the minimum ways to generate a sum with given coins. I did figure out a way to do using a global variable but I've heard it's not really optimal to do it this way This is my code minres = 10000 def count(sum, i, coins, temp, res): global minres i...
[ "Here's a modified version of your function that doesn't rely on a global definition of minres. By passing minres to and returning it from every function call, it no longer needs to be \"remembered\" outside the scope of each function call:\ndef count(sm, i, coins, res, temp=None, minres = 10000):\n if temp is N...
[ 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074591092_python_recursion.txt
Q: How to convert an "attribute call" into a "method call" in Python? From my understanding of OOP in Python, if there is no attribute named xyz on an object a, then invoking a.xyz raises "AttributeError." But in beautifulsoup, if we call any arbitrary attribute on an object of type Tag, we always get some output. Fo...
How to convert an "attribute call" into a "method call" in Python?
From my understanding of OOP in Python, if there is no attribute named xyz on an object a, then invoking a.xyz raises "AttributeError." But in beautifulsoup, if we call any arbitrary attribute on an object of type Tag, we always get some output. For instance, >>> from bs4 import BeautifulSoup >>> import requests >>> ...
[ "No imagination necessary. We can just look at the source: (abbreviated by me)\nclass Tag(PageElement):\n ...\n\n def __getattr__(self, tag):\n \"\"\"Calling tag.subtag is the same as calling tag.find(name=\"subtag\")\"\"\"\n if not tag.startswith(\"__\") and not tag == \"contents\":\n ...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "class", "oop", "python" ]
stackoverflow_0074590670_beautifulsoup_class_oop_python.txt
Q: Is there a way to count the frequency of an element in a list without using predefined functions/sets/dictionaries? first want to say I am new to Python but I am eager to learn and have searched around for a solution, can't seem to figure this problem out without resorting to many lines of code. We recently reciev...
Is there a way to count the frequency of an element in a list without using predefined functions/sets/dictionaries?
first want to say I am new to Python but I am eager to learn and have searched around for a solution, can't seem to figure this problem out without resorting to many lines of code. We recently recieved an assignment for our course which looks this: Write a program that, given a text, computes the frequency of every let...
[ "For each character in the string, add it and its count to a list if it's not already in the list. This requires nested loops and therefore has terrible performance implications for large strings.\ndef count(s):\n counts = []\n for c in s:\n if not any(True for (k, _) in counts if k == c):\n counts.append...
[ 0, 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074591588_list_python_python_3.x.txt
Q: python endpoint starting a thread with locking I'm using FASTApi and trying to implement an endpoint, which starts a job. Once the job is started, the endpoint shall be "locked" until the previous job finished. So far its implemented like this: myapp.lock = threading.Lock() @myapp.get("/jobs") def start_job(some_...
python endpoint starting a thread with locking
I'm using FASTApi and trying to implement an endpoint, which starts a job. Once the job is started, the endpoint shall be "locked" until the previous job finished. So far its implemented like this: myapp.lock = threading.Lock() @myapp.get("/jobs") def start_job(some_args): if myapp.lock.acquire(False): th ...
[ "I figured out this kind of solution:\nmyapp.lock = False\n\n@myapp.get(\"/jobs\")\nasync def start_job(some_args, background_tasks: BackgroundTasks):\n if not myapp.lock:\n background_tasks.add_task(job, some_args)\n return \"Job started\"\n else:\n raise HTTPException(status_code=400,de...
[ 0, 0 ]
[]
[]
[ "fastapi", "multithreading", "python" ]
stackoverflow_0067193397_fastapi_multithreading_python.txt
Q: Folium - KeyErrors I'm currently trying to plot AirBnb locations in Paris using folium. My code is as below: f = folium.Figure(width = 800, height = 500) map = folium.Map(location = [48.8569421129686, 2.3503337285332204], # Coords for Paris zoom_start = 10, ti...
Folium - KeyErrors
I'm currently trying to plot AirBnb locations in Paris using folium. My code is as below: f = folium.Figure(width = 800, height = 500) map = folium.Map(location = [48.8569421129686, 2.3503337285332204], # Coords for Paris zoom_start = 10, tiles = 'CartoDB positron'...
[ "In your case, it is better to use the iterrows() method from the Pandas dataframe to iterate over the rows of the dataframe :\nfor row in df4.iterrows():\n lat = row[1]['latitude']\n long = row[1]['longitude']\n temp = lat, long\n folium.Marker(temp, marker_icon = 'cloud').add_to(map)\n\n" ]
[ 0 ]
[]
[]
[ "folium", "geospatial", "python" ]
stackoverflow_0074578542_folium_geospatial_python.txt
Q: The same message appears when I type `yes` in the loop When I enter yes to repeat the game, then instead of repeating, this message appears: do you want to play again (yes or no): This only happens when I enter yes. But if I enter no, then it exits from the game. Code I have print(' ...
The same message appears when I type `yes` in the loop
When I enter yes to repeat the game, then instead of repeating, this message appears: do you want to play again (yes or no): This only happens when I enter yes. But if I enter no, then it exits from the game. Code I have print(' Welcome to the gussing game :)') print("\n\nyou have o...
[ "This is because you didn't reset the value of your variable, guess_word and count_attempts. Therefore, while (guess_word != hidden_word) and (count_attempts < limit_attempts): is always false in your second iteration onwards, and the inner while loop is skipped.\nYou can reset the value before the inner while loop...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074591692_python.txt
Q: When I want to remove an element from the list, it deletes it incorrectly pasw = "1234abc" mylist = list(pasw) a = list(map(lambda x: mylist.remove(x) if x.isnumeric() == True else False, mylist)) print(mylist) Output: ['2', '4', 'a', 'b', 'c'] I want to check if there is a number in the list, and if there is a ...
When I want to remove an element from the list, it deletes it incorrectly
pasw = "1234abc" mylist = list(pasw) a = list(map(lambda x: mylist.remove(x) if x.isnumeric() == True else False, mylist)) print(mylist) Output: ['2', '4', 'a', 'b', 'c'] I want to check if there is a number in the list, and if there is a number, I want to delete it from the list.
[ "As a general rule, it's not recommanded to modify a sequence you are iterating upon. The below function is similar to your map.\ndef deleting_while_iterating(iterable):\n for i in iterable:\n iterable.remove(i)\n print(f\"i: {i}, iterable: {iterable}\")\n\nIf I give this function your input, the o...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074591788_list_python.txt
Q: Is there a way to insert an arbitrary symbol before the Python output value? I'm calculating the matrix value with Python, but I want to distinguish the value of equtaion, is there a way? x - y - 2z = 4 2x - y - z = 2 2x +y +4z = 16 I want to make the expression above like this when I print out the matrix from the...
Is there a way to insert an arbitrary symbol before the Python output value?
I'm calculating the matrix value with Python, but I want to distinguish the value of equtaion, is there a way? x - y - 2z = 4 2x - y - z = 2 2x +y +4z = 16 I want to make the expression above like this when I print out the matrix from the function I created 1 -1 -2 | 4 2 -1 -1 | 2 2 1 4 | 16 Same as the rref result of ...
[ "Here is a function which takes a list of 4 numbers and returns a string representing an equation in x,y,z. It handles coefficients which are negative, zero, or +/-1 appropriately:\ndef make_equation(nums):\n coefficients = nums[:3]\n variables = 'xyz'\n terms = []\n for c,v in zip(coefficients,variable...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074591197_python.txt
Q: Trying to understand signature in numpy.vectorize I am trying to understand the signature functionality in numpy.vectorize. I have some examples but did not help much in the understanding. >>import scipy.stats >>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()') >>pearsonr([[0, 1, 2, 3]], [[...
Trying to understand signature in numpy.vectorize
I am trying to understand the signature functionality in numpy.vectorize. I have some examples but did not help much in the understanding. >>import scipy.stats >>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()') >>pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) (array([ 1., -1.]), array([...
[ "I think the explanation would be clearer if we knew the 'signature' of the individual functions - what they expect, and what they produce. But I can make some deductions from the code you show.\n>>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()')\n>>pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], ...
[ 2 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074589308_numpy_python_vectorization.txt