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: Aure cognitive services text to speech REST API I am calling a Azure Text to Speech REST API to get audio response from my flask API. When I call the Azure REST API from postman I get the output as audio file and can play what I have given as text but when I call the API from my flask I get empty video file instea...
Aure cognitive services text to speech REST API
I am calling a Azure Text to Speech REST API to get audio response from my flask API. When I call the Azure REST API from postman I get the output as audio file and can play what I have given as text but when I call the API from my flask I get empty video file instead of audio file def call_azure_cognitive_api(text): ...
[ "I think you should use response.content instead of the Response object itself to get the response body as bytes.\nMeanwhile, I recommened you to use the Azure Speech SDK for speech synthesis, which has an easy-to-use interface. Refer to the Python Quickstart for TTS for more details.\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_cognitive_services", "flask", "python" ]
stackoverflow_0074609190_azure_azure_cognitive_services_flask_python.txt
Q: How to draw a patterned curve with Python Let's say I have a set of coordinates that when plotted looks like this: I can turn the dots into a smooth-ish line by simply drawing lines from adjacent pair of points: That one's easy. However, I need to draw a line with a pattern because it represents a railroad track...
How to draw a patterned curve with Python
Let's say I have a set of coordinates that when plotted looks like this: I can turn the dots into a smooth-ish line by simply drawing lines from adjacent pair of points: That one's easy. However, I need to draw a line with a pattern because it represents a railroad track, so it should look like this: (This is simula...
[ "I got it!\nOkay first a bit of maths theory. There are several ways of depicting a line in geometry.\nThe first is the \"slope-intercept\" form: y = mx + c\nThen there's the \"point-slope\" form: y = y1 + m * (x - x1)\nAnd finally there's the \"generalized form\":\n\nNone of these forms are practical for several r...
[ 0 ]
[]
[]
[ "curve", "python" ]
stackoverflow_0074588881_curve_python.txt
Q: Elasticsearch query to match values from list of values in Excel [Python] I'm new to Elasticsearch. I have a list of values for example: id_list=[1111,2222,3333,4444,5555] Now I want to match those ids in that id_list to match with some information stored in Elasticsearch having the same id no. I'm thinking to us...
Elasticsearch query to match values from list of values in Excel [Python]
I'm new to Elasticsearch. I have a list of values for example: id_list=[1111,2222,3333,4444,5555] Now I want to match those ids in that id_list to match with some information stored in Elasticsearch having the same id no. I'm thinking to use for loop to loop all the ids to match using the ES query, but I not sure how ...
[ "You can use terms query from elasticsearch to query list of ids:\n{\n \"query\": {\n \"terms\": {\n \"id_list\": [1111,2222,3333,4444,5555]\n }\n }\n}\n\nUpdated Based on comments:\nAs mentioned in documentation maximum of 65,536 terms.\n\nBy default, Elasticsearch limits the terms query to a maximum ...
[ 0 ]
[]
[]
[ "boolean_logic", "elasticsearch", "elasticsearch_dsl", "python" ]
stackoverflow_0074623369_boolean_logic_elasticsearch_elasticsearch_dsl_python.txt
Q: Visual studio don't have parameter detectMultiScale I'm newbie at here. I don't know why my visual studio code doesn't show parameter detectMultiScale. What should I fix it? I attach image here for detail. image I try to reinstall for several times but it still not show parameter. A: Add these two lines in the s...
Visual studio don't have parameter detectMultiScale
I'm newbie at here. I don't know why my visual studio code doesn't show parameter detectMultiScale. What should I fix it? I attach image here for detail. image I try to reinstall for several times but it still not show parameter.
[ "Add these two lines in the settings.json to enable type hints\n \"python.analysis.inlayHints.variableTypes\": true,\n \"python.analysis.inlayHints.functionReturnTypes\": true,\n\n\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074617111_python_visual_studio_code.txt
Q: How can find iframe value in Selenium? Above is webpage html code. In python selenium, How i can find iframe value? Below is my code. frame = driver.find_element(By.NAME, "frm") frame = driver.find_elements(By.TAG_NAME, "iframe") frame = driver.find_elements(By.TAG_NAME, "body_iframe") frame = driver.find_element(...
How can find iframe value in Selenium?
Above is webpage html code. In python selenium, How i can find iframe value? Below is my code. frame = driver.find_element(By.NAME, "frm") frame = driver.find_elements(By.TAG_NAME, "iframe") frame = driver.find_elements(By.TAG_NAME, "body_iframe") frame = driver.find_element(By.CSS_SELECTOR, '.Center_top iframe') Whe...
[ "Try the below locator:\ndriver.find_element(By.XPATH, \".//iframe[@id='body_iframe' and @name='body_iframe']\")\n\n" ]
[ 0 ]
[]
[]
[ "html", "iframe", "python", "selenium" ]
stackoverflow_0074623330_html_iframe_python_selenium.txt
Q: Sliding time window with python deque I have deque. Each element of the deque consists of time and event field. So, this is similar to list of dicts. Data is always sorted by time from oldest to newest. First element of the deque is the oldest. Please, note that deque is infinite and every time new element(s) are ...
Sliding time window with python deque
I have deque. Each element of the deque consists of time and event field. So, this is similar to list of dicts. Data is always sorted by time from oldest to newest. First element of the deque is the oldest. Please, note that deque is infinite and every time new element(s) are added with unknown time. This means that ne...
[ "You did not explain how your deque was updated, and how it should affect the window processing.\nBut here is a proof-of-concept of the algorithm :\nfrom datetime import datetime\nfrom typing import Generator, List, Dict, Union\n\nElement = Dict[str, Union[str, int]]\nSeries = List[Element]\n\ndef sliding_window(se...
[ 1 ]
[]
[]
[ "deque", "python", "python_3.x", "queue" ]
stackoverflow_0074600559_deque_python_python_3.x_queue.txt
Q: How to filter fows in Pandas using partial string in column I've used the SerpAPI to pull down some data about jobs in a sector I want to return to. There is a lot of junk about training and I'd like to remove the results based on the displayed_link column. position title link displayed_link date snip...
How to filter fows in Pandas using partial string in column
I've used the SerpAPI to pull down some data about jobs in a sector I want to return to. There is a lot of junk about training and I'd like to remove the results based on the displayed_link column. position title link displayed_link date snippet snippet_highlighted_words sitelinks about_this_result a...
[ "Use Series.str.contains with chain list by | for regex OR:\ndf['test1'] = np.where(df['displayed_link'].str.contains('|'.join(promotions)), 'T', 'F')\ndf['test2'] = (df['displayed_link'].str.contains('|'.join(promotions))\n .map({True:'T',False: 'F'}))\n\nIf necessary, use words b...
[ 1 ]
[]
[]
[ "pandas", "python", "serpapi" ]
stackoverflow_0074623631_pandas_python_serpapi.txt
Q: Replace consecutive delimiters in string with values from list I have a string, for example: s = "I ? am ? a ? string" And I have a list equal in length to the number of ? in the string: l = ['1', '2', '3'] What is a pythonic way to return s with each consecutive ? replaced with the values in l?, e.g.: s_new = '...
Replace consecutive delimiters in string with values from list
I have a string, for example: s = "I ? am ? a ? string" And I have a list equal in length to the number of ? in the string: l = ['1', '2', '3'] What is a pythonic way to return s with each consecutive ? replaced with the values in l?, e.g.: s_new = 'I 1 am 2 a 3 string'
[ "2 Methods:\n# Method 1\ns = \"I ? am ? a ? string\"\nl = ['1', '2', '3']\n\nfor i in l:\n s = s.replace('?', i, 1) \n\nprint(s)\n# Output: I 1 am 2 a 3 string\n\n\n# Method 2\nfrom functools import reduce\ns = \"I ? am ? a ? string\"\nl = ['1', '2', '3']\n\ns_new = reduce(lambda x, y: x.replace('?', y, 1), l, s...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0074623448_python.txt
Q: web scraping all universities with websites and description WHED website anyone can help with scraping from https://www.whed.net/home.php the code I'm using is giving me empty df. would love to have universities with websites and maybe field of study. My scraping skills are weak so if you can guide me through this...
web scraping all universities with websites and description WHED website
anyone can help with scraping from https://www.whed.net/home.php the code I'm using is giving me empty df. would love to have universities with websites and maybe field of study. My scraping skills are weak so if you can guide me through this would be great thanks guys. begin=time.time() countries=['Emirates','United S...
[ "Update 1/12/22 - Async\nFound a much better solution using aiohttp, it also runs the entire list of countries in ~30 seconds instead of 3 hours\nimport json\nimport time\nimport aiohttp\nimport asyncio\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom...
[ 0 ]
[ "You can use Selenium to scrape data. The following code will help you scrape the university names for \"United States of America (all)\". Similarly, you can scrape for other countries as well using Loop or entering the name manually. If you need the field of study for every university, you can scrape its href usin...
[ -1 ]
[ "python" ]
stackoverflow_0072800062_python.txt
Q: Tranformdata in pandas I am trying to tranform data from raw data to goal/output. I know the logic when writing basic python but i am failing to implement in pandas. for i in range (0, qty[i]); number =[] np.append number [start[i]+1] I am failing to apply the same logic in pandas data frame sample dat...
Tranformdata in pandas
I am trying to tranform data from raw data to goal/output. I know the logic when writing basic python but i am failing to implement in pandas. for i in range (0, qty[i]); number =[] np.append number [start[i]+1] I am failing to apply the same logic in pandas data frame sample data item id qty start end ...
[ "Use:\ndf = df.loc[df.index.repeat(df['end'].sub(df['start']))]\n\ndf['number'] = df['start'].add(df.groupby(level=0).cumcount())\n\ndf = df.reset_index(drop=True)\nprint (df)\n item id qty start end number\n0 1 3 1000 1003 1000\n1 1 3 1000 1003 1001\n2 1 3 1000 1...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074619614_pandas_python.txt
Q: Rows as dictionaries - pymssql I want to receive rows as dictionaries in pymssql. in python-idle i ran: >>> conn = pymssql.connect(host='192.168.1.3', user='majid', password='123456789', database='GeneralTrafficMonitor', as_dict=True) >>> cur = conn.cursor() >>> cur.execute('SELECT TOP 10 * FROM dbo.tblTrafficCoun...
Rows as dictionaries - pymssql
I want to receive rows as dictionaries in pymssql. in python-idle i ran: >>> conn = pymssql.connect(host='192.168.1.3', user='majid', password='123456789', database='GeneralTrafficMonitor', as_dict=True) >>> cur = conn.cursor() >>> cur.execute('SELECT TOP 10 * FROM dbo.tblTrafficCounterData') >>> cur.as_dict True >>> f...
[ "You need to add the parameter as_dict=True like so:\n cursor = conn.cursor(as_dict=True)\n\nYou will then be able to access row['id'] if it is a field name in the result set.\nAs per documentation below:\nhttps://pythonhosted.org/pymssql/pymssql_examples.html#rows-as-dictionaries\n", "Look at the version of p...
[ 5, 1, 0, 0 ]
[]
[]
[ "dictionary", "pymssql", "python" ]
stackoverflow_0009972944_dictionary_pymssql_python.txt
Q: How to merge folders in every subdirectory using python code? my directory now.[1] I want to combine every Sub in every Folder so it should look something like this [2] [1]: https://i.stack.imgur.com/xz7FJ.png [2]: https://i.stack.imgur.com/scK48.png A: You can iterate through all the files/dirs in a directory u...
How to merge folders in every subdirectory using python code?
my directory now.[1] I want to combine every Sub in every Folder so it should look something like this [2] [1]: https://i.stack.imgur.com/xz7FJ.png [2]: https://i.stack.imgur.com/scK48.png
[ "You can iterate through all the files/dirs in a directory using os.walk().\nWe are just iterating over all files in a dir and then moving them to a destination directory using os.rename()\nimport os\ndirectory = '/tmp/dataset'\n\ndef move_all_files_to_destination_dir(original_dir, destination_dir):\n # moves al...
[ 1 ]
[]
[]
[ "directory", "directory_structure", "merge", "python" ]
stackoverflow_0074623529_directory_directory_structure_merge_python.txt
Q: How to convert a False or True boolean values inside nested python dictionary into javascript in Django template? This is my views.py: context = { "fas": fas_obj, } # TemplateResponse can only be rendered once return render(request, "project_structure.html", context) In the project_struc...
How to convert a False or True boolean values inside nested python dictionary into javascript in Django template?
This is my views.py: context = { "fas": fas_obj, } # TemplateResponse can only be rendered once return render(request, "project_structure.html", context) In the project_structure.html and javascript section: const pp = {{ fas|safe }}; I get an error here. because fas contains a False or Tru...
[ "Try this:\nconst pp = JSON.parse(\"{{fas_json|safe}}\");\n\n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "json", "python" ]
stackoverflow_0074623687_django_javascript_json_python.txt
Q: Timestring passed into URL to output JSON file - Python API Call I'm getting the following error for my python scraper: import requests import json symbol_id = 'COINBASE_SPOT_BTC_USDT' time_start = '2022-11-20T17:00:00' time_end = '2022-11-21T05:00:00' limit_levels = 100000000 limit = 100000000 url = 'https://re...
Timestring passed into URL to output JSON file - Python API Call
I'm getting the following error for my python scraper: import requests import json symbol_id = 'COINBASE_SPOT_BTC_USDT' time_start = '2022-11-20T17:00:00' time_end = '2022-11-21T05:00:00' limit_levels = 100000000 limit = 100000000 url = 'https://rest.coinapi.io/v1/orderbooks/{symbol_id}/history?time_start={time_start...
[ "Incorrect syntax for python. To concatenate strings, stick them together like such:\na = 'a' + 'b' + 'c'\n\n", "string formatting is invalid, and also need use & in between different url params\n# python3\nurl = f\"https://rest.coinapi.io/v1/orderbooks/{symbol_id}/history?time_start={time_start}&limit={limit}&li...
[ 0, 0 ]
[]
[]
[ "python", "time", "url" ]
stackoverflow_0074593089_python_time_url.txt
Q: Bunch of errors while using Flask command to make simple website so I've been following this tutorial on how to build an basic Flask website off youtube Tutorial. Currently trying to add HTML templates which are giving me "500 Internal Server Error" with application errors in the CMD. **My python code **` from fl...
Bunch of errors while using Flask command to make simple website
so I've been following this tutorial on how to build an basic Flask website off youtube Tutorial. Currently trying to add HTML templates which are giving me "500 Internal Server Error" with application errors in the CMD. **My python code **` from flask import Flask, redirect, url_for, render_template app = Flask(__n...
[ "it happens to work on mine though.\nmain.py\nfrom flask import Flask, redirect, url_for, render_template \n\napp = Flask(__name__)\n\n@app.route(\"/<name>\")\ndef home(name):\n return render_template(\"index.html\", content=name)\n\n\nif __name__ == \"__main__\":\n app.run()\n\nindex.html:\n<head>\n <titl...
[ 1 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074623084_flask_html_python.txt
Q: Splitting text in a column into multiple rows in python (data wrangling) channelTitle video_id tags 0 Channel1 ojPuGJaiVjE [tag3, tag4, tag5] 1 Channel1 NdWI3sov93I [tag1, tag4] 2 Channel1 67PYna-rScE [tag1, tag2, tag3, tag5] 3 Channel2 lNoDeZzn_4o NaN 4 Ch...
Splitting text in a column into multiple rows in python (data wrangling)
channelTitle video_id tags 0 Channel1 ojPuGJaiVjE [tag3, tag4, tag5] 1 Channel1 NdWI3sov93I [tag1, tag4] 2 Channel1 67PYna-rScE [tag1, tag2, tag3, tag5] 3 Channel2 lNoDeZzn_4o NaN 4 Channel3 QJSOGP-nJto [tag3] Hi all, I have a pandas dataframe (video_d...
[ "Use DataFrame.explode():\nvideo_df = video_df.explode('tags', ignore_index=True)\n\nprint(video_df)\n# channelTitle video_id tags\n#0 Channel1 ojPuGJaiVjE tag3\n#1 Channel1 ojPuGJaiVjE tag4\n#2 Channel1 ojPuGJaiVjE tag5\n#3 Channel1 NdWI3sov93I tag1\n#4 Channel1 NdWI3sov93I...
[ 1 ]
[]
[]
[ "data_wrangling", "python", "split" ]
stackoverflow_0074623564_data_wrangling_python_split.txt
Q: How to make lists equal a quadrilateral in Python? I am having difficulty figuring out to make user-entered lists of numbers equal a quadrilateral, specifically a rhombus and square, in Python. I do not know if my code needs a function or loops or if/else statements to know if it is a rhombus or square. So far, I ...
How to make lists equal a quadrilateral in Python?
I am having difficulty figuring out to make user-entered lists of numbers equal a quadrilateral, specifically a rhombus and square, in Python. I do not know if my code needs a function or loops or if/else statements to know if it is a rhombus or square. So far, I have this, but I can't figure out how to go through each...
[ "First we need some tweaking in the edge control.\nBecause \"if sides[i] == sides[i]:\" statement returns always True.\nInstead, let's write a function that checks that all edges are the same.\ndef is_same_edges(edges) -> bool:\n sum_edges = sum(edges)\n return (sum_edges / len(edges)) == edges[0]\n\nThis fun...
[ 0, 0 ]
[]
[]
[ "list", "python", "shapes" ]
stackoverflow_0074623458_list_python_shapes.txt
Q: Mask RCNN, AttributeError: module 'keras.engine' has no attribute 'Layer I tried to run matterport/MaskRCNN. Even though I've tried to change import keras.engine as KE to import keras.engine.topology as KE topology didn't work because topology module could not be resolved. I've also tried pip uninstall keras -y pi...
Mask RCNN, AttributeError: module 'keras.engine' has no attribute 'Layer
I tried to run matterport/MaskRCNN. Even though I've tried to change import keras.engine as KE to import keras.engine.topology as KE topology didn't work because topology module could not be resolved. I've also tried pip uninstall keras -y pip uninstall keras-nightly -y pip uninstall keras-Preprocessing -y pip uninstal...
[ "Change\n\"keras.engine as KE\"\nto\n\"keras.layers as KE\"\n" ]
[ 1 ]
[]
[]
[ "keras", "mask_rcnn", "python" ]
stackoverflow_0074023523_keras_mask_rcnn_python.txt
Q: python selenium clicking a list object I am trying to click 1 Min button on this site below is my python code url = 'https://www.investing.com/technical/technical-analysis' driver.get(url) events = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "section#leftColumn"))) print("...
python selenium clicking a list object
I am trying to click 1 Min button on this site below is my python code url = 'https://www.investing.com/technical/technical-analysis' driver.get(url) events = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "section#leftColumn"))) print("Required elements found") events.find_elemen...
[ "You have to use 'for' loop to iterate through all the elements in 'events' element:\nevents = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"section#leftColumn\")))\nprint(\"Required elements found\")\nfor event in events:\n event.find_element(By.XPATH,\"//a[text()='1 Mi...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "web_crawler", "web_scraping" ]
stackoverflow_0074623368_python_selenium_web_crawler_web_scraping.txt
Q: Fast method for key-point based image matching [Python] The scenario is, Let's suppose I took random images from my Gallery and put in some folder, and also print these image in hard form. Now I turned on my laptop camera and place an image in front of camera, My code need the tell the name of matching image from ...
Fast method for key-point based image matching [Python]
The scenario is, Let's suppose I took random images from my Gallery and put in some folder, and also print these image in hard form. Now I turned on my laptop camera and place an image in front of camera, My code need the tell the name of matching image from the folder. Actually the code I have add in the question work...
[ "One way to speed up the process is to use a feature descriptor that is more efficient than ORB. For example, you can use SIFT or SURF which are more efficient than ORB. You can also use a combination of feature descriptors such as ORB + SIFT or ORB + SURF.\nAnother way to speed up the process is to use a faster fe...
[ 3, 1 ]
[]
[]
[ "cbir", "computer_vision", "machine_learning", "opencv", "python" ]
stackoverflow_0074499400_cbir_computer_vision_machine_learning_opencv_python.txt
Q: can find the problem to solve Template doesn't working? from django.shortcuts import render # Create your views here. def home(request): return render(request, 'dashboard/home.html') from django.urls import path from . import views urlpatterns = [ path('', views.home), ] Plz Help me to Resolve the Pro...
can find the problem to solve Template doesn't working?
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'dashboard/home.html') from django.urls import path from . import views urlpatterns = [ path('', views.home), ] Plz Help me to Resolve the Problem adding path in template_DIRs
[ "In your settings.py add this variable:\nimport os\n\nTEMPLATE_DIR = os.path.join(BASE_DIR, \"templates\")\n\nAdd TEMPLATE_DIR in TEMPLATE_DIRS.\nThen, at the root of your project create a folder named templates. Or create a folder named templates inside your app's directory. Inside the templates folder place your ...
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0074623851_django_django_templates_django_views_python.txt
Q: Django Rest Framework, how to use serializers.ListField with model and view? I want to store an array of integers in the day_of_the_week field. for which I am using the following code models.py class Schedule(models.Model): name = models.CharField(max_length=100) day_of_the_week = models.CharField(max_leng...
Django Rest Framework, how to use serializers.ListField with model and view?
I want to store an array of integers in the day_of_the_week field. for which I am using the following code models.py class Schedule(models.Model): name = models.CharField(max_length=100) day_of_the_week = models.CharField(max_length=100) serializers.py class ScheduleSerializer(serializers.ModelSerializer): ...
[ "While saving try to add the child field in the serializer:\nclass ScheduleSerializer(serializers.ModelSerializer):\n day_of_the_week = serializers.SerializerMethodField()\n def get_day_of_the_week(self, instance):\n\n return instance.day_of_the_week[1:-1].split(',')\n\n\n class Meta():\n mod...
[ 1 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "mysql", "python" ]
stackoverflow_0074623523_django_django_models_django_rest_framework_mysql_python.txt
Q: maximum word split using Recursion Given a string s and a dictionary of valid words d, determine the largest number of valid words the string can be split up into using Recursion I tried solving this problem with the code below but it is not giving me the answer I am looking for. Can someone please help me underst...
maximum word split using Recursion
Given a string s and a dictionary of valid words d, determine the largest number of valid words the string can be split up into using Recursion I tried solving this problem with the code below but it is not giving me the answer I am looking for. Can someone please help me understand how Recursion can be used to solve t...
[ "There are these issues:\n\nThe recursive call is made with the same values for both arguments, which means the recursion -- if it starts -- will never end: the conditions are always the same. The aim of recursion is to solve a smaller problem, so you should pass a shorter string -- without the prefix that was just...
[ 0 ]
[]
[]
[ "algorithm", "dynamic_programming", "python", "recursion" ]
stackoverflow_0074621047_algorithm_dynamic_programming_python_recursion.txt
Q: typeerror print_slow() takes 1 positional argument but 2 were given so im fiddling around in pytbon cuz im bored and i realise i try to slow print a input i have earlier in the code i bave defined slow print ive imported every thing i need but when i run it it saw its got 1 positional argument buts been give 2 and...
typeerror print_slow() takes 1 positional argument but 2 were given
so im fiddling around in pytbon cuz im bored and i realise i try to slow print a input i have earlier in the code i bave defined slow print ive imported every thing i need but when i run it it saw its got 1 positional argument buts been give 2 and im not that good at coding and am only a young student so coupd anyone b...
[ "You are implicitly checking that the input value is of type int by converting the input string. If you insist on doing that then you might find this easier:\nfrom time import sleep\n\ndef print_slow(*args):\n for arg in args:\n for c in str(arg):\n print(c, flush=True, end='')\n sle...
[ 0, 0 ]
[]
[]
[ "input", "printing", "python", "python_2.7" ]
stackoverflow_0074623860_input_printing_python_python_2.7.txt
Q: Is there a way to grab list attributes that have been initialized using self and append data to them in Python? I have a class in Python that initializes the attributes of an environment. I am attempting to grab the topographyRegistry attribute list of my Environment class in a separate function, which when called...
Is there a way to grab list attributes that have been initialized using self and append data to them in Python?
I have a class in Python that initializes the attributes of an environment. I am attempting to grab the topographyRegistry attribute list of my Environment class in a separate function, which when called, should take in the parameters of 'self' and the topography to be added. When this function is called, it should sim...
[ "Comments\n\nDespite having def getRegisteredEnvironment(self): it wasn't indented, so it's not recognized as a class method.\nself is a keyword used in conjunction with classes (class methods or attributes) - not functions. self is implied to be the instantiated object (eg a = Environment(...) -> self would refer ...
[ 1, 0 ]
[]
[]
[ "object", "python", "self" ]
stackoverflow_0074623581_object_python_self.txt
Q: Using function scoped fixture to setup a class I have a fixture in conftest.py with a function scope. @pytest.fixture() def registration_setup( test_data, # fixture 1 credentials, # fixture 2 deployment # fixture 3 deployment_object # fixture 4 ): # pre-test cleanup do_cleanup() yield ...
Using function scoped fixture to setup a class
I have a fixture in conftest.py with a function scope. @pytest.fixture() def registration_setup( test_data, # fixture 1 credentials, # fixture 2 deployment # fixture 3 deployment_object # fixture 4 ): # pre-test cleanup do_cleanup() yield # post-test cleanup do_cleanup() I use it in...
[ "Option 1\nYou can use the same approach you did on your other test class, but set the fixture scope to class:\nclass TestClass:\n\n @pytest.fixture(scope='class', autouse=True)\n def _inventory_cleanup(self, registration_setup):\n log('Cleanup Done!')\n \n def test_1():\n ...\n\n def t...
[ 0, 0 ]
[]
[]
[ "fixtures", "pytest", "pytest_fixtures", "python", "selenium" ]
stackoverflow_0074561999_fixtures_pytest_pytest_fixtures_python_selenium.txt
Q: Standardize same-scale variables? thinking about a problem… should you standardize two predictors that are already on the same scale (say kilograms) but may have different ranges? The model is a KNN I think you should because the model will give the predictor eith the higher range more importance in calculating di...
Standardize same-scale variables?
thinking about a problem… should you standardize two predictors that are already on the same scale (say kilograms) but may have different ranges? The model is a KNN I think you should because the model will give the predictor eith the higher range more importance in calculating distance
[ "It is better to standardize the data even though being on same scale. Standardizing would reduce the distance (specifically euclidean) that would help weights to not vary much from the point intial to them. Having huge seperated distance would rather have more calculation involved. Also distance calculation done i...
[ 0 ]
[]
[]
[ "knn", "machine_learning", "python", "standardization" ]
stackoverflow_0074623115_knn_machine_learning_python_standardization.txt
Q: How can I know a anaconda installer is for which python version? I want to install python3.7 by anaconda and the anaconda list is shown below: anaconda version list。 My question is how can I know a anaconda installer is for a special verison of python? Actually, I know "Anaconda3-2020.05-Linux-x86_64.sh" is for py...
How can I know a anaconda installer is for which python version?
I want to install python3.7 by anaconda and the anaconda list is shown below: anaconda version list。 My question is how can I know a anaconda installer is for a special verison of python? Actually, I know "Anaconda3-2020.05-Linux-x86_64.sh" is for python3.7。However, I am confused that by what infomation we can get the ...
[ "You can install specific version of python through the anaconda prompt, using:\nconda install python = 2.7.8 or conda install python = 3.5.0 (for example).\nYou can even create a dedicated python environnement for a specific version:\nconda create --name py36 python=3.6\n", "Anton B answer is correct, but if you...
[ 1, 1 ]
[]
[]
[ "anaconda", "python" ]
stackoverflow_0074623821_anaconda_python.txt
Q: Application runs with uvicorn but can't find Module (No module named 'app') . ├── __pycache__ │ └── api.cpython-310.pyc ├── app │ ├── __pycache__ │ │ └── main.cpython-310.pyc │ ├── api_v1 │ │ ├── __pycache__ │ │ │ └── apis.cpython-310.pyc │ │ ├── apis.py │ │ └── endpoints │ │ ├─...
Application runs with uvicorn but can't find Module (No module named 'app')
. ├── __pycache__ │ └── api.cpython-310.pyc ├── app │ ├── __pycache__ │ │ └── main.cpython-310.pyc │ ├── api_v1 │ │ ├── __pycache__ │ │ │ └── apis.cpython-310.pyc │ │ ├── apis.py │ │ └── endpoints │ │ ├── __pycache__ │ │ │ └── message_prediction.cpython-310.pyc │ │ ...
[ "python app/main.py will make app/ the first entry in sys.path, so app imports within won't work.\nDo python -m app.main to run app/main.py as a module without having Python touch sys.path.\n" ]
[ 1 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0074624111_fastapi_python.txt
Q: Running Json file in VScode using Python I am very fresh in Python. I would like to read JSON files in Python, but I did not get what are the problems. Please see the image. A: You have to specify a mode to the open() function. In this case I think you're trying to read the file, so your mode would be "r". Your ...
Running Json file in VScode using Python
I am very fresh in Python. I would like to read JSON files in Python, but I did not get what are the problems. Please see the image.
[ "You have to specify a mode to the open() function. In this case I think you're trying to read the file, so your mode would be \"r\". Your code should be:\nwith open(r'path/to/read/','r') as file: \n data = json.load(file)\n\nYour code should run now.\n", "Your path should not contain spaces. Please modify the ...
[ 1, 0, 0 ]
[]
[]
[ "json", "python", "visual_studio_code" ]
stackoverflow_0074623982_json_python_visual_studio_code.txt
Q: Object Detection Using YOLOv3 I was implementing YOLOv3 for object detection using python in visual studio. My code is working fine but it's not detecting bounding boxes with it's label which means that bounding boxes code is not working. I am unable to find the error behind it. I have used yolov3 pretrained model...
Object Detection Using YOLOv3
I was implementing YOLOv3 for object detection using python in visual studio. My code is working fine but it's not detecting bounding boxes with it's label which means that bounding boxes code is not working. I am unable to find the error behind it. I have used yolov3 pretrained models in my code. Can any one tell me w...
[ "try to replace layer_names[i[0] - 1] with layer_name[i-1]\ndef getOutputsNames(net):\n # Get the names of all the layers in the network\n layersNames = net.getLayerNames()\n # Get the names of the output layers, i.e. the layers with unconnected outputs\n return [layersNames[i - 1] for i in net.getUncon...
[ 0 ]
[]
[]
[ "python", "python_3.x", "visual_c++", "visual_studio", "yolo" ]
stackoverflow_0060427567_python_python_3.x_visual_c++_visual_studio_yolo.txt
Q: ETL from SQL Server with AWS Glue in Python I need to write an ETL job that run regularly with AWS Glue, in Python. The job is to query data SQL Server. If I do this on local machine, I need to install pyodbc (pip install pyodbc and an ODBC driver (from here), and run this sample Python code (referenced from here)...
ETL from SQL Server with AWS Glue in Python
I need to write an ETL job that run regularly with AWS Glue, in Python. The job is to query data SQL Server. If I do this on local machine, I need to install pyodbc (pip install pyodbc and an ODBC driver (from here), and run this sample Python code (referenced from here): cnxn_str = ("Driver={SQL Server Native Client 1...
[ "pyodbc is available by default in aws glue python shell jobs. Please keep track of the official aws docs to know the latest running version. You may also find a list of other supported and managed libraries in below link\nhttps://docs.aws.amazon.com/glue/latest/dg/add-job-python.html\nYou could go ahead and import...
[ 0 ]
[]
[]
[ "aws_glue", "pyodbc", "python" ]
stackoverflow_0073979688_aws_glue_pyodbc_python.txt
Q: Problem with for loop, break statement does not do what I thought it would This is my first time posting here, so be gentle, please. I have written the following code: import pandas as pd import spacy df = pd.read_csv('../../../Data/conll2003.dev.conll', sep='\t', on_bad_lines='skip', header=None) nlp = spacy.lo...
Problem with for loop, break statement does not do what I thought it would
This is my first time posting here, so be gentle, please. I have written the following code: import pandas as pd import spacy df = pd.read_csv('../../../Data/conll2003.dev.conll', sep='\t', on_bad_lines='skip', header=None) nlp = spacy.load('en_core_web_sm') nlp.max_length = 1500000 ## https://stackoverflow.com/quest...
[ "You should preserve the original tokenization. To do this, manually create the Doc in order to skip the tokenizer in the pipeline:\nimport spacy\nfrom spacy.tokens import Doc\n\nnlp = spacy.load(model)\nwords = [\"here\", \"are\", \"the\", \"original\", \"tokens\"]\ndoc = Doc(nlp.vocab, words=words)\n\n# apply the...
[ 1 ]
[]
[]
[ "conll", "nlp", "pandas", "python", "spacy" ]
stackoverflow_0074623127_conll_nlp_pandas_python_spacy.txt
Q: What will be the python regex to match this? Given this string: var python_books = { 'name': 'Python Notebooks', 'sub-menu': [{ 'name' : 'Python Research Notebook', 'snippet' : [ 'import os, sys, json, time', '', 'import numpy as np...
What will be the python regex to match this?
Given this string: var python_books = { 'name': 'Python Notebooks', 'sub-menu': [{ 'name' : 'Python Research Notebook', 'snippet' : [ 'import os, sys, json, time', '', 'import numpy as np', 'import pandas as pd', ...
[ "try this\nvar_python_books = {\n 'name': 'Python Notebooks',\n 'sub-menu': [{\n 'name': 'Python Research Notebook',\n 'snippet': [\n 'import os, sys, json, time',\n '',\n 'import numpy as np',\n 'import pandas as pd',\n 'import matplotlib.p...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074623680_python_regex.txt
Q: Serialize QuerySet to JSON with FK DJANGO I want to send a JSON of a model of an intersection table so I only have foreign keys saved, I tried to make a list and then convert it to JSON but I only receive the ids and I need the content, I also tried in the back as a temporary solution to make a dictionary with the...
Serialize QuerySet to JSON with FK DJANGO
I want to send a JSON of a model of an intersection table so I only have foreign keys saved, I tried to make a list and then convert it to JSON but I only receive the ids and I need the content, I also tried in the back as a temporary solution to make a dictionary with the Queryset but the '<>' makes it mark an error i...
[ "I am not sure that I get the question right, but if you need a special field value from foreign key you can use smth like:\nPrograma_periodo.objects.values(\"id\", \"periodo__periodo\", \"programa__programa\")\n\nWith double underscore. Try it in the shell first. Check the docs here https://docs.djangoproject.com/...
[ 1 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0074622766_django_django_queryset_python.txt
Q: Adding background image to the window with Qt-Designer (Pyqt5)- Error: Could not create pixmap from : Why is it so hard to get a 'bcg-image' in the background with PyQt5? Please read my explanation before answering, I am a beginner in programming and it has been a week looking for a solution for the problem. I hav...
Adding background image to the window with Qt-Designer (Pyqt5)- Error: Could not create pixmap from :
Why is it so hard to get a 'bcg-image' in the background with PyQt5? Please read my explanation before answering, I am a beginner in programming and it has been a week looking for a solution for the problem. I have a program with the first window that has many input fields to enter some data from the user. After that, ...
[ "At MainWindow on the Qt Designer\nMouse Right Click --> Change styleSheet --> Add Resources\nadd your image\n" ]
[ 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qt", "qt_designer" ]
stackoverflow_0074623965_pyqt_pyqt5_python_qt_qt_designer.txt
Q: Maximum of Each Row and return the columname in a dataframe having a data frame as below: I need to find the largest value in each row and return the column name. Expected output: I tried the below code: df['Max'] = df.idxmax(axis=1) error:TypeError: reduction operation 'argmax' not allowed for this dtype A: I...
Maximum of Each Row and return the columname in a dataframe
having a data frame as below: I need to find the largest value in each row and return the column name. Expected output: I tried the below code: df['Max'] = df.idxmax(axis=1) error:TypeError: reduction operation 'argmax' not allowed for this dtype
[ "It seems that adding numeric_only flag would solve your problem:\n# Panda 1.5.2\nimport pandas as pd\n\nd = {'prod': ['p1', 'p2', 'p3'], 'p1': [10, 20.0, 30], 'p2': [7 ,6 ,4], 'p3': [12,50,5], 'MAX': ['','','']}\ndf = pd.DataFrame(data=d)\nprint(type(df)) # <class 'pandas.core.frame.DataFrame'>\ndf['MAX'] = df.idx...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074624062_dataframe_python.txt
Q: Randomly remove 'x' elements from a list I'd like to randomly remove a fraction of elements from a list without changing the order of the list. Say I had some data and I wanted to remove 1/4 of them: data = [1,2,3,4,5,6,7,8,9,10] n = len(data) / 4 I'm thinking I need a loop to run through the data and delete a...
Randomly remove 'x' elements from a list
I'd like to randomly remove a fraction of elements from a list without changing the order of the list. Say I had some data and I wanted to remove 1/4 of them: data = [1,2,3,4,5,6,7,8,9,10] n = len(data) / 4 I'm thinking I need a loop to run through the data and delete a random element 'n' times? So something like: ...
[ "Sequential deleting is a bad idea since deletion in a list is O(n). Instead do something like this:\ndef delete_rand_items(items,n):\n to_delete = set(random.sample(range(len(items)),n))\n return [x for i,x in enumerate(items) if not i in to_delete]\n\n", "You can use random.sample like this:\nimport rando...
[ 11, 5, 1, 0, 0 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0044883905_list_python_random.txt
Q: How to apply aplhabetic and numeric validation rule to database columns in pyspark? I have one DB contains emp table ID,NAME,YEAR,AGE,DEPT columns. I want to print pass if the NAME column passes the condition that contains characters only else fail. And pass if year is in dd-mm-yyyy format else fail pass if age co...
How to apply aplhabetic and numeric validation rule to database columns in pyspark?
I have one DB contains emp table ID,NAME,YEAR,AGE,DEPT columns. I want to print pass if the NAME column passes the condition that contains characters only else fail. And pass if year is in dd-mm-yyyy format else fail pass if age col contains integers only else fail And is it possible that above whole process can move t...
[ "For each part of your question, you can use a trick.\nname: you can use regular-expression with rlike() function.\ndate: you can cast date string to date format and check if it is valid.\nname: you can cast to integer and check if it is valid.\nnote that if a cast is not valid pyspark returns Null.\nschema = ['age...
[ 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074623785_pyspark_python.txt
Q: Sudoku Backtracking Python to find Multiple Solutions I have a code to solve a Sudoku recursively and print out the one solution it founds. But i would like to find the number of multiple solutions. How would you modify the code that it finds all possible solutions and gives out the number of solutions? Thank you!...
Sudoku Backtracking Python to find Multiple Solutions
I have a code to solve a Sudoku recursively and print out the one solution it founds. But i would like to find the number of multiple solutions. How would you modify the code that it finds all possible solutions and gives out the number of solutions? Thank you! :) code: board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,...
[ "From a high-level view, it seems to me that a recursive approach to this should work as follows:\n\nCheck if the grid is valid:\n\nIf the grid is invalid, return immediately\nElse, check if the grid is complete:\n\nIf the the grid is complete, add (a copy of) it to the list of\nsolutions\nElse, the grid is valid a...
[ 0, 0 ]
[]
[]
[ "backtracking", "python", "recursion", "sudoku" ]
stackoverflow_0074622588_backtracking_python_recursion_sudoku.txt
Q: JSON pandas dataframe ValueError: Expected object or value I am trying to read a JSON file using pandas. The JSON file is in this format: { "category": "CRIME", "headline": "There Were 2 Mass Shootings In Texas Last Week, But Only 1 On TV", "authors": "Melissa Jeltsen", "link": "https://www.huff...
JSON pandas dataframe ValueError: Expected object or value
I am trying to read a JSON file using pandas. The JSON file is in this format: { "category": "CRIME", "headline": "There Were 2 Mass Shootings In Texas Last Week, But Only 1 On TV", "authors": "Melissa Jeltsen", "link": "https://www.huffingtonpost.com/entry/texas-amanda-painter-mass-shooting_us_5b081...
[ "You can wrap it in square brackets [] and add a comma between the dictionaries for valid json.\n[{\n \"category\": \"CRIME\",\n \"headline\": \"There Were 2 Mass Shootings In Texas Last Week, But Only 1 On TV\",\n \"authors\": \"Melissa Jeltsen\",\n \"link\": \"https://www.huffingtonpost.com/entry/texa...
[ 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074624275_dataframe_json_pandas_python.txt
Q: How to add array of integer field in Django Rest Framework? I want to add an array of integer fields in my model class Schedule(models.Model): name = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) day_of_t...
How to add array of integer field in Django Rest Framework?
I want to add an array of integer fields in my model class Schedule(models.Model): name = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) day_of_the_week = ?? ( array of integer ) I tried with class Schedule(mo...
[ "Try this:\nclass Schedule(models.Model):\n name = models.CharField(max_length=100)\n start_time = models.DateTimeField(auto_now_add=True)\n end_time = models.DateTimeField(null=True, blank=True)\n day_of_the_week = models.JSONField(default=list)\n\nclass ScheduleSerializer(serializers.ModelSerializer):...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_serializer", "python" ]
stackoverflow_0074624299_django_django_models_django_rest_framework_django_serializer_python.txt
Q: Selenium overlay button cannot be clicked I am having some issues with one website's button. Here is my driver function. def get_driver(): options = webdriver.ChromeOptions() # options.add_argument("--headless") options.add_argument("--incognito") driver = webdriver.Chrome(executable_path = ChromeD...
Selenium overlay button cannot be clicked
I am having some issues with one website's button. Here is my driver function. def get_driver(): options = webdriver.ChromeOptions() # options.add_argument("--headless") options.add_argument("--incognito") driver = webdriver.Chrome(executable_path = ChromeDriverManager().install(), chrome_options = ...
[ "Try this:\nWebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"ModalFocusTrapZone30\")))\ndriver.find_element(By.ID, \"Dropdown31-option\").click()\ntime.sleep(1)\ndriver.find_element(By.XPATH, \".//*[contains(text(), 'Šilutės 28B, Klaipėda')]\").click()\ntime.sleep(1)\ndriver.find_element(By....
[ 1 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074624230_python_selenium_web_scraping.txt
Q: How can I label a column of strings into numbered groups based on another column containing substrings? I have the 1st column that is around 4920 different chemical compounds. For example: 0 Ag(AuS)2 1 Ag(W3Br7)2 2 Ag0.5Ge1Pb1.75S4 3 Ag0.5Ge1Pb1.75Se4 4 ...
How can I label a column of strings into numbered groups based on another column containing substrings?
I have the 1st column that is around 4920 different chemical compounds. For example: 0 Ag(AuS)2 1 Ag(W3Br7)2 2 Ag0.5Ge1Pb1.75S4 3 Ag0.5Ge1Pb1.75Se4 4 Ag2BBr ... ... 4916 ZrTaN3 4917 ZrTe ...
[ "Since the first element could be a varying number of letters, the simplest solution would be to use the regex approach for getting the first section.\nFor example:\nimport re\n\ncompounds = [\"Ag(AuS)2\", \"HTiF\", \"ZrTaN3\"]\n\nfor compound in compounds:\n match = re.match(r\"[A-Z][a-z]*\", compound)\n if ...
[ 2 ]
[]
[]
[ "categorical_data", "floating_point", "grouping", "python", "string" ]
stackoverflow_0074624050_categorical_data_floating_point_grouping_python_string.txt
Q: How to round only numbers in python dataframe columns with object mixed I have a dataframe named "df" as the picture. In this dataframe there are "null" as object(dtype) and numerics. I wish to round(2) only the numeric values in multiple columns. I have written this code but keep getting "TypeError: 'int' object ...
How to round only numbers in python dataframe columns with object mixed
I have a dataframe named "df" as the picture. In this dataframe there are "null" as object(dtype) and numerics. I wish to round(2) only the numeric values in multiple columns. I have written this code but keep getting "TypeError: 'int' object is not iterable" as TypeError. *The first line code is to convert na's to "n...
[ "round before fillna:\ndf['skor_change_w_ts'] = (pd.to_numeric(df['skor_change_w_ts'], errors='coerce')\n .round(2).fillna(\"null\", downcast='infer')\n )\n\nExample input:\ndf = pd.DataFrame({'skor_change_w_ts': [1, 2.6666, 'null']})\n\nOutput:\n skor_change_w_...
[ 1, 1 ]
[]
[]
[ "dataframe", "numeric", "pandas", "python", "rounding" ]
stackoverflow_0074624331_dataframe_numeric_pandas_python_rounding.txt
Q: Python Creating Dictionary from excel data I want to create a dictionary from the values, i get from excel cells, My code is below, wb = xlrd.open_workbook('foo.xls') sh = wb.sheet_by_index(2) for i in range(138): cell_value_class = sh.cell(i,2).value cell_value_id = sh.cell(i,0).value and I want to c...
Python Creating Dictionary from excel data
I want to create a dictionary from the values, i get from excel cells, My code is below, wb = xlrd.open_workbook('foo.xls') sh = wb.sheet_by_index(2) for i in range(138): cell_value_class = sh.cell(i,2).value cell_value_id = sh.cell(i,0).value and I want to create a dictionary, like below, that consists of...
[ "or you can try pandas\nfrom pandas import *\nxls = ExcelFile('path_to_file.xls')\ndf = xls.parse(xls.sheet_names[0])\nprint df.to_dict()\n\n", "d = {}\nwb = xlrd.open_workbook('foo.xls')\nsh = wb.sheet_by_index(2) \nfor i in range(138):\n cell_value_class = sh.cell(i,2).value\n cell_value_id = sh.cell(i,...
[ 49, 20, 17, 5, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0014196013_python_xlrd.txt
Q: Adding nested dictionary to another one would like to make a contact book using dictinaries but i cant figure out how to add a nested dict to the current dict i have. would be something like this my_contacts = {"1": { "Tom Jones", "911", "22.10.1995"}, "2": { "Bob Marley", "0800838383", "22.10.1991"}...
Adding nested dictionary to another one
would like to make a contact book using dictinaries but i cant figure out how to add a nested dict to the current dict i have. would be something like this my_contacts = {"1": { "Tom Jones", "911", "22.10.1995"}, "2": { "Bob Marley", "0800838383", "22.10.1991"} } def add_contact(): user_i...
[ "This will be a nice solution for you.\nAll i'm doing here is every time you iterate inside your for loop you are creating a new dictionary of the details you want to put in for a contact and adding that dictionary to the original dictionary, therefor adding a new contact as a dictionary. There should be some extra...
[ 0, 0 ]
[]
[]
[ "contacts", "dictionary", "list", "nested", "python" ]
stackoverflow_0074624280_contacts_dictionary_list_nested_python.txt
Q: How to calculate time in pairs - python dataframe I have a data frame with data: Transaction group - superior Application number - could be different in one transaction group Created time – data time Status - application or calculation. And I want to calculate time between Created time for each pair in status ap...
How to calculate time in pairs - python dataframe
I have a data frame with data: Transaction group - superior Application number - could be different in one transaction group Created time – data time Status - application or calculation. And I want to calculate time between Created time for each pair in status application – calculation. Data doesn’t have column ‘pair...
[ "Use a pivot and rename:\ndf['pairs'] = df.groupby('Status').cumcount()\n\n(df.pivot(index=['pairs', 'Transaction group', 'Application number'],\n columns='Status', values='Created time')\n .rename(columns={'application': 'start_time', 'calculation': 'end_time'})\n .reset_index()\n)\n\nOutput:\nStatus p...
[ 0 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074624381_dataframe_group_by_pandas_python.txt
Q: Stop pip from failing on single package when installing with requirements.txt I am installing packages from requirements.txt pip install -r requirements.txt The requirements.txt file reads: Pillow lxml cssselect jieba beautifulsoup nltk lxml is the only package failing to install and this leads to everything fai...
Stop pip from failing on single package when installing with requirements.txt
I am installing packages from requirements.txt pip install -r requirements.txt The requirements.txt file reads: Pillow lxml cssselect jieba beautifulsoup nltk lxml is the only package failing to install and this leads to everything failing (expected results as pointed out by larsks in the comments). However, after lx...
[ "Running each line with pip install may be a workaround.\ncat requirements.txt | xargs -n 1 pip install\n\nNote: -a parameter is not available under MacOS, so old cat is more portable.\n", "This solution handles empty lines, whitespace lines, # comment lines, whitespace-then-# comment lines in your requirements.t...
[ 395, 27, 12, 9, 4, 4, 3, 2, 0, 0, 0 ]
[ "For Windows:\nimport os\nfrom pip.__main__ import _main as main\n\nerror_log = open('error_log.txt', 'w')\n\ndef install(package):\n try:\n main(['install'] + [str(package)])\n except Exception as e:\n error_log.write(str(e))\n\nif __name__ == '__main__':\n f = open('requirements1.txt', 'r')...
[ -2 ]
[ "pip", "python" ]
stackoverflow_0022250483_pip_python.txt
Q: found changes on same id (column A) pandas I have dataframe # | A | B | C | D | E --+-------+-------+-------+-------+------- 1 | "5" | "4" | "2" | "3" | "2022-11-29" | 2 | "5" | "d" | "2" | "3" | "2022-11-30" | 3 | "5" | "4" | "2" | "h" | "2022-11-29" | 4 | "4" ...
found changes on same id (column A) pandas
I have dataframe # | A | B | C | D | E --+-------+-------+-------+-------+------- 1 | "5" | "4" | "2" | "3" | "2022-11-29" | 2 | "5" | "d" | "2" | "3" | "2022-11-30" | 3 | "5" | "4" | "2" | "h" | "2022-11-29" | 4 | "4" | "4" | "2" | "3" | "2022-11-28" | 5 | ...
[ "You can compare most common value per columns by DataFrame.mode by DataFrame.eq, set missing values by DataFrame.where if no match, reshape by DataFrame.stack, last convert to DataFrame:\ndf1 = df.set_index('A').drop('E', axis=1)\n\nprint (df1)\n B C D\nA \n5 4 2 3\n5 d 2 g <- added new not match...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074624488_dataframe_pandas_python.txt
Q: Is there any library like arch unit for Django? I've been searching for a library or tool to test my Django project architecture, check the dependencies, layers, etc. like Arch Unit for Java. But until now, I didn't find anything. I don't even know if it's viable doing these kinds of tests in Python/Django project...
Is there any library like arch unit for Django?
I've been searching for a library or tool to test my Django project architecture, check the dependencies, layers, etc. like Arch Unit for Java. But until now, I didn't find anything. I don't even know if it's viable doing these kinds of tests in Python/Django projects. I know that Django itself already checks for cycli...
[ "Check out what you can find under Python complexity metrics.\nA tool called Wily may be of use. However, what counts as good practices will be very different for Java and Python.\n", "The closest that I know of is https://github.com/seddonym/import-linter\nIt's capable only of linting - as the name suggests - i...
[ 2, 0, 0 ]
[]
[]
[ "architecture", "archunit", "django", "python", "testing" ]
stackoverflow_0066692195_architecture_archunit_django_python_testing.txt
Q: Implementing a function that returns a n x m matrix in counter-clockwise spiral order starting from at the bottom right entry of the matrix So I'm trying to implement a function in python that returns all elements of a n x m matrix in counter-clockwise spiral order, starting at the bottom furthest-right entry of t...
Implementing a function that returns a n x m matrix in counter-clockwise spiral order starting from at the bottom right entry of the matrix
So I'm trying to implement a function in python that returns all elements of a n x m matrix in counter-clockwise spiral order, starting at the bottom furthest-right entry of the matrix. For example, let's say the input was: matrix = [[1,2,3], [4,5,6], [7,8,9]] Then our output would be [9, 6, 3, 2,...
[ "You could consider using a while-loop:\ndef spiralOrder(self, matrix: list[list[int]]) -> list[int]:\n result = []\n left, right = 0, len(matrix[0]) - 1\n up, down = 0, len(matrix) - 1\n step = 0\n while left <= right and up <= down:\n match step % 4:\n case 0:\n for...
[ 1 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0074623945_matrix_python.txt
Q: How to use MLFlow in a functional style / functional programming? Is there a reliable way to use MLFlow in a functional style? As it is not possible to pass the run ID for example to the function which logs a parameter, I wonder whether it is possible to seperate code executed in my MLFLow run into multiple pure f...
How to use MLFlow in a functional style / functional programming?
Is there a reliable way to use MLFlow in a functional style? As it is not possible to pass the run ID for example to the function which logs a parameter, I wonder whether it is possible to seperate code executed in my MLFLow run into multiple pure fuctions. Have I overlooked something, or is it simply not possible? So ...
[ "https://mlflow.org/docs/latest/python_api/mlflow.client.html#mlflow.client.MlflowClient.log_param\nlog_param(run_id: str, key: str, value: Any)\n", "The solution is to use the mlflow.client module instead of the mlflow module as stated in the documentation of the mlflow client:\n\nThe mlflow.client module provid...
[ 0, 0 ]
[]
[]
[ "contextmanager", "functional_programming", "machine_learning", "mlflow", "python" ]
stackoverflow_0074603005_contextmanager_functional_programming_machine_learning_mlflow_python.txt
Q: i have made a function to stem by data, but it gives error def stem(text): y=[] for i in text.split(): y.append(ps.stem(i)) return " ".join(y) new_df['tags'].apply(stem()) error:stem() missing 1 required positional argument: 'text' A: try this code.. def stem(text): y=...
i have made a function to stem by data, but it gives error
def stem(text): y=[] for i in text.split(): y.append(ps.stem(i)) return " ".join(y) new_df['tags'].apply(stem()) error:stem() missing 1 required positional argument: 'text'
[ "try this code..\ndef stem(text):\n y=[]\n for i in text.split():\n y.append(ps.stem(i))\n return \" \".join(y)\n\nnew_df['tags']=new_df['tags'].apply(stem)\n\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0070912880_pandas_python.txt
Q: How can I get the node where the pod is located using kubernetes python client? I have a Pod name and I want to know where the Pod is located using kubernetes python client. Is it possible to use kubernetes python client in order to get the node name by Pod? (Just like the NODE column in kubectl get pod -o wide) I...
How can I get the node where the pod is located using kubernetes python client?
I have a Pod name and I want to know where the Pod is located using kubernetes python client. Is it possible to use kubernetes python client in order to get the node name by Pod? (Just like the NODE column in kubectl get pod -o wide) I've referred to the document https://github.com/kubernetes-client/python/blob/master/...
[ "I think read_namespaced_pod has the information (spec.nodeName).\nhttps://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md#read_namespaced_pod\n" ]
[ 0 ]
[]
[]
[ "api", "client", "kubernetes", "python" ]
stackoverflow_0074623810_api_client_kubernetes_python.txt
Q: How can you compare two lists in such a way that you find out how many times a word from one list is in the second list? I have two lists, one containing true values selected by humans and a second list with extracted values. I would like to measure how well the pipeline is performing based on how many true values...
How can you compare two lists in such a way that you find out how many times a word from one list is in the second list?
I have two lists, one containing true values selected by humans and a second list with extracted values. I would like to measure how well the pipeline is performing based on how many true values are contained in the extracted list. Example: extracted_value = ["value", "of", "words", "that", "were", "tracked"] real_valu...
[ "Will something simple like this work?\nscore = len([x for x in real_value if x in extracted_value])/len(extracted_value)\nprint(score)\n>>> 0.5\n\n", "The metric you're looking for is recall.\n@sfat's solution works well for a single document, you can then get the average over multiple documents by summing the s...
[ 1, 0, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0074624497_performance_python.txt
Q: Linux Selenium Chromedriver can't connect to chrome version I'm transferring my python scraper to a vps on Ubuntu. I've installed chromedriver using apt get and I'm getting an error when running my script. selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:...
Linux Selenium Chromedriver can't connect to chrome version
I'm transferring my python scraper to a vps on Ubuntu. I've installed chromedriver using apt get and I'm getting an error when running my script. selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:51757 from session not created: This version of ChromeDriver only...
[ "You have to have the version that your Selenium driver was downloaded for.\nIf you want to maintain your 107.0.5304.121 version on Chrome, download the selenium 107.x.x.x driver\nhttps://chromedriver.chromium.org/downloads\nYou can check here all the latest versions\n" ]
[ 0 ]
[]
[]
[ "linux", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074624643_linux_python_selenium_selenium_chromedriver.txt
Q: SQLAlchemy: Separation of table classes by different files I will try to explain in order so that my question is clear. The simplified code executed according to the lesson: engine = create_engine(...) session = (...) Base = declarative_base() class <someTable>(Base): ... Base.metadata.create_all(bind=engine...
SQLAlchemy: Separation of table classes by different files
I will try to explain in order so that my question is clear. The simplified code executed according to the lesson: engine = create_engine(...) session = (...) Base = declarative_base() class <someTable>(Base): ... Base.metadata.create_all(bind=engine) And in this case, everything works as it should. A table in t...
[ "Each model class must be read by the interpreter before create_all is called, otherwise they will not be in the metadata and so will not be created. So what you need to do is:\n\nDefine Base in a module.\nAll the files that declare model classes must import the module that defines Base, and use that Base as their ...
[ 0 ]
[]
[]
[ "orm", "python", "python_3.x", "sqlalchemy" ]
stackoverflow_0074623946_orm_python_python_3.x_sqlalchemy.txt
Q: server starts to closed the connection unexpectedly I have a project with 10+ parsers and at the end have this code: ` cursor = conn.cursor() my_file = open(r'csv\file.csv') sql_statement = """ CREATE TEMP TABLE temp ( LIKE vhcl ) ON COMMIT DROP; ...
server starts to closed the connection unexpectedly
I have a project with 10+ parsers and at the end have this code: ` cursor = conn.cursor() my_file = open(r'csv\file.csv') sql_statement = """ CREATE TEMP TABLE temp ( LIKE vhcl ) ON COMMIT DROP; COPY temp FROM STDIN WITH CSV ...
[ "You have a network problem.\nBoth the server and the client complain that the other side unexpectedly hung up on them. So it was some misconfigured network component in the middle that cut the line. You have two options:\n\nfix the network\n\nlower tcp_keepalives_idle on the PostgreSQL client or server, so that th...
[ 0, 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074611976_postgresql_psycopg2_python.txt
Q: fake_useragent module not connecting properly - IndexError: list index out of range I tried to use fake_useragent module with this block from fake_useragent import UserAgent ua = UserAgent() print(ua.random) But when the execution reached this line ua = UserAgent(), it throws this error Traceback (most recent ca...
fake_useragent module not connecting properly - IndexError: list index out of range
I tried to use fake_useragent module with this block from fake_useragent import UserAgent ua = UserAgent() print(ua.random) But when the execution reached this line ua = UserAgent(), it throws this error Traceback (most recent call last): File "/home/hadi/Desktop/excel/gatewayform.py", line 191, in <module> gat...
[ "There is a solution for this, from Github pull request #110. Basically, all you need to do is change one character in one line of the fake_useragent/utils.py source code.\nTo do this on your system, open /usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py† in your favorite text editor using admin privil...
[ 15, 0 ]
[]
[]
[ "python", "user_agent" ]
stackoverflow_0068772211_python_user_agent.txt
Q: Getting Errors When Using Google Search API on Python I'm trying to run a Google Search API on Python, specifically this one: https://github.com/abenassi/Google-Search-API. When I try to test it out by running this code on Sublime Text 3, from google import google num_page = 1 search_results = google.search("This ...
Getting Errors When Using Google Search API on Python
I'm trying to run a Google Search API on Python, specifically this one: https://github.com/abenassi/Google-Search-API. When I try to test it out by running this code on Sublime Text 3, from google import google num_page = 1 search_results = google.search("This is my query", num_page) for result in search_results: p...
[ "fake_useragent is only to mimic as a user agent but not official. Hence it throws error when detected. For the most recent call lost I did the following:\n\npip3 install fake_useragent --upgrade\nua = UserAgent(use_cache_server = False, verify_ssl=False) #Very important step, after this step you can write your cod...
[ 1, 0, 0 ]
[]
[]
[ "google_search_api", "python", "python_3.x" ]
stackoverflow_0057531742_google_search_api_python_python_3.x.txt
Q: ModuleNotFoundError: No module named 'pandas.compat' I have been working with pandas all the time, but now it suddenly says: "ModuleNotFoundError: No module named 'pandas.compat'" when importing it. I didnt (knowlingly) change anything. I already reainstalled it (and pandas-compat). I even created a whole new envi...
ModuleNotFoundError: No module named 'pandas.compat'
I have been working with pandas all the time, but now it suddenly says: "ModuleNotFoundError: No module named 'pandas.compat'" when importing it. I didnt (knowlingly) change anything. I already reainstalled it (and pandas-compat). I even created a whole new environment. I still cant import it. Anybody has a clue what t...
[ "You may have several installations of pandas library. So uninstall pandas using\n\"pip uninstall pandas\".\n(If on linux use:\n\" sudo apt-get purge python3-pandas\")\nand install again.\nThis helped solve my problem.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0073258906_pandas_python.txt
Q: Find number of datapoints in each range I have a data frame that looks like this data = [['A', 0.20], ['B',0.25], ['C',0.11], ['D',0.30], ['E',0.29]] df = pd.DataFrame(data, columns=['col1', 'col2']) Col1 is a primary key (each row has a unique value) The max of col2 is 1 and the min is 0. I want to find the numb...
Find number of datapoints in each range
I have a data frame that looks like this data = [['A', 0.20], ['B',0.25], ['C',0.11], ['D',0.30], ['E',0.29]] df = pd.DataFrame(data, columns=['col1', 'col2']) Col1 is a primary key (each row has a unique value) The max of col2 is 1 and the min is 0. I want to find the number of datapoint in ranges 0-.30 (both 0 and 0...
[ "One option using numpy broadcasting:\nstep = 0.01\nup = np.arange(0, 0.3+step, step)\n\nout = pd.Series((df['col2'].to_numpy()[:,None] <= up).sum(axis=0), index=up)\n\nOutput:\n0.00 0\n0.01 0\n0.02 0\n0.03 0\n0.04 0\n0.05 0\n0.06 0\n0.07 0\n0.08 0\n0.09 0\n0.10 0\n0.11 1\n0.12 ...
[ 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074624685_numpy_pandas_python.txt
Q: How to convert list of list binary into list of decimal? LIST OF LIST BIN DIVIDED INTO 8 : [[0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1, 1, 1]] the output I want is: [101, 119] A: This is more complex but significantly faster than any kind of string manipulation as it's essentially just integer arithmetic. from...
How to convert list of list binary into list of decimal?
LIST OF LIST BIN DIVIDED INTO 8 : [[0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1, 1, 1]] the output I want is: [101, 119]
[ "This is more complex but significantly faster than any kind of string manipulation as it's essentially just integer arithmetic.\nfrom timeit import timeit\n\nlob = [[0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1, 1, 1]]\n\ndef v1():\n result = []\n for e in lob:\n r = 0\n for _e in e:\n ...
[ 2 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0074624691_arrays_list_python.txt
Q: How to double for loop over two dataframes I have dataframe consisting of unknown places, just a set of latitude and longitudes. This list contains of a lot of places that almost have the same coordinates. I want to create a new dataframe with 'filtered unknown places', where places that are almost the same are me...
How to double for loop over two dataframes
I have dataframe consisting of unknown places, just a set of latitude and longitudes. This list contains of a lot of places that almost have the same coordinates. I want to create a new dataframe with 'filtered unknown places', where places that are almost the same are merged into one place. For each 'filtered unknown ...
[ "Your df_unknown_places_filtered has no rows.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "python" ]
stackoverflow_0074624784_dataframe_for_loop_python.txt
Q: Integration of a curve generated using matplotlib I have generated a graph using basic function - plt.plot(tm, o1) tm is list of all x coordinates and o1 is a list of all y coordinates NOTE there is no specific function such as y=f(x), rather a certain y value remains constant for a given range of x.. see figure...
Integration of a curve generated using matplotlib
I have generated a graph using basic function - plt.plot(tm, o1) tm is list of all x coordinates and o1 is a list of all y coordinates NOTE there is no specific function such as y=f(x), rather a certain y value remains constant for a given range of x.. see figure for clarity My question is how to integrate this func...
[ "The integral corresponds to computing the area under the curve.\nThe most easy way to compute (or approximate) the integral \"numerically\" is using the rectangle rule which is basically approximating the area under the curve by summing area of rectangles (see https://en.wikipedia.org/wiki/Numerical_integration#Qu...
[ 1 ]
[]
[]
[ "graph", "integral", "list", "matplotlib", "python" ]
stackoverflow_0074624574_graph_integral_list_matplotlib_python.txt
Q: Using click.command to make a function as a command I am trying to make the function log into a command using the following code inside simple.py: import click @click.command() @click.option('-v', '--verbose', count=True) def log(verbose): click.echo(f"Verbosity: {verbose}") When I type the following on the ...
Using click.command to make a function as a command
I am trying to make the function log into a command using the following code inside simple.py: import click @click.command() @click.option('-v', '--verbose', count=True) def log(verbose): click.echo(f"Verbosity: {verbose}") When I type the following on the command terminal:log -vvv , I get an error as : Command '...
[ "import click\n\n@click.command()\n@click.option('-v', '--verbose', count=True)\ndef log(verbose):\n click.echo(f\"Verbosity: {verbose}\")\n\nif __name__ == '__main__':\n log()\n\nThen calling it like\n$ python simple.py \nVerbosity: 0\n\n$ python simple.py -v\nVerbosity: 1\n\nThe way you try to run it, su...
[ 0 ]
[]
[]
[ "command", "python", "python_click" ]
stackoverflow_0074624467_command_python_python_click.txt
Q: Enable Python to Connect to MySQL via SSH Tunnelling I'm using MySqldb with Python 2.7 to allow Python to make connections to another MySQL server import MySQLdb db = MySQLdb.connect(host="sql.domain.com", user="dev", passwd="*******", db="appdb") Instead of connecting normally like this, how c...
Enable Python to Connect to MySQL via SSH Tunnelling
I'm using MySqldb with Python 2.7 to allow Python to make connections to another MySQL server import MySQLdb db = MySQLdb.connect(host="sql.domain.com", user="dev", passwd="*******", db="appdb") Instead of connecting normally like this, how can the connection be made through a SSH tunnel using SSH k...
[ "Only this worked for me\nimport pymysql\nimport paramiko\nimport pandas as pd\nfrom paramiko import SSHClient\nfrom sshtunnel import SSHTunnelForwarder\nfrom os.path import expanduser\n\nhome = expanduser('~')\nmypkey = paramiko.RSAKey.from_private_key_file(home + pkeyfilepath)\n# if you want to use ssh password u...
[ 42, 30, 9, 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "mysql", "python", "python_2.7", "ssh" ]
stackoverflow_0021903411_mysql_python_python_2.7_ssh.txt
Q: Python3 easysnmp querying multiple switches results in a random timeout for some random switches I've got 3 switches I'm trying to get SNMP data from. Every switch does respond from time to time, but which switches respond depends upon the order I'm querying them. I'm using easysnmp.Session. My code (passwords obv...
Python3 easysnmp querying multiple switches results in a random timeout for some random switches
I've got 3 switches I'm trying to get SNMP data from. Every switch does respond from time to time, but which switches respond depends upon the order I'm querying them. I'm using easysnmp.Session. My code (passwords obviously not shown): import easysnmp switches_dns1 = { "switch1": "switch-mBvk1-1.obis.ns.n...
[ "I've been digging a bit deeper and it turns out this issue is caused by several devices using the same engine ID.\nSee https://github.com/easysnmp/easysnmp/issues/156 for more information.\n" ]
[ 0 ]
[]
[]
[ "easysnmp", "python" ]
stackoverflow_0074613299_easysnmp_python.txt
Q: Applying a function depending of index and column of a dataframe to a dataframe I have a dataframe df whose index is [x[0], ..., x[N]] and column is [y[0], ..., y[M]] and whose data is a 2D array of z[i,j]'s. I have a python function def f(x, y, z) of 3 float variables and I would like to calculate the 2d array of...
Applying a function depending of index and column of a dataframe to a dataframe
I have a dataframe df whose index is [x[0], ..., x[N]] and column is [y[0], ..., y[M]] and whose data is a 2D array of z[i,j]'s. I have a python function def f(x, y, z) of 3 float variables and I would like to calculate the 2d array of f(x[i], y[j], z[i,j])'s in the fastest way using numpy and/or pandas but I don't see...
[ "You could do a pd.melt:\ndf.reset_index().rename(columns={'index':'x'}).melt(var_name='y', value_name='z', id_vars='x')\n\nIt essentially transform the dataframe to the long format, making each row to have three entries: x, y and z.\n", "If you don't want to rewite the function, then using loop for to apply the ...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "pybind11", "python" ]
stackoverflow_0074606401_dataframe_numpy_pandas_pybind11_python.txt
Q: Calling TaskGroup with Dynamic sub task id from BranchPythonOperator I want to call a TaskGroup with a Dynamic sub-task id from BranchPythonOperator. This is the DAG flow that I have: branch_dag My case is I want to check whether a table exists in BigQuery or not. If exists: do nothing and end the DAG If not exi...
Calling TaskGroup with Dynamic sub task id from BranchPythonOperator
I want to call a TaskGroup with a Dynamic sub-task id from BranchPythonOperator. This is the DAG flow that I have: branch_dag My case is I want to check whether a table exists in BigQuery or not. If exists: do nothing and end the DAG If not exists: Ingest the data from Postgres to Google Cloud Storage I know that t...
[ "When designing your data pipelines, you may encounter use cases that require more complex task flows than \"Task A > Task B > Task C.\" For example, you may have a use case where you need to decide between multiple tasks to execute based on the results of an upstream task. Or you may have a case where part of your...
[ 0, 0 ]
[]
[]
[ "airflow", "airflow_2.x", "python" ]
stackoverflow_0074612781_airflow_airflow_2.x_python.txt
Q: create a table and different columns within that table based on input of other columns using python I have been working on a python code to try to create the output below in the python terminal. Basically what I'm trying to accomplish is I want the user to input the numbers for Columns A and B, then the code outpu...
create a table and different columns within that table based on input of other columns using python
I have been working on a python code to try to create the output below in the python terminal. Basically what I'm trying to accomplish is I want the user to input the numbers for Columns A and B, then the code outputs Columns C, D and E. In Column C, I show how I want the python code to compute that particular column a...
[ "You could use something like this:\nimport itertools\nimport statistics\n\nnumber_of_classes = int(input(\"Enter the number of Classes: \"))\n\ndef ask_numbers(name, amount_to_ask):\n print('Please enter the numbers for Column', name)\n for how_many_asked_yet in range(amount_to_ask):\n yield (int(inpu...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074248354_python.txt
Q: how to connect two raspberry pi using OPCUA? I have two Raspberry Pi and i want to connect these two via OPC UA making one of them as Server and other as Client. Do you have any Idea or clues or you knows any Websites which helps me to understand the basic ? your prompt reply would be appreciated. Thank you very m...
how to connect two raspberry pi using OPCUA?
I have two Raspberry Pi and i want to connect these two via OPC UA making one of them as Server and other as Client. Do you have any Idea or clues or you knows any Websites which helps me to understand the basic ? your prompt reply would be appreciated. Thank you very much in advance. Best regards, Ankit Mavani I have ...
[ "I can not recommend any resources. But from your tags I quess you want to use Python for your client and server. So for this task you can use asyncua.\nA good starting point are the various examples. Also you can find some docs.\nFor debuging the server and understanding I would recomend to use UAExpert where you ...
[ 0 ]
[]
[]
[ "communication_protocol", "opc_ua", "python", "raspberry_pi" ]
stackoverflow_0074598319_communication_protocol_opc_ua_python_raspberry_pi.txt
Q: How do I export CSVs saved in AWS S3 to DynamoDB? I saw that it's possible to import CSVs uploaded to s3 directly to dynamodb but I haven't figured out how to do it properly yet. I'm guessing my issue is likely related to the naming of my partition key vs the actual headers in my csvs but I am unsure. Is there a w...
How do I export CSVs saved in AWS S3 to DynamoDB?
I saw that it's possible to import CSVs uploaded to s3 directly to dynamodb but I haven't figured out how to do it properly yet. I'm guessing my issue is likely related to the naming of my partition key vs the actual headers in my csvs but I am unsure. Is there a way to easily import CSVs to dynamodb from s3 programati...
[ "You have not gotten a few different errors, you get the same one each time. Item.Score is ambiguous.\nCan you share a snippet of your CSV file, that will help us determine the issue.\n" ]
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_s3", "python" ]
stackoverflow_0074621907_amazon_dynamodb_amazon_s3_python.txt
Q: how to play youtube video with sound in wxpython window? I am making a simple youtube player and downloader app accessible for blind people with screenreaders, but also usable by sighted people. I chose wxpython because it has best accessibility ever. How to play a youtube video in the wx window? Do I need to use ...
how to play youtube video with sound in wxpython window?
I am making a simple youtube player and downloader app accessible for blind people with screenreaders, but also usable by sighted people. I chose wxpython because it has best accessibility ever. How to play a youtube video in the wx window? Do I need to use wx.media.MediaCtrl and how to correctly use it? can I play you...
[ "wx.media will play direct from a URL, although I have no idea if it can access a YouTube url directly (I'm not a fan).\nHere's a very bare bones player accessing a url rather than a file.\nI would suggest that you test the media link to see if it is a url or a file, then use LoadURI or Load depending on the outcom...
[ 0 ]
[]
[]
[ "accessibility", "python", "wxpython", "youtube" ]
stackoverflow_0074583726_accessibility_python_wxpython_youtube.txt
Q: Is there a way for my discord bot to change a message it sent prior, completing replacing that message with a new one? I'm creating a connect 4 game in discord.py, using buttons to place pieces. Currently, it resends a new gameboard every time a piece is placed, with the buttons causing issues as they display "thi...
Is there a way for my discord bot to change a message it sent prior, completing replacing that message with a new one?
I'm creating a connect 4 game in discord.py, using buttons to place pieces. Currently, it resends a new gameboard every time a piece is placed, with the buttons causing issues as they display "this interaction failed", even though its code ran fine. So is there a way to edit the message of the game board to prevent thi...
[ "Search in the docs: I did it for you\nThe docs is the most useful thing readily available to you.\n.\n.\nmessage = piece + \" turn\\n\" +L1 + \"\\n\" + L2 + \"\\n\" + L3 + \"\\n\" + L4 + \"\\n\" + L5 + \"\\n\" + L6\nm = await ctx.send(message, view=view1) #btw this still sends the message\n.\n.\nm.edit(content=mes...
[ 0 ]
[]
[]
[ "button", "discord", "discord.py", "python" ]
stackoverflow_0074624777_button_discord_discord.py_python.txt
Q: Is requirements.txt still needed when using pyproject.toml? Since mid 2022 it is now possible to get rid of setup.py, setup.cfg in favor of pyproject.toml. Editable installs work with recent versions of setuptools and pip and even the official packaging tutorial switched away from setup.py to pyproject.toml. Howev...
Is requirements.txt still needed when using pyproject.toml?
Since mid 2022 it is now possible to get rid of setup.py, setup.cfg in favor of pyproject.toml. Editable installs work with recent versions of setuptools and pip and even the official packaging tutorial switched away from setup.py to pyproject.toml. However, documentation regarding requirements.txt seems to be have bee...
[ "This is the pip documentation for pyproject.toml\n\n...This file contains build system requirements and information, which are used by pip to build the package.\n\nSo this is not the correct place. Looking at the side bar we can see there is an entry for Requirements File Format which is the \"old\" requirements.t...
[ 1, 0 ]
[ "I suggest switching to poetry, it's way better than a standard pip for dependency management. And because it uses pyproject.toml your dependencies and configs are in one place so it's easier to manage everything \n" ]
[ -1 ]
[ "python", "python_packaging", "requirements.txt" ]
stackoverflow_0074508024_python_python_packaging_requirements.txt.txt
Q: run a robot file and get its log with python and return log back to that robot file run a robot file and get its log with python and return log back to that robot file . I try to use subprocess.run() but I think it does not get the log pythonfile ` @keywords("") def cal() p1=subprocess.run("robot cmnd to run a...
run a robot file and get its log with python and return log back to that robot file
run a robot file and get its log with python and return log back to that robot file . I try to use subprocess.run() but I think it does not get the log pythonfile ` @keywords("") def cal() p1=subprocess.run("robot cmnd to run a testcase") return p1.stdout `
[ "You should also use PIPE for reading the output;\nfrom subprocess import Popen, PIPE, STDOUT\n\ncommand = f\"shell command with arguments\"\nprocess = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)\n\nwith process.stdout:\n for line in iter(process.stdout.readline, b''):\n print(line.decode(\"utf...
[ 0 ]
[]
[]
[ "keyword", "loops", "python", "robotframework", "time" ]
stackoverflow_0074624284_keyword_loops_python_robotframework_time.txt
Q: How to check if there is a line segment between two given points? I made a model that predicts electrical symbols and junctions: image of model inference. Given the xywh coordinates of each junctions' bounding box in a form of a dataframe: image of the dataframe, how would I make an output that stores the location...
How to check if there is a line segment between two given points?
I made a model that predicts electrical symbols and junctions: image of model inference. Given the xywh coordinates of each junctions' bounding box in a form of a dataframe: image of the dataframe, how would I make an output that stores the location of all the wires in a .txt file in a form of: (xstart,ystart), (xend,y...
[ "This should be doable using findContours(). A wire is always a (roughly) straigt line, right ?\n\nPaint the classified boxes white, as you said\nthreshold() to get a binary image with the wires (and other symbols and letters) in white, everything else black.\nrun findContours() on that to extract objects.\nGet the...
[ 0 ]
[]
[]
[ "deep_learning", "image_processing", "object_detection", "opencv", "python" ]
stackoverflow_0074620007_deep_learning_image_processing_object_detection_opencv_python.txt
Q: request.session.get('user') returning AnonymousUser when there is a user logged in I am somewhat new at this so apologies in advance. I have run into a problem where I am using Auth0 with a custom db. I have created a user Profile model with a one-to-one relationship with User I am trying to allow the user to upd...
request.session.get('user') returning AnonymousUser when there is a user logged in
I am somewhat new at this so apologies in advance. I have run into a problem where I am using Auth0 with a custom db. I have created a user Profile model with a one-to-one relationship with User I am trying to allow the user to update their profile using a modelform Where I am getting stuck is that I am trying to sav...
[ "There is a django.contrib.auth.models.User object attached to the request. You can access it in a view via request.user. You must have the auth middleware installed, though.\ndef view(request):\n if request.user.is_authenticated:\n user = request.user\n print(user)\n # do something with use...
[ 0 ]
[]
[]
[ "auth0", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074612251_auth0_django_forms_django_models_django_views_python.txt
Q: Pandas: group by and Pivot table difference I just started learning Pandas and was wondering if there is any difference between groupby() and pivot_table() functions. Can anyone help me understand the difference between them. A: Both pivot_table and groupby are used to aggregate your dataframe. The difference is...
Pandas: group by and Pivot table difference
I just started learning Pandas and was wondering if there is any difference between groupby() and pivot_table() functions. Can anyone help me understand the difference between them.
[ "Both pivot_table and groupby are used to aggregate your dataframe. The difference is only with regard to the shape of the result.\nUsing pd.pivot_table(df, index=[\"a\"], columns=[\"b\"], values=[\"c\"], aggfunc=np.sum) a table is created where a is on the row axis, b is on the column axis, and the values are the ...
[ 127, 15, 12, 0 ]
[]
[]
[ "dataframe", "pandas", "pandas_groupby", "pivot_table", "python" ]
stackoverflow_0034702815_dataframe_pandas_pandas_groupby_pivot_table_python.txt
Q: How to display code line number (without additional context) in Icecream print outputs? I am currently using Icecream (https://github.com/gruns/icecream) to print variables and other info for debugging and review purposes. I would like to be able to display the line number where the print call originated from, wit...
How to display code line number (without additional context) in Icecream print outputs?
I am currently using Icecream (https://github.com/gruns/icecream) to print variables and other info for debugging and review purposes. I would like to be able to display the line number where the print call originated from, without including additional information. I don't need to be using Icecream if there is a better...
[ "I think you can use \"inspect\" library for this purpose;\nfrom inspect import currentframe\n\ndef get_line();\n return currentframe().f_back_f_lineno\n\nprint(\"this is sample:\", get_line())\n\n" ]
[ 0 ]
[]
[]
[ "debugging", "icecream", "python" ]
stackoverflow_0074624205_debugging_icecream_python.txt
Q: To find the transpose of a given matrix I have been trying to run the code but its giving error that - "list index out of range" What is the reason? And is there any other way to find the transpose of a matrix without using numpy This is the code I wrote n = int(input("Enter the size of square matrix")) matrix = ...
To find the transpose of a given matrix
I have been trying to run the code but its giving error that - "list index out of range" What is the reason? And is there any other way to find the transpose of a matrix without using numpy This is the code I wrote n = int(input("Enter the size of square matrix")) matrix = [] for i in range(n): a =[] for j in ...
[ "The matrix1 is a list of dim 1 you try to index it as it already is a 2-d list. Try to use the b list to append the elements of the transposed matrix and then append it to matrix1 like below:\nn = int(input(\"Enter the size of square matrix\"))\nmatrix = []\nfor i in range(n): \n a =[]\n for j in range(n): \...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074624974_python.txt
Q: Why replacing in range "(len(list)" with "in list" changing output of the program I was writing code for a program which performs intersection of elements in the two lists, which means the common elements in both the lists are returned. changing "in _list" with "in range (len(list))" used for traversing in one of ...
Why replacing in range "(len(list)" with "in list" changing output of the program
I was writing code for a program which performs intersection of elements in the two lists, which means the common elements in both the lists are returned. changing "in _list" with "in range (len(list))" used for traversing in one of the list changed the output of the function Input code 1: def inn(nums1,nums2): ...
[]
[]
[ "You can simplify your inn function with the built in set operations in python:\ndef inn(nums1,nums2):\n return set(nums1) & set(nums2)\n\n", "In the first listing, j is an element of the list num1.\nIn the second listing, j is used as the index of an element in the list num1.\nYou understood the difference wh...
[ -2, -2 ]
[ "list", "python", "range", "set" ]
stackoverflow_0074624924_list_python_range_set.txt
Q: Shifting start position of X Axis of line chart I want to shift the start position of the red line from "FEB-2020" to "JAN-2021". Currently this is my code and a picture of my current output. Basically Shorten the period of the whole graph to the dates stated above. # plot daily vaccinated fig, ax1= plt.subplots(1...
Shifting start position of X Axis of line chart
I want to shift the start position of the red line from "FEB-2020" to "JAN-2021". Currently this is my code and a picture of my current output. Basically Shorten the period of the whole graph to the dates stated above. # plot daily vaccinated fig, ax1= plt.subplots(1,figsize=(20,10)) # set up plt.ticklabel_format(style...
[ "Here is a very basic example using pandas, datetime index and matplotlib altogether. It is important to make sure the index is of type DatetimeIndex.\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.DataFrame({'a':[3,4,5]}, index=pd.date_range('2020-01-03', '2020-01-05', freq='D'))\ndf_2 = pd.DataF...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python", "x_axis" ]
stackoverflow_0074623492_matplotlib_pandas_python_x_axis.txt
Q: Append matrices generated in for loop that have different col names to an external list of empty dataframes I have a large dataset that I am trying to perform various analyses on, but first need to transform into matrices grouped by different variables. For example, here is a toy dataset: myData = pd.DataFrame({'d...
Append matrices generated in for loop that have different col names to an external list of empty dataframes
I have a large dataset that I am trying to perform various analyses on, but first need to transform into matrices grouped by different variables. For example, here is a toy dataset: myData = pd.DataFrame({'dataset': ['cat', 'cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'dog', 'bird', 'bird', 'bird', 'bird'], ...
[ "I'm not sure what you mean, is this the result you want to achieve?\nmyData = pd.DataFrame({'dataset': ['cat', 'cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'dog', 'bird', 'bird', 'bird', 'bird'], \n 'category_1': ['orange', 'orange', 'white', 'white', 'black', 'brown', 'brown', 'black', 'red', 'green...
[ 0 ]
[]
[]
[ "dataframe", "matrix", "pandas", "python" ]
stackoverflow_0074622555_dataframe_matrix_pandas_python.txt
Q: how to add the SECRET path so that i can get the client email in python secrets_base_path = os.environ['SECRETS_PATH'] SECRET = open(secrets_base_path+"/bbak_crewl.yaml", "r") with open(SECRET) as jf: json_secrets = json_load(jf) json_secrets['client_email'] gs = pygsheets.authorize(service_ file=SECRET) r...
how to add the SECRET path so that i can get the client email in python
secrets_base_path = os.environ['SECRETS_PATH'] SECRET = open(secrets_base_path+"/bbak_crewl.yaml", "r") with open(SECRET) as jf: json_secrets = json_load(jf) json_secrets['client_email'] gs = pygsheets.authorize(service_ file=SECRET) receiving an error when trying to run this python file, i know the code needs ...
[ "You should convert the TextIO to string and you should use \"loads\" function;\nfrom json import loads\n\nwith open(SECRET) as jf:\n data = loads(jf.read())\n\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074624139_jupyter_notebook_python.txt
Q: The size of torch.cat ((x1, x2, x3, x4), 1) does not match I'm creating a model like the one in the figure below based on this paper but concat doesn't match the size and I get an error RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 128 but got size 64 for tensor number 2 in the li...
The size of torch.cat ((x1, x2, x3, x4), 1) does not match
I'm creating a model like the one in the figure below based on this paper but concat doesn't match the size and I get an error RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 128 but got size 64 for tensor number 2 in the list. My code: import torch from torch import nn import torch.nn....
[ "You forgot the padding=same in inception_block_4. That would change the output size of the block to such that it does not fit the other blocks:\nself.inception_block_4 = nn.Conv2d(256,64,(1,1),stride=(1,2), padding='same')\n\nedit:\nThis is not possible for strided convolutions, so instead a pointwise convolution...
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074625002_python_pytorch.txt
Q: Use Snowpark python to unload snowflake data to S3. How to provide storage integration option I am trying to unload snowflake data to S3, I have storage integration setup for the same. I could unload using SQL query, but wanted to do that using snowpark python. DataFrameWriter.copy_into_location - this snowpark me...
Use Snowpark python to unload snowflake data to S3. How to provide storage integration option
I am trying to unload snowflake data to S3, I have storage integration setup for the same. I could unload using SQL query, but wanted to do that using snowpark python. DataFrameWriter.copy_into_location - this snowpark method does not have any parameter for storage_integration, which leaves me clue less on how to get t...
[ "You are right, DataFrameWriter.copy_into_location does not have the storage integration parameter.\nYou can create an external stage object pointing to your S3 location using your storage integration.\n create stage my_stage_s3\n storage_integration = my_storage_int\n url = 's3://mybucket/encrypted_files/'\n f...
[ 1 ]
[]
[]
[ "amazon_s3", "python", "snowflake_cloud_data_platform", "snowpark" ]
stackoverflow_0074625149_amazon_s3_python_snowflake_cloud_data_platform_snowpark.txt
Q: Boto3 Athena are not showing all tables trying to get a list of table names in Athena Table using BOTO3 python. this is my code; I think my attempts to do paginator is not correct. Any help is appreciated import boto3 client = boto3.client('glue') responseGetDatabases = client.get_databases() databaseList = resp...
Boto3 Athena are not showing all tables
trying to get a list of table names in Athena Table using BOTO3 python. this is my code; I think my attempts to do paginator is not correct. Any help is appreciated import boto3 client = boto3.client('glue') responseGetDatabases = client.get_databases() databaseList = responseGetDatabases['DatabaseList'] for databas...
[ "The get_paginator function parameter must be the name of the operation. It looks like you're trying to paginate on the get_tables function so\n paginator = client.get_paginator(['TableList'])\n\nshould be:\n paginator = client.get_paginator('get_tables')\n\nOnce you have the paginator object, you need to cal...
[ 2, 0 ]
[]
[]
[ "amazon_athena", "aws_glue", "boto3", "paginator", "python" ]
stackoverflow_0047933931_amazon_athena_aws_glue_boto3_paginator_python.txt
Q: ImportError: cannot import name 'config' from partially initialized module 'panel.config' I'm trying to import the package panel, however, when I try to do that I receive the following message: Output exceeds the size limit. Open the full output data in a text editor ImportError Trace...
ImportError: cannot import name 'config' from partially initialized module 'panel.config'
I'm trying to import the package panel, however, when I try to do that I receive the following message: Output exceeds the size limit. Open the full output data in a text editor ImportError Traceback (most recent call last) c:\Users\nicol\Documents\Gist\Centrafrique Python\6. Draft_keyword...
[ "Give this a try\nfrom panel import panel as pn\n\n" ]
[ 0 ]
[]
[]
[ "panel", "python" ]
stackoverflow_0074625277_panel_python.txt
Q: How to check if further `scroll down` is not possible using Selenium Am using Selenium + python to scrap a page which has infinite scroll (basically scroll till max first 500 results are shown) Using below code, am able to scroll to bottom of the page. Now i want to stop when further scrolling doesn't fetches any ...
How to check if further `scroll down` is not possible using Selenium
Am using Selenium + python to scrap a page which has infinite scroll (basically scroll till max first 500 results are shown) Using below code, am able to scroll to bottom of the page. Now i want to stop when further scrolling doesn't fetches any content. (say, page only has 200 results, i don't want to keep on scrollin...
[ "I'm using Selenium with Chrome, not Firefox, but the following worked for me:\n\ncapture page height before scrolling down;\nscroll down using key down;\ncapture page height after scrolling down;\nif page height was same before and after scrolling, stop scrolling\n\nMy code looks like this:\nimport time\nfrom sele...
[ 2, 0, 0 ]
[ "You can check document.body.scrollTop by before and after each scroll attempt if there is no data to fetch then this value will stay the same \ndistanceToTop = driver.execute_script(\"return document.body.scrollTop);\")\n\n" ]
[ -1 ]
[ "python", "selenium" ]
stackoverflow_0044721009_python_selenium.txt
Q: Django error: list index out of range (when there's no objects) Everything works fine until I delete all the objects and try to trigger the url, then it gives me this traceback: list index out of range. I can't use get because there might be more than one object and using [0] with filter leads me to this error whe...
Django error: list index out of range (when there's no objects)
Everything works fine until I delete all the objects and try to trigger the url, then it gives me this traceback: list index out of range. I can't use get because there might be more than one object and using [0] with filter leads me to this error when there's no object present, any way around this? I'm trying to get t...
[ "You can also do this:\nticket = Ticket.objects.filter(customer=customer).order_by(\"-id\").first() or None\nif ticket is not None: \n now = datetime.now().date()\n set_date = ticket.date_posted\n check_time = now - set_date <= timedelta(hours=24)\n if check_time:\n print('working')\n else:...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074624343_django_python.txt
Q: Get Top 3 max values I used to have a list and only needed to extract the max values in column 33 every day using below code and then export the data. df_= pd.read_excel (r'file_location.xlsx') df['Date'] = pd.to_datetime(df['Date'], errors='coerce') df_new = (df.groupby(pd.Grouper(key="Date",freq="D")) ...
Get Top 3 max values
I used to have a list and only needed to extract the max values in column 33 every day using below code and then export the data. df_= pd.read_excel (r'file_location.xlsx') df['Date'] = pd.to_datetime(df['Date'], errors='coerce') df_new = (df.groupby(pd.Grouper(key="Date",freq="D")) .agg({df.columns[33]: ...
[ "You need specify column after groupby and call GroupBy.head without agg:\ndf_e_new = df.groupby(pd.Grouper(key=\"Date\",freq=\"D\"))[df.columns[33]].head(3)\n \n\nOr use SeriesGroupBy.nlargest for top3 sorted values:\ndf_e_new = df.groupby(pd.Grouper(key=\"Date\",freq=\"D\"))[df.columns[33]].nlargest(3)\n\nFo...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074625434_pandas_python.txt
Q: How do I change background color in pysimplegui? I'm working on UI for a virus simulation me and a friend are making and I'm really struggling to change the background color of the UI. I took most of the code from the one of the demo projects because i couldn't figure out how to implement matplotlib with pysimpleg...
How do I change background color in pysimplegui?
I'm working on UI for a virus simulation me and a friend are making and I'm really struggling to change the background color of the UI. I took most of the code from the one of the demo projects because i couldn't figure out how to implement matplotlib with pysimplegui so there's some things I don't fully understand but...
[ "You can change the background color by specifying a Hex Color Code in the following argument under layout:\nbackground_color='#DAE0E6'\n\nYou can use a Color Picker like this one https://htmlcolorcodes.com/color-picker/ to get your color\nYou can also use:\nwindow = sg.Window('Virus Simulation', layout, background...
[ 3, 0, 0 ]
[]
[]
[ "pysimplegui", "python", "tkinter", "user_interface" ]
stackoverflow_0069151062_pysimplegui_python_tkinter_user_interface.txt
Q: Speed logic for pygame game I'm doing a final project for my coding class at school. I learnt from a tutorial online on how to use pygame by making pong. Then, I decided to create an Undertale battle system with the knowledge I had gained from learning how to make pong in pygame. I have come across an issue howeve...
Speed logic for pygame game
I'm doing a final project for my coding class at school. I learnt from a tutorial online on how to use pygame by making pong. Then, I decided to create an Undertale battle system with the knowledge I had gained from learning how to make pong in pygame. I have come across an issue however, and its regarding the heart's ...
[ "I figured out the solution:\nheart_x += 0 - heart_speed_x\n\nand\nheart_y += 0 - heart_speed_y\n\nThe problem was that the either or both of the x and y position constantly changed after hitting the surface. This was because the speed of the variables stayed the same. So in the solution, I made it so that the x an...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074624768_pygame_python.txt
Q: how to redirect to homepage in django-microsoft-auth if there is no next parameter? I registered the app in Azure AD and configured my Django app so I can log in using a Microsoft account. The problem I am facing is changing the redirect from the admin page to my homepage. Mu redirect URI on Azure looks like this:...
how to redirect to homepage in django-microsoft-auth if there is no next parameter?
I registered the app in Azure AD and configured my Django app so I can log in using a Microsoft account. The problem I am facing is changing the redirect from the admin page to my homepage. Mu redirect URI on Azure looks like this: https://localhost:8000/microsoft/auth-callback/ What do I need to do to change the redi...
[ "After a few days of researching I cloned the repository and found in the login.js file this piece of code:\n// redirect to next URL if it was provided\nlet new_path = this.parseGETParam('next') || '/admin';\nwindow.location = origin + new_path;\n\nThe only thing to do is to change /admin to /home or whatever path ...
[ 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0074564581_django_django_authentication_python.txt
Q: 503 service is unavailable in Analytics Reporting API V4 Sample Call: https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json Sample Error: googleapiclient.errors.HttpError: <HttpError 503 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "The service i...
503 service is unavailable in Analytics Reporting API V4
Sample Call: https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json Sample Error: googleapiclient.errors.HttpError: <HttpError 503 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "The service is currently unavailable.". Details: "The service is currently ...
[ "First off 500 errors are something is wrong on Googles end. There is nothing you can do to fix it. Its often caused by the server being over loaded, and your script timing out.\nA tip would be to never run on the hour, everyone that has a cron job set up has it set to run on the hour and your going to be complet...
[ 1 ]
[]
[]
[ "google_analytics_api", "google_api", "google_api_python_client", "python" ]
stackoverflow_0074624361_google_analytics_api_google_api_google_api_python_client_python.txt
Q: Django/Python - AssertionError: Class ThreadSerializer missing "Meta.model" attribute I've been trying to build the backend of a forum board for a mobile application and I've been running into an issue when trying to test the API endpoints over Postman. It says that my ThreadSerializer class is missing the "Meta.m...
Django/Python - AssertionError: Class ThreadSerializer missing "Meta.model" attribute
I've been trying to build the backend of a forum board for a mobile application and I've been running into an issue when trying to test the API endpoints over Postman. It says that my ThreadSerializer class is missing the "Meta.model" attribute. My serializer code: from rest_framework import serializers from forum.mode...
[ "change\nfrom rest_framework import serializers\nfrom forum.models import Thread\nfrom forum.models import Post\n\nclass ThreadSerializer(serializers.ModelSerializer):\n class Meta: ...
[ 0 ]
[]
[]
[ "django", "postman", "python", "request" ]
stackoverflow_0074625451_django_postman_python_request.txt
Q: Better fuzzy matching performance? I'm currently using method get_close_matches method from difflib to iterate through a list of 15,000 strings to get the closest match against another list of approx 15,000 strings: a=['blah','pie','apple'...] b=['jimbo','zomg','pie'...] for value in a: difflib.get_close_matc...
Better fuzzy matching performance?
I'm currently using method get_close_matches method from difflib to iterate through a list of 15,000 strings to get the closest match against another list of approx 15,000 strings: a=['blah','pie','apple'...] b=['jimbo','zomg','pie'...] for value in a: difflib.get_close_matches(value,b,n=1,cutoff=.85) It takes .5...
[ "fuzzyset indexes strings by their bigrams and trigrams so it finds approximate matches in O(log(N)) vs O(N) for difflib. For my fuzzyset of 1M+ words and word-pairs it can compute the index in about 20 seconds and find the closest match in less than a 100 ms.\n", "Perhaps you can build an index of the trigrams (...
[ 7, 3, 3, 1, 0, 0 ]
[]
[]
[ "difflib", "fuzzy_comparison", "levenshtein_distance", "performance", "python" ]
stackoverflow_0021408760_difflib_fuzzy_comparison_levenshtein_distance_performance_python.txt