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 to represent graph's node/vertex as alphabetic or name value instead of numeric This is the code I wrote for Graph structure, which works in the value passed in numeric class Graph: def __init__(self, nVertices): self.nVertices = nVertices self.adjList = [[]for i in range(nVertices)] ...
How to represent graph's node/vertex as alphabetic or name value instead of numeric
This is the code I wrote for Graph structure, which works in the value passed in numeric class Graph: def __init__(self, nVertices): self.nVertices = nVertices self.adjList = [[]for i in range(nVertices)] def addEdge(self, v1, v2): self.adjList[v1].append(v2) self.adjLis...
[ "You could define your adjList attribute as a dictionary of lists:\n self.adjList = defaultdict(list)\n\nAlso the visited structure needs to change. I would suggest a set instead of a list of booleans, and it should start as an empty set.\nThe driver code surely needs to change. Passing 0 as first argument to df...
[ 2 ]
[]
[]
[ "algorithm", "data_structures", "graph_theory", "python" ]
stackoverflow_0074335151_algorithm_data_structures_graph_theory_python.txt
Q: awaiting a Future versus Event.wait() In the UDP client example in the Python docs, they use loop.create_future() to create a new Future. The main program awaits this future until result is set on it, at which point the program cleans up resources and terminates. However, I have always used an asyncio.Event for th...
awaiting a Future versus Event.wait()
In the UDP client example in the Python docs, they use loop.create_future() to create a new Future. The main program awaits this future until result is set on it, at which point the program cleans up resources and terminates. However, I have always used an asyncio.Event for this kind of thing. Is there any difference b...
[ "They can be both used for synchronization, but a Future has a proper result and can raise exceptions.\nSo, Event provides less features, but when the use case is only synchronization, it may express the intent better and be less error-prone. In fact, an Event is implemented as a list of futures.\n" ]
[ 2 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074322978_python_python_asyncio.txt
Q: AttributeError: module 'streamlit' has no attribute '_is_running_with_streamlit'. This attribute used to work properly but now it doesn't work anymore from streamlit.web import cli as stcli import sys if __name__ == '__main__': if st._is_running_with_streamlit: main() else: sys.argv = ["st...
AttributeError: module 'streamlit' has no attribute '_is_running_with_streamlit'. This attribute used to work properly but now it doesn't work anymore
from streamlit.web import cli as stcli import sys if __name__ == '__main__': if st._is_running_with_streamlit: main() else: sys.argv = ["streamlit", "run", sys.argv[0]] sys.exit(stcli.main()) Above codes used to work without having any problem but now it doesn't work anymore when I upg...
[ "I got the solution from the Streamlit community where I was actually using an internal API that Streamlit doesn't necessarily support. They wouldn’t recommend using this.\nTo replace that code so that it works, Streamlit suggests that I can use this:\nfrom streamlit import runtime\nruntime.exists()\n\nSo my code s...
[ 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074251573_python_streamlit.txt
Q: Determine if folder or file using Dropbox Python API I am trying to use the Dropbox API v2 to get a list of all folders and all files, and view the metadata associated with each. I have been able to make it list all files and folders in my Dropbox root, and return the metadata, however I can't figure out how to de...
Determine if folder or file using Dropbox Python API
I am trying to use the Dropbox API v2 to get a list of all folders and all files, and view the metadata associated with each. I have been able to make it list all files and folders in my Dropbox root, and return the metadata, however I can't figure out how to determine if the output metadata is for a file FileMetadata ...
[ "You can use this function/line if you don't want to read through the accepted answers code:\ndef isFile(dropboxMeta):\n return isinstance(dropboxMeta,dropbox.files.FileMetadata)\n\n", "You can use isinstance to check the type of the object, which can be FileMetadata, FolderMetadata, or DeletedMetadata. There'...
[ 4, 1, 0 ]
[]
[]
[ "dropbox", "dropbox_api", "python", "python_3.x" ]
stackoverflow_0045871774_dropbox_dropbox_api_python_python_3.x.txt
Q: How to remove the already iterated rows of a csv file I have a csv file with 100 records. I want to write the first 50 records in a new csv file i.e 'newFile.csv' in the first iteration. In the second iteration, I want to write the next 50 records in the 'newFile.csv' file after reading the next 50 records from th...
How to remove the already iterated rows of a csv file
I have a csv file with 100 records. I want to write the first 50 records in a new csv file i.e 'newFile.csv' in the first iteration. In the second iteration, I want to write the next 50 records in the 'newFile.csv' file after reading the next 50 records from the original csv file. I am able to perform the first Iterati...
[ "import pandas as pd\n\noldData = pd.read_csv('oldFile.csv') # Has 100 rows\n\nfor newData in pd.read_csv('oldFile.csv', chunksize=50) # Has 50 rows:\n\n newCsv = newData.to_csv('newFile.csv', index=False)\n\n newData = newData.iloc[50:] # Removes those 50 rows\n\nIn this way each time you read the .csv file ...
[ 0, 0 ]
[]
[]
[ "csv", "for_loop", "pandas", "python" ]
stackoverflow_0074335237_csv_for_loop_pandas_python.txt
Q: Logical OR constraint in PulP I am new to PulP. Below is the optimization problem. Consider x11, x12, x13 be units of FG1 to be loaded on Medium Truck 1, Small Truck and Medium Truck 2 respectively. Similarly, consider x21,x22,x23 be variables to denote units of FG2 to be loaded on Medium Truck 1, Small Truck and ...
Logical OR constraint in PulP
I am new to PulP. Below is the optimization problem. Consider x11, x12, x13 be units of FG1 to be loaded on Medium Truck 1, Small Truck and Medium Truck 2 respectively. Similarly, consider x21,x22,x23 be variables to denote units of FG2 to be loaded on Medium Truck 1, Small Truck and Medium Truck 2 respectively. The ob...
[ "!pip install PulP\nfrom pulp import LpMinimize, LpProblem, LpStatus, lpSum, LpVariable\n\n!apt-get install -y -qq glpk-utils\nimport pulp as pl\nsolver = pl.GLPK_CMD()\n\nmodel = LpProblem(name=\"load_receipts\", sense=LpMinimize)\n\nx11 = LpVariable(name=\"x11\", lowBound=0, cat='Continuous')\nx12 = LpVariable(na...
[ 0, 0, 0 ]
[]
[]
[ "mathematical_optimization", "pulp", "python" ]
stackoverflow_0074319829_mathematical_optimization_pulp_python.txt
Q: Add data to CSV file I need to write/append this kind of data to a csv file {'ACW': 1431, 'ACA': 6.066, 'ACV': 237.2, 'PEAK_POW': 1.853, 'DCV_1': 192.2, 'DCA_1': 7.72, 'DCW': 1461, 'AC_EFFI': 97.91, 'LINEA_DISTR': 1033} I take it each 5 seconds from a solar inverter and record on this object in my code inverter =...
Add data to CSV file
I need to write/append this kind of data to a csv file {'ACW': 1431, 'ACA': 6.066, 'ACV': 237.2, 'PEAK_POW': 1.853, 'DCV_1': 192.2, 'DCA_1': 7.72, 'DCW': 1461, 'AC_EFFI': 97.91, 'LINEA_DISTR': 1033} I take it each 5 seconds from a solar inverter and record on this object in my code inverter = {} I have tried with thi...
[ "import time\nimport csv\n#example of data taken from Solar Inverter\n#inversor = {'ACW': 65, 'ACA': 0.379, 'ACV': 237.2, 'PEAK_POW': 2.264, \n#'DCV_1': 176.0, 'DCA_1': 0.41, 'DCW': 72, 'AC_EFFI': 90.32, \n#'LINEA_DISTR': -402}\n\nheaders = ['ACW', 'ACA', 'ACV', 'PEAK_POW',\n 'DCV_1', 'DCA_1', 'DCW', '...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074316434_python_python_3.x.txt
Q: Issue in uploading image for prediction using a MultiPart POST Request The call is currently happening via a Flutter application which makes a multi-part POST request. Flutter Code var request = http.MultipartRequest( 'POST', Uri.parse('https://techfarmtest.herokuapp.com/upload'), ); Map<String...
Issue in uploading image for prediction using a MultiPart POST Request
The call is currently happening via a Flutter application which makes a multi-part POST request. Flutter Code var request = http.MultipartRequest( 'POST', Uri.parse('https://techfarmtest.herokuapp.com/upload'), ); Map<String, String> headers = {"Content-type": "multipart/form-data"}; request.fil...
[ "So, I figured it out by myself.\nI will be attaching the code below for future references.\nFlutter Code :\nvar request = http.MultipartRequest(\n 'POST',\n Uri.parse('https://techfarmtest.herokuapp.com/upload'),\n);\nrequest.files.add(\n await http.MultipartFile.fromPath('image', img.path),\n);\nvar r...
[ 1 ]
[]
[]
[ "flask", "flask_restful", "flutter", "heroku", "python" ]
stackoverflow_0074224367_flask_flask_restful_flutter_heroku_python.txt
Q: Selenium python TypeError: 'str' object is not callable when finding element I'm getting: "TypeError: 'str' object is not callable" when I execute this code: iframe=driver.find_element(By.XPATH("//iframe[contains(@src,'https://pianomarvel.com/uploads/editSlicings/85810')]")); Why? What is the correct syntax? Than...
Selenium python TypeError: 'str' object is not callable when finding element
I'm getting: "TypeError: 'str' object is not callable" when I execute this code: iframe=driver.find_element(By.XPATH("//iframe[contains(@src,'https://pianomarvel.com/uploads/editSlicings/85810')]")); Why? What is the correct syntax? Thanks I tried iframe=driver.find_element(By.XPATH("//iframe[contains(@src,'https://pi...
[ "The proper way of doing this would be:\nxpath should be in small case\niframe=driver.find_element(By.xpath(\"//iframe[contains(@src,'https://pianomarvel.com/uploads/editSlicings/85810')]\"));\n\nOR\niframe = driver.find_element_by_xpath(\"//iframe[contains(@src,'https://pianomarvel.com/uploads/editSlicings/85810')...
[ 0, 0 ]
[]
[]
[ "python", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074335291_python_selenium_chromedriver_selenium_webdriver.txt
Q: Retrieving Powershell Proxy Config On Powershell, I am currently performing this request, copied from the network tab on developer tools $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession $session.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106...
Retrieving Powershell Proxy Config
On Powershell, I am currently performing this request, copied from the network tab on developer tools $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession $session.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36" Invoke-WebRequest ...
[ "For most commands, Powershell uses the system proxy by default (or they have a -Proxy switch to tell them where it is, but some don't and have to be told to use it.\nFrom memory, Invoke-WebRequest can be problematical as (I think) it uses the .NET web client\nTry adding this to the start of the PS script:\n[System...
[ 0 ]
[]
[]
[ "networking", "powershell", "proxy", "python" ]
stackoverflow_0074332989_networking_powershell_proxy_python.txt
Q: On the wrong foot with regular python reading of a text file, error line at the exception is wrong When reading an utf-8 text file in Python you may encounter an illegal utf character. Next you probably will try to find the line (number) containing the illegal character, but probably this will fail. This is illust...
On the wrong foot with regular python reading of a text file, error line at the exception is wrong
When reading an utf-8 text file in Python you may encounter an illegal utf character. Next you probably will try to find the line (number) containing the illegal character, but probably this will fail. This is illustrated by the code below. Step 1: Create a file containing an illegal utf-8 character (a1 hex = 161 decim...
[ "The actual cause is indeed the way Python internally processes text files.They are read in chunks, each chunk is decoded according the the specified encoding, and they if you use readline or iterate the file object, the decoded buffer is split in lines which are returned one at a time.\nYou can have an evidence of...
[ 1, 0 ]
[]
[]
[ "decode", "line_numbers", "python", "readlines", "utf_8" ]
stackoverflow_0074327407_decode_line_numbers_python_readlines_utf_8.txt
Q: Python dataframe: copy index column into a new column (error) I have a dataframe (with the first column being index column)(below). I would like to add(create) a (last) column which is a copy of the index column (desired result below). However I have the error (below). Is there a workaround? Thanks in advance impo...
Python dataframe: copy index column into a new column (error)
I have a dataframe (with the first column being index column)(below). I would like to add(create) a (last) column which is a copy of the index column (desired result below). However I have the error (below). Is there a workaround? Thanks in advance import pandas as pd df1 = pd.DataFrame({"date": ['2021-3-22', '2021-3-2...
[ "df1.index instead df1['date'] :\ndf1['date1'] = df1.index.copy()\ndf1.reset_index()\n\noutput:\n date x date1\n0 2021-3-22 nan 2021-3-22\n1 2021-3-23 1 2021-3-23\n2 2021-3-24 nan 2021-3-24\n3 2021-3-25 nan 2021-3-25\n4 2021-3-26 nan 2021-3-26\n\n", "To keep the date column adapt...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074335421_dataframe_pandas_python.txt
Q: Django serialize function returns error JSONEncoder.__init__() got an unexpected keyword argument 'fields' I'm trying to serilize my salesnetwork.agency model into a geojson file, and according to Django docs I'm using the following code: (I'm using Django 4.1.2) markers = Agency.objects.all() geojson_file = seria...
Django serialize function returns error JSONEncoder.__init__() got an unexpected keyword argument 'fields'
I'm trying to serilize my salesnetwork.agency model into a geojson file, and according to Django docs I'm using the following code: (I'm using Django 4.1.2) markers = Agency.objects.all() geojson_file = serialize("geojson", markers, geometry_field="location", ...
[ "From your error traceback it can be noticed that some code in djgeojson\\serializers.py is called instead of django/contrib/gis/... also as you've confirmed you've set the following in your setting:\nSERIALIZATION_MODULES = {\"geojson\": \"djgeojson.serializers\"}\n\nThis means when you want Django to use a forma...
[ 2 ]
[]
[]
[ "django", "django_serializer", "python" ]
stackoverflow_0074335330_django_django_serializer_python.txt
Q: BeautifulSoup Split Text from Tag I can find and print the tag: name = soup.find("h1") print(name) gives: <h1>Coriander<span>Herb / Cilantro</span></h1> But how can I return the different parts separately? i.e. Isolated as 3 separate data points? Coriander Herb Cilantro When I try: name = soup.find("h1 span") p...
BeautifulSoup Split Text from Tag
I can find and print the tag: name = soup.find("h1") print(name) gives: <h1>Coriander<span>Herb / Cilantro</span></h1> But how can I return the different parts separately? i.e. Isolated as 3 separate data points? Coriander Herb Cilantro When I try: name = soup.find("h1 span") print(name) I get: None So I'm stuck a...
[ "One solution might be using .get_text() with custom separator and then .split():\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(\n \"<h1>Coriander<span>Herb / Cilantro</span></h1>\", \"html.parser\"\n)\n\ndata = [t.strip() for t in soup.h1.get_text(separator=\"/\").split(\"/\")]\nprint(data)\n\nPrints:\...
[ 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074335437_beautifulsoup_python.txt
Q: how to change boolean value thats another file Im trying to make a thing that can detect whether or not a user wants their password stored for next time they run the program, The reason im using a boolean for this is so in the files that need to use the password they can check to see if storepass is True then get ...
how to change boolean value thats another file
Im trying to make a thing that can detect whether or not a user wants their password stored for next time they run the program, The reason im using a boolean for this is so in the files that need to use the password they can check to see if storepass is True then get the pass/user from a .env if not they can get the pa...
[ "\nThen i think booleans.storepass is like a variable but like a copy of the one in booleans? Because when i go on the booleans file again its still False.\n\nThat's correct - you can't change the values inside a .py file just by importing and then setting within another. py file. The standard way to manipulate fil...
[ 1, 0 ]
[ "You are changing the value inside the runtime, meaning you can actually change it. Meaning if you are ever trying to print out the value inside the if condition like this:\n booleans.storepass = True\n print(booleans.storepass)#This should return True\n\nBut your problem is that you are not actually changing t...
[ -1 ]
[ "python" ]
stackoverflow_0074334979_python.txt
Q: How does import work with Boost.Python from inside python files I am using Boost.Python to embed an interpreter in my C++ executable and execute some prewritten scripts. I have got it working so that I can call functions in the python file but the python code I want to use imports external files and these imports ...
How does import work with Boost.Python from inside python files
I am using Boost.Python to embed an interpreter in my C++ executable and execute some prewritten scripts. I have got it working so that I can call functions in the python file but the python code I want to use imports external files and these imports fail because 'no module named '. If I run the script directly from py...
[ "So it turns out that my problem is a simple case of the module search path not being set correctly when initialised from within C++.\nFrom the Python Documentation intro: \n\nOn most systems (in particular, on Unix and Windows, although the\n details are slightly different), Py_Initialize() calculates the module\...
[ 15, 0 ]
[]
[]
[ "boost", "boost_python", "c++", "import", "python" ]
stackoverflow_0009285384_boost_boost_python_c++_import_python.txt
Q: Django: normalize/modify a field in model serializer I have a model serializer like this: class FoooSerializers(serializers.ModelSerializer): class Meta: model = Food fields = [ 'id', 'price',] Here I have the price with trailing zeros like this: 50.000 and I want to .n...
Django: normalize/modify a field in model serializer
I have a model serializer like this: class FoooSerializers(serializers.ModelSerializer): class Meta: model = Food fields = [ 'id', 'price',] Here I have the price with trailing zeros like this: 50.000 and I want to .normalize() to remove the trailing zeros from it. Is this ...
[ "class FoooSerializers(serializers.ModelSerializer):\n class Meta:\n model = Food\n fields = ['id','price',]\ndef to_representation(self, instance):\n representation = super().to_representation(instance)\n representation['price'] = int(price)\n return representation\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "serialization" ]
stackoverflow_0074335396_django_python_serialization.txt
Q: what does the lsamp in "stats.ttest_1samp" stand for? What does "lsamp" stand for? Abbreviation or others meaningful explaination from semantics point? import scipy as sp from scipy import stats stats.ttests_lsamp() A: Calculate the T-test for the mean of ONE group of scores. So it stands for 1 sample. Here is ...
what does the lsamp in "stats.ttest_1samp" stand for?
What does "lsamp" stand for? Abbreviation or others meaningful explaination from semantics point? import scipy as sp from scipy import stats stats.ttests_lsamp()
[ "Calculate the T-test for the mean of ONE group of scores. So it stands for 1 sample. Here is the documentation.\nThere are:\n\nttest_1samp: Calculate the T-test for the mean of ONE group of scores\nttest_ind: Calculate the T-test for the means of two independent samples of scores\nttest_ind_from_stats: T-test for ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074335530_python.txt
Q: an notAdirectoryerror in python3.7 i am making a face recognition program but i am facing NotADirectoryError error whenever i run it i tried coping the full directory as well as using os.join.path and nothing worked i am using pycharm. import face_recognition import cv2 import os import numpy os.chdir('C:/Users/a/...
an notAdirectoryerror in python3.7
i am making a face recognition program but i am facing NotADirectoryError error whenever i run it i tried coping the full directory as well as using os.join.path and nothing worked i am using pycharm. import face_recognition import cv2 import os import numpy os.chdir('C:/Users/a/Desktop/ftp') KNOWN_FACE_DIR = "known...
[ "The os.listdir function requires a directory name, and something called Madj.jpg is most likely to be a JPEG file rather than a directory.\nIt looks like your assumption that everything in C:/Users/a/Desktop/ftp/known_faces is a directory containing files that you want to process may not be correct.\n" ]
[ 1 ]
[]
[]
[ "face_recognition", "python", "python_3.x" ]
stackoverflow_0074335240_face_recognition_python_python_3.x.txt
Q: Python: How do I take two different column inputs from the user and return the value of another column? Using the first row as an example, let's say the user types in Arsenal and Leicester City. How do I get the code to match the inputted teams to "home_team" and "away_team" in the table and finally return the val...
Python: How do I take two different column inputs from the user and return the value of another column?
Using the first row as an example, let's say the user types in Arsenal and Leicester City. How do I get the code to match the inputted teams to "home_team" and "away_team" in the table and finally return the value 'H' which is from the column 'result' ? I tried doing x = input("Enter Home Team: ") y = input("\nEnter A...
[ "Here is simplified and relevant version of your dataframe.\nSay your dataframe is named (df):\nimport pandas as pd\n\ndf = pd.DataFrame({'home_team':['Arsenal', 'Watford', 'Chelsea'],\n 'away_team':['Leicester City','Liverpool','Burnley'],\n 'result':['H','D','A']})\n\nThen you ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074335364_python.txt
Q: How to stop loop after user "input" 4 digits in a row Good afternoon! I wanted to ask how to make it so that if the user enters text into "input" and there are 4 numbers in a row (for example: mmm4213), then the loop ends and "print" is displayed about this eventю numbers_row = 4 while True: user_sms = input("...
How to stop loop after user "input" 4 digits in a row
Good afternoon! I wanted to ask how to make it so that if the user enters text into "input" and there are 4 numbers in a row (for example: mmm4213), then the loop ends and "print" is displayed about this eventю numbers_row = 4 while True: user_sms = input("Enter: ") if ? == ?: print("4 numbers in a row"...
[ " numbers_row = 4\n while True:\n user_sms = input(\"Enter: \")\n bools = [c.isdigit() for c in user_sms]\n c = 0\n for flag in bools:\n if flag: \n c +=1\n else: \n c = 0\n if c == numbers_row:\n print(\"4 numbers in a row\")\n break\...
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074335506_loops_python.txt
Q: How do i convert a modified list of The Alphabet into a number? i want to convert the sentence from variable (salam) into numbers. The conversion table is like a modified alphabet just like in (char2). My expected output is a 3x3 matrix, inside is the converted number from(salam) using (char2) salam = "APAKABARBRO...
How do i convert a modified list of The Alphabet into a number?
i want to convert the sentence from variable (salam) into numbers. The conversion table is like a modified alphabet just like in (char2). My expected output is a 3x3 matrix, inside is the converted number from(salam) using (char2) salam = "APAKABARBROOOOO" salam = salam.lower output = [] char2 = [' ','a','b','c','d','e...
[ "The problem is from salam.lower. It should be salam.lower().\nWithout the () you are just referencing the .lower object.\n" ]
[ 1 ]
[]
[]
[ "list", "numpy", "python" ]
stackoverflow_0074335669_list_numpy_python.txt
Q: Using a distance function on an image to compare colors of each pixel and to change their color for y in range(image.getHeight()): for x in range(image.getWidth()): def GetDistance(tuple1,tuple2): tuple1=(r,g,b) tuple2=(r2,g2,b2) import math math.sqrt(((r-r2)**2)+((g-g2)**2)+((b-b2)**2)) r...
Using a distance function on an image to compare colors of each pixel and to change their color
for y in range(image.getHeight()): for x in range(image.getWidth()): def GetDistance(tuple1,tuple2): tuple1=(r,g,b) tuple2=(r2,g2,b2) import math math.sqrt(((r-r2)**2)+((g-g2)**2)+((b-b2)**2)) return I am trying to compare to pixel colors in an image. For the colors that are the closest to red...
[ "Personally, I wouldn't approach this using for loops as they are slow, inefficient and error-prone in Python. However, I have implemented it with for loops so it matches your way of thinking and is easier to understand. If you look through some of my other answers you will find better ways of doing it.\nI note a c...
[ 1 ]
[]
[]
[ "colors", "image", "python" ]
stackoverflow_0074329229_colors_image_python.txt
Q: How to run coverage for a Python project with src-layout? My python project is structured in the so called src-layout. hyperorg ├── README.md ├── setup.cfg ├── setup.py ├── src │   └── hyperorg │   ├── content.py │   ├── exporter.py │   ├── __init__.py │   ├── __main__.py │   └── reader.py └── ...
How to run coverage for a Python project with src-layout?
My python project is structured in the so called src-layout. hyperorg ├── README.md ├── setup.cfg ├── setup.py ├── src │   └── hyperorg │   ├── content.py │   ├── exporter.py │   ├── __init__.py │   ├── __main__.py │   └── reader.py └── tests ├── helper.py ├── __init__.py ├── test_conten...
[ "One of the ways of doing that is entering the src folder by cd src and then running coverage from there as following:\ncoverage run -m unittest discover -s ../tests\n\nYou can also leverage rcfile (default .coveragerc) to specify configurations and change HTML report path to be created outside the src folder as we...
[ 2 ]
[]
[]
[ "coverage.py", "python" ]
stackoverflow_0072054945_coverage.py_python.txt
Q: Google API Client for Python. Batch requests: how to access to a specific request in the callback According to official doc, you can make batch request through Google API Client Libraries for Python. Here, there is an example from apiclient.http import BatchHttpRequest def list_animals(request_id, response, excep...
Google API Client for Python. Batch requests: how to access to a specific request in the callback
According to official doc, you can make batch request through Google API Client Libraries for Python. Here, there is an example from apiclient.http import BatchHttpRequest def list_animals(request_id, response, exception): if exception is not None: # Do something with the exception pass else: # Do some...
[ "I ran into this same issue, as I needed the original request for using compute.instances().aggregatedList_next() function.\nI ended up passing a unique request_id to batch.add() and created a dictionary to keep track of the original requests that were made. Then within the callback, I referenced that dictionary an...
[ 3, 1 ]
[]
[]
[ "google_api", "google_api_python_client", "python" ]
stackoverflow_0041454504_google_api_google_api_python_client_python.txt
Q: sys.argv not appearing when passing argument with # System: Linux - Ubuntu Python: python3 PASSING ARGUMENT WITH # NOT WORKING Hey so i have a bug when im passing arguments using the sys package with a # in one of the arguments. it just doesnt appear in the print i do. code: import sys print(sys.argv) IMAGE OF CO...
sys.argv not appearing when passing argument with #
System: Linux - Ubuntu Python: python3 PASSING ARGUMENT WITH # NOT WORKING Hey so i have a bug when im passing arguments using the sys package with a # in one of the arguments. it just doesnt appear in the print i do. code: import sys print(sys.argv) IMAGE OF CONSOLE RESPONSE WHEN RUNNING FILE: https://imgur.com/a/y4l...
[ "it’s not a bug, just put it in quotes\n#is a reserved character\nso python3 test.py hello \"#0000\"on the console\nthanks kelyan#4642\n" ]
[ 0 ]
[]
[]
[ "python", "sys" ]
stackoverflow_0074334656_python_sys.txt
Q: 404 error not found when debug = False in django multilanguages web app Hello I am making a multilanguages django web app, When DEBUG = True => the multilanguages works fine means when i click on localhost:8000 it redirect me to localhost:8000/en or the last language I am puting anyway. When DEBUG = FALSE => I ent...
404 error not found when debug = False in django multilanguages web app
Hello I am making a multilanguages django web app, When DEBUG = True => the multilanguages works fine means when i click on localhost:8000 it redirect me to localhost:8000/en or the last language I am puting anyway. When DEBUG = FALSE => I enter to localhost:8000 it gives me an error of 404 not found, here is my settin...
[ "I don't know if this can help you but I had configured my translations this way on one of my Django projects:\n# Internationalization\n# https://docs.djangoproject.com/en/3.2/topics/i18n/\n\nLANGUAGE_CODE = 'fr'\nTIME_ZONE = 'Europe/Paris'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# This is defined here ...
[ 0 ]
[]
[]
[ "django", "gettext", "python" ]
stackoverflow_0074335420_django_gettext_python.txt
Q: Python ThreadPoolExecutor: How to evaluate what caused a timeout Given the following simple method that causes a TimeoutError at some point. How can I determine what were the conditions (e.g. arguments or something else) that caused the timeout? In [82]: def f(i): ...: print(i) ...: if i == 2: time...
Python ThreadPoolExecutor: How to evaluate what caused a timeout
Given the following simple method that causes a TimeoutError at some point. How can I determine what were the conditions (e.g. arguments or something else) that caused the timeout? In [82]: def f(i): ...: print(i) ...: if i == 2: time.sleep(1) ...: return "done" ...: In [83]: with ThreadPoo...
[ "The exception itself does not carry any relevant information. However, as the documentation says:\n\nThe returned iterator raises a concurrent.futures.TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to Executor.map()\n\nSo the exception is always ass...
[ 1 ]
[]
[]
[ "concurrency", "exception", "python", "python_multithreading" ]
stackoverflow_0074334868_concurrency_exception_python_python_multithreading.txt
Q: How to assign keys of dictionary with coordinates to keys of another dictionary with coordinates uniquely based on distance? I have 2 dictionaries: AllDepotsDict = {'01': [30, 48], '02': [49, 17]} where keys must be strings, and the values are x and y coordinates respectively, and AllClusterCentersDict = {0: [29....
How to assign keys of dictionary with coordinates to keys of another dictionary with coordinates uniquely based on distance?
I have 2 dictionaries: AllDepotsDict = {'01': [30, 48], '02': [49, 17]} where keys must be strings, and the values are x and y coordinates respectively, and AllClusterCentersDict = {0: [29.67, 23.33], 1: [38.5, 87.0]} where keys are centroids' ids and the values are the x and y coordinates respectively. I want to ass...
[ "Maybe you just have to delete the centroids 0 once you have assigned point '01' to center 0. And then, search the closest center for point '02'.\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "variable_assignment" ]
stackoverflow_0074335762_dictionary_list_python_variable_assignment.txt
Q: How can I concatenate two different model query and order by a field that both models has How can I concatenate two different model query and order by a field that both models has like progress fields. For example models.py class Gig(models.Model): author= models.ForeignKey(User) title = models.CharFields(...
How can I concatenate two different model query and order by a field that both models has
How can I concatenate two different model query and order by a field that both models has like progress fields. For example models.py class Gig(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() class Project(models.Model): author= models.Foreig...
[ "You can let Python do the sorting for you, like:\nfrom operator import attrgetter\n\n\ndef fetch_all_item(request):\n gig = Gig.objects.filter(author=request.user)\n project = Project.objects.filter(author=request.user)\n total_item = sorted([*gig, *project], attrgetter('progress'))\n return render(req...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074335653_django_django_models_python.txt
Q: Python missing or unusable while compiling gdb under Cent OS 5 I checked this question and it is not applicable. Python missing or unusable error while cross compiling GDB I'm trying to build gdb 7.5 with python support on Cent OS 5. configure --with-expat --with-python Does not log any errors and the Python dev...
Python missing or unusable while compiling gdb under Cent OS 5
I checked this question and it is not applicable. Python missing or unusable error while cross compiling GDB I'm trying to build gdb 7.5 with python support on Cent OS 5. configure --with-expat --with-python Does not log any errors and the Python devel files are installed. I set LDFLAGS="L/usr/local/expat-2.1 -L/opt/...
[ "The next line AFTER the configure: error: line should be something like:\nmake[1]: [configure-gdb]: ....\n\ntelling you that this error comes from running configure in the gdb subdirectory. So you should look in the config.log file there. This should show you something that configure tried to do that failed -- p...
[ 3, 1, 0 ]
[]
[]
[ "gdb", "makefile", "python", "python_2.7" ]
stackoverflow_0015797424_gdb_makefile_python_python_2.7.txt
Q: How to replace repeated items in the row of my array with zeros I am trying to write a code that replaces all rows of three or more continuous values for zeros. so the three threes on the first row should become zero. I wrote this code which in my mind should work but when I execute my code it seems to me that I a...
How to replace repeated items in the row of my array with zeros
I am trying to write a code that replaces all rows of three or more continuous values for zeros. so the three threes on the first row should become zero. I wrote this code which in my mind should work but when I execute my code it seems to me that I am stuck in an infinite loop. import numpy as np A = np.array([[1, 2,...
[ "Don't use if-else. It gets messy easily. Here's an approach without if-else.\n\nIterate over each row, and find unique element and their counts in it.\nIf an element occurs three or more times, filter that into an array.\nStart iteration for each filtered element (val)\nFind the indices of val in the given row\nDo...
[ 3, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074333770_numpy_python.txt
Q: How to Parse a Text Which is Outside of Tag I'm parsing a text, which every word is made into a link. Problem is that punctuation marks aren't the content of that tags <a>, they just lie outside the tags, so I don't know what to do to get punctuation marks too. <table> <tbody> <tr> <td> <a href...
How to Parse a Text Which is Outside of Tag
I'm parsing a text, which every word is made into a link. Problem is that punctuation marks aren't the content of that tags <a>, they just lie outside the tags, so I don't know what to do to get punctuation marks too. <table> <tbody> <tr> <td> <a href="#">Lorem</a> ", " <a href="#">I...
[ "The text content between a tag elements belongs to the parent td element itself.\nYou can directly grab text from td elements, as following:\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome(executable_path=\"...\")\ndriver.get(url=...)\nsoup = BeautifulSoup(driver.page_so...
[ 0 ]
[]
[]
[ "beautifulsoup", "parsing", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074335964_beautifulsoup_parsing_python_selenium_selenium_webdriver.txt
Q: Python Quantlib ->TypeError: Wrong number or type of arguments for overloaded function 'new_Thirty360' I am trying to run the code below, but for some reason on 1 pc it runs normally, on the 2nd one it fails with the below error message; what is the reason that on 1 pc it runs normally and on the 2nd one it fails?...
Python Quantlib ->TypeError: Wrong number or type of arguments for overloaded function 'new_Thirty360'
I am trying to run the code below, but for some reason on 1 pc it runs normally, on the 2nd one it fails with the below error message; what is the reason that on 1 pc it runs normally and on the 2nd one it fails? the code source :http://gouthamanbalaraman.com/blog/quantlib-bond-modeling.html !pip install QuantLib impor...
[ "This is expected in version 1.28, as per release notes (see https://github.com/lballabio/QuantLib-SWIG/releases/tag/QuantLib-SWIG-v1.28). The default constructors are no longer available in the underlying C++ library, that deprecated them back in version 1.23.\nThe rationale is that there are several different 30/...
[ 1 ]
[]
[]
[ "python", "quantlib" ]
stackoverflow_0074329593_python_quantlib.txt
Q: How can "NameError: free variable 'var' referenced before assignment in enclosing scope" occur in real code? While I was hanging out in the Python chatroom, someone dropped in and reported the following exception: NameError: free variable 'var' referenced before assignment in enclosing scope I'd never seen that e...
How can "NameError: free variable 'var' referenced before assignment in enclosing scope" occur in real code?
While I was hanging out in the Python chatroom, someone dropped in and reported the following exception: NameError: free variable 'var' referenced before assignment in enclosing scope I'd never seen that error message before, and the user provided only a small code fragment that couldn't have caused the error by itsel...
[ "Think of a more complex function where n is bound depending on some condition, or not. You don't have to del the name in question, it also happens if the compiler sees an assignment, so the name is local, but the code path is not taken and the name gets never assigned anything. Another stupid example:\ndef f():\...
[ 5, 0 ]
[]
[]
[ "closures", "exception", "free_variable", "python", "scope" ]
stackoverflow_0024707379_closures_exception_free_variable_python_scope.txt
Q: Converting Hugging Face Transformer Text Embeddings Back to Text Is there a method for converting Hugging Face Transformer embeddings back to text? Suppose that I have text embeddings created using Hugging Face's ClipTextModel using the following method: import torch from transformers import CLIPTokenizer, CLIPTex...
Converting Hugging Face Transformer Text Embeddings Back to Text
Is there a method for converting Hugging Face Transformer embeddings back to text? Suppose that I have text embeddings created using Hugging Face's ClipTextModel using the following method: import torch from transformers import CLIPTokenizer, CLIPTextModel class_list = [ "i love going home and playing with my wife...
[ "Did you try this?\nhttps://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizer.decode\nhttps://huggingface.co/docs/transformers/v4.24.0/en/model_doc/clip#transformers.CLIPProcessor.batch_decode\ntokenizer.decode(embeddings)\n# OR\ntokenizer.batch_decode(embeddings)\n\n" ]
[ 0 ]
[]
[]
[ "huggingface_transformers", "pipeline", "python", "tokenize" ]
stackoverflow_0074335577_huggingface_transformers_pipeline_python_tokenize.txt
Q: An Unexpected value changed in JavaScript while solving Maximum Subarray with Divide & Conquer Approach I am trying to solve LeetCode problem 53. Maximum Subarray: Given an integer array nums, find the subarray which has the largest sum and return its sum. Here is my failing attempt: /** * @param {number[]} nu...
An Unexpected value changed in JavaScript while solving Maximum Subarray with Divide & Conquer Approach
I am trying to solve LeetCode problem 53. Maximum Subarray: Given an integer array nums, find the subarray which has the largest sum and return its sum. Here is my failing attempt: /** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { function mergeSort(all, left, right) { ...
[ "This happens because this doesn't declare all three variables:\n let leftSum = rightSum = currentSum = 0;\n\nThis implicitly defines the second and third variables as globals.\nIt should be:\n let leftSum = 0, rightSum = 0, currentSum = 0;\n\nThis difference matters when the expression leftSum + all[...
[ 2 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0074335978_javascript_python.txt
Q: bash VsCode and "autosave" Morning guys, I am a beginner programmer who was using PyCharm and recently moved to VsCode. Some days ago I started running scripts from Bash, but there is something that I do not understand why is not working properly. Imagine I have a script called script.py and go to bash terminal an...
bash VsCode and "autosave"
Morning guys, I am a beginner programmer who was using PyCharm and recently moved to VsCode. Some days ago I started running scripts from Bash, but there is something that I do not understand why is not working properly. Imagine I have a script called script.py and go to bash terminal and code: $ python script.py Ok, i...
[ "\nI do not understand why is not working properly.\n\nIt is working properly, just differently from what you're used to. You have to save the file before you can use it. I'm in the habit of pressing the key combination for Save All before I switch to the terminal window.\nYou can turn on auto-save by following the...
[ 1 ]
[]
[]
[ "bash", "python", "shell", "visual_studio_code" ]
stackoverflow_0074336081_bash_python_shell_visual_studio_code.txt
Q: Easier way to do nested for loops? So in a lot of my coding problems, I end up doing something along the lines of: for i in range(10): for j in range(10): for k in range(10): print(i, j, k) I was just wondering if there was a simpler way to iterate through multiple ranges of numbers? I wan...
Easier way to do nested for loops?
So in a lot of my coding problems, I end up doing something along the lines of: for i in range(10): for j in range(10): for k in range(10): print(i, j, k) I was just wondering if there was a simpler way to iterate through multiple ranges of numbers? I want to have it so I can give an argument o...
[ "You can use itertools.product to do this, it will effectively write the nested loops for you, but it's not more efficient as far as I know, it's mostly just more convenient:\nfrom itertools import product\nfor i, j, k in product(range(10), range(10), range(10)):\n print(i, j, k)\n\nEDIT: As @interjay pointed ou...
[ 3, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074335990_for_loop_python.txt
Q: how do I identify sequence equation Python Am I able to identify sequence, but not formula I have the whole code def analyse_sequence_type(y:list[int]): if len(y) >= 5: res = {"linear":[],"quadratic":[],"exponential":[],"cubic":[]} for i in reversed(range(len(y))): if i-2>=0 and (y...
how do I identify sequence equation Python
Am I able to identify sequence, but not formula I have the whole code def analyse_sequence_type(y:list[int]): if len(y) >= 5: res = {"linear":[],"quadratic":[],"exponential":[],"cubic":[]} for i in reversed(range(len(y))): if i-2>=0 and (y[i] + y[i-2] == 2*y[i-1]): res["linear"].append(...
[ "So, firstly we will need to create two functions for linear and quadratic (formulae attached below).\ndef linear(y):\n \"\"\"\n Returns equation in format (str)\n y = mx + c\n \"\"\"\n d = y[1]-y[0] # get difference\n c = f\"{y[0]-d:+}\" # get slope\n if d == 0: c = y[0] - d # if no difference...
[ 1 ]
[]
[]
[ "math", "python", "sequence" ]
stackoverflow_0074336083_math_python_sequence.txt
Q: Python lazy attributes that don't eval on hasattr() Is it possible to make a decorator that makes attributes lazy that do not eval when you try to access it with hasattr()? I worked out how to make it lazy, but hasattr() makes it evaluate prematurely. E.g., class lazyattribute: # Magic. class A: @lazyattr...
Python lazy attributes that don't eval on hasattr()
Is it possible to make a decorator that makes attributes lazy that do not eval when you try to access it with hasattr()? I worked out how to make it lazy, but hasattr() makes it evaluate prematurely. E.g., class lazyattribute: # Magic. class A: @lazyattribute def bar(self): print("Computing") r...
[ "It may be difficult to do. From the hasattr documentation:\n\nhasattr(object, name)\nThe arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exceptio...
[ 4, 2, 0, 0, 0 ]
[ "well the fix is a little hackish but it consists of the following\n\nrename hasattr (say as _hasattr)\nrebind hasattr as the following:\n\n\n def hasattr(obj, name):\n try:\n return obj._hasattr(name) or _hasattr(obj, name)\n except:\n return _hasattr(obj, name)\n\n\nimplement class method _h...
[ -2 ]
[ "decorator", "lazy_evaluation", "python" ]
stackoverflow_0001286548_decorator_lazy_evaluation_python.txt
Q: check if space is before and after a string, to remove the string I am analyzin lycris and want to remove such words like "la la la", "na na na", etc. I want to do that with a list of words and then with the re.sub function. But this also removes eh "na" from words, which starts with na. How can I just remove the ...
check if space is before and after a string, to remove the string
I am analyzin lycris and want to remove such words like "la la la", "na na na", etc. I want to do that with a list of words and then with the re.sub function. But this also removes eh "na" from words, which starts with na. How can I just remove the strings, which has "na na na na na na na" and "ah-ah ah-ah-ah ah-ah ah-...
[ "A simply try to use a for loop:\nlyrics = \"say my name say my name drei zwei eins null baby make it rain baby ruf honigtopf tropft bleibe ganze nacht lang online yeah screenshots kopf na na na na na na na baby ruf honigtopf tropft bleibe ganze nacht lang online yeah screenshots kopf na na na na na na na ah-ah ah-...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074336143_python.txt
Q: How to scale down a list of integers I have a list, that can be of various lengths (less than 100 or more than 1.800.000) and I need to display all those values on a graph (a waveform) of 800 points on which I can draw. I have tried taking a value for every step, where a step is the list length / 800. And it is th...
How to scale down a list of integers
I have a list, that can be of various lengths (less than 100 or more than 1.800.000) and I need to display all those values on a graph (a waveform) of 800 points on which I can draw. I have tried taking a value for every step, where a step is the list length / 800. And it is the closest I can get to. I have tried takin...
[ "First of all this is more resampling than scaling. As mentioned in the comments you have 2 cases:\n\nupscaling/sampling n<800\nthis is relatively simple you just interpolate the missing values. I would go for piecewise cubic interpolation however you did not show any sample input so other methods might look better...
[ 0, 0 ]
[]
[]
[ "algorithm", "javascript", "python" ]
stackoverflow_0074323563_algorithm_javascript_python.txt
Q: Check if folder exists in the S3 bucket and create a folder if not I am trying to write a code wherein in the S3 bucket I want to check if the folder exists and if not, I want to create the folder. Following is my code. def checkiffolderexists(bucket:str, path:str) -> bool: s3 = boto3.Session(profile_name='sa...
Check if folder exists in the S3 bucket and create a folder if not
I am trying to write a code wherein in the S3 bucket I want to check if the folder exists and if not, I want to create the folder. Following is my code. def checkiffolderexists(bucket:str, path:str) -> bool: s3 = boto3.Session(profile_name='saml').client('s3') if not path.endswith('/'): path = path + '...
[ "Keys that match the Delimiter will not show up in the Contents.\nFrom the documentation:\n\nCauses keys that contain the same string between the prefix and the first occurrence of the delimiter to be rolled up into a single result element in the CommonPrefixes collection. These rolled-up keys are not returned else...
[ 1 ]
[]
[]
[ "amazon_web_services", "boto3", "python" ]
stackoverflow_0074336003_amazon_web_services_boto3_python.txt
Q: GRPC_TOOLS.PROTOC generates broken pb2 python file I am trying to build an application using gRPC in Python. I have the following directory layout: service/ ├─ auth/ │ ├─ auth_pb2_grpc.py │ ├─ auth_pb2.py │ ├─ auth.py │ ├─ client.py ├─ flask/ ├─ todo/ ├─ app.py ├─ auth.proto/ ├─ generate.sh/ ├─ requ...
GRPC_TOOLS.PROTOC generates broken pb2 python file
I am trying to build an application using gRPC in Python. I have the following directory layout: service/ ├─ auth/ │ ├─ auth_pb2_grpc.py │ ├─ auth_pb2.py │ ├─ auth.py │ ├─ client.py ├─ flask/ ├─ todo/ ├─ app.py ├─ auth.proto/ ├─ generate.sh/ ├─ requirements.txt I set up the code for proto file in the fo...
[ "I think you're encountering this issue with Python code-generation.\nYou don't include the proto file but I suspect (?) you're not generating the services/messages into a package {foo};.\nIn this case, I recommend that you put the generated sources into the root directory (not ./auth). import'ing the file should t...
[ 0, 0, 0 ]
[]
[]
[ "grpc", "grpc_python", "protocol_buffers", "python" ]
stackoverflow_0073939276_grpc_grpc_python_protocol_buffers_python.txt
Q: Append is overwriting existing data in list I have a python program which is supposed to append list to a global variable, but instead of appending it is overwriting the list. This a demo function I made which works in the same way: var_gobal = [] def parse(list_parse,stack): for element in list_parse: ...
Append is overwriting existing data in list
I have a python program which is supposed to append list to a global variable, but instead of appending it is overwriting the list. This a demo function I made which works in the same way: var_gobal = [] def parse(list_parse,stack): for element in list_parse: stack.append(element["a"]) print(stack)...
[ "You have to copy stack to the var_global instead of appending a reference.\nvar_gobal.append(stack.copy())\n\n", "You can use slice stack = stack[:] + [element[\"a\"]] instead of append method of list:\nvar_gobal = []\n\ndef parse(list_parse,stack):\n global var_gobal\n\n for element in list_parse:\n ...
[ 10, 6, 2, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0042955147_python_python_2.7.txt
Q: Swapping in dataframe columns between odd and even indices I have a dataframe named 'original' that follows the pattern below: game team 0 1 A 1 1 B 2 2 C 3 2 D ... What I want to do is, to create a new column where for each game the team...
Swapping in dataframe columns between odd and even indices
I have a dataframe named 'original' that follows the pattern below: game team 0 1 A 1 1 B 2 2 C 3 2 D ... What I want to do is, to create a new column where for each game the teams are swapped, that is A for B, B for A, C for D, D for C, etc. ...
[ "A possible solution, based on the idea of reversing order of team inside each group (g[::-1]):\ndf['team'] = df.groupby('game')['team'].apply(\n lambda g: g[::-1]).reset_index(drop=True)\n\nOutput:\n game team\n0 1 B\n1 1 A\n2 2 D\n3 2 C\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074332528_pandas_python.txt
Q: Calculate an Qobjevo operator of qutip I define a time-dependent operator in the form of an Qobjevo and pass it to sesolve() to solve for Schrodinger's equation. Below is an MWE. from qutip import * import numpy as np tlist = np.linspace(0, np.pi / 2) H = [ sigmaz(), [sigmax(), 'cos(t)'] ] psi0 = basis(2,...
Calculate an Qobjevo operator of qutip
I define a time-dependent operator in the form of an Qobjevo and pass it to sesolve() to solve for Schrodinger's equation. Below is an MWE. from qutip import * import numpy as np tlist = np.linspace(0, np.pi / 2) H = [ sigmaz(), [sigmax(), 'cos(t)'] ] psi0 = basis(2, 1) result = sesolve(H, psi0, tlist) Now I ...
[ "You could simply define a function returning the Hamiltonian at each time step:\ndef h(t):\n return sigmaz() + np.cos(t) * sigmax()\n\n" ]
[ 0 ]
[]
[]
[ "python", "quantum_computing", "qutip" ]
stackoverflow_0073272446_python_quantum_computing_qutip.txt
Q: docker python package 4.3.1 not working with Docker Desktop 4.12.0 on Windows 10 The error I was getting on executing container.exec_run() method, when upgraded to Docker Desktop 4.12.0: out = self.container.exec_run(command, user=user, demux=demux, environment=environment, workdir=workdir) File "C:\test-proj\bui...
docker python package 4.3.1 not working with Docker Desktop 4.12.0 on Windows 10
The error I was getting on executing container.exec_run() method, when upgraded to Docker Desktop 4.12.0: out = self.container.exec_run(command, user=user, demux=demux, environment=environment, workdir=workdir) File "C:\test-proj\build_en\lib\site-packages\docker\models\containers.py", line 198, in exec_run exec_outpu...
[ "Figured out the problem - it seems is due to the latest docker desktop installed. If I downgrade from 4.12.0 to 4.11.1, error no more appears.\nFor downgrading, I've uninstalled from control panel and installed the 4.11.1 version downloading from https://docs.docker.com/desktop/release-notes/#docker-desktop-4111\n...
[ 5, 1 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0073610213_docker_python.txt
Q: Registering classes to factory with classes in different files I have a factory as shown in the following code: class ClassFactory: registry = {} @classmethod def register(cls, name): def inner_wrapper(wrapped_class): if name in cls.registry: print(f'Class {name} al...
Registering classes to factory with classes in different files
I have a factory as shown in the following code: class ClassFactory: registry = {} @classmethod def register(cls, name): def inner_wrapper(wrapped_class): if name in cls.registry: print(f'Class {name} already exists. Will replace it') cls.registry[name] = wra...
[ "\nHow can I ensure that the class is registered when placed in a file different from the factory, without making changes to the factory file whenever I want to add a new class?\n\nI'm playing around with a similar problem, and I've found a possible solution. It seems too much of a 'hack' though, so set your critic...
[ 1 ]
[]
[]
[ "factory_pattern", "python" ]
stackoverflow_0070854464_factory_pattern_python.txt
Q: Plot multiple lines in one chart using function I am working on a project and I need to plot multiple lines in one chart using function, I tried several times but I still don't know what is missing. I did it without a function and it was successful but using the function is mandatory. A: What you see is an ar...
Plot multiple lines in one chart using function
I am working on a project and I need to plot multiple lines in one chart using function, I tried several times but I still don't know what is missing. I did it without a function and it was successful but using the function is mandatory.
[ "What you see is an artifact of using Matplotlib's \"inline\" backend in a notebook, the same code tested in a command line interpreter works as you intended, three lines and a single legend in a single Axes.\nTo remedy the problem is, fortunately, very easy: just dedent plt.show, so that it's executed once, when a...
[ 2 ]
[]
[]
[ "function", "jupyter_notebook", "matplotlib", "python" ]
stackoverflow_0074336118_function_jupyter_notebook_matplotlib_python.txt
Q: FlappyBird on Pygame. How can I change speed of pipe with buttons? # Import module import random import sys import pygame from pygame.locals import * # All the Game Variables window_width = 600 window_height = 499 # set height and width of window window = pygame.display.set_mode((window_width, window_height)) el...
FlappyBird on Pygame. How can I change speed of pipe with buttons?
# Import module import random import sys import pygame from pygame.locals import * # All the Game Variables window_width = 600 window_height = 499 # set height and width of window window = pygame.display.set_mode((window_width, window_height)) elevation = window_height * 0.8 game_images = {} framepersecond = 32 pipei...
[ "You remove the pipes when the x coordinate is in a certain range on the left side of the screen:\n\nif 0 < up_pipes[0]['x'] < 5:\n\n\nWhen the velocity increases, the x coordinate of the pipes may never be in this range. It is absolutely not necessary to test for an range. Simply remove the pipes when they are off...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074336226_pygame_python.txt
Q: Remove duplicate mutable objects from a list When I have a list of immutable objects, lst and want to get rid of duplicates, I can just use set(lst): lst = [0,4,2,6,3,6,4,9,2,2] # integers are immutable in python print(set(lst)) # {0,2,3,4,6,9} However suppose I have a list of mutable objects, lst and want to get...
Remove duplicate mutable objects from a list
When I have a list of immutable objects, lst and want to get rid of duplicates, I can just use set(lst): lst = [0,4,2,6,3,6,4,9,2,2] # integers are immutable in python print(set(lst)) # {0,2,3,4,6,9} However suppose I have a list of mutable objects, lst and want to get rid of duplicates. set(lst) won't work because mu...
[ "Working with object ids is dangerous.\nIt doesn't work anymore if you have two dicts with the same content.\nYou can use the json module to serialize the dict as strings.\nimport json\n\ndef dedup(lst):\n myset = {json.dumps(x) for x in lst} # serialize to a set\n return [json.loads(x) for x in myset] # de...
[ 3, 1 ]
[ "This method use 2 lists: a list of ids and a list of elements.\nd0 = {0:'a', 1:'b', 9:'j'}\nd1 = {'jan':1, 'jul':7, 'dec':12}\nd2 = {'hello':'hola', 'goodbye':'adios', 'happy':'feliz', 'sad':'triste'}\nlst = [d0, d1, d1, d0, d2, d1, d0]\n\ndef dedup( lst):\n id_seen = []\n elems = []\n for elem in lst:\n if ...
[ -1 ]
[ "duplicates", "identity", "mutable", "python" ]
stackoverflow_0074335864_duplicates_identity_mutable_python.txt
Q: How to set font size/weight for small ticks in simple Matplotlib chart? I try to make a simple plot and set the size and weight of the font for ticks, however, even after reading matplotlib manual I am not clear what is the algorithm for that. I am using recommended OOP-approach with matplotlib 3.3. Here is the MW...
How to set font size/weight for small ticks in simple Matplotlib chart?
I try to make a simple plot and set the size and weight of the font for ticks, however, even after reading matplotlib manual I am not clear what is the algorithm for that. I am using recommended OOP-approach with matplotlib 3.3. Here is the MWE: import numpy as np from matplotlib import pyplot as plt import matplotlib....
[ "\nHow to specify font size (in pt) and font weight (i.e. bold) for labels on both major and minor ticks?\n\nIf you just want to set the label size, then tick_params is more easier to use. To set the font weight, then you can get the Text instance for each tick labels by Axis.get_majorticklabels:\nfor tick in ax.xa...
[ 1 ]
[]
[]
[ "matplotlib", "python", "visualization" ]
stackoverflow_0074332711_matplotlib_python_visualization.txt
Q: how I can extract the list of skills from job skill column? I'm trying to extract every skill from job_skills to be attribute and encoding it by zero or one , how i can do that ? note : im trying to create a data frame but its not worth to fill the data frame manually (the code is below) , im search for method to ...
how I can extract the list of skills from job skill column?
I'm trying to extract every skill from job_skills to be attribute and encoding it by zero or one , how i can do that ? note : im trying to create a data frame but its not worth to fill the data frame manually (the code is below) , im search for method to extract a list from the column . i need to apply ML algorithms on...
[ "I can't think of anything out of the pandas box that will do this straight off. If I understand you want one hot variables for each skill for each person (row). Have you got a unique identifier for each job. If not you need one. In the example below I use the row.\nskills = []\n\nrow = []\n\n\n\nfor index, row in ...
[ 1, 0, 0 ]
[]
[]
[ "data_extraction", "dataframe", "pandas", "python", "split" ]
stackoverflow_0074336130_data_extraction_dataframe_pandas_python_split.txt
Q: Python3 plot not showing in WSL I'm pretty new to Python. I have a simple script that shows a simple plot on the console. It works perfectly when I execute the script in VSCode, and the plots shows up as expected. However, when running the same script in Python in WSL, the plot doesn't show up, and I also don't g...
Python3 plot not showing in WSL
I'm pretty new to Python. I have a simple script that shows a simple plot on the console. It works perfectly when I execute the script in VSCode, and the plots shows up as expected. However, when running the same script in Python in WSL, the plot doesn't show up, and I also don't get any error messages. I'm on Windows...
[ "Since you say that your MRE works in Visual Studio Code, I'm guessing:\n\nYou are using the Windows version of Python in VSCode\nOr you are using Jupyter Notebooks there.\n\nEdit: I just noticed your comment:\n\nIt's interesting because when I run the same code in regular command prompt (not bash), the plot shows...
[ 0 ]
[]
[]
[ "matplotlib", "python", "windows_subsystem_for_linux" ]
stackoverflow_0074330611_matplotlib_python_windows_subsystem_for_linux.txt
Q: pip/python: normal site-packages is not writeable I have a new Macbook - a user installed it, and then I installed a new user (mine), granted admin privileges and deleted the old one. I am on OS Catalina. Since the installation I've been having several permission problems. VSCode can't find Jupyter Notebook, pip i...
pip/python: normal site-packages is not writeable
I have a new Macbook - a user installed it, and then I installed a new user (mine), granted admin privileges and deleted the old one. I am on OS Catalina. Since the installation I've been having several permission problems. VSCode can't find Jupyter Notebook, pip installs packages at ~/Library/Python/3.7/site-packages....
[ "As @TomdeGeus mentioned in the comments, this command works for me:\nPython 3:\npython3 -m pip install [package_name]\n\nPython 2:\npython -m pip install [package_name]\n\n", "It's best to not use the system-provided Python directly. Leave that one alone since the OS can change it in undesired ways, as you exper...
[ 42, 23, 19, 4, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0059997065_pip_python.txt
Q: Is there a way to get "text" or "fg_color" value from custom Tkinter button widget? I have a customtkinter (CTk) button widget that, when pressed, sends an encoded message to a client depending on the button's "text" value; in this case, if the button's text is "Off", it sends the message "On" and vice versa to th...
Is there a way to get "text" or "fg_color" value from custom Tkinter button widget?
I have a customtkinter (CTk) button widget that, when pressed, sends an encoded message to a client depending on the button's "text" value; in this case, if the button's text is "Off", it sends the message "On" and vice versa to the client. import tkinter as tk import traceback import customtkinter as cust import socke...
[ "Per @jasonharper's comment above, CTkButton is\n\nnot actually a Tkinter Button at all (it's made from a Frame containing a Canvas and a Label), so the normal Tkinter attribute-getting functions don't apply.\n\nInstead of using self.ecdpower[\"text\"] or self.ecdpower.cget(\"text\"): I should use\n\nself.ecdpower....
[ 0 ]
[]
[]
[ "customtkinter", "python" ]
stackoverflow_0074328779_customtkinter_python.txt
Q: Cannot install PyTorch with Python 3.11 (Windows) I recently upgraded to Python 3.11 and proceeded to get my usual libraries back. I managed to install everything back without much trouble. However I cannot get Pytorch! I installed everything through pip which worked fine until getting to Pytorch. I get this error...
Cannot install PyTorch with Python 3.11 (Windows)
I recently upgraded to Python 3.11 and proceeded to get my usual libraries back. I managed to install everything back without much trouble. However I cannot get Pytorch! I installed everything through pip which worked fine until getting to Pytorch. I get this error: "ERROR: Could not find a version that satisfies the r...
[ "I saw this issue on github: https://github.com/pytorch/pytorch/issues/86566 it looks like PyTorch doesn't support 3.11 yet.\nApparently there's a nightly build that you can try to use, I haven't tested it though.\n", "As of now, PyTorch only provides a Linux build with python 3.11\nYou can check here.\nhttps://d...
[ 1, 1 ]
[]
[]
[ "pip", "python", "python_3.11", "pytorch" ]
stackoverflow_0074219480_pip_python_python_3.11_pytorch.txt
Q: How can I dynamically create derived classes from a base class For example I have a base class as follows: class BaseClass(object): def __init__(self, classtype): self._type = classtype From this class I derive several other classes, e.g. class TestClass(BaseClass): def __init__(self): su...
How can I dynamically create derived classes from a base class
For example I have a base class as follows: class BaseClass(object): def __init__(self, classtype): self._type = classtype From this class I derive several other classes, e.g. class TestClass(BaseClass): def __init__(self): super(TestClass, self).__init__('Test') class SpecialClass(BaseClass)...
[ "This bit of code allows you to create new classes with dynamic \nnames and parameter names. \nThe parameter verification in __init__ just does not allow\nunknown parameters, if you need other verifications, like\ntype, or that they are mandatory, just add the logic\nthere:\nclass BaseClass(object):\n def __ini...
[ 172, 111, 0 ]
[ "To create a class with a dynamic attribute value, checkout the code below.\nNB. This are code snippets in python programming language\ndef create_class(attribute_data, **more_data): # define a function with required attributes\n class ClassCreated(optional extensions): # define class with optional inheritance\n...
[ -5 ]
[ "class", "inheritance", "python" ]
stackoverflow_0015247075_class_inheritance_python.txt
Q: how to fill zeros matrix with ones based on a list of values I have k = [3, 2, 0, 1] and A array filled with zeros. I want to fill A with ones such that each row sums up to a value in k k = [3, 2, 0, 1] A = np.zeros((n, n), dtype=int) for i in k: A = np.random.randint(2, size=i) the expected output: ([[1., 0.,...
how to fill zeros matrix with ones based on a list of values
I have k = [3, 2, 0, 1] and A array filled with zeros. I want to fill A with ones such that each row sums up to a value in k k = [3, 2, 0, 1] A = np.zeros((n, n), dtype=int) for i in k: A = np.random.randint(2, size=i) the expected output: ([[1., 0., 1., 1.], [0., 1., 1., 0.], [1., 0., 1., 0.], [0., ...
[ "You may use numpy.random.choice\nnumpy.random.choice\n\nGenerates a random sample from a given 1-D array\n\nimport numpy as np\n\nk = [3, 2, 0, 1]\nn = 4\nA = np.zeros((n, n), dtype=int)\n\nfor idx, row_sum in enumerate(k):\n x = np.random.choice(n, row_sum, replace=False)\n A[idx, x] = 1\n\nprint(A)\n\noutp...
[ 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074336343_numpy_python.txt
Q: Computing the cardinality of an elliptic curve group over the finite field My objective is to get the number of points on a curve over Fp with prime p being at least 160 bit and then print it out into a textBox in Winform. y^2= x^3 + Ax + B mod p After some research, I stumbled upon SageMath, which I have downloa...
Computing the cardinality of an elliptic curve group over the finite field
My objective is to get the number of points on a curve over Fp with prime p being at least 160 bit and then print it out into a textBox in Winform. y^2= x^3 + Ax + B mod p After some research, I stumbled upon SageMath, which I have downloaded version 9.3. However, now I'm stuck. I tried ProcessStartInfo on SageMath 9....
[ "Partially solved.\nI used pari/gp system instead. It turns out Sage can only be called through virtual machine on Windows unlike others on cmd. So all that's left for me now is to call its GP expression equivalence\nellinit([1,1]*Mod(1,1032419464881212325676479338986998839248491144169)).no\nin Python, before Proce...
[ 0 ]
[]
[]
[ "c#", "elliptic_curve", "python", "sage" ]
stackoverflow_0074330521_c#_elliptic_curve_python_sage.txt
Q: Writing to a CSV file using tkinter i want to save some information in a csv file. The file is supposed to contain a message from a user, the date and time and his or her name, all in one line. How would i go about making a GUI with Tkinter so a user can input that information and save it to a CSV file Any help wo...
Writing to a CSV file using tkinter
i want to save some information in a csv file. The file is supposed to contain a message from a user, the date and time and his or her name, all in one line. How would i go about making a GUI with Tkinter so a user can input that information and save it to a CSV file Any help would be appreciated. I tried looking for d...
[ "To start off with tkinter you need to create a window by doing\nwindow = tkinter.Tk()\n\nThen you need to create some text boxes to input the info with text above to say what they are\nMessage_Text = tkinter.Label(window, text=\"Input a message\", font=(\"Calibri\", 50), bg=\"#a9a9a9\", fg=\"#ffffff\")\nMessage = ...
[ 0 ]
[]
[]
[ "csv", "python", "tkinter" ]
stackoverflow_0074336072_csv_python_tkinter.txt
Q: Is there any function in discord.py 2.0 where the bot responds in the same way if the same message was called? I'm making a discord bot, and one of the commands is like a "gaycount" random number generation command, I've made it fine but I want functionality where if the same message was said twice it would show t...
Is there any function in discord.py 2.0 where the bot responds in the same way if the same message was called?
I'm making a discord bot, and one of the commands is like a "gaycount" random number generation command, I've made it fine but I want functionality where if the same message was said twice it would show the same results as the first one. e.g: a person pings @user with !gay, it shows that they're 68% gay. if they ping @...
[ "I would create a small json database.\nCode logic:\n@bot.command()\nasync def gay(ctx, arg):\n with open(\"database path\", \"a+\") as data:\n Database = json.loads(data)\n #arg = ping\n if arg in Database[\"pings\"] # ˘˘ getting info from db ˘˘\n ctx.send(f\"Your custom message {Database[...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074336419_discord_discord.py_python.txt
Q: Pydrive upload error: pydrive.files.ApiRequestError I am creating a flask application in python that needs to move local files to google drive using the Pydrive library and Google Drive API. All goes well until I upload the file and then I get the following error: pydrive.files.ApiRequestError: <HttpError 404 whe...
Pydrive upload error: pydrive.files.ApiRequestError
I am creating a flask application in python that needs to move local files to google drive using the Pydrive library and Google Drive API. All goes well until I upload the file and then I get the following error: pydrive.files.ApiRequestError: <HttpError 404 when requesting None returned "File not found: 2". Details: ...
[ "Turns out the fix was simple, I wasn't providing a correct fileID in the line file1 = drive.CreateFile({\"mimeType\": mimeType, \"parents\": [{\"kind\": \"drive#fileLink\", \"id\": uniqueID}]}), I was creating my own fileID as uniqueID thinking this was just an ID assigned to the file, it actually is the ID that r...
[ 0 ]
[]
[]
[ "flask", "google_drive_api", "pydrive", "python" ]
stackoverflow_0074322911_flask_google_drive_api_pydrive_python.txt
Q: How can i modify the program to return false if the value is not present in an Array I am using recursion to find an element in an array def recur_search(arr,n,x): #n is the starting index and x is the target value if (arr[n] == x): return n else: return recur_search(arr,n+1,x) arr = [1,2,...
How can i modify the program to return false if the value is not present in an Array
I am using recursion to find an element in an array def recur_search(arr,n,x): #n is the starting index and x is the target value if (arr[n] == x): return n else: return recur_search(arr,n+1,x) arr = [1,2,3,4,5,6,7,8] print(recur_search(arr,0,5)) This program only works if i have the element...
[ "I think you could make the first condition to check if the index is out of bound, then the element doesn't exist, like so:\ndef recur_search(arr,n,x): #n is the starting index and x is the target value\n if n == len(arr):\n return False\n elif (arr[n] == x):\n return n\n else:\n retur...
[ 0, 0 ]
[]
[]
[ "algorithm", "python", "recursion" ]
stackoverflow_0074336430_algorithm_python_recursion.txt
Q: Find the coordinate of users given a specific range I have a list of users' latitude and longitude. The input will be the user's lat/lon and a range. ex. 500 meters  I want to find out which users are in the range of 500 meters from that list. using geopy.distance I can find the distance between two points.. newpo...
Find the coordinate of users given a specific range
I have a list of users' latitude and longitude. The input will be the user's lat/lon and a range. ex. 500 meters  I want to find out which users are in the range of 500 meters from that list. using geopy.distance I can find the distance between two points.. newport_ri = (41.49008, -71.312796, 100) cleveland_oh = (41.49...
[ "For example, if the number of users is not very large, you can sort users by distances and return the closest users according to ranges. The function would begin like this:\ndef findClosest(coor, userCoor, ranges):\n dist = []\n for i, u in enumerate(userCoor):\n dist.append((distance.distance(coor, u)...
[ 0 ]
[]
[]
[ "geolocation", "geopy", "python" ]
stackoverflow_0074336463_geolocation_geopy_python.txt
Q: how to extract words from the string in the list in python? I have a string of type string = "[A] Assam[B] Meghalaya[C] West Bengal[D] Odisha " Output = ['Assam', 'Meghalaya','West Bengal','Odhisa'] I tried many ways, but I always end up splitting the substring West Bengal into two halves... I am not able to cov...
how to extract words from the string in the list in python?
I have a string of type string = "[A] Assam[B] Meghalaya[C] West Bengal[D] Odisha " Output = ['Assam', 'Meghalaya','West Bengal','Odhisa'] I tried many ways, but I always end up splitting the substring West Bengal into two halves... I am not able to cover the edge case mentioned above. What I tried was pass the strin...
[ "You can use regex for this:\nimport re\n\nstring = \"[A] Assam[B] Meghalaya[C] West Bengal[D] Odisha \"\npattern = re.compile(r\"] (.*?)(?:\\[|$)\")\n\noutput = pattern.findall(string.strip())\nprint(output)\n# ['Assam', 'Meghalaya', 'West Bengal', 'Odisha']\n\n\nHow it works: https://regex101.com/r/5peFyC/1\nre m...
[ 3, 1, 0, 0 ]
[]
[]
[ "list", "python", "python_2.7", "python_3.x", "web_scraping" ]
stackoverflow_0074336023_list_python_python_2.7_python_3.x_web_scraping.txt
Q: How to make DeepDiff output human readable? DeepDiff results look like: {'dictionary_item_added': [root[5], root[6]], 'dictionary_item_removed': [root[4]]} For human review of changes, this only works for small examples. I need something like the code file differences displayed in GitHub commits and pull requests...
How to make DeepDiff output human readable?
DeepDiff results look like: {'dictionary_item_added': [root[5], root[6]], 'dictionary_item_removed': [root[4]]} For human review of changes, this only works for small examples. I need something like the code file differences displayed in GitHub commits and pull requests but for json. So here is my question: How to con...
[ "difflib's ndiff may be what you're trying to accomplish:\nimport difflib\nimport json\nfrom typing import Callable\n\nt1 = {1:1, 3:3, 4:4}\nt2 = {1:1, 3:3, 5:5, 6:6}\n\nRED: Callable[[str], str] = lambda text: f\"\\u001b[31m{text}\\033\\u001b[0m\"\nGREEN: Callable[[str], str] = lambda text: f\"\\u001b[32m{text}\\0...
[ 4 ]
[]
[]
[ "c++", "deep_diff", "python" ]
stackoverflow_0074317707_c++_deep_diff_python.txt
Q: Python: How to login with web browser login prompt in code I am trying to login into a website from a python script. I read a few tutorials about it and currently I'm stuck at the process to get the login form from the website (how to name the data for username and password). The login button on the website just r...
Python: How to login with web browser login prompt in code
I am trying to login into a website from a python script. I read a few tutorials about it and currently I'm stuck at the process to get the login form from the website (how to name the data for username and password). The login button on the website just redirects to another site. On this site a web browser prompt pops...
[ "Looks like Basic Auth to me (See Mozilla Developer Network for reference). Assuming your using requests library in python you could give HTTPBasicAuth from requests.auth a try.\nFrom https://requests.readthedocs.io/en/latest/user/authentication/ :\nfrom requests.auth import HTTPBasicAuth\nbasic = HTTPBasicAuth('us...
[ 0 ]
[]
[]
[ "authentication", "browser", "python", "web" ]
stackoverflow_0074336550_authentication_browser_python_web.txt
Q: Use Lightstreamer with IG Index API I am trying to use the streaming API from IG Index their documentation is here. The Api requires the light streamer client to be included in the app. So I have used this version and added it to my project. I have created a function which connects to the server. (I believe) def ...
Use Lightstreamer with IG Index API
I am trying to use the streaming API from IG Index their documentation is here. The Api requires the light streamer client to be included in the app. So I have used this version and added it to my project. I have created a function which connects to the server. (I believe) def connect_light_stream_client(): if cst...
[ "There's a few things wrong:\n\nYou must wait for the subscription request to respond with any\nupdates. In your code, execution ends before any ticks are received. I put the code from light_stream_chart_tick() into the connect method, with a request for input as a wait\nThe items and fields parameters need to be l...
[ 0 ]
[]
[]
[ "lightstreamer", "python", "python_3.x" ]
stackoverflow_0065480735_lightstreamer_python_python_3.x.txt
Q: Different way of handling POST requests on URL i have seen two different ways of handling post requests on a route: @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): # insert logic on data return render_template('regist...
Different way of handling POST requests on URL
i have seen two different ways of handling post requests on a route: @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): # insert logic on data return render_template('register.html', title="Register", form=form) and: @app.ro...
[ "The GET method should not be used to transmit sensitive information (like passwords), as GET encodes form data in the URL, whereas POST data is sent in the request body. W3Schools has a fairly simple comparison between GET and POST methods, further explaining the differences between the two. Just note that POST do...
[ 2, 1 ]
[]
[]
[ "flask", "flask_login", "flask_restful", "flask_wtforms", "python" ]
stackoverflow_0074335779_flask_flask_login_flask_restful_flask_wtforms_python.txt
Q: super().__init__(....) in mixins fails with `Too many arguments for "__init__" of "object" ` When I create a mixin class that extends the logic of __init__, the regular thing to do is: class ExtraValuemixin: def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) # som...
super().__init__(....) in mixins fails with `Too many arguments for "__init__" of "object" `
When I create a mixin class that extends the logic of __init__, the regular thing to do is: class ExtraValuemixin: def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) # some extra initialization self._extra_value = 1 def retrieve_extra_value(self): ...
[ "super().__init__(...)\n\nCalls the __init__ function of it's parent class.\n\nDefining a class with\nclass XXX:\n\n(Omitting the hierarchal parent), leaves the parent as the default: our friend and beloved object class.\nAnd we know the source of that class looks like:\nclass object:\n def __init__():\n\nMeanin...
[ 1 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0053264151_mypy_python.txt
Q: How can I randomly select groups in a proportionate way? I would like to random select rows proportionate to the number of unique values in column "ID" grouping by column "Team". Further, I would like to only retrieve 9 total rows. I have: | ID | Team | Color | | ----- | ----- | ------------ | | 1 |...
How can I randomly select groups in a proportionate way?
I would like to random select rows proportionate to the number of unique values in column "ID" grouping by column "Team". Further, I would like to only retrieve 9 total rows. I have: | ID | Team | Color | | ----- | ----- | ------------ | | 1 | A | Blue | | 2 | B | Red | | 2 ...
[ "With the datafram you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"ID\": [1, 2, 2, 3, 6, 1, 2, 9, 6, 1, 9, 1],\n \"Team\": [\"A\", \"B\", \"B\", \"A\", \"C\", \"B\", \"B\", \"A\", \"C\", \"B\", \"A\", \"A\",],\n \"Color\": [\"Blue\", \"Red\", \"Green\", \"Blue\", \"Red\", \"...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074268600_numpy_pandas_python.txt
Q: Hello guys, I'm not experienced with programming and I would like to run the Mergesort algorithm in Python for a default generated list It takes the random list I generated but the output is something a lot different than I expected. I think that something goes wrong with merging. e.g. : Input --> [267,168,236,190...
Hello guys, I'm not experienced with programming and I would like to run the Mergesort algorithm in Python for a default generated list
It takes the random list I generated but the output is something a lot different than I expected. I think that something goes wrong with merging. e.g. : Input --> [267,168,236,190,2,500,4,45,86] Output --> [2,2,2,2,2,4,4,4,45,45,86] Thank you in advance. import numpy as np def mergeSort(myList): if len(myList) > 1...
[ "The problem with your code is only with inplace manipulation of your original list. merge sort needs extra space O(n).\nyou could simply rewrite your code like this to work: (notice that it is your code, only I modified two lines, look for # changed ...)\nimport numpy as np\n\ndef mergeSort(myList):\n if len(my...
[ 1 ]
[]
[]
[ "mergesort", "numpy", "python" ]
stackoverflow_0074336146_mergesort_numpy_python.txt
Q: rendering freetype font with pygame I was trying to print out just a simple title page using pygame. My original code looked like: import pygame import pygame.freetype pygame.init() pygame.display.set_caption('hello world') screen = pygame.display.set_mode((800, 600), 0, 32) title_font = pygame.font.Font(".../...
rendering freetype font with pygame
I was trying to print out just a simple title page using pygame. My original code looked like: import pygame import pygame.freetype pygame.init() pygame.display.set_caption('hello world') screen = pygame.display.set_mode((800, 600), 0, 32) title_font = pygame.font.Font(".../Montserrat-BlackItalic.ttf", 24) title = ...
[ "The API interface of pygame.freetype is different from that of pygame,fon. The pygame.freetype module has 2 options to display the text. It can either create a Surface like the pygame.fornt module or it can render the text directly on the screen (respectively a Surface). pygame.freetype.Font.render returns a tupl...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0066887578_pygame_python_python_3.x.txt
Q: Python asyncio.create_task() - really need to keep a reference? The documentation of asyncio.create_task() states the following warning: Important: Save a reference to the result of this function, to avoid a task disappearing mid execution. (source) My question is: Is this really true? I have several IO bound "f...
Python asyncio.create_task() - really need to keep a reference?
The documentation of asyncio.create_task() states the following warning: Important: Save a reference to the result of this function, to avoid a task disappearing mid execution. (source) My question is: Is this really true? I have several IO bound "fire and forget" tasks which I want to run concurrently using asyncio ...
[ "There is an open issue at the cpython bug tracker at github about this topic I just found:\nhttps://github.com/python/cpython/issues/88831\nQuote:\n\nasyncio will only keep weak references to alive tasks (in _all_tasks). If a user does not keep a reference to a task and the task is not currently executing or sleep...
[ 10, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0071938799_python_python_asyncio.txt
Q: CommandNotFoundError: No command 'conda mamba' I installed mamba yesterday via conda install -n base -c conda-forge mamba. But after installing it , my terminal is still saying zsh: command not found mamba. What do I do? I did mamba env create -f environment.yml. And was expecting to use mamba for package manageme...
CommandNotFoundError: No command 'conda mamba'
I installed mamba yesterday via conda install -n base -c conda-forge mamba. But after installing it , my terminal is still saying zsh: command not found mamba. What do I do? I did mamba env create -f environment.yml. And was expecting to use mamba for package management.
[ "zsh uses the $PATH environment variable to find ncommands that you issue when you don't include a filepath in command. There are exceptions, such as built-ins and aliases and other stuff, but that's not important right now. And so, when you type the literal command mamba at the command line, each directory in th...
[ 0 ]
[]
[]
[ "anaconda", "mamba", "python" ]
stackoverflow_0074336680_anaconda_mamba_python.txt
Q: how to use the href attribute in django templates When I try to use a link in my Django template from /appname/index/ to get to /appname/detail/### I am instead getting to /appname/index/detail/### which is not what I'm trying to get so my app can't find it in the urlconf of course. First the urls.py line for th...
how to use the href attribute in django templates
When I try to use a link in my Django template from /appname/index/ to get to /appname/detail/### I am instead getting to /appname/index/detail/### which is not what I'm trying to get so my app can't find it in the urlconf of course. First the urls.py line for the detail page url(r'detail/(?P<jobID>\d+)/$', 'appname....
[ "Add / at start in href:\n<a href=\"/appname/detail/{{ job.id }}/\">{{ job.name }}</a>\n\nAnd for the url tag to work you need to do it like this:\n<a href=\"{% url 'appname.views.detail' jobID=job.id %}\">{{ job.name }}</a>\n\n", "From my experience, as long as you have defined the url of the page the href tag s...
[ 49, 2, 1, 0, 0 ]
[]
[]
[ "django", "href", "python", "url" ]
stackoverflow_0017200389_django_href_python_url.txt
Q: How can I search the value in list when get the input value from users? python I'm asking a user to input a year from the keyboard. For example users input 2008, How can I get the maximum value of the year from list that user input the value of year? This is my code: data_list = [(20070101, 619), (20070102, 615), ...
How can I search the value in list when get the input value from users? python
I'm asking a user to input a year from the keyboard. For example users input 2008, How can I get the maximum value of the year from list that user input the value of year? This is my code: data_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940),...
[ "You can use python's built-in max() function.\nhttps://docs.python.org/3/library/functions.html#max\ndata_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940), (20090108, 970), (20090109, 939), (20090110, 936)]\ninput_year = input(\"Enter yea...
[ 0, 0, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074336396_list_python_tuples.txt
Q: Register classes in different files to a Class factory I am trying to register classes that are in different files to the factory class. The factory class has a dictionary called "registry" which hold/maps the a user defined name to the registering class. My issue is that if my factory class and registering classe...
Register classes in different files to a Class factory
I am trying to register classes that are in different files to the factory class. The factory class has a dictionary called "registry" which hold/maps the a user defined name to the registering class. My issue is that if my factory class and registering classes are in the same .py file everything works as expected but ...
[ "I'm currently exploring a similar problem, and I think I may have found a solution. It is a bit of a 'hack' though, so take it with a grain of salt.\n\nWhat why keeping them in the same file work while splitting them out doest\n\nIn order to make your classes self-register in the factory while keeping their defini...
[ 0 ]
[]
[]
[ "factory_pattern", "oop", "python" ]
stackoverflow_0073829483_factory_pattern_oop_python.txt
Q: How to pass variable in shell script and read it in python script I want to run my python script through the shell, passing variable a. Here is my code: else a=0 osascript -e 'tell application "Terminal" to activate' \ -e 'tell application "System Events" to keystroke "n" using {command down}' \ ...
How to pass variable in shell script and read it in python script
I want to run my python script through the shell, passing variable a. Here is my code: else a=0 osascript -e 'tell application "Terminal" to activate' \ -e 'tell application "System Events" to keystroke "n" using {command down}' \ -e 'tell application "Terminal" to do script "python /Users/kacpe...
[ "You can pass arguments as input using the sys module.\nWhen using your script, you call:\npython test.py var1 \n\nInside test.py, in the first lines you must import sys:\nimport sys\nprint(sys.argv[0]) # prints test.py\nprint(sys.argv[1]) # prints var1 \n\nYou can use a instead of var1 as input.\n", "There are a...
[ 1, 1 ]
[]
[]
[ "bash", "macos", "python", "shell" ]
stackoverflow_0074335091_bash_macos_python_shell.txt
Q: Generate list of months between interval in python I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15'...
Generate list of months between interval in python
I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows: date1 = "2014-10-10" # input start date date2 = "2016-01-07" # input end date month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15', 'Jul...
[ "I found a very succinct way to do this with Pandas, sharing in case it helps anybody:\n\nUPDATE: I've got it down to a one-liner with the help of this post :) \npd.date_range('2014-10-10','2016-01-07', \n freq='MS').strftime(\"%Y-%b\").tolist()\n\n\nOLD ANSWER:\ndaterange = pd.date_range('2014-10-10',...
[ 159, 57, 16, 11, 4, 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0034898525_python_python_2.7.txt
Q: How do I keep a script running forever on repl.it? I have a Python Scipt running over on repl.it, but I assume it stops when I close the tab, since I don't own a Premium ("Hacker") account. When hosting my Discord Bot, I tried to add a piece of python that SHOULD make it run forever. Why SHOULD? I checked on it a ...
How do I keep a script running forever on repl.it?
I have a Python Scipt running over on repl.it, but I assume it stops when I close the tab, since I don't own a Premium ("Hacker") account. When hosting my Discord Bot, I tried to add a piece of python that SHOULD make it run forever. Why SHOULD? I checked on it a few days ago, it was offline :-/ But confusingly, this s...
[ "Well, replit doesn't offer complete 24/7 uptime on any repls, even the hacker repls. The UptimeRobot trick may have been an accident but it works well for slightly less important projects. If you have a school email account, GitHub offers a plan which lets you get free Hacker for 6 months here and others services....
[ 0, 0 ]
[ "You could use a Oracle Cloud Free Tier virtual instance, which is always on and easy to setup.\n" ]
[ -1 ]
[ "hosting", "python", "web_hosting" ]
stackoverflow_0069347968_hosting_python_web_hosting.txt
Q: pyttsx3 stopped working after updating to macOS Ventura Here is the code that I wrote earlier on Python3.11. ` import pyttsx3 engine = pyttsx3.init('nsss') # object creation TTS_RATE = 150 # speed of tts TTS_VOLUME = 1.0 # volume of tts TTS_GENDER = "Male" # gender of tts (Male or Female) """R...
pyttsx3 stopped working after updating to macOS Ventura
Here is the code that I wrote earlier on Python3.11. ` import pyttsx3 engine = pyttsx3.init('nsss') # object creation TTS_RATE = 150 # speed of tts TTS_VOLUME = 1.0 # volume of tts TTS_GENDER = "Male" # gender of tts (Male or Female) """RATE""" rate = engine.getProperty('rate') # getting details ...
[ "I think this is due to the OS upgrade to Ventura. I encountered the same issue after upgrading from montery to ventura. While waiting for pyttsx3 to fix the issue, you can update the following line. You can find the file to be updated with the following snippet:\n$ python -c 'import inspect; from pyttsx3.drivers.n...
[ 1 ]
[]
[]
[ "macos", "macos_ventura", "python", "python_3.x", "pyttsx3" ]
stackoverflow_0074268825_macos_macos_ventura_python_python_3.x_pyttsx3.txt
Q: How to get suspended users or deleted users difference via TwitterApi? I want to get the records that which user is suspended and which one is deleted, is there any way to get? from TwitterAPI import TwitterAPI api = TwitterAPI(consumer_key, consumer_secret, auth_type='oAuth2') usersfiles=['',''] #LIST of users fo...
How to get suspended users or deleted users difference via TwitterApi?
I want to get the records that which user is suspended and which one is deleted, is there any way to get? from TwitterAPI import TwitterAPI api = TwitterAPI(consumer_key, consumer_secret, auth_type='oAuth2') usersfiles=['',''] #LIST of users for user in usersfiles: print(user,type(user)) #api.request('users/show', us...
[ "Check for suspended response code for suspended user, it goes in the error with code 63.\nFor a full list of response codes go to\nhttps://developer.twitter.com/ja/docs/basics/response-codes\nEdit\nIf you have large users, go for batch compliance. Quick start guide:\nhttps://developer.twitter.com/en/docs/twitter-a...
[ 1, 0 ]
[]
[]
[ "python", "twitter", "twitterapi_python" ]
stackoverflow_0074165515_python_twitter_twitterapi_python.txt
Q: How to optimise Collatz sequence in python sequence? The Collatz sequence rules are as follows: If n = odd: n = 3n + 1 If n = even: n = n/2 I am a student with a basic level of python and need to minimise the number of numbers I check to find the longest sequence less than 100. I need to output the starting term...
How to optimise Collatz sequence in python sequence?
The Collatz sequence rules are as follows: If n = odd: n = 3n + 1 If n = even: n = n/2 I am a student with a basic level of python and need to minimise the number of numbers I check to find the longest sequence less than 100. I need to output the starting term of said sequence. Both even numbers and multiples of five...
[ "You can save result of previously computed numbers is some dict and then use it when you reach some of that numbers. Here is sample code:\ncache = {}\nmax_iter = 0\nmax_iter_num = 0\n\ndef collatz(num):\n global cache\n global max_iter\n global max_iter_num\n \n iterations = 0\n n = num\n numb...
[ 0 ]
[]
[]
[ "collatz", "logic", "math", "python" ]
stackoverflow_0074336619_collatz_logic_math_python.txt
Q: Django: usage of prefetch_related I have some models with this relation: EmailReport --many-to-many--> PaymentReport --foreign-key--> Shop --many-to-many--> users Now I want to reach the users from EmailReport. I tried this query but failed: query = models.EmailReport.objects.prefetch_related('payment_report').pr...
Django: usage of prefetch_related
I have some models with this relation: EmailReport --many-to-many--> PaymentReport --foreign-key--> Shop --many-to-many--> users Now I want to reach the users from EmailReport. I tried this query but failed: query = models.EmailReport.objects.prefetch_related('payment_report').prefetch_related('shop__users').filter(pk...
[ "Probably:\nemail_reports = EmailReport.objects.prefetch_related('payment_report__shop__users').filter(pk__in=ids)\n\n(That are ids here? Users ids or EmailReport ids?)\nThis shoud be minimal amount of queries. Just remember that you can't do further filtering or it will break the prefetch.\nThen there are few ways...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074336791_django_python.txt
Q: Python Micro:bit Bitio Error - microbit.repl.repl.REPLException: Timeout trying to receive I have a micro:bit (v1.3 B) and am trying to use the Python bitio library on a MacBook (macOS Monterey). I've been following the getting started section and have gotten to the 'making a connection' section. I've already 'fla...
Python Micro:bit Bitio Error - microbit.repl.repl.REPLException: Timeout trying to receive
I have a micro:bit (v1.3 B) and am trying to use the Python bitio library on a MacBook (macOS Monterey). I've been following the getting started section and have gotten to the 'making a connection' section. I've already 'flashed' the bitio.hex file to the micro:bit by uploading the file, and it successfully shows the b...
[ "Fixed the issue, turns out I had to give the terminal (or whatever editor/IDE used) full disk access in settings\n" ]
[ 2 ]
[]
[]
[ "bbc_microbit", "python" ]
stackoverflow_0074335503_bbc_microbit_python.txt
Q: I am converting annotated data(JSON) to COCO format while making Tensorflow Object detetction API, this is the error I am facing from last 2 days import os import argparse import json from labelme import utils import numpy as np import glob import PIL.Image class labelme2coco(object): def init(self, labelme_json=[...
I am converting annotated data(JSON) to COCO format while making Tensorflow Object detetction API, this is the error I am facing from last 2 days
import os import argparse import json from labelme import utils import numpy as np import glob import PIL.Image class labelme2coco(object): def init(self, labelme_json=["new_images\Train"], save_json_path="new_images\Train_Coco/coco.json"): """ :param labelme_json: the list of all labelme json file paths :param save_js...
[ "Try using the below correction:\nimport argparse\n\nparser = argparse.ArgumentParser(\n description=\"labelme annotation to coco data json file.\"\n)\nparser.add_argument(\n \"labelme_images\",\n help=\"Directory to labelme images and annotation json files.\",\n type=str,\n)\nparser.add_argument(\n ...
[ 0 ]
[]
[]
[ "annotations", "computer_vision", "object_detection_api", "python", "tensorflow" ]
stackoverflow_0073065367_annotations_computer_vision_object_detection_api_python_tensorflow.txt
Q: How can I separate multiple graphs in this code? I'm new learner of python. I am trying to split the graphs into 4 separated blocks. I know I need to use subplots but I dont know how to. Here is my code Im trying right now. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['...
How can I separate multiple graphs in this code?
I'm new learner of python. I am trying to split the graphs into 4 separated blocks. I know I need to use subplots but I dont know how to. Here is my code Im trying right now. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['lines.color'] = 'k' mpl.rcParams['axes.prop_cycle'] = ...
[ "plt.subplots returns a 2D array of axes.\nSo, you must call plot or contour on ax[i,j] i and j being integers, not on plt or ax[i].\nBesides, that goes also for your axhline and axvline\nLastly, you must call plt.show() only once if you want one window to show up.\nSo\n# Untouched code before that\ndef axes(ax):\n...
[ 1 ]
[]
[]
[ "graph", "python", "subplot" ]
stackoverflow_0074336759_graph_python_subplot.txt
Q: Hypothesis strategy from_regex does not respect min_size and max_size I am having issues with Hypothesis generating strings which do not respect the given min/max sizes. Example: @given( st.text( alphabet=st.from_regex(regex=r"^[a-z][b-z]$", fullmatch=True), min_size=0, max_size=15, ...
Hypothesis strategy from_regex does not respect min_size and max_size
I am having issues with Hypothesis generating strings which do not respect the given min/max sizes. Example: @given( st.text( alphabet=st.from_regex(regex=r"^[a-z][b-z]$", fullmatch=True), min_size=0, max_size=15, ) ) def test_foobar(username: str): assert len(username) <= 20 Output...
[ "According to the text strategy docs:\n\n... alphabet, which should be a collection of length one strings or a strategy generating such strings.\n\nYou are using a strategy (st.from_regex(regex=r\"^[a-z][b-z]$\", fullmatch=True) that generates length two strings.\nIf you really need the test strings to be of that f...
[ 1 ]
[]
[]
[ "pytest", "python", "python_hypothesis" ]
stackoverflow_0074336794_pytest_python_python_hypothesis.txt
Q: Why don't slash commands work? Discord.py Slash commands don't appear in the command tree. The error pops up in the console: "discord.app_commands.errors.MissingApplicationID: Client does not have an application_id set. Either the function was called before on_ready was called or application_id was not passed to t...
Why don't slash commands work? Discord.py
Slash commands don't appear in the command tree. The error pops up in the console: "discord.app_commands.errors.MissingApplicationID: Client does not have an application_id set. Either the function was called before on_ready was called or application_id was not passed to the Client constructor." from discord import app...
[ "Firstly, never mix discord.Client and commands.Bot!\nThere are couple reasons why your code isn't working:\n\nyou are missing import discord\ncommand test(interaction): needs to be replaced with test(interaction: discord.Interaction)\nsyncing command is wrong AND instead of putting guild ID (intiger), you put guil...
[ 0 ]
[]
[]
[ "bots", "discord.py", "python" ]
stackoverflow_0074336580_bots_discord.py_python.txt
Q: Fastest way of filter index values based on list values from multiple columns in Pandas Dataframe? I have a data frame like below. It has two columns column1,column2 from these two columns I want to filter few values(combinations of two lists) and get the index. Though I wrote the logic for it. It is will be too s...
Fastest way of filter index values based on list values from multiple columns in Pandas Dataframe?
I have a data frame like below. It has two columns column1,column2 from these two columns I want to filter few values(combinations of two lists) and get the index. Though I wrote the logic for it. It is will be too slow for filtering from a larger data frame. Is there any faster way to filter the data and get the list ...
[ "You can just use underlying numpy array and create the boolean indexing:\nmask=(df[['col1', 'col2']].values[:,None]==np.vstack([l1,l2]).T).all(-1).any(1)\n# mask\n# array([ True, False, True, False, True])\n\ndf.index[mask]\n# prints\n# Int64Index([0, 2, 4], dtype='int64')\n\n", "here is one way to do it. Merg...
[ 3, 1, 1 ]
[]
[]
[ "dataframe", "for_loop", "list", "pandas", "python" ]
stackoverflow_0074336822_dataframe_for_loop_list_pandas_python.txt
Q: How to get max value record per a group in polars dataframe? I have a dataframe as: pl.DataFrame( [{'row_nr': 0, 'middle_name_or_initial': 'R.', 'count': 8}, {'row_nr': 0, 'middle_name_or_initial': 'B.', 'count': 1}, {'row_nr': 1, 'middle_name_or_initial': 'D.', 'count': 1}, {'row_nr': 1, 'middle_name_or_initia...
How to get max value record per a group in polars dataframe?
I have a dataframe as: pl.DataFrame( [{'row_nr': 0, 'middle_name_or_initial': 'R.', 'count': 8}, {'row_nr': 0, 'middle_name_or_initial': 'B.', 'count': 1}, {'row_nr': 1, 'middle_name_or_initial': 'D.', 'count': 1}, {'row_nr': 1, 'middle_name_or_initial': 'J.', 'count': 11}, {'row_nr': 2, 'middle_name_or_initial': '...
[ "Here you go. It would have been nice if you had a clearer example, with fewer rows and more cases of count != 1, as well as the expected solution as code rather than screenshot so the responder can test their solution (using test_df.frame_equal(solution_df)). See below for a suggestion for how to create this.\nI a...
[ 1, 0 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074335540_python_python_polars.txt
Q: AttributeError: 'Misc' object has no attribute 'bot' - When adding a cog INSIDE MAIN DISCORDBOT FILE import discord from discord.ext import commands import random import json import os import asyncio def get_prefix(bot, message): with open("jsonfiles/prefixes.json", "r") as f: prefixes = json.load(f) ...
AttributeError: 'Misc' object has no attribute 'bot' - When adding a cog
INSIDE MAIN DISCORDBOT FILE import discord from discord.ext import commands import random import json import os import asyncio def get_prefix(bot, message): with open("jsonfiles/prefixes.json", "r") as f: prefixes = json.load(f) return prefixes[str(message.guild.id)] bot = command...
[ "This line is the wrong way around\nbot = self.bot\n\nYou're now saying:\n\n\"The variable bot should be equal to the attribute bot stored in this class\"\n\nHowever, at that point the attribute doesn't exist yet, because you've never created it. You want to do it the other way around, and set the value of the attr...
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074336731_discord.py_python.txt
Q: Kernel keeps dying when plotting a graph after importing the torch library I'm trying to run the following code: import matplotlib.pyplot as plt %matplotlib inline import torch x = y = torch.tensor([1,2,3]).numpy() plt.plot(x,y); I keep getting the message: The kernel appears to have died. It will restart automa...
Kernel keeps dying when plotting a graph after importing the torch library
I'm trying to run the following code: import matplotlib.pyplot as plt %matplotlib inline import torch x = y = torch.tensor([1,2,3]).numpy() plt.plot(x,y); I keep getting the message: The kernel appears to have died. It will restart automatically. and a restart and a red "Dead kernel" tag on the toolbar. But the weird...
[ "import os\nos.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"\n\nRun this first, then it'll resolve your problem. Although I guess, it is a temporary solution you can refer to this link: https://www.programmersought.com/article/53286415201/\n", "I followed the link above and deleted a couple of duplicate .dll's in To...
[ 3, 0, 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "python", "pytorch" ]
stackoverflow_0064216189_jupyter_notebook_matplotlib_python_pytorch.txt
Q: Create DataFrame where all data is in lists, but one has a nested list I have the following data: Dog: Male, Brown, 10 Years, Sausage, Happy Cat: Female, Black, 5 Years, Pippin, Angry Hamster: Male, Yellow, 1 Year, Jeff, Moody I receive the data structured as follows: Animals = ['dog', 'cat', 'hamster'] Genders = ...
Create DataFrame where all data is in lists, but one has a nested list
I have the following data: Dog: Male, Brown, 10 Years, Sausage, Happy Cat: Female, Black, 5 Years, Pippin, Angry Hamster: Male, Yellow, 1 Year, Jeff, Moody I receive the data structured as follows: Animals = ['dog', 'cat', 'hamster'] Genders = ['male', 'female', 'male'] Properties = [ ['Brown', '10 Years', 'Sa...
[ "Let us try two step with concat\nout = pd.concat([pd.DataFrame({'Animals':Animals,'Gender':Genders}),\n pd.DataFrame(Properties,columns = ['Colour','Age','Name','Sentiment'])],\n axis=1)\n\nOut[82]: \n Animals Gender Colour Age Name Sentiment\n0 dog male Brow...
[ 2 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074336933_dataframe_list_pandas_python.txt
Q: mac homebrew install opencv I did homebrew download opencv but something wrong. if i try to intstall again it shows Warning: opencv 4.6.0_1 is already installed and up-to-date. To reinstall 4.6.0_1, run: brew reinstall opencv but if i check the version, it shows ➜ ~ opencv --version zsh: command not found: ope...
mac homebrew install opencv
I did homebrew download opencv but something wrong. if i try to intstall again it shows Warning: opencv 4.6.0_1 is already installed and up-to-date. To reinstall 4.6.0_1, run: brew reinstall opencv but if i check the version, it shows ➜ ~ opencv --version zsh: command not found: opencv I am a super begineer of it. ...
[ "The homebrew OpenCV package doesn't install a runnable program called opencv that you can run with:\nopencv\n\nRather, it installs libraries and packages that you can use from Python or C++. If you want to see all the stuff it installs, you can run:\nbrew ls -v opencv\n\nAny binary (executable) programs will likel...
[ 1 ]
[]
[]
[ "homebrew", "macos", "opencv", "python" ]
stackoverflow_0074335860_homebrew_macos_opencv_python.txt
Q: I need to scrape the instagram link that is highlighted in the image I am trying regex in python. I am facing a problem how to clip out the portion that is< "www.instagram.com%2FMohakMeet" I need to know the characters which I need to use in regex. #python3 for d in g: stripped = (d.rstrip()) url = stripped+"...
I need to scrape the instagram link that is highlighted in the image
I am trying regex in python. I am facing a problem how to clip out the portion that is< "www.instagram.com%2FMohakMeet" I need to know the characters which I need to use in regex. #python3 for d in g: stripped = (d.rstrip()) url = stripped+"/about" print("Retreiving" + url) response = requests.get(url) data ...
[ "\nthis link will let you debug your regex https://regex101.com/\na common pitfall when creating regex, is using standard string ('my string') and not raw strings r'my string' .\nsee also https://docs.python.org/3/library/re.html\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex", "web_scraping" ]
stackoverflow_0074336801_python_regex_web_scraping.txt