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: How do I increase a variable by 1 every time a sprite is clicked and then print the variable I have tried to get the variable 'clicks' by 1 every time the red sprite is clicked. Then I need the variable to update so that I can print out the updated number of clicks. What i have tried: import pygame pygame.init() ...
How do I increase a variable by 1 every time a sprite is clicked and then print the variable
I have tried to get the variable 'clicks' by 1 every time the red sprite is clicked. Then I need the variable to update so that I can print out the updated number of clicks. What i have tried: import pygame pygame.init() WIDTH = 600 HEIGHT = 600 window = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_ca...
[ "See How can I add objects to a \"pygame.sprite.Group()\"?. You cannot add rectangle to a pygame.sprite.Group(). You have to crate a pygame.sprite.Sprite object.\nclass RectSprite(pygame.sprite.Sprite):\n def __init__(self, rect):\n super().__init__() \n self.rect = pygame.Rect(rect)\n self....
[ 0 ]
[]
[]
[ "events", "pygame", "python", "sprite", "variables" ]
stackoverflow_0074160681_events_pygame_python_sprite_variables.txt
Q: Code transformation from Scala to Pyspark I am very new to Scala and Pyspark, I have to transform this piece of code which is written in Scala to Pyspark. can someone help me to understand the syntax in Scala in order to be able to transform it? val df= spark.read.parquet(s"$basePath/dod_m/") .select(df2.map(x => ...
Code transformation from Scala to Pyspark
I am very new to Scala and Pyspark, I have to transform this piece of code which is written in Scala to Pyspark. can someone help me to understand the syntax in Scala in order to be able to transform it? val df= spark.read.parquet(s"$basePath/dod_m/") .select(df2.map(x => col(x._1).as(x._2)).toList :_*)
[ "Most likely, df2 is a simple scala collection here.\nIf it were a dataframe, df2.map(x => col(x._1).as(x._2)) would yield error: value _1 is not a member of org.apache.spark.sql.Row. Indeed, the map function on a dataframe allows you to work on a Row object, not a tuple.\nIf it were a dataset of (String, String) f...
[ 2 ]
[]
[]
[ "apache_spark", "pyspark", "python", "scala" ]
stackoverflow_0074155555_apache_spark_pyspark_python_scala.txt
Q: Python: TypeError: draw_geometries(): incompatible function arguments I am trying to implement an Open3D model to generate point cloud from a monocular depth map. Referred to this YouTube video - https://youtu.be/teHGdlGhQZo OpenCV == 4.4.0 Open3D == 0.15.1 BGR Image - 640x480x3 Depth Image - 640x480x3 Code - impo...
Python: TypeError: draw_geometries(): incompatible function arguments
I am trying to implement an Open3D model to generate point cloud from a monocular depth map. Referred to this YouTube video - https://youtu.be/teHGdlGhQZo OpenCV == 4.4.0 Open3D == 0.15.1 BGR Image - 640x480x3 Depth Image - 640x480x3 Code - import open3d as o3d import numpy as np import matplotlib.pyplot as plt import ...
[ "remove the zoom parameter, just checked that draw_geometries isn't currently supporting this.\nRemove it and your code will work just fine.\n" ]
[ 2 ]
[]
[]
[ "numpy", "open3d", "python" ]
stackoverflow_0074161738_numpy_open3d_python.txt
Q: VSCode Jupyter not connecting to python kernel Launching a cell will make this message appear: Connecting to kernel: Python 3.9.6 64-bit: Activating Python Environment 'Python 3.9.6 64-bit'. This message will then stay up loading indefinitely, without anything happening. No actual error message. I've already tried...
VSCode Jupyter not connecting to python kernel
Launching a cell will make this message appear: Connecting to kernel: Python 3.9.6 64-bit: Activating Python Environment 'Python 3.9.6 64-bit'. This message will then stay up loading indefinitely, without anything happening. No actual error message. I've already tried searching for this problem, but every other post se...
[ "Not sure what did the trick but downgrading VSCode to November version and after that reinstalling Jupyter extension worked for me.\n", "If anyone has the same problem, before reinstalling VSCode as the accepted answer said, try closing and reopening VSCode first.\nThat worked for me, saving me the agony of havi...
[ 3, 1, 0 ]
[]
[]
[ "jupyter", "python", "visual_studio_code" ]
stackoverflow_0071053839_jupyter_python_visual_studio_code.txt
Q: Python: Process finished with exit code -1073741819 (0xC0000005). How to Debug? I'm getting a strange error "Process finished with exit code -1073741819 (0xC0000005)" running python 3.7 on a windows machine. The process just crashes. The error comes in random time. It seems to appear inside a thread. Is there som...
Python: Process finished with exit code -1073741819 (0xC0000005). How to Debug?
I'm getting a strange error "Process finished with exit code -1073741819 (0xC0000005)" running python 3.7 on a windows machine. The process just crashes. The error comes in random time. It seems to appear inside a thread. Is there someway to get more information where exactly the error comes from? Right now my only so...
[ "I've seen this error occur when a Python script has infinite (or very deep) recursion and the following code is used to increase the recursion limit:\nimport sys\nsys.setrecursionlimit(4000)\n\nI would guess that the error means we are running out of memory.\n", "I had the same issue, not long time ago and I hav...
[ 1, 0 ]
[]
[]
[ "crash", "python", "python_3.7" ]
stackoverflow_0063762702_crash_python_python_3.7.txt
Q: how to find all "1401\/07\/29 19:00:00" pattern in a text with regex in python i have a text that contain "1401/07/29 19:00:00" pattern. how find all top pattern in text with re.findall method in python A: if string = "1401/07/29 19:00:00" re.findall(r'\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', string) if string = '...
how to find all "1401\/07\/29 19:00:00" pattern in a text with regex in python
i have a text that contain "1401/07/29 19:00:00" pattern. how find all top pattern in text with re.findall method in python
[ "if string = \"1401/07/29 19:00:00\"\nre.findall(r'\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}', string)\n\nif string = '1401\\/07\\/29 19:00:00'\nstring = '1401\\/07\\/29 19:00:00'\n\n#variant 1\nprint(re.findall(r'\\d{4}\\\\/\\d{2}\\\\/\\d{2} \\d{2}:\\d{2}:\\d{2}', string)) \n#output: ['1401\\\\/07\\\\/29 19:00:00'...
[ 1 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074161867_python_python_re_regex.txt
Q: How to delete specific elements of arrays without listing index Attendance = ['Holly','James','Barry','John','Lewy'] Present = input("Is number Holly present?") if Present == "N": Attendance.pop("Holly") print(Attendance[0]) Is there anyway to delete a specific term from the array by name? This doesn't...
How to delete specific elements of arrays without listing index
Attendance = ['Holly','James','Barry','John','Lewy'] Present = input("Is number Holly present?") if Present == "N": Attendance.pop("Holly") print(Attendance[0]) Is there anyway to delete a specific term from the array by name? This doesn't seem to work? Or can i only delete a specific element of the array...
[ "Yes you can by using LIST_VARIABLE.remove('ELEMENT_TO_BE_REMOVED')\nAttendance = ['Holly','James','Barry','John','Lewy']\nprint(Attendance)\nAttendance.remove('Holly')\nprint(Attendance)\n\nThe output will be:\n['Holly', 'James', 'Barry', 'John', 'Lewy']\n['James', 'Barry', 'John', 'Lewy']\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074161863_python.txt
Q: Django JSONField Aggregate and Sum I have the below JSON saved in PostgreSQL 9.4 DB and running Django 2.2 [{"rating": 6, "companyvalue_id": 188, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 7, "companyvalue_id": 207, "team_members_name": "pidofod tester", "users_teammember_id": ...
Django JSONField Aggregate and Sum
I have the below JSON saved in PostgreSQL 9.4 DB and running Django 2.2 [{"rating": 6, "companyvalue_id": 188, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 7, "companyvalue_id": 207, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 4, "companyvalue_id": ...
[ "Try postgresql jsonb instead of json\njsonb allow effisienty extract values in sql queries\nhttps://www.postgresql.org/docs/current/functions-json.html\nalso\nhttps://pganalyze.com/blog/postgres-jsonb-django-python\ncan be usefull\n" ]
[ 0 ]
[]
[]
[ "django", "json", "jsonb", "python" ]
stackoverflow_0074161619_django_json_jsonb_python.txt
Q: FieldError: Related Field got invalid lookup: contains I am trying to implement a simple search where the user enters any string in the search input and the entire table is checked for the presence of string. My model class S_Owner_Master(models.Model): User= settings.AUTH_USER_MODEL flat_status = (('0', "...
FieldError: Related Field got invalid lookup: contains
I am trying to implement a simple search where the user enters any string in the search input and the entire table is checked for the presence of string. My model class S_Owner_Master(models.Model): User= settings.AUTH_USER_MODEL flat_status = (('0', "Vacant"), ('1', "Occupied")) occupants = (('0', "Vacant"...
[ "assuming your model 'User' contains field 'name' (must be string), try:\nQ(created_by__name__contains=search_text) |\nQ(updated_by__name__contains=search_text)\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074161875_django_python.txt
Q: How to extract content from website(url) using machine learning? I have used scrapy (beautiful soup module) to extract specific content from website (given URL). But I want to do the same in machine learning Python. Is there any way? I searched a lot but found none. Everyone in internet uses scrapy. But I want to ...
How to extract content from website(url) using machine learning?
I have used scrapy (beautiful soup module) to extract specific content from website (given URL). But I want to do the same in machine learning Python. Is there any way? I searched a lot but found none. Everyone in internet uses scrapy. But I want to extract content from website using Python machine learning. Beautifuls...
[ "Your question is not clear, but starting with the point of extracting / scrape information from table, I would recommend using pandas to simplify:\nimport pandas as pd\npd.read_html('https://bevco.in/sales-details/')[0]\n\nTo save the result as excel file:\nimport pandas as pd\npd.read_html('https://bevco.in/sales...
[ 1 ]
[]
[]
[ "machine_learning", "python", "scrapy", "web_crawler", "web_scraping" ]
stackoverflow_0074161789_machine_learning_python_scrapy_web_crawler_web_scraping.txt
Q: Django template - get object's choice field text This is my model: class Person(models.Model): ... DOP = 1 PPP = 2 contract_choices = ( (DOP, 'always'), (PPP, 'sometimes'), ) contract = models.CharField(max_length=3, choices = contract_choices) ... I need contract fiel...
Django template - get object's choice field text
This is my model: class Person(models.Model): ... DOP = 1 PPP = 2 contract_choices = ( (DOP, 'always'), (PPP, 'sometimes'), ) contract = models.CharField(max_length=3, choices = contract_choices) ... I need contract field value in my template: {% for person in persons %} {{...
[ "Create a model like this:\nclass Person(models.Model):\n contract_choices = (\n ('DOP', 'always'),\n ('PPP', 'sometimes'),\n )\n\n contract = models.CharField(max_length=3, choices = contract_choices)\n\nAnd then you can access keys:\n{{ person.contract_choices }}\n\nreturns: 'DOP' or 'PPP'\...
[ 1, 0 ]
[]
[]
[ "choicefield", "django", "django_models", "python", "templates" ]
stackoverflow_0048842022_choicefield_django_django_models_python_templates.txt
Q: How can I store a huge list into a csv file? For example: header = ['a','b','c'] data = ['1','2','3','4','5','6',...,'100'] How can I combine each three of the data to match the header? Expected output: A: Here's how you can do this. import csv header = ['a','b','c'] data = ['1','2','3','4','5','6','7','8','9'...
How can I store a huge list into a csv file?
For example: header = ['a','b','c'] data = ['1','2','3','4','5','6',...,'100'] How can I combine each three of the data to match the header? Expected output:
[ "Here's how you can do this.\nimport csv\n\nheader = ['a','b','c']\ndata = ['1','2','3','4','5','6','7','8','9']\n\nfile = csv.writer(open(f\"testing.csv\", \"a\",newline=''))\nfile.writerow(header)\n\nfor i in range(0,len(data),3):\n new_list = data[i:i+3]\n file.writerow(new_list)\n\n\n\nHere's the screensh...
[ 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074161814_csv_python.txt
Q: How to set max_proc_per_cpu in Scrapyd I have the following two Scrapy projects with the following configurations The Project1's scrapy.cfg [settings] default = Project1.settings [deploy] url = http://localhost:6800/ project = Project1 [scrapyd] eggs_dir = eggs logs_dir = logs logs_to_keep = 500 dbs_dir ...
How to set max_proc_per_cpu in Scrapyd
I have the following two Scrapy projects with the following configurations The Project1's scrapy.cfg [settings] default = Project1.settings [deploy] url = http://localhost:6800/ project = Project1 [scrapyd] eggs_dir = eggs logs_dir = logs logs_to_keep = 500 dbs_dir = dbs max_proc = 5 max_proc_per_cpu = 10...
[ "According to the documentation, in Unix-like systems, the configuration file is first looked upon in the /etc/scrapyd/scrapyd.conf location. I entered the configuration file here, but it did not work. Finally, it worked when I kept the scrapy.conf file as a hidden file in the directory from which the scrapy server...
[ 1 ]
[]
[]
[ "python", "scrapy", "scrapyd" ]
stackoverflow_0047732772_python_scrapy_scrapyd.txt
Q: Looping dataframe to check for specific condition using if and loc I have a data frame of temperatures with below columns, | datetime | 0 | 1 | 2 | 3 | |--------------------------|---|-------|-------|-------| | 21-10-2022 09:17:21.1721 | 0 | 47.79 | 43.62 | 46.22 | | 21-10-2022 09:17:31...
Looping dataframe to check for specific condition using if and loc
I have a data frame of temperatures with below columns, | datetime | 0 | 1 | 2 | 3 | |--------------------------|---|-------|-------|-------| | 21-10-2022 09:17:21.1721 | 0 | 47.79 | 43.62 | 46.22 | | 21-10-2022 09:17:31.1731 | 0 | 47.79 | 43.56 | 46.22 | | 21-10-2022 09:17:41.1741 | 0 | 47....
[ "With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"datetime\": [\n \"21-10-2022 09:17:21.1721\",\n \"21-10-2022 09:17:31.1731\",\n \"21-10-2022 09:17:41.1741\",\n \"21-10-2022 09:17:51.1751\",\n \"21-10-2022 09:18:01....
[ 1 ]
[]
[]
[ "dataframe", "if_statement", "pandas", "python" ]
stackoverflow_0074151714_dataframe_if_statement_pandas_python.txt
Q: Python Array Rotation So I am implementing a block swap algorithm in python. The algorithm I am following is this: Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A an...
Python Array Rotation
So I am implementing a block swap algorithm in python. The algorithm I am following is this: Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABlBr into B...
[ "You can rotate a list in place in Python by using a deque:\n>>> from collections import deque\n>>> d=deque([1,2,3,4,5])\n>>> d\ndeque([1, 2, 3, 4, 5])\n>>> d.rotate(2)\n>>> d\ndeque([4, 5, 1, 2, 3])\n>>> d.rotate(-2)\n>>> d\ndeque([1, 2, 3, 4, 5])\n\nOr with list slices:\n>>> li=[1,2,3,4,5]\n>>> li[2:]+li[:2]\n[3,...
[ 30, 18, 13, 5, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "arrays", "python", "recursion", "rotation", "swap" ]
stackoverflow_0017350330_arrays_python_recursion_rotation_swap.txt
Q: Why can't I use my local variable despite already returning it? It says I haven't defined the variable even though the code that does that is literally right above it, the error message appears: "Traceback (most recent call last): File "main.py", line 55, in if kategoribmi == "underweight": NameError: name 'kateg...
Why can't I use my local variable despite already returning it?
It says I haven't defined the variable even though the code that does that is literally right above it, the error message appears: "Traceback (most recent call last): File "main.py", line 55, in if kategoribmi == "underweight": NameError: name 'kategoribmi' is not defined" if kelas == "('15', 'P')": if bmi >...
[ "Your code is a bit incomplete, perhaps it is inside a function? Is there a previous condition that has to evaluate to True? For better help you should provide more code. Are you sure your code can evaluate to True for the condition if kelas == \"('15', 'P')\" every time you run it?. On a side note, you are leaving...
[ 0, 0, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0074161966_python_variables.txt
Q: How to run great expectations on AWS lambda I am trying to use great-expectations, i.e., run expectations suites within an AWS Lambda function. When I am trying to install the packages in the requirements.txt, I get an error re jupyter lab: aws-sam\\build\\ValidationFunction\\.\\jupyterlab_widgets-1.1.0.data\\data...
How to run great expectations on AWS lambda
I am trying to use great-expectations, i.e., run expectations suites within an AWS Lambda function. When I am trying to install the packages in the requirements.txt, I get an error re jupyter lab: aws-sam\\build\\ValidationFunction\\.\\jupyterlab_widgets-1.1.0.data\\data\\share\\jupyter\\labextension s\\@jupyter-widget...
[ "Can you show a bit more of your code and the full error stack? I would start as simple as possible get basic validation working and then add back in dependencies until you find the culprit.\nAdd a simple lambda and the minimum dependencies, maybe pandas and great expectations and then validate one rule as in:\ncus...
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "great_expectations", "python" ]
stackoverflow_0071667578_amazon_web_services_aws_lambda_great_expectations_python.txt
Q: Value being updated in a different function doesn't return its updated value This is a simplified version I made of the problem I'm having I have my Game() function that calls the other UpdateScore() and Score() functions, UpdateScore() adds 1 to computerScore, and Score() prints that updated value. But that value...
Value being updated in a different function doesn't return its updated value
This is a simplified version I made of the problem I'm having I have my Game() function that calls the other UpdateScore() and Score() functions, UpdateScore() adds 1 to computerScore, and Score() prints that updated value. But that value either doesn't get updated, what am I doing wrong? import time def Game(): ...
[ "Python doesn't pass variables by value. It doesn't pass it by reference either. It passes variables by assignment.\nRefer to the code snippet below.\n>>> def main():\n... n = 9001\n... print(f\"Initial address of n: {id(n)}\")\n... increment(n)\n... print(f\"Final address of n: {id(n)}\")\n...\n>>>...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074162061_python.txt
Q: How to get token in Python 0AuthLib OLX Partner API V2 I study API OLX https://developer.olx.ua/api/doc. I'm trying to implement authorization and getting a token in Python. Stuck at the moment of receiving the Authorization Code. I am a beginner, I have never worked with this type of authorization. Here is my pie...
How to get token in Python 0AuthLib OLX Partner API V2
I study API OLX https://developer.olx.ua/api/doc. I'm trying to implement authorization and getting a token in Python. Stuck at the moment of receiving the Authorization Code. I am a beginner, I have never worked with this type of authorization. Here is my piece of code client_id = 'xxxx' client_secret = 'xxxx' authori...
[ "There are two things here. You first need to construct Authorize url with expected parameters like redirect_uri, grant_type,client_id, client_secret and state. state here would be some random string that is an identifier for your state. Some auth providers expect PKCE strings.\nFor eg. Auth Url can be https://www....
[ 0, 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074153240_api_python.txt
Q: Importing error "from google.cloud import bigquery" I'm trying to import the google.cloud bigquery library, but I keep getting an error. The error I got: ImportError: cannot import name 'bigquery' from 'google.cloud' (unknown location) pip install google-cloud-bigquery pip install --upgrade google-cloud pip inst...
Importing error "from google.cloud import bigquery"
I'm trying to import the google.cloud bigquery library, but I keep getting an error. The error I got: ImportError: cannot import name 'bigquery' from 'google.cloud' (unknown location) pip install google-cloud-bigquery pip install --upgrade google-cloud pip install --upgrade google-cloud-bigquery I also tried these m...
[ "If you are writing python code in Apigee cloud function, There should be one requirements.txt file, add the below line in it\ngoogle-cloud-bigquery\n\nthen import it in python file\nfrom google.cloud import bigquery\n\n", "If you are using virtual environment, activate it:\nsource <your-env>/bin/activate\n\nInst...
[ 1, 1 ]
[]
[]
[ "google_bigquery", "python" ]
stackoverflow_0074155056_google_bigquery_python.txt
Q: DataFrame Pandas datetime error: hour must be in 0..23 I have the following time series and I want to convert to datetime in DataFrame using "pd.to_datetime". I am getting the following error: "hour must be in 0..23: 2017/ 01/01 24:00:00". How can I go around this error? DateTime 0 2017/ 01/01 01:00:00 1 201...
DataFrame Pandas datetime error: hour must be in 0..23
I have the following time series and I want to convert to datetime in DataFrame using "pd.to_datetime". I am getting the following error: "hour must be in 0..23: 2017/ 01/01 24:00:00". How can I go around this error? DateTime 0 2017/ 01/01 01:00:00 1 2017/ 01/01 02:00:00 2 2017/ 01/01 03:00:00 3 2017/ 01/01...
[ "Given:\n DateTime\n0 2017/01/01 01:00:00\n1 2017/01/01 02:00:00\n2 2017/01/01 03:00:00\n3 2017/01/01 04:00:00\n4 2017/01/01 23:00:00\n5 2017/01/01 24:00:00\n\nAs the error says, 24:00:00 isn't a valid time. Depending on what it actually means, we can salvage it like this:\n# Split up your Date a...
[ 1, 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074160151_dataframe_datetime_pandas_python.txt
Q: How to take an arbitrary sequence of bits from a byte array and turn it into an integer in Python? I am looking for a python equivalent of https://www.npmjs.com/package/bit-sequence. That is to say, I need a function which takes some 'bytes', some 'start' value corresponding to an integer bit index to start extrac...
How to take an arbitrary sequence of bits from a byte array and turn it into an integer in Python?
I am looking for a python equivalent of https://www.npmjs.com/package/bit-sequence. That is to say, I need a function which takes some 'bytes', some 'start' value corresponding to an integer bit index to start extraction (not byte index), and some 'length' value to correspond to the amount of bits to extract from the b...
[ "I think that solves your problem, for more information about bit manipulation in python take a look at this link ->https://realpython.com/python-bitwise-operators/#bit-strings-in-python\ndef bytes_extraction(bytes, start, length):\n bytes = bin(bytes)\n result = bytes[start:start+length]\n result = int(re...
[ 0, 0 ]
[]
[]
[ "byte", "python" ]
stackoverflow_0074160159_byte_python.txt
Q: How to reorder indexed rows based on a list in Pandas data frame I have a data frame that looks like this: company Amazon Apple Yahoo name A 0 130 0 C 173 0 0 Z 0 0 150 It was created using this code: import pandas as pd df = pd.DataFrame({'name' : ['...
How to reorder indexed rows based on a list in Pandas data frame
I have a data frame that looks like this: company Amazon Apple Yahoo name A 0 130 0 C 173 0 0 Z 0 0 150 It was created using this code: import pandas as pd df = pd.DataFrame({'name' : ['A', 'Z','C'], 'company' : ['Apple', 'Yahoo','Amazon...
[ "You could set index on predefined order using reindex like\nIn [14]: df.reindex([\"Z\", \"C\", \"A\"])\nOut[14]:\ncompany Amazon Apple Yahoo\nZ 0 0 150\nC 173 0 0\nA 0 130 0\n\nHowever, if it's alphabetical order, you could use sort_index(ascending=Fal...
[ 150, 5, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0030009948_dataframe_pandas_python.txt
Q: How to use the value of a Python variable as the callback name? Edit: The following is a simplified code of a more complex example. def lottery(amount, callback=None): print(f'You spent {amount} on a lottery ticket.') if callback: callback(amount) def win(amount): print(f'You won ${amount * 10...
How to use the value of a Python variable as the callback name?
Edit: The following is a simplified code of a more complex example. def lottery(amount, callback=None): print(f'You spent {amount} on a lottery ticket.') if callback: callback(amount) def win(amount): print(f'You won ${amount * 1000}!!!') def lose(amount): print(f"Sorry, you spent {amount} and...
[ "This should do the job:\ndef lottery(amount, win_lose):\n print(f'You spent {amount} on a lottery ticket.')\n if win_lose ==\"win\":\n print(f'You won ${amount * 1000}!!!')\n if win_lose ==\"lose\":\n print(f\"Sorry, you spent {amount} and didn't win anything.\")\n \n#Example\nwin_lose = ...
[ 0, 0, 0 ]
[]
[]
[ "callback", "python", "variable_assignment" ]
stackoverflow_0074160902_callback_python_variable_assignment.txt
Q: Plotnine : Secondary y-axis (dual axes) I am using python's wonderful plotnine package. I would like to make a plot with dual y-axis, let's say Celsius on the left axis and Fahrenheit on the right. I have installed the latest version of plotnine, v0.10.1. This says the feature was added in v0.10.0. I tried to fol...
Plotnine : Secondary y-axis (dual axes)
I am using python's wonderful plotnine package. I would like to make a plot with dual y-axis, let's say Celsius on the left axis and Fahrenheit on the right. I have installed the latest version of plotnine, v0.10.1. This says the feature was added in v0.10.0. I tried to follow the syntax on how one might do this in R'...
[ "This github issue thread that was mentioned in the question does not say in any way that the secondary axis feature has been implemented. It was added to v0.10.0 milestones list before it was released. Here, milestones list means a todo list of what was planned to be implemented before the version releases. Howeve...
[ 0 ]
[]
[]
[ "plotnine", "python" ]
stackoverflow_0074162027_plotnine_python.txt
Q: How to convert a number to its correlating day of the week? How do I convert a number to its correlating day of the week? For example: def string(hour_of_day, day_of_week, date) : print(f'{day_of_week} {date} at hour {hour_of_day}') how can I re-write the 'day_of_week' part in print so that when I use the func...
How to convert a number to its correlating day of the week?
How do I convert a number to its correlating day of the week? For example: def string(hour_of_day, day_of_week, date) : print(f'{day_of_week} {date} at hour {hour_of_day}') how can I re-write the 'day_of_week' part in print so that when I use the function: string(12, 1, '2020/02/18') How can I get Tuesday 2020/02...
[ "Use a dictionary along the lines of\ndaysdict = { 1: 'Monday', 2: 'Tuesday'} exetended for all the days\nthen access using daysdict[1]\nAlthough your day 1 seems to be Tuesday!\nIt is possible to get the day directly from the date itself - something for you to check out.\n", "Use calendar module\nIf you have al...
[ 2, 1, 1 ]
[]
[]
[ "numbers", "python", "weekday" ]
stackoverflow_0074162172_numbers_python_weekday.txt
Q: Why is Ergebniss1 "none" The code from my project The output: How long is the lasagna in the oven: 10 30 How many layers do you want to make: 20 40 None My question is why is the Ergebniss1 a "none" and not the number from the function?
Why is Ergebniss1 "none"
The code from my project The output: How long is the lasagna in the oven: 10 30 How many layers do you want to make: 20 40 None My question is why is the Ergebniss1 a "none" and not the number from the function?
[]
[]
[ "print() always returns None.\nSo you'd want to write your code like this:\nErgebniss1 = Expected_Bake_Time - Minutes_Baked\nprint(Ergebniss1)\n\n", "You are trying to print a print statement, a cleaner approach would be to return values from the function and then print them:\nExpected_Bake_Time = 40\nLayers_Time...
[ -1, -1 ]
[ "function", "nonetype", "python" ]
stackoverflow_0074162243_function_nonetype_python.txt
Q: map probabilities and classes (multiclass) to dataframe most efficiently I have trained an xgboost nulticlass classifier. I want predictions for the class and for the probabilities Let's say I have: import pandas as pd import numpy as np result = pd.DataFrame({'id': [1,2,3,4], 'Pred class': ['a', 'b', 'c', 'c']})...
map probabilities and classes (multiclass) to dataframe most efficiently
I have trained an xgboost nulticlass classifier. I want predictions for the class and for the probabilities Let's say I have: import pandas as pd import numpy as np result = pd.DataFrame({'id': [1,2,3,4], 'Pred class': ['a', 'b', 'c', 'c']}) predictions = np.array([[0.2, 0.3, 0.5], [0.1, 0.5, 0...
[ "Here is one way to do it using Pandas max:\nresult[\"probs\"] = pd.DataFrame(predictions).max(axis=1) * 100\n\nprint(result)\n# Output\n id Pred class probs\n0 1 a 50.0\n1 2 b 50.0\n2 3 c 70.0\n3 4 c 60.0\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074150700_numpy_pandas_python.txt
Q: How to check if a number in a list range I have a float number x and a list range list_ = [[a, b], [c,d], [e,f]] How can check if the number x is in the list. It means the function will return True in case of a<=x <=b or c<=x <=d or e<=x <=f Otherwise, the function will return False. Could you help me to write ...
How to check if a number in a list range
I have a float number x and a list range list_ = [[a, b], [c,d], [e,f]] How can check if the number x is in the list. It means the function will return True in case of a<=x <=b or c<=x <=d or e<=x <=f Otherwise, the function will return False. Could you help me to write a Python code for the function function (x, li...
[ "Clean solution:\ndef function(x, list_):\n return any([l[0] < x < l[1] for l in list_])\n\nOptimized solution:\ndef function(x, list_):\n for l in list_:\n if l[0] < x < l[1]:\n return True\n return False\n\n", "The idiomatic solution would be this:\ndef f(x: int, ls: List[Tuple[float, ...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074162136_python_python_3.x.txt
Q: tkinter and time.sleep I am trying to delete text inside a text box after waiting 5 seconds, but instead the program wont run and does sleep over everything else. Also is there a way for me to just make my textbox sleep so i can run other code while the text is frozen? from time import time, sleep from Tkinter imp...
tkinter and time.sleep
I am trying to delete text inside a text box after waiting 5 seconds, but instead the program wont run and does sleep over everything else. Also is there a way for me to just make my textbox sleep so i can run other code while the text is frozen? from time import time, sleep from Tkinter import * def empty_textbox(): ...
[ "You really should be using something like the Tkinter after method rather than time.sleep(...).\nThere's an example of using the after method at this other stackoverflow question.\nHere's a modified version of your script that uses the after method:\nfrom time import time, sleep\nfrom Tkinter import *\n\ndef empty...
[ 23, 2 ]
[]
[]
[ "elapsedtime", "python", "sleep", "time", "tkinter" ]
stackoverflow_0010393886_elapsedtime_python_sleep_time_tkinter.txt
Q: How can I schedule updates (f/e, to update a clock) in tkinter? I'm writing a program with Python's tkinter library. My major problem is that I don't know how to create a timer or a clock like hh:mm:ss. I need it to update itself (that's what I don't know how to do); when I use time.sleep() in a loop the whole GUI...
How can I schedule updates (f/e, to update a clock) in tkinter?
I'm writing a program with Python's tkinter library. My major problem is that I don't know how to create a timer or a clock like hh:mm:ss. I need it to update itself (that's what I don't know how to do); when I use time.sleep() in a loop the whole GUI freezes.
[ "Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. If that function itself calls after you've set up an automatically recurring event. \nHere is a working example:\n# for python 3.x use 'tkinter' rather than 'Tkinter'\nimport Tkinter ...
[ 143, 12, 6, 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0002400262_python_tkinter_user_interface.txt
Q: UnicodeEncodeError: 'latin-1' codec can't encode characters in position 2082-2084: ordinal not in range(256) I don't know why this is happening. Whenever I add Arabic content it shows the above error, otherwise works fine with the English language Same code is working in another project perfectly but not here. vie...
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 2082-2084: ordinal not in range(256)
I don't know why this is happening. Whenever I add Arabic content it shows the above error, otherwise works fine with the English language Same code is working in another project perfectly but not here. views.py def generate_pdf_for_gift_and_add_to_cart(request): cart = Cart(request) if request.method == 'POST'...
[ "Your code needs a few tweaks to work without generating the block characters in the output.\n\nAdd a font that supports Arabic\n\nBy default, xhtml2pdf only provides a handful of fonts, none of which support Arabic:\n\nTimes-Roman: Times New Roman, Times, Georgia, serif\nHelvetica: Arial, Verdana, Geneva, sansseri...
[ 3 ]
[ "If you want to download the pdf of html pages\n<div id=\"content\">\n <h3>Hello, this is a H3 tag</h3>\n\n <p>A paragraph</p>\n</div>\n<button onclick=\"CreatePDFfromHTML()\">generate PDF</button>\n\nYou need to refer both JS libraries,\n<script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/aj...
[ -2 ]
[ "css", "django", "python", "xhtml2pdf" ]
stackoverflow_0072763668_css_django_python_xhtml2pdf.txt
Q: Serving large files ( with high loads ) in Django I've been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk was that everyone with the link could have downloaded the file ! ) so i now serve the file ...
Serving large files ( with high loads ) in Django
I've been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk was that everyone with the link could have downloaded the file ! ) so i now serve the file via my views , that way only users with permission can ...
[ "Your opening of the image loads it in memory and this is what causes the increase in load under heavy use. As posted by Martin the real solution is to serve the file directly.\nHere is another approach, which will stream your file in chunks without loading it in memory.\nimport os\nimport mimetypes\n\nfrom wsgiref...
[ 67, 15, 4, 4, 4, 0 ]
[]
[]
[ "django", "download", "permissions", "python" ]
stackoverflow_0008600843_django_download_permissions_python.txt
Q: Short syntax for if true then break I'm looking for options of shortening syntax for breaking (and continuing) a loop on a condition for _ in range(10): if condition: break ... I supposed that short curcuits should work, e.g. x == 2 and break, but they cause SyntaxError. What are Python's options ...
Short syntax for if true then break
I'm looking for options of shortening syntax for breaking (and continuing) a loop on a condition for _ in range(10): if condition: break ... I supposed that short curcuits should work, e.g. x == 2 and break, but they cause SyntaxError. What are Python's options for one-line conditioning, except if cond...
[ "You could use itertools.takewhile to combine aspects of a for and while loop, moving the (negated) break condition to the loop's head. The condition in the lambda can use both variables from the enclosing scope and the current item from the iterable.\nfrom itertools import takewhile\n\nfor x in takewhile(lambda x:...
[ 2 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074162033_if_statement_python.txt
Q: My images are not displaying the post.photo.url call on my cpanel hosting Hello I just put my blog online on cpanel hosting. I managed the display with the whitenoise library of python. The static images work normally. But when I call the image from blogpost to display my image does not appear with post.photo.url....
My images are not displaying the post.photo.url call on my cpanel hosting
Hello I just put my blog online on cpanel hosting. I managed the display with the whitenoise library of python. The static images work normally. But when I call the image from blogpost to display my image does not appear with post.photo.url. I am under cpanel and I would like to ask for your help to display the images ...
[ "First of all I think you have not configured your static files and media files. Try configuring it as follows. In your settings.py ensure to include STATICFILES_DIR, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT in your settings.py and then add the below lines below STATIC_URL = 'static/'\nMEDIA_URL = 'media/'\nSTATICFILES_D...
[ 0 ]
[]
[]
[ "django", "model", "python", "whitenoise" ]
stackoverflow_0074159294_django_model_python_whitenoise.txt
Q: Python slice data from multiple child column Its possible to slice my data where I have the main key for all child codes, considering the main code will be duplicate in some moments, so i have year column to support the data slice. Thats my current data and I need to transform it cod child code year text M01Q005...
Python slice data from multiple child column
Its possible to slice my data where I have the main key for all child codes, considering the main code will be duplicate in some moments, so i have year column to support the data slice. Thats my current data and I need to transform it cod child code year text M01Q00500 M01Q00800 2018 text01 M01Q00800 M01Q008...
[ "If I have this correct I think you are looking to get a row in the data frame with every possible combiantion of the data.\nAlso eliminate spaces in column headers is a good habit and will save a lot of time. The code looks cleaners and faster to type\n\ndf = df.rename(columns={'child code' : 'child_code'})\n\ndf2...
[ 0 ]
[]
[]
[ "pandas", "python", "slice" ]
stackoverflow_0074159090_pandas_python_slice.txt
Q: Positive Negative - Simple Python exercise Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. I finally figured it out. def pos_neg(a, b, negative): if negative: return (a < 0 and b < 0) else: r...
Positive Negative - Simple Python exercise
Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. I finally figured it out. def pos_neg(a, b, negative): if negative: return (a < 0 and b < 0) else: return (a > 0 and b < 0) or (a < 0 and b > 0) Bu...
[ "You are not returning those two lines. You are returning the values that those two lines evaluate to. In your cases, those are boolean expressions that will evaluate to either true or false. That final boolean value is what your function returns.\n", "Python evaluates whatever expression follows the return state...
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0039186071_python.txt
Q: Pydantic - Turn attribute immutable when defined as non-None for the first time I have the following model: from pydantic import BaseModel class User(BaseModel): user_id: Optional[int] = None name: str The user_id may be initially unknown (None), but when it is set to a non-None value then it should be i...
Pydantic - Turn attribute immutable when defined as non-None for the first time
I have the following model: from pydantic import BaseModel class User(BaseModel): user_id: Optional[int] = None name: str The user_id may be initially unknown (None), but when it is set to a non-None value then it should be immutable afterwards. Examples: user1 = User(name="John") user1.user_id = 1 # user_...
[ "I agree with @chepner that you should probably re-think your algorithm. It seems strange that you even have the possibility of re-assignment, if you know that this is not supposed to happen. In addition, you could just simply check before assigning. But it is hard to tell, what may be a better course of action wit...
[ 1 ]
[]
[]
[ "immutability", "pydantic", "python", "validation" ]
stackoverflow_0074158269_immutability_pydantic_python_validation.txt
Q: Pandas combine df with a list by duplicating records for each list element I have a df like this. Date 2022-10-22 2022-10-21 2022-10-20 I want to combine and duplicate for each element in this list ['NAB', 'CBA'] To get a result df like this. Date Bank 2022-10-22 NAB 2022-10-22 CBA 2022-10-21 NAB 2022-1...
Pandas combine df with a list by duplicating records for each list element
I have a df like this. Date 2022-10-22 2022-10-21 2022-10-20 I want to combine and duplicate for each element in this list ['NAB', 'CBA'] To get a result df like this. Date Bank 2022-10-22 NAB 2022-10-22 CBA 2022-10-21 NAB 2022-10-21 CBA 2022-10-20 NAB 2022-10-20 CBA Thanks in advance.
[ "You can use a cross merge:\nlst = ['NAB', 'CBA']\nout = df.merge(pd.Series(lst, name='Bank'), how='cross')\n\nOutput:\n Date Bank\n0 2022-10-22 NAB\n1 2022-10-22 CBA\n2 2022-10-21 NAB\n3 2022-10-21 CBA\n4 2022-10-20 NAB\n5 2022-10-20 CBA\n\n", "Add fixed Bank=[\"NAB\", \"CBA\"] column to df:\...
[ 1, 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074161516_pandas_python.txt
Q: how to make the user choose between options I make password genrator using python then the teacher told to create a code that make the user choose what he want in the password the password contains 1- lower case characters 2- upper case characters 3- numbers 4- punticuation marks the teacher want me to make the ...
how to make the user choose between options
I make password genrator using python then the teacher told to create a code that make the user choose what he want in the password the password contains 1- lower case characters 2- upper case characters 3- numbers 4- punticuation marks the teacher want me to make the user choose if he want punticution or not if he d...
[ "You can write a function like this:\ndef isUserNeedPunctuationMarks():\n result = None\n while True:\n inp = input(\"Do you need punctuation marks in your password? (y/n)\")\n inp = inp.lower()\n if inp == \"y\":\n result = True\n break\n elif inp == \"n\":\n...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074162368_python.txt
Q: Python default and multi level logging From what I read and understood, Python logging module by default logs to stderr. If I run this python code: import logging logging.info('test') logging.warning('test') logging.error('test') logging.debug('test') as python main.py 1> stdout.txt 2> stderr.txt I get my logs ...
Python default and multi level logging
From what I read and understood, Python logging module by default logs to stderr. If I run this python code: import logging logging.info('test') logging.warning('test') logging.error('test') logging.debug('test') as python main.py 1> stdout.txt 2> stderr.txt I get my logs in stderr.txt and nothing in stdout.txt - m...
[ "You can probably benefit from the approach described here in the official documentation.\n", "Following the approach described in the official documentation:\nhttps://docs.python.org/3.10/howto/logging-cookbook.html#custom-handling-of-levels\nHere's my code with stream segregation:\nimport sys\nimport logging\n\...
[ 1, 0 ]
[]
[]
[ "logging", "observability", "python", "stderr", "stdout" ]
stackoverflow_0074123158_logging_observability_python_stderr_stdout.txt
Q: Pyaudio be used in colab I have installed pyaudio in colab but when I import pyaudio I get an error, I tried using the command: !pip install pipwin !pipwin install pyaudio A: It was mentioned in PyAudio that you need to install it on GNU/Linux with sudo apt install python3-pyaudio. So to install PyAudio you need...
Pyaudio be used in colab
I have installed pyaudio in colab but when I import pyaudio I get an error, I tried using the command: !pip install pipwin !pipwin install pyaudio
[ "It was mentioned in PyAudio that you need to install it on GNU/Linux with sudo apt install python3-pyaudio.\nSo to install PyAudio you need to install on google colab with !sudo apt install python3-pyaudio\n" ]
[ 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074134225_google_colaboratory_python.txt
Q: NLTK Perceptron Tagger - What does it recognize as FW (foreign word)? Relatively new to NLP and working on tagging sentences that contain foreign words using NLTK's PerceptronTagger (in Python) - but it continues to tag the tokenized foreign word by position in the syntax rather than as a 'FW'. Does the whole sen...
NLTK Perceptron Tagger - What does it recognize as FW (foreign word)?
Relatively new to NLP and working on tagging sentences that contain foreign words using NLTK's PerceptronTagger (in Python) - but it continues to tag the tokenized foreign word by position in the syntax rather than as a 'FW'. Does the whole sentence have to be in the language (with the appropriate language pickle file...
[ "in Spacy it means \"Foreign Word\". Maybe it is the same in NLTK.\n" ]
[ 0 ]
[]
[]
[ "nlp", "nltk", "perceptron", "pos_tagger", "python" ]
stackoverflow_0044550883_nlp_nltk_perceptron_pos_tagger_python.txt
Q: How to open gmap via bokeh in a zoom value that will show all markers? I run the following code, displaying google map via bokeh with markers on the map: gmap_options = GMapOptions(lat=lat, lng=lng, map_type=map_type, zoom=zoom) p = gmap(api_key, gmap_options, title='PhotosTrip', ...
How to open gmap via bokeh in a zoom value that will show all markers?
I run the following code, displaying google map via bokeh with markers on the map: gmap_options = GMapOptions(lat=lat, lng=lng, map_type=map_type, zoom=zoom) p = gmap(api_key, gmap_options, title='PhotosTrip', width=bokeh_width, height=bokeh_height, tooltips=TOOLTIPS, tools=...
[ "Assuming that by omitting zoom it defaults to 12, and given the limited information, an approach would be as follows:\ndef get_outer_markers(marker_source):\n # read dataset\n # process dataset. See e.g. https://stackoverflow.com/questions/25787637/python-plot-only-the-outermost-points-of-a-dataset\n oute...
[ 0 ]
[]
[]
[ "bokeh", "google_maps", "pandas_bokeh", "python" ]
stackoverflow_0073851853_bokeh_google_maps_pandas_bokeh_python.txt
Q: Check for special characters in Python while loop Below is code for a password generator which I've written using Python3 and tkinter. I'm having difficulty with the last line of code and any(c in spec for c in password). The while loop does not terminate when I add this last line to the if statement in the while ...
Check for special characters in Python while loop
Below is code for a password generator which I've written using Python3 and tkinter. I'm having difficulty with the last line of code and any(c in spec for c in password). The while loop does not terminate when I add this last line to the if statement in the while loop. I've looked at all the other answers online for "...
[ "The code and any(c in spec for c in password) does in fact work. After PyxlDavon pointed out that my code does work, I closed and restarted my python interpreter and the code did work. So my only conclusion is that my python interpreter became unstable for some unkown reason. I haven't seen this code style in any ...
[ 1, 0 ]
[]
[]
[ "python", "special_characters", "while_loop" ]
stackoverflow_0074162292_python_special_characters_while_loop.txt
Q: Pandas - modify cell if match and if not match delete row i need modify a csv file with pandas, I have the following table: Interface Description Gi0/3/4/3 ISP Gi0/3/4/3.401 Cliente A Gi0/3/4/3.402 Cliente B Gi0/3/4/3.403 Cliente C Gi0/3/4/4 Cliente D Gi0/3/4/4.1 Cliente E Gi0/3/4/4.2 ...
Pandas - modify cell if match and if not match delete row
i need modify a csv file with pandas, I have the following table: Interface Description Gi0/3/4/3 ISP Gi0/3/4/3.401 Cliente A Gi0/3/4/3.402 Cliente B Gi0/3/4/3.403 Cliente C Gi0/3/4/4 Cliente D Gi0/3/4/4.1 Cliente E Gi0/3/4/4.2 Cliente F Gi0/3/4/5 Cliente G I need to modify the In...
[ "Extract the suffix after Gi0/3/4/3. and then filter by non nulls:\ndf.Interface = df.Interface.str.extract('Gi0/3/4/3\\.(\\d+)')\ndf[df.Interface.notnull()]\n\n Interface Description\n1 401 Cliente A\n2 402 Cliente B\n3 403 Cliente C\n\n", "\nPlease be sure to answer the question. Provid...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074161093_pandas_python.txt
Q: Using dateadd in django filter I have a model that defines subscription periods by start date and duration (in days): class SubscriptionProduct(models.Model): start_date = models.DateField() duration = models.IntegerField() I need to be able to filter subscriptions that are currently active, e.g. star...
Using dateadd in django filter
I have a model that defines subscription periods by start date and duration (in days): class SubscriptionProduct(models.Model): start_date = models.DateField() duration = models.IntegerField() I need to be able to filter subscriptions that are currently active, e.g. start_date < now < start_date+duration I...
[ "I ended up writing a custom Func expression that does exacly what I was looking for. \nThis is very Postgresql specific and a bit hacky but it works, even when used in more complex queries than the one illustrated above.\nclass DateAdd(Func):\n \"\"\"\n Custom Func expression to add date and int fields as da...
[ 9, 4, 0 ]
[]
[]
[ "django", "django_orm", "postgresql", "python" ]
stackoverflow_0033981468_django_django_orm_postgresql_python.txt
Q: Import "matplotlib" could not be resolved from source Pylance(reportMissingModuleSource) whenever I try to import matplotlib or matplotlib.pyplot in VS Code I get the error in the title: Import "matplotlib" could not be resolved from source Pylance(reportMissingModuleSource) or Import "matplotlib.pyplot" could no...
Import "matplotlib" could not be resolved from source Pylance(reportMissingModuleSource)
whenever I try to import matplotlib or matplotlib.pyplot in VS Code I get the error in the title: Import "matplotlib" could not be resolved from source Pylance(reportMissingModuleSource) or Import "matplotlib.pyplot" could not be resolved from source Pylance(reportMissingModuleSource) The hyperlink of the reportMissi...
[ "I can reproduce your question when I select a python interpreter where doesn't exist matplotlib:\n\nSo, the solution is opening an integrated Terminal then run pip install matplotlib. After it's installed successfully, please reload window, then the warning should go away.\n", "Just changes the interpreter to 2....
[ 12, 2, 1, 0, 0 ]
[]
[]
[ "matplotlib", "pylance", "python", "visual_studio_code" ]
stackoverflow_0070709406_matplotlib_pylance_python_visual_studio_code.txt
Q: How would you unit test this SQLAlchemy Core query/function? I'm working on learning how to unit test properly. Given this function... def get_user_details(req_user_id): users = sa.Table('users', db.metadata, autoload=True) s = sa.select([users.c.username, users.c.favorite_color, ...
How would you unit test this SQLAlchemy Core query/function?
I'm working on learning how to unit test properly. Given this function... def get_user_details(req_user_id): users = sa.Table('users', db.metadata, autoload=True) s = sa.select([users.c.username, users.c.favorite_color, users.c.favorite_book ]).select_fr...
[ "\nFollowing from this comment:\n\nwhat you need to test is if the statements in your code produce\nexpected results. – Shod\n\nand your code, here's what I'm aiming to answer:\nHow can I test a method that is dynamically generating SQLAlchemy queries ?\nThat is the issue I was having, as I wanted to make sure the ...
[ 0 ]
[]
[]
[ "pytest", "python", "sqlalchemy" ]
stackoverflow_0060080521_pytest_python_sqlalchemy.txt
Q: I dont know why my code isn't counting the last 2 values I'm trying to make a code (for school) that compresses and counts the number of adjacent characters that are the same. in this example it would be 4(1) 4(0) 2(1) 2(0). it is supposed to output: 4 4 2 2 but for some reason, it leaves out the last 2. does any...
I dont know why my code isn't counting the last 2 values
I'm trying to make a code (for school) that compresses and counts the number of adjacent characters that are the same. in this example it would be 4(1) 4(0) 2(1) 2(0). it is supposed to output: 4 4 2 2 but for some reason, it leaves out the last 2. does anyone know how to fix this or make my code more optimised? my co...
[ "You could use itertools.groupby.\nTo see how it works, here is what it does to your val:\nprint([(k, list(v)) for k,v in itertools.groupby(val)])\n\n[('1', ['1', '1', '1', '1']),\n ('0', ['0', '0', '0', '0']),\n ('1', ['1', '1']),\n ('0', ['0', '0'])]\n\nTo get your desired output, we only need to get the length o...
[ 2, 0 ]
[]
[]
[ "compression", "python" ]
stackoverflow_0074162074_compression_python.txt
Q: yolov5 rstp OSError: [WinError 123] I used yolov5 with python detect.py --source rtsp://admin:xxxxx@10.xx.xx.xxx//streaming/channels/1 --weights runs/train/exp4/weights/best.pt but happened OSError: [WinError 123] Incorrect filename, directory name, or volume tagline method How to solve this problem? Thank you! ...
yolov5 rstp OSError: [WinError 123]
I used yolov5 with python detect.py --source rtsp://admin:xxxxx@10.xx.xx.xxx//streaming/channels/1 --weights runs/train/exp4/weights/best.pt but happened OSError: [WinError 123] Incorrect filename, directory name, or volume tagline method How to solve this problem? Thank you!
[ "python detect.py --source rtsp://admin:xxxxx@10.xx.xx.xxx//streaming/channels/1\nlook this\nhttps://github.com/ultralytics/yolov5/pull/9879\n" ]
[ 0 ]
[]
[]
[ "deep_learning", "python", "pytorch", "yolov5" ]
stackoverflow_0074088767_deep_learning_python_pytorch_yolov5.txt
Q: Django queryset filter based on slug I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current u...
Django queryset filter based on slug
I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current url then shows the video selecting that alb...
[ "got too the same problem I've tried this in get_context_data()\ndef get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n movies = Video.objects.filter(slug=SlugField) #SlugField is the source of the problem I got I think\n context[\"movies\"] = movies\n return context\n\nB...
[ 1 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074156348_django_html_python.txt
Q: A problem when writing in json file (python) I'm new to kinda python so this is my code (a part of it) : import json from time import sleep as sl logs = open('C://Users//pc//Desktop//tikmoh//Dev//projects//other//Python//log and reg sys//users.json','r+') data = json.load(logs) def reg(): def remove_quotes(x...
A problem when writing in json file (python)
I'm new to kinda python so this is my code (a part of it) : import json from time import sleep as sl logs = open('C://Users//pc//Desktop//tikmoh//Dev//projects//other//Python//log and reg sys//users.json','r+') data = json.load(logs) def reg(): def remove_quotes(x=str): x = x.replace("\"","").replace('\''...
[ "Apart from the logic errors, try using seek() instead of truncate().\n" ]
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074162364_json_python.txt
Q: justPy toggle a Quasar drawer I copied some HTML from Quasar for a page layout with a drawer and can not figure out how to toggle the drawer (sidebar). The button works to hide the drawer, but can not get it visible again. Or if you have an example or can point me in direction of a non-Quasar sidebar that works i...
justPy toggle a Quasar drawer
I copied some HTML from Quasar for a page layout with a drawer and can not figure out how to toggle the drawer (sidebar). The button works to hide the drawer, but can not get it visible again. Or if you have an example or can point me in direction of a non-Quasar sidebar that works in a similar manner, that would be h...
[ "import justpy as jp\n\n\ndef toggle_visible_drawer(self, msg):\n self.drawer.value = not self.drawer.value\n\n\ndef quasar_page():\n wp = jp.QuasarPage()\n\n btn_drawer = jp.QBtn(\n flat=True,\n round=True,\n dense=True,\n icon=\"menu\",\n a=wp,\n click=toggle_vis...
[ 1 ]
[]
[]
[ "justpy", "python" ]
stackoverflow_0070743332_justpy_python.txt
Q: Is it possible to plot a map with only whole latitude or longitude? I have some code that plots a map with markers that represent a given pair of longitude and latitude (as a point). df = pd.read_csv("geo.csv", delimiter=';', skiprows=0, low_memory=False) geometry = [Point(xy) for xy in zip(df['longitude'], df['la...
Is it possible to plot a map with only whole latitude or longitude?
I have some code that plots a map with markers that represent a given pair of longitude and latitude (as a point). df = pd.read_csv("geo.csv", delimiter=';', skiprows=0, low_memory=False) geometry = [Point(xy) for xy in zip(df['longitude'], df['latitude'])] gdf = GeoDataFrame(df, geometry=geometry) world = gpd.read...
[ "There are lots of way to do this! Here are a few...\nUsing matplotlib: matplotlib.pyplot.grid\nOne would be to add gridlines at specific lat/lons. You're just using matplotlib (i.e., not cartopy with a specific projection), so the way to do this is to set specific major and minor tick locations, then draw lines wi...
[ 0, 0 ]
[]
[]
[ "geopandas", "python", "shapely" ]
stackoverflow_0074155724_geopandas_python_shapely.txt
Q: @staticmethod used in qiksit hybrid neural network I am very new to python. I was studing some code from qiskit - https://qiskit.org/textbook/ch-machine-learning/machine-learning-qiskit-pytorch.html. I have a lot of doubt in the below code. After doing some study of neural network, I can intrepret that below code ...
@staticmethod used in qiksit hybrid neural network
I am very new to python. I was studing some code from qiskit - https://qiskit.org/textbook/ch-machine-learning/machine-learning-qiskit-pytorch.html. I have a lot of doubt in the below code. After doing some study of neural network, I can intrepret that below code is for back progpogation. But above the function backwa...
[ "The @staticmethod decorator indicates that this method is static, which means that it can be run without being attached to a particular instance of the class.\nIt simply means that you can consider it as a normal function, the only thing to remember is that you will call it with Class.backward(ctx, grad_output), w...
[ 1 ]
[]
[]
[ "neural_network", "python", "qiskit" ]
stackoverflow_0074162691_neural_network_python_qiskit.txt
Q: How do I add multiple tuples and convert into only list I got confused between Representations. But I checked, my output is "class tuple" My code is: for key, value in analysis.items(): tvi = (key, {k:v for k, v in value.indicators.items() if k in indica}) TVA = print(tvi) And I had a list of multiple tup...
How do I add multiple tuples and convert into only list
I got confused between Representations. But I checked, my output is "class tuple" My code is: for key, value in analysis.items(): tvi = (key, {k:v for k, v in value.indicators.items() if k in indica}) TVA = print(tvi) And I had a list of multiple tuples: ('James',{'hair':'black','eye':'brown'}) ...
[ "You can do this with list comprehension,\n[(key, {k:v for k, v in value.indicators.items() if k in indica}) \n for key, value in analysis.items()]\n\n" ]
[ 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074162248_list_python_tuples.txt
Q: Multi Dimension Python Lists I am new to python 3 and trying to work with a list but struggling. I have read things but some are quite confusing, so I have been playing with code but getting nowhere fast. I want to store 3 elements (Count,Angle,Speed) for every second of the day which is 86400 entries. To make thi...
Multi Dimension Python Lists
I am new to python 3 and trying to work with a list but struggling. I have read things but some are quite confusing, so I have been playing with code but getting nowhere fast. I want to store 3 elements (Count,Angle,Speed) for every second of the day which is 86400 entries. To make things easier for this example lets h...
[ "[[0,0,0]]*2\n\nmeans that you evaluate [0,0,0], that is build such a list. And then create an array of 2 elements whose each element is this [0,0,0]. So it is the same one!\nIt is like doing\narr=[]\narr0=[0,0,0]\nfor i in range(2):\n arr.append(arr0)\n\nSo, since arr[0] and arr[1] are the same list, altering o...
[ 1, 1, 1, 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074162456_list_python_python_3.x.txt
Q: Check if there is any repeated element in a dataframe (excluding empty cells) Hi I am trying to get "True" as output if there is a repeated element in a dataframe, and "False" if there is no repeated element. This should not take the empty cells into account. Example 1: import pandas as pd data_df = {'col1': ['A',...
Check if there is any repeated element in a dataframe (excluding empty cells)
Hi I am trying to get "True" as output if there is a repeated element in a dataframe, and "False" if there is no repeated element. This should not take the empty cells into account. Example 1: import pandas as pd data_df = {'col1': ['A','B', 'C', 'D'], 'col2': ['E','F', '', 'G'], 'col3': ['H', '...
[ "You can use:\nout = (df.stack() # stack to Series, removing NaNs\n # remove empty/space strings\n .loc[lambda s: s.str.strip().ne('')]\n # is there any duplicate?\n .duplicated().any()\n )\n\nOutputs:\nFalse\nTrue\nTrue\n\n" ]
[ 3 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074162733_dataframe_numpy_pandas_python.txt
Q: How to pass a list of tuples in template file from views so I can separately iterate each data member in template? I'm working on a django project , I got a list of tuples accessed from postgres database using psycopg2. Now I want to pass this list of tuples to my template file in such way that I can access each e...
How to pass a list of tuples in template file from views so I can separately iterate each data member in template?
I'm working on a django project , I got a list of tuples accessed from postgres database using psycopg2. Now I want to pass this list of tuples to my template file in such way that I can access each element of individual tuple. As I have to put this data into a html table. views.py file : def search_owner_prop(requ...
[ "If you want to display in templates, simply you can pass context in views.\nNow pass the context here:\nreturn render(request,'owner_with_prop.html',{'rows':rows}) #rows is a context from views\n\nAnd in templates:\n{% for tuple in rows %}\n {{tuple}}\n{% endfor %}\n\nUsing above code, you can display all tuples ...
[ 0 ]
[]
[]
[ "backend", "database", "django", "python" ]
stackoverflow_0074162744_backend_database_django_python.txt
Q: from gcn.utils import * ModuleNotFoundError: No module named 'gcn.utils'. Why can't it find it? https://github.com/tkipf/gcn I am trying to run this graph neural network code from github on my google colab. When I run the train.py file it gives me this error: from gcn.utils import * ModuleNotFoundError: No module ...
from gcn.utils import * ModuleNotFoundError: No module named 'gcn.utils'. Why can't it find it?
https://github.com/tkipf/gcn I am trying to run this graph neural network code from github on my google colab. When I run the train.py file it gives me this error: from gcn.utils import * ModuleNotFoundError: No module named 'gcn.utils' I ran !python3 /content/drive/MyDrive/GNN/gcn/setup.py install - the setup file and...
[ "The folder name is gcn,there are some conflicts,change the folder name, or remove all the gcn. from imports of gcn.xx.\nsuch as: from gcn.utils -> from utils\n" ]
[ 0 ]
[]
[]
[ "graph", "neural_network", "python" ]
stackoverflow_0072556163_graph_neural_network_python.txt
Q: Why Python shell shows 'NameError: name 'inputwhichpower' is not defined. Did you mean: 'inputwhichpet'?' I am making a text adventure game while i get stuck in 'NameError: name 'inputwhichpower' is not defined. Did you mean: 'inputwhichpet'?' inputwhichpower and inputwhichpet is a input. I have no idea what is ca...
Why Python shell shows 'NameError: name 'inputwhichpower' is not defined. Did you mean: 'inputwhichpet'?'
I am making a text adventure game while i get stuck in 'NameError: name 'inputwhichpower' is not defined. Did you mean: 'inputwhichpet'?' inputwhichpower and inputwhichpet is a input. I have no idea what is causing the problem and how to fix it. my code is so big, so i am just uploading the code where the problem is fa...
[ "Your variable inputwhichpower is out of the second if statement's scope.\nHere's the solution, you jsut have to specifiy that there IS a variable like that:\ninputwhichpower = \"\";\nif inputcattype==\"fire\":\n inputwhichpower = input(\"Choose a power. [Fire Balls]\")\n\nif inputwhichpower==\"fire balls\":\n ...
[ 0 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0074155908_error_handling_python.txt
Q: Add emoticons in tweet text updated using tweepy I am creating an auto-DM bot using tweepy. I want to add emojis to the text. Is it possible? I have tried adding '' and :heartpulse::heart_eyes_cat: without luck. A: Adding :heartpulse::heart_eyes_cat: like this doesn't help. Since emoticons are just special chara...
Add emoticons in tweet text updated using tweepy
I am creating an auto-DM bot using tweepy. I want to add emojis to the text. Is it possible? I have tried adding '' and :heartpulse::heart_eyes_cat: without luck.
[ "Adding :heartpulse::heart_eyes_cat: like this doesn't help.\nSince emoticons are just special characters, all you have to do is use the right encoding to add them in the text. All you need to display is the font that support them. \nU+1F601 is 16 bit unicode. In this U+1F601 is unicode representation of emoticon ...
[ 1, 1, 0 ]
[]
[]
[ "python", "tweepy" ]
stackoverflow_0051451854_python_tweepy.txt
Q: How to print an input using the print function? (It should allow the user to type) How do i print an input using the print function? (it should allow the user to type) if ChooseGame=="1": part1story = input("Do you want to skip the story[y] or [n]") if part1story=="y": robotwarpart1() As you can see, the...
How to print an input using the print function? (It should allow the user to type)
How do i print an input using the print function? (it should allow the user to type) if ChooseGame=="1": part1story = input("Do you want to skip the story[y] or [n]") if part1story=="y": robotwarpart1() As you can see, the robotwarpart1 function will only be called if we give input to part1story. Yes i know, ...
[ "your code should look like:\npart1story = 'n'\nif ChooseGame == '1':\n part1story = input(\"Do you want to skip the story[y] or [n]\")\n\nif part1story == 'y':\n robotwarpart1()\n\nYou get a NameError because as the comment mentions, part1story isn't even getting defined if ChooseGame is not \"1\".\n", "Like @...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074162607_python.txt
Q: 'AppSettings' object has no attribute 'STORE_TOKENS' I have Object: AppSettings in app_settings.py class AppSettings(object): def init(self, prefix): self.prefix = prefix def _setting(self, name, dflt): from django.conf import settings getter = getattr( settings, "ALLAUTH_SETTING_GETTER", ...
'AppSettings' object has no attribute 'STORE_TOKENS'
I have Object: AppSettings in app_settings.py class AppSettings(object): def init(self, prefix): self.prefix = prefix def _setting(self, name, dflt): from django.conf import settings getter = getattr( settings, "ALLAUTH_SETTING_GETTER", lambda name, dflt: getattr(settings, name, dflt), ...
[ "In your settings.py you need to add this line :\nSTORE_TOKENS= True\n\n" ]
[ 0 ]
[ "Actually the problem was....I was trying to authenticate during the logged in django administration.\n" ]
[ -1 ]
[ "django", "django_allauth", "python", "twitter_oauth" ]
stackoverflow_0074009466_django_django_allauth_python_twitter_oauth.txt
Q: Cant find out how can I compare two manytomany fields and show the result in context So, I am doing a project where there are posts of 3 categories (movies(model name="List"), music(model name="MusicList"), books(model name="BookList")) each category is a model. and each model has its own genre set model (Genre, M...
Cant find out how can I compare two manytomany fields and show the result in context
So, I am doing a project where there are posts of 3 categories (movies(model name="List"), music(model name="MusicList"), books(model name="BookList")) each category is a model. and each model has its own genre set model (Genre, MusicGenre, BookGenre). There is a profile model which has - favourite_music_genre, favouri...
[ "For the books, you could try something like\nBookList.objects.filter(genre__id__in=current_profile.fav_Book_genre.values_list(\"id\", flat=True))\n\nIf it works you'll be able to do the same for movies and musics\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074162773_django_django_models_python.txt
Q: How to invert the result of this for loop pyramid? Our professor wants us to perform our previous problem of inverting the result of a pyramid of numbers, given a certain height, but now using for loops. I seem to be doing something wrong with my code. What I have so far: size = int(input("Height: ")) for num in r...
How to invert the result of this for loop pyramid?
Our professor wants us to perform our previous problem of inverting the result of a pyramid of numbers, given a certain height, but now using for loops. I seem to be doing something wrong with my code. What I have so far: size = int(input("Height: ")) for num in range(size, 0, -1): for num2 in range(1, num + 1): ...
[ "you need to reverse your second for loop to achieve your the desired output.\nTry like this:\nsize = int(input(\"Height: \"))\nfor num in range(size, 0, -1):\n for num2 in range(1, num + 1)[::-1]:\n print(num2, end=\" \")\n print(\"\\n\")\n\n", "You just need a descending range within a descending rang...
[ 1, -1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074162782_for_loop_python.txt
Q: How do you display a Flask variable in HTML? My application takes user input (params.json and an image), uses machine learning to determine an output, and I want it to be able to show the output on the frontend. The output can either be in string, float, or json form — I can change its format as long as it's able ...
How do you display a Flask variable in HTML?
My application takes user input (params.json and an image), uses machine learning to determine an output, and I want it to be able to show the output on the frontend. The output can either be in string, float, or json form — I can change its format as long as it's able to reach the frontend. The only problem is, none o...
[ "Solved by receiving the response in JS:\n@app.route('/predict/input', methods=['POST', 'GET'])\ndef predict():\n if request.method == 'POST':\n file = request.form\n params = file['params']\n params = json.loads(params)\n photo = str(file['photo'])\n photo = urllib.request.url...
[ 0 ]
[]
[]
[ "flask", "html", "javascript", "json", "python" ]
stackoverflow_0074161427_flask_html_javascript_json_python.txt
Q: Python code to generate all the 6 digit numeric code Am trying to use a brute force attack to generate all the whole possible 6-digit numeric code with python i want all the code possible with this code from number 0,1,2,3,4,5,6,7,8,9 how do i generate all the possible digits code for a six digit using python. imp...
Python code to generate all the 6 digit numeric code
Am trying to use a brute force attack to generate all the whole possible 6-digit numeric code with python i want all the code possible with this code from number 0,1,2,3,4,5,6,7,8,9 how do i generate all the possible digits code for a six digit using python. import string import random def brute_force(size=6, chars=st...
[ "Given that your possible passwords are all strings from 000000 to 999999, you can use range(1000000) to get the numbers below 1m and then format those numbers with leading zeros like this:\nf\"{password:06d}\"\n# or \nstr(password).zfill(6)\n\nAs a loop:\nfor password in range(100):\n print(f\"{password:06d}\")...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074162825_python.txt
Q: Getting a floating point number input to print out as integer and a decimal I'm trying to ask a user to type in a floating point number. My program should then print it out as integer and a decimal. What I'm looking for is: If user types : 1.34 ... then integer should print: 1 and decimal should print: 0.34 Here's...
Getting a floating point number input to print out as integer and a decimal
I'm trying to ask a user to type in a floating point number. My program should then print it out as integer and a decimal. What I'm looking for is: If user types : 1.34 ... then integer should print: 1 and decimal should print: 0.34 Here's what I'm doing: number = float(input('Number: ')) print('integer: ', int(number)...
[ "Just take the integer from the original float (assuming the number is positive)\nnumber = float(input('Number: '))\nprint('integer: ', int(number))\nprint('decimal: ', number - int(number)))\n\nYes sometimes the result may be slightly inaccurate. This is a consequence of using floating point numbers here's an expl...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0072440221_python_python_3.x.txt
Q: How to check if I have a numpy array for any library nickname? I'm writing a type checker for a function which needs to check if an argument is of type <class 'numpy.ndarray'>. However, if v is a NumPy array, checking if type(v) == np.array eventually depends on how one globally imports numpy. For example if impor...
How to check if I have a numpy array for any library nickname?
I'm writing a type checker for a function which needs to check if an argument is of type <class 'numpy.ndarray'>. However, if v is a NumPy array, checking if type(v) == np.array eventually depends on how one globally imports numpy. For example if import numpy is solely used, then the type checker can't run as type(v) =...
[ "Convert the output of type to string and check if it's \"<class 'numpy.ndarray'>\"\nThis works:\nimport numpy\n\nv = numpy.array([1.])\n\nprint(str(type(v)) == \"<class 'numpy.ndarray'>\")\n\nAnd this too:\nimport numpy as np\n\nv = np.array([1.])\n\nprint(str(type(v)) == \"<class 'numpy.ndarray'>\")\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074162696_numpy_python.txt
Q: How to select child element using BeatifulSoup Html code How can i select all of titleline href's with using BeatifulSoup ? A: Given soup as a BeautifilSoup object of your website, try this: soup.find("span", {"class": "titleline"}).findChildren("a") edit: [a['href'] for elem in soup.find_all("span", {"class": ...
How to select child element using BeatifulSoup
Html code How can i select all of titleline href's with using BeatifulSoup ?
[ "Given soup as a BeautifilSoup object of your website, try this:\nsoup.find(\"span\", {\"class\": \"titleline\"}).findChildren(\"a\")\n\nedit:\n[a['href'] for elem in soup.find_all(\"span\", {\"class\": \"titleline\"}) for a in elem.findChildren(\"a\")]\n\nFull example:\nimport requests\nfrom bs4 import BeautifulSo...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074162909_python.txt
Q: In PyQt5 How to call function or method after load aplication? from PyQt5 import QtWidgets import time def show_message(self): time.sleep(5) self.label.setText("It's me") class Main(QtWidgets.QMainWindow): def __init__(self): super(Main, self).__init__() self.label = QtW...
In PyQt5 How to call function or method after load aplication?
from PyQt5 import QtWidgets import time def show_message(self): time.sleep(5) self.label.setText("It's me") class Main(QtWidgets.QMainWindow): def __init__(self): super(Main, self).__init__() self.label = QtWidgets.QLabel('Hello', self) #How to call this func...
[ "I am guessing you want to start the application and then after 5 seconds the text in the label will get changed to the new text.\nWhat you have right now is almost working, however the problem is that when you call time.sleep(5) then the whole execution of the program will get paused and nothing gets shown for tha...
[ 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074162738_pyqt5_python.txt
Q: Autofit column width to text using Python for excel files independent of character count I am searching for a while and I found no straight forward answer to do so except using xlwings, which needs to use microsoft excel which is not desired in my case... Only way to autofit column width to text is below code for ...
Autofit column width to text using Python for excel files independent of character count
I am searching for a while and I found no straight forward answer to do so except using xlwings, which needs to use microsoft excel which is not desired in my case... Only way to autofit column width to text is below code for col in sheet.columns: max_length = 0 column = col[0].column_letter # Get the column n...
[ "Below code doesn't impact the performance significantly, but you need to have your font file and it's location for this code.\nBut still xlwings' way is more reliable\nIt is based on this answer on stack overflow\nfunction for getting the width\ndef get_text_width(text_input, point_size):\n font = TTFont('../fo...
[ 1 ]
[]
[]
[ "excel", "openpyxl", "python", "python_3.x", "xlwings" ]
stackoverflow_0074157571_excel_openpyxl_python_python_3.x_xlwings.txt
Q: Mapping a list right in Python I have a question on how to map correctly my list. I have the following code: class Bar(): def __init__(self, i, j): self.i = i-1 self.j = j-1 For the following list: bars = [Bar(1,2), Bar(2,3), Bar(3,4), Bar(4,5), Bar(5,1),Bar(1,4), Bar(2,4), Bar(4,6), Bar(6,5)]...
Mapping a list right in Python
I have a question on how to map correctly my list. I have the following code: class Bar(): def __init__(self, i, j): self.i = i-1 self.j = j-1 For the following list: bars = [Bar(1,2), Bar(2,3), Bar(3,4), Bar(4,5), Bar(5,1),Bar(1,4), Bar(2,4), Bar(4,6), Bar(6,5)] But for my problem, I have an arra...
[ "You can use itertools.starmap instead of map (after importing itertools). Your current way calls Bar([1, 2]). starmap unpacks the lists into arguments. A generator/list comprehension is also an option.\n(Bar(*x) for x in r)\n\nNow you see why it's called starmap.\n", "You need to unpack the nested lists into the...
[ 1, 1, 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074162467_list_python_python_3.x.txt
Q: create Xero invoice using python request raise "No data has been processed for this endpoint. This endpoint is expecting Invoice data to be specifed" I am trying to create an Invoice in Xero accounting using one of the Xero provided rest api, i used a Python requests library to access the certain Invoice rest api ...
create Xero invoice using python request raise "No data has been processed for this endpoint. This endpoint is expecting Invoice data to be specifed"
I am trying to create an Invoice in Xero accounting using one of the Xero provided rest api, i used a Python requests library to access the certain Invoice rest api but unable to create an invoice. It raise following error {'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed fo...
[ "You need to give data like this as per the API documentation\ndata = {\n \"Invoices\": [{\n \"Type\": \"ACCREC\",\n \"Contact\": {\n \"ContactID\": \"eaa28f49-6028-4b6e-bb12-d8f6278073fc\"\n },\n \"Date\": \"\\/Date(1518685950940+0000)\\/\",...
[ 0 ]
[]
[]
[ "python", "python_requests", "xero_api" ]
stackoverflow_0074162990_python_python_requests_xero_api.txt
Q: Django connection to postgres by docker-compose My django project cannot connect to postgres database container. What I should to do? It crashes on commands python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate. I know docker run command creates a new containe...
Django connection to postgres by docker-compose
My django project cannot connect to postgres database container. What I should to do? It crashes on commands python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate. I know docker run command creates a new container but I have more commands as one by bash in docker-...
[ "Each container in docker by default gets its own hostname and IP. When compose spins up the containers for you, it also places all of the containers on a network by default to permit DNS based discovery.\nWhat this means is that your database is not reachable on localhost, but you can reach it by the service name ...
[ 35, 4, 0 ]
[]
[]
[ "django", "docker", "docker_compose", "postgresql", "python" ]
stackoverflow_0042811727_django_docker_docker_compose_postgresql_python.txt
Q: Numpy polyfit find least divergent I am using numpy polyfit to create a number of plots which show a line of best fit. This works fine.. But I am wondering... Is it possible to assertain WHICH one of my plots has got the "straightest" line Not sure what the correct term is... I guess from the data points given, wh...
Numpy polyfit find least divergent
I am using numpy polyfit to create a number of plots which show a line of best fit. This works fine.. But I am wondering... Is it possible to assertain WHICH one of my plots has got the "straightest" line Not sure what the correct term is... I guess from the data points given, which set of data is least divergent? ie: ...
[ "Fitting Algorithms like Regression has a metric showing it's accuracy named RMSE (root mean square error) which shows how much does curve deviates from points. It is explained here well.\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074162996_numpy_python.txt
Q: obtaining correct IMU values I am reading data from an AHRS / IMU sensor via USB with Python 2.7. To obtain the acceleration the manufacturer specifies according to the image below: supplier's description IMU My code in python is this, but when the acceleration is negative the values are wrong. I believe I need t...
obtaining correct IMU values
I am reading data from an AHRS / IMU sensor via USB with Python 2.7. To obtain the acceleration the manufacturer specifies according to the image below: supplier's description IMU My code in python is this, but when the acceleration is negative the values are wrong. I believe I need to check the first bit of the MSB (...
[ "Using struct\nThe axes data are stored as a little-endian signed short (2 byte) integers, so we can use struct to unpack the data. The struct module will take care of the correct interpretation of the bytes as short integers.\nimport struct\n\ng = 9.81\nconv = 16.0 / 32768.0 * g\n\n# ...\n\n elif data[1] == b'\...
[ 1, 0 ]
[]
[]
[ "imu", "python" ]
stackoverflow_0055406762_imu_python.txt
Q: Type hint for returning loguru logger Does anyone know the proper type hint for returning a loguru logger? Using loguru.Logger passes mypy checks, but when the function get_logger is called I get the error AttributeError: module 'loguru' has no attribute 'Logger' import copy from pathlib import Path from sys impor...
Type hint for returning loguru logger
Does anyone know the proper type hint for returning a loguru logger? Using loguru.Logger passes mypy checks, but when the function get_logger is called I get the error AttributeError: module 'loguru' has no attribute 'Logger' import copy from pathlib import Path from sys import stdout from loguru import logger import ...
[ "I learned that loguru.Logger is correct and can be used without throwing an error if from __future__ import annotations is added to the list of imports.\nThis comes from the loguru type hint documentation\n", "I tried the answer above answer but failed, well I solved it by\nfrom typing import TYPE_CHECKING\n\n\n...
[ 1, 0 ]
[]
[]
[ "logging", "python", "python_3.x" ]
stackoverflow_0066411218_logging_python_python_3.x.txt
Q: Generate random number in range excluding some numbers Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range? For example, I know that you can generate a random number between 0 and 9 with: from random import randint randint(0,9) What if I have a lis...
Generate random number in range excluding some numbers
Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range? For example, I know that you can generate a random number between 0 and 9 with: from random import randint randint(0,9) What if I have a list, e.g. exclude=[2,5,7], that I don't want to be returned?
[ "Try this:\nfrom random import choice\n\nprint(choice([i for i in range(0,9) if i not in [2,5,7]]))\n\n", "Try with something like this:\nfrom random import randint\n\ndef random_exclude(*exclude):\n exclude = set(exclude)\n randInt = randint(0,9)\n return my_custom_random() if randInt in exclude else randInt ...
[ 43, 7, 3, 1, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0042999093_python_random.txt
Q: Check if date falls between two other dates Edit: Added more data to the table I have two dataframes in Python: df1: Date Company 2022-01-04 Apple 2020-01-03 Apple 2000-01-03 Apple and df2: Start End CEO Company 2022-01-01 2022-01-05 Tim Cook Apple 2022-01-01 2022-01-05 Bill Gates Microsoft I would like t...
Check if date falls between two other dates
Edit: Added more data to the table I have two dataframes in Python: df1: Date Company 2022-01-04 Apple 2020-01-03 Apple 2000-01-03 Apple and df2: Start End CEO Company 2022-01-01 2022-01-05 Tim Cook Apple 2022-01-01 2022-01-05 Bill Gates Microsoft I would like to add a new column to my fir...
[ "Have a look at pandas.merge_asof.\nExample data:\nimport numpy as np\nimport pandas as pd\n\ndf1 = pd.DataFrame({\"Date\": [\"2022-01-04\", \"2000-01-01\", \"2000-01-01\", \"2022-10-22\"],\n \"Company\": [\"Apple\", \"Apple\", \"Microsoft\", \"Company\"]})\ndf2 = pd.DataFrame(\n {\"Start\": [...
[ 1 ]
[]
[]
[ "lookup", "merge", "python" ]
stackoverflow_0074162499_lookup_merge_python.txt
Q: Can you set a variable for LIMIT OFFSET in SQLite? So I was doing a project that required us to create a program in python and I was wondering if you could use a variable for the OFFSET value so that it can be increased through "if" functions. Here is the code I came up with. > c.execute("SELECT * FROM Book_reserv...
Can you set a variable for LIMIT OFFSET in SQLite?
So I was doing a project that required us to create a program in python and I was wondering if you could use a variable for the OFFSET value so that it can be increased through "if" functions. Here is the code I came up with. > c.execute("SELECT * FROM Book_reservation WHERE Status='Pending' LIMIT 20 OFFSET ?",(Num)) ...
[ "An int in parentheses is just an int. See what type( (5) ) returns. The argument to execute requires a sequence. It will be seen as a tuple if written (Num,). Or the argument can be a list, eg [Num].\n", "AS @DinoCoderSaurus mentioned, the argument to execute requires a sequence.Just add a comma(,) after the va...
[ 0, 0 ]
[]
[]
[ "limit", "offset", "python", "sqlite" ]
stackoverflow_0069986760_limit_offset_python_sqlite.txt
Q: Changing dataframe columns in streamlit I cant change the 0 (see the image) in the columns or even add column name similar = pd.DataFrame() for question, rating in ratings: similar=similar.append(get_similar(question, rating), ignore_index=True) similar.head(10) similar.sum().sort_values(...
Changing dataframe columns in streamlit
I cant change the 0 (see the image) in the columns or even add column name similar = pd.DataFrame() for question, rating in ratings: similar=similar.append(get_similar(question, rating), ignore_index=True) similar.head(10) similar.sum().sort_values(ascending=False).head(17) I've tried renami...
[ "The line similar=pd.DataFrame(columns=['new_text','new_text1']) will return a new dataframe with only column names but no rows.\nThere are two issues:\n\nYou have not specified the dataframe whose column name you want to assign or change.\nWrong syntax of changing or assigning column name\n\nThe correct way to ass...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "streamlit" ]
stackoverflow_0074161851_dataframe_pandas_python_streamlit.txt
Q: Python plt plot error with dataframe and array I got error while plotting with Matplotlib X_train.shape gives (1343, 1). It is a dataframe len(y_pred_baseline) is 1343. It is an array The code I use is plt.plot(X_train, y_pred_baseline, color = "orange", label = "Baseline Model") I got the below error message: --...
Python plt plot error with dataframe and array
I got error while plotting with Matplotlib X_train.shape gives (1343, 1). It is a dataframe len(y_pred_baseline) is 1343. It is an array The code I use is plt.plot(X_train, y_pred_baseline, color = "orange", label = "Baseline Model") I got the below error message: ------------------------------------------------------...
[ "Please insert you code from *.py file, not debugging info of your terminal.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074162229_matplotlib_python.txt
Q: Running a python file on the button click in Node JS I am trying to run a python file (which is actually running a Deep learning model) on a button click using Node JS. I am trying to achieve this using input form in html and routes in index.js file. But this is causing this error after running for a while: I jus...
Running a python file on the button click in Node JS
I am trying to run a python file (which is actually running a Deep learning model) on a button click using Node JS. I am trying to achieve this using input form in html and routes in index.js file. But this is causing this error after running for a while: I just want to run the python file in the background, no argume...
[ "Why are you using res.send(data.toString());, I don't see any use of this line in your code. Try removing the mentioned code and run again.\n" ]
[ 1 ]
[]
[]
[ "express", "javascript", "node.js", "python", "python_3.x" ]
stackoverflow_0074138480_express_javascript_node.js_python_python_3.x.txt
Q: How to efficiently count the number of two word combinations in human names? I have a dataframe with a single column which contains the names of people as shown below. name -------------- john doe john david doe doe henry john john henry I want to count the number of time each two words appear together in a name ...
How to efficiently count the number of two word combinations in human names?
I have a dataframe with a single column which contains the names of people as shown below. name -------------- john doe john david doe doe henry john john henry I want to count the number of time each two words appear together in a name regardless of the order. In this example, the words john and doe appear in the sam...
[ "Here's a solution which is still quadratic but over smaller n and also hides most of it in compiled code (which should hopefully execute faster):\nfrom itertools import combinations\n\ncombs = df['name'].apply(lambda x:list(combinations(sorted(x.split()),2)))\ncounts = Counter(combs.explode())\nres = pd.Series(cou...
[ 2, 1, 1 ]
[]
[]
[ "nlp", "performance", "python", "python_3.x", "time_complexity" ]
stackoverflow_0074162214_nlp_performance_python_python_3.x_time_complexity.txt
Q: Azure ML Studio: OSError: Cannot save file into a non-existent directory I am using Azure ML Studio to read data from a csv file by creating a data asset test5 and write data into a csv file for my current working directory (which is failing). I am submitting a Job using a Compute Cluster and a Custom Environment ...
Azure ML Studio: OSError: Cannot save file into a non-existent directory
I am using Azure ML Studio to read data from a csv file by creating a data asset test5 and write data into a csv file for my current working directory (which is failing). I am submitting a Job using a Compute Cluster and a Custom Environment and I am following the instructions from this tutorial. I have written the cod...
[ "The error is telling you that the directory you wish to save the CSV into doesn't exist. So, to make sure that everything is right, you should make sure that there exist an \"azureml-in-a-day\" folder under \"Ankit19.Gupta\", and the same for \"src\" under \"azureml-in-a-day\".\nAlso, try this:\nimport os\n\n...\n...
[ 1 ]
[]
[]
[ "azure", "azure_machine_learning_service", "azure_machine_learning_studio", "oserror", "python" ]
stackoverflow_0074163156_azure_azure_machine_learning_service_azure_machine_learning_studio_oserror_python.txt
Q: Adding individual items from two lists into a new list Write a function that expects two lists of integers, a and b, as parameters and returns a list. The function should merge the elements of both input lists by index and return them as tuples in a new list. If one list is shorter than the other, the last element...
Adding individual items from two lists into a new list
Write a function that expects two lists of integers, a and b, as parameters and returns a list. The function should merge the elements of both input lists by index and return them as tuples in a new list. If one list is shorter than the other, the last element of the shorter list should be repeated as often as necessar...
[ "There are a few things to update in your code:\n(1) change this format mergelist = [a[i], b[i]] to this format mergelist.append((a[i], b[i]))\n(2) need to take care of the case when len(a) == len(b)\n(3) list index is out of range because list index starts with zero. For example if len(a) is 2, the allowed index i...
[ 4, 2, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "for_loop", "function", "if_statement", "list", "python" ]
stackoverflow_0074161800_for_loop_function_if_statement_list_python.txt
Q: Parsing an XML Directory and appending to a single pandas dataframe I need to parse a directory of nested XML files and append the results into a single dataframe For a single file it works. Here is a sample XML file from the directory: <annotation> <folder>VOC2007</folder> <filename>361_0_00020.jpg</filen...
Parsing an XML Directory and appending to a single pandas dataframe
I need to parse a directory of nested XML files and append the results into a single dataframe For a single file it works. Here is a sample XML file from the directory: <annotation> <folder>VOC2007</folder> <filename>361_0_00020.jpg</filename> <size> <width>800</width> <height>800</height> ...
[ "I hope this help you. I just changed it to use concat instead of append and seems it works.\nimport os \nimport pandas as pd \nimport xml.etree.ElementTree as et\ndf_cols= ['filename','xmin', 'ymin', 'xmax', 'ymax']\ndf= pd.DataFrame([], columns=df_cols)\npath= 'C:/Users/rober/CursoPython/'\nfor filename in os.lis...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074162735_pandas_python.txt
Q: Python too slow to find text in string in for loop I want to improve the loop performance where it counts word occurrences in text, but it runs around 5 minutes for 5 records now DataFrame No Text 1 I love you forever...*500 other words 2 No , i know that you know xxx *100 words My wor...
Python too slow to find text in string in for loop
I want to improve the loop performance where it counts word occurrences in text, but it runs around 5 minutes for 5 records now DataFrame No Text 1 I love you forever...*500 other words 2 No , i know that you know xxx *100 words My word list wordlist =['i','love','David','Mary',......] My ...
[ "You can do this by making a Counter from the words in each Text value, then converting that into columns (using pd.Series), summing the columns that don't exist in wordlist into other_words and then dropping those columns:\nimport re\nimport pandas as pd\nfrom collections import Counter\n\nwordlist = list(map(str....
[ 2, 0 ]
[]
[]
[ "for_loop", "nlp", "performance", "python", "python_3.x" ]
stackoverflow_0074161769_for_loop_nlp_performance_python_python_3.x.txt
Q: Python Dict Comprehension retrieve value from 1 dataframe column if match another column value I have a dataframe and there are 2 columns ["country"] and ["city"] which basically informs of the country and their cities. I need to create a dict using dict comprehensions, to get as a key, the country and as values, ...
Python Dict Comprehension retrieve value from 1 dataframe column if match another column value
I have a dataframe and there are 2 columns ["country"] and ["city"] which basically informs of the country and their cities. I need to create a dict using dict comprehensions, to get as a key, the country and as values, a list of the city/cities (some of them only have one city, others many). I'm able to define the key...
[ "Since you are doing the groupby, You need to fetch city from the group\nDic = {k: f['city'].unique() for k,f in megacities.groupby('country')}\n\n", "Try:\nd = {i: g[\"city\"].to_list() for i, g in df.groupby(\"country\")}\nprint(d)\n\nPrints:\n{\n \"Argentina\": [\"Buenos Aires\"],\n \"Bangladesh\": [\"Dh...
[ 0, 0 ]
[]
[]
[ "conditional_statements", "dictionary", "dictionary_comprehension", "python" ]
stackoverflow_0074163014_conditional_statements_dictionary_dictionary_comprehension_python.txt
Q: WHAT IS THE PROPER WAY OF CREATING A FUNCTION WITH GROUPBY FUNCTION def find_corr (data,x,y): corr=data.groupby(by=['x','y']).size() corr=corr.reset_index().rename(columns={0:'count'}).sort_values('count', ascending=False)[:10] plot=sns.barplot(data=corr,'count',y=y,hue=x,orient= 'h') plt.title(f'Correlation betwe...
WHAT IS THE PROPER WAY OF CREATING A FUNCTION WITH GROUPBY FUNCTION
def find_corr (data,x,y): corr=data.groupby(by=['x','y']).size() corr=corr.reset_index().rename(columns={0:'count'}).sort_values('count', ascending=False)[:10] plot=sns.barplot(data=corr,'count',y=y,hue=x,orient= 'h') plt.title(f'Correlation between {y} and {x}'.title(), fontsize = 14, weight = "bold") plt.xlabel(x.tit...
[ "The error message leads me to suspect that \"x\" is not a column of data. Try data.groupby(by=[x, y]).size() if you pass the column names as x and y to your function.\n", "Since you are using a dataframe, you should pass the column names as string. Also, the x argument for the plot seems to be missing.\nThe plot...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074163175_pandas_python.txt
Q: skip hidden files and directories in pathlib glob With from pathlib import Path path = Path("/my/path") for p in path.rglob("*"): print(p) I can get all files and directories in /my/path. How can I skip hidden files and directories? From file .hidden_file dir / file .hidden_file .hidden_dir / file ...
skip hidden files and directories in pathlib glob
With from pathlib import Path path = Path("/my/path") for p in path.rglob("*"): print(p) I can get all files and directories in /my/path. How can I skip hidden files and directories? From file .hidden_file dir / file .hidden_file .hidden_dir / file .hidden_file I just want to get file dir / file ...
[ "Instead of:\npath.rglob('*')\nTry this:\npath.rglob('[!.]*') if not os.path.isdir(p)\nUnfortunately I can't test now, but hopefully it'll do.\n", "There is no builtin way to do this, and glob definitely in not suitable for it. You can build it on top of os.walk I guess: filter the files array at each step, as we...
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "pathlib", "python" ]
stackoverflow_0067175881_pathlib_python.txt
Q: django - set user permissions when user is automatically created using get_or_create Django 1.5, python 2.6 The model automatically creates a user under certain conditions: User.objects.get_or_create(username=new_user_name, is_staff=True) u = User.objects.get(username=new_user_name) u.set_password('temporary') I...
django - set user permissions when user is automatically created using get_or_create
Django 1.5, python 2.6 The model automatically creates a user under certain conditions: User.objects.get_or_create(username=new_user_name, is_staff=True) u = User.objects.get(username=new_user_name) u.set_password('temporary') In addition to setting the username, password, and is_staff status, I would like to set the...
[ "Use add and remove methods:\n from django.contrib.auth.models import Permission\n permission = Permission.objects.get(name='Can view poll')\n u.user_permissions.add(permission)\n\n", "Andrew M. Farrell's answer is correct. I only add the use of get_user_model() and a full example.\nfrom django.contrib.auth impo...
[ 76, 25, 0 ]
[]
[]
[ "django", "django_admin", "django_authentication", "python" ]
stackoverflow_0020361235_django_django_admin_django_authentication_python.txt
Q: Specified python version in dockerfile not reflecting in the container I have a python-django web app that I want to run in a docker container. I am using MySql for my database, so I need to use mysqlclient, which does not work for python 3.10 and above when installing using pip, so I am using python 3.9. The foll...
Specified python version in dockerfile not reflecting in the container
I have a python-django web app that I want to run in a docker container. I am using MySql for my database, so I need to use mysqlclient, which does not work for python 3.10 and above when installing using pip, so I am using python 3.9. The following is my dockerfile: FROM python:3.9.13 ENV PYTHONUNBUFFERED 1 WORKDIR /a...
[ "Using FROM python:3.9 instead of FROM python:3.9.13 seems to solve the issue. Still not sure why it would go and take python 3.10+. Guess there might have been some problems pulling the image and it defaulted to something.\n" ]
[ 0 ]
[]
[]
[ "docker", "docker_compose", "python" ]
stackoverflow_0074156908_docker_docker_compose_python.txt
Q: PyMuPDF: skipping bad link / annot item 0 I use PyMuPDF's insert_link to add links to a PDF. But when I do it, I sometimes get the warning skipping bad link / annot item 0. When I highlight the same rect with add_highlight_annot the area is highlighted. There is just no link. This happens to some words, but I can'...
PyMuPDF: skipping bad link / annot item 0
I use PyMuPDF's insert_link to add links to a PDF. But when I do it, I sometimes get the warning skipping bad link / annot item 0. When I highlight the same rect with add_highlight_annot the area is highlighted. There is just no link. This happens to some words, but I can't find a connection between them. What does the...
[ "This may happen if some text of the link is not UTF-8 encodedable.\nInternally in PyMuPDF's C code, PDF objects for defining the link are created from their representation as text source. The error occurs if the Python C-function PyUnicode_AsUTF8 fails.\nIn your context most probably the URI text should be the pro...
[ 1 ]
[]
[]
[ "pymupdf", "python" ]
stackoverflow_0074143972_pymupdf_python.txt
Q: Why my boolean doesnt change in function? i have a noob question. I'm trying to make a blackjack and in my "turn" function i put a variable change to False. I have no clue why it doesnt work... It says local variable is never used, but how's that possible if it is used in the while loop... import random p1 = [] p2...
Why my boolean doesnt change in function?
i have a noob question. I'm trying to make a blackjack and in my "turn" function i put a variable change to False. I have no clue why it doesnt work... It says local variable is never used, but how's that possible if it is used in the while loop... import random p1 = [] p2 = [] cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
[ "You have to set game_on variable as global:\ndef turn(x):\n global game_on\n pick_card(x)\n if calculate_score(x) == 0:\n print(\"blackjack\")\n game_on = False\n elif calculate_score(x) > 21:\n print(\"You lost\")\n game_on = False\n else:\n print(p1)\n\nAlso, fix...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074163275_python.txt
Q: How can I run this code and how can I improve this code? import sys as s import datetime class LoginPage: def __int__(self, username, password): self.username = username self.password = password self.incorrectPass = 0 def loginProgrma(self): while True: while...
How can I run this code and how can I improve this code?
import sys as s import datetime class LoginPage: def __int__(self, username, password): self.username = username self.password = password self.incorrectPass = 0 def loginProgrma(self): while True: while True: nameInput = input("Enter your username...
[ "You have typed __int__ instead of __init__. (You forgot an extra i) If you fixed that, you can after you called the class LoginPage call the loginProgrma function.\n", "First of all remove the typo in __init__ from __int__ to __init__\nAnyway there seem to be some typos in your code but to run the method you sho...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074163327_python.txt
Q: Python. returning the file name from the folder help pls, I need a program that will add the names of files from a certain folder to the array, I tried to find something similar on the Internet, but I didn't find it A: You can create a list of all files in a folder with os.listdir() Try this: import os def add_f...
Python. returning the file name from the folder
help pls, I need a program that will add the names of files from a certain folder to the array, I tried to find something similar on the Internet, but I didn't find it
[ "You can create a list of all files in a folder with os.listdir()\nTry this:\nimport os\ndef add_filenames_to_array(folder):\n filenames = []\n for filename in os.listdir(folder):\n filenames.append(filename)\n return filenames\n\nOr with list comprehension\ndef add_filenames_to_array(folder):\n ...
[ 0 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0074163418_filenames_python.txt