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 can we mock several exception in Pytest, Mock_Response? We're revising our pytest script, according to parent 'executor' method revision -- added retry logic, to retry 3 times until get response and raise error on 4th.attempt. Used to be, we test to raise socket error exception as follows, now we need to raise...
How can we mock several exception in Pytest, Mock_Response?
We're revising our pytest script, according to parent 'executor' method revision -- added retry logic, to retry 3 times until get response and raise error on 4th.attempt. Used to be, we test to raise socket error exception as follows, now we need to raise that exception after 3 times retry (below pytest code encountere...
[ "You can use mocker fixture like so:\ndef test_retry_exception(mocker):\n mocker.patch(\"parent_module_path.requests.post\", side_effect = [Exception(\"first time\"), Exception(\"second time\"), Exception(\"third time\"), Exception(\"forth time\")])\n\n with pytest.raises(CommunicationError) as ce:\n j...
[ 1, 1 ]
[]
[]
[ "pytest", "pytest_mock", "python" ]
stackoverflow_0074087441_pytest_pytest_mock_python.txt
Q: pickle/joblib AttributeError: module '__main__' has no attribute 'thing' in pytest I have built a custom sklearn pipeline, as follows: pipeline = make_pipeline( SelectColumnsTransfomer(features_to_use), ToDummiesTransformer('feature_0', prefix='feat_0', drop_first=True, dtype=bool), # Dummify customer_typ...
pickle/joblib AttributeError: module '__main__' has no attribute 'thing' in pytest
I have built a custom sklearn pipeline, as follows: pipeline = make_pipeline( SelectColumnsTransfomer(features_to_use), ToDummiesTransformer('feature_0', prefix='feat_0', drop_first=True, dtype=bool), # Dummify customer_type ToDummiesTransformer('feature_1', prefix='feat_1'), # Dummify the feature ToDu...
[ "I had the same error message when I was trying to save a Pytorch class like this:\nimport torch.nn as nn\n\nclass custom(nn.Module):\n def __init__(self):\n super(custom, self).__init__()\n print(\"Class loaded\")\n\nmodel = custom()\n\nAnd then using Joblib to dump this model like so:\nfrom jobli...
[ 1, 0, -1 ]
[]
[]
[ "joblib", "pickle", "pytest", "python", "scikit_learn" ]
stackoverflow_0053177389_joblib_pickle_pytest_python_scikit_learn.txt
Q: I am trying to find the complexity of this code def f1(seq,thelast): for i in range(0,thelast): print(seq[i]) def f2(seq,thefirst,thelast): if thefirst==thelast: f1(seq,thelast) else: for i in range(thefirst,thelast): temp= seq[thefirst] seq[thefirst]=se...
I am trying to find the complexity of this code
def f1(seq,thelast): for i in range(0,thelast): print(seq[i]) def f2(seq,thefirst,thelast): if thefirst==thelast: f1(seq,thelast) else: for i in range(thefirst,thelast): temp= seq[thefirst] seq[thefirst]=seq[i] seq[i]=temp f2(seq, thef...
[ "You should solve the corresponding recurrence relation:\nT(n) = n T(n-1) + c for n>1 (with T(1) = n)\n\nIndeed you have n recursive calls with decreased input n. By iteration, you find it is O(n*n!).\nIf you try simulating the code, you'll see it prints all permutations of seq that are n!. Printing the sequence ha...
[ 0 ]
[]
[]
[ "big_o", "complexity_theory", "python", "recursion", "time_complexity" ]
stackoverflow_0074155736_big_o_complexity_theory_python_recursion_time_complexity.txt
Q: What does if __name__ == "__main__": do? What does this do, and why should one include the if statement? if __name__ == "__main__": print("Hello, World!") If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of Why is Python running my modul...
What does if __name__ == "__main__": do?
What does this do, and why should one include the if statement? if __name__ == "__main__": print("Hello, World!") If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of Why is Python running my module when I import it, and how do I stop it? ins...
[ "Short Answer\nIt's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:\n\nIf you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the lat...
[ 8516, 2122, 858, 598, 170, 111, 94, 78, 70, 66, 58, 57, 46, 44, 42, 36, 36, 29, 27, 26, 26, 21, 21, 20, 19, 16, 14, 13, 12, 9, 8, 8, 7, 5, 4, 3, 1 ]
[ "if __name__ == \"__main__\" means that if you are running the Python file normally like python foo.py, it will assign the special variable __name__ to \"__main__\".\nBut if you are importing the file like \"import foo\", it will assign __name__ to \"foo\" and will not run the function.\n", "When you import some ...
[ -1, -1, -1, -2, -2, -4 ]
[ "idioms", "namespaces", "program_entry_point", "python", "python_module" ]
stackoverflow_0000419163_idioms_namespaces_program_entry_point_python_python_module.txt
Q: Why is list() not creating a new list I created a list named route in createRoute() and copied the list using list(route) to copyRoute. However, once I change the index route[0][0] in route, it also changes in copyRoute. I can't spot where the error is. from random import randint def createRoute(): route = []...
Why is list() not creating a new list
I created a list named route in createRoute() and copied the list using list(route) to copyRoute. However, once I change the index route[0][0] in route, it also changes in copyRoute. I can't spot where the error is. from random import randint def createRoute(): route = [] for horizon in range(8): row =...
[ "from random import randint\nimport copy\n\ndef createRoute():\n route = []\n for horizon in range(8):\n row = []\n for vertical in range(4):\n row.append(randint(0, 50))\n route.append(row)\n return route\n\ndef printRoute(list):\n for i in range(8):\n for j in ra...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074236839_python.txt
Q: How to get classes to inherit the attributes of their parent classes? I am trying to get classes to inherit attributes of the parent class. The main class is Country and has two attributes that're the country's capital and president. The class State is derived from Country, and should have the attributes of the st...
How to get classes to inherit the attributes of their parent classes?
I am trying to get classes to inherit attributes of the parent class. The main class is Country and has two attributes that're the country's capital and president. The class State is derived from Country, and should have the attributes of the state's capital and the governor. The class County is derived from State, and...
[ "Since you're constructing the \"parent\" object separately from the \"child\", I might suggest composition rather than inheritance. Note that inheritance implies an \"is a\" relationship rather than an \"has a\" relationship -- is it correct to say that a State is a Country, or that a State has a Country that it ...
[ 1, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074236808_class_python.txt
Q: How to fix pandas FutureWarning: inferring datetime64[ns] from data containing strings is deprecated I have the following code which worked fine until I've upgraded pandas to the latest version: def group_amounts_by_batch(self) -> pd.DataFrame: data_frame = ( self.data_frame[self.columns.amount] ...
How to fix pandas FutureWarning: inferring datetime64[ns] from data containing strings is deprecated
I have the following code which worked fine until I've upgraded pandas to the latest version: def group_amounts_by_batch(self) -> pd.DataFrame: data_frame = ( self.data_frame[self.columns.amount] .groupby( [ self.data_frame[ExtraColumnNames.BatchId], self....
[ "I have got similar warning while parsing an excel file with string dates:\ndf = pd.read_excel('path/to/file')\n\nWorkaround that helped me to get rid of it is following:\ndf = pd.read_excel('path/to/file', \n parse_dates=['col_date1', 'col_date2', ...], \n date_parser=lambda x...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0070367488_pandas_python.txt
Q: How to make the error messages not appear below the fields, but on top of the table Django I'm writing a Django site, I made a registration form, but I don't like the fact that error messages appear under the corresponding fields, thereby stretching the table I want these messages to be displayed somewhere above ...
How to make the error messages not appear below the fields, but on top of the table Django
I'm writing a Django site, I made a registration form, but I don't like the fact that error messages appear under the corresponding fields, thereby stretching the table I want these messages to be displayed somewhere above the form, is this possible?
[ "{% for message in messages %}\n <p>{{ message }}</p>\n{% endfor %}\n\nIn your Html code, you are going to add this block of code to wherever you want the error message to appear which in this would be at the top of the table tag in your html code.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0074224535_django_django_forms_python.txt
Q: How to get an element of a NumPy list without bracket and '' I have a NumPy list (Distances). When I print it, the result is: array([[ 1. ], [600. ], [456.03971033], [294.94188261], [286.47232436], [ 92.08606785]]) However, I want to get any specific element of th...
How to get an element of a NumPy list without bracket and ''
I have a NumPy list (Distances). When I print it, the result is: array([[ 1. ], [600. ], [456.03971033], [294.94188261], [286.47232436], [ 92.08606785]]) However, I want to get any specific element of this list as a float number without any brackets, array, and '' sign...
[ "This is a 2-D array, so you need to specify both indices:\nelement1 = Distance[0][0]\n\nAnd the 600. will be at 1,0:\nelement2 = Distance[1][0]\n\n", "You can first flatten the array to make it one dimensional:\nflatdistance = Distance.flatten()\nelement1 = flatdistance[0]\n\n", "Note that your result is a mat...
[ 1, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074236830_numpy_python.txt
Q: How to convert 1D array containing dictionaries as its values into a 2D array I want to change the below 1D array having dictionaries as its value into 2D array. I don't want to use numpy or pandas. array = [{"id": "123", 'name-code': 'user-1666935009', 'r.no.': '1', 'start_time': '1666955702', 'state_msg': 'Finis...
How to convert 1D array containing dictionaries as its values into a 2D array
I want to change the below 1D array having dictionaries as its value into 2D array. I don't want to use numpy or pandas. array = [{"id": "123", 'name-code': 'user-1666935009', 'r.no.': '1', 'start_time': '1666955702', 'state_msg': 'Finished', 'state_details': '', 'setup_time': '2371'}] I am expecting the output as arr...
[ "Try:\narray = [\n {\n \"id\": \"123\",\n \"name-code\": \"user-1666935009\",\n \"r.no.\": \"1\",\n \"start_time\": \"1666955702\",\n \"state_msg\": \"Finished\",\n \"state_details\": \"\",\n \"setup_time\": \"2371\",\n }\n]\n\narray = [list(array[0]), list(arr...
[ 1, 0, 0 ]
[]
[]
[ "arrays", "dictionary", "python" ]
stackoverflow_0074236851_arrays_dictionary_python.txt
Q: Matplotlib - Series of curves on with individual markers I am trying to plot a series of curves on the same graph with individual markers: Each curve has one colour Each data point has its own markers For this, I created 3 lists of lists: x_data, y_data and markers. Using np.array(), x_data and y_data can be plo...
Matplotlib - Series of curves on with individual markers
I am trying to plot a series of curves on the same graph with individual markers: Each curve has one colour Each data point has its own markers For this, I created 3 lists of lists: x_data, y_data and markers. Using np.array(), x_data and y_data can be plotted properly as different curves (with individual colours). H...
[ "One option is an inner loop to scatter plot each marker individually:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx_data=[[1,2,3,4,5],[5,10,3,8,6]]\ny_data=[[5,10,3,8,6],[1,2,3,4,5]]\nmarkers=[[\"o\",\"+\",\"D\",\"+\",\"D\"],[\"D\",\"o\",\"o\",\"D\",\"+\"]]\n\nfig, ax = plt.subplots()\n\nfor xs, ys, ma...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074236795_matplotlib_python.txt
Q: Python / Import module pymssql / from Linux to Windows I have a python script running on linux, with this declaration : import _mssql In the library listed there is pymssql (I can't find other relative library) I am trying to adapt this code to windows, so I have installed pymssql but when I try to declare it lik...
Python / Import module pymssql / from Linux to Windows
I have a python script running on linux, with this declaration : import _mssql In the library listed there is pymssql (I can't find other relative library) I am trying to adapt this code to windows, so I have installed pymssql but when I try to declare it like in the linux version, I have this message : ModuleNotFoun...
[ "That's not how you should be importing it. Please read their documentation: https://pymssql.readthedocs.io/en/stable/pymssql_examples.html\n", "Yes obviously the correct syntax is :\nimport pymssql._mssql\n\n" ]
[ 0, 0 ]
[]
[]
[ "pymssql", "python" ]
stackoverflow_0074236803_pymssql_python.txt
Q: DataSpell & AWS Sagemaker Connection Haven't been able to find this answer online, so I'm asking the stackoverflow community... I'm wondering if DataSpell can connect to a SageMaker instance and use the EC2 instance hardware (i.e. virtual CPUs, GPUs, RAM, etc.) to run data transformations and machine learning mode...
DataSpell & AWS Sagemaker Connection
Haven't been able to find this answer online, so I'm asking the stackoverflow community... I'm wondering if DataSpell can connect to a SageMaker instance and use the EC2 instance hardware (i.e. virtual CPUs, GPUs, RAM, etc.) to run data transformations and machine learning model training on python and Jupyter notebook ...
[ "I'm exactly in the same boat.\nAt the moment I still use PyCharm pro and configure it to do remote code execution on my Dev ec2 instance. I can also run Jupiter notebooks remotely and ssh tunnel the remote port to my local machine, then I can actually have jupiter notebooks in my IDE but execute on hardware.\nAt t...
[ 1 ]
[ "This can not be done. You can't bring your own IDE to SageMaker. You can use SageMaker's native IDE - SageMaker Studio which will give you an integrated experience with all of SageMaker's capabilities.\nI work at AWS and my opinions are my own.\n" ]
[ -1 ]
[ "amazon_sagemaker", "dataspell", "jupyter_notebook", "pycharm", "python" ]
stackoverflow_0071382998_amazon_sagemaker_dataspell_jupyter_notebook_pycharm_python.txt
Q: How to add CSS Styling to FastAPI Documentation So we have built an API using FastAPI and for the documentation of the API we first used markdown and passed it while initializing the FastAPI object something like this main = FastAPI( root_path="/public", title="API", description="""{}""".format(open("p...
How to add CSS Styling to FastAPI Documentation
So we have built an API using FastAPI and for the documentation of the API we first used markdown and passed it while initializing the FastAPI object something like this main = FastAPI( root_path="/public", title="API", description="""{}""".format(open("public/app/description.md").read()), ) In our descrip...
[ "You can inject HTML in your documentation's markdown that you include in your FastAPI descriptions. However by default FastAPI runs a sanitizer on your markdown that removes style and class, as well as data-* attributes.\nIf you do not want to have CSS styling attributes removed by FastAPI, you may use swagger_ui_...
[ 0 ]
[]
[]
[ "fastapi", "markdown", "openapi", "python", "swagger" ]
stackoverflow_0064717887_fastapi_markdown_openapi_python_swagger.txt
Q: Python: Best way to get shared object library path from within a pypi package I'm developing a Python package that includes an extension module: # setup.py from distutils.core import setup, Extension setup( name="myPythonPkg", # ... all other args packages=["myPythonPkg"], ext_modules=[ E...
Python: Best way to get shared object library path from within a pypi package
I'm developing a Python package that includes an extension module: # setup.py from distutils.core import setup, Extension setup( name="myPythonPkg", # ... all other args packages=["myPythonPkg"], ext_modules=[ Extension('myFastCfunctions', ['myFastCfunctions.c']) ] ) When I test the insta...
[ "Use EXTENSION_SUFFIXES[0], example:\nfrom importlib.machinery import EXTENSION_SUFFIXES\n\nmyFastCfunctions_file = path.join(\n path.join(\n path.dirname(__file__), '..',\n 'myFastCfunctions{}'.format(\n EXTENSION_SUFFIXES[0]\n )\n )\n)\n\nmyFastCfunctions = cdll.LoadLibrary(m...
[ 0 ]
[]
[]
[ "extension_modules", "python", "setuptools" ]
stackoverflow_0074196473_extension_modules_python_setuptools.txt
Q: In Python can class.main() calls init method automatically? I have a code snippet. Can anyone tell me whether class.main calls the initi method automatically? I cannot find a main method defined here, but calling to main. What is TwitterStreamWarcIter.main calling? #!/usr/bin/env python3 from __future__ import ab...
In Python can class.main() calls init method automatically?
I have a code snippet. Can anyone tell me whether class.main calls the initi method automatically? I cannot find a main method defined here, but calling to main. What is TwitterStreamWarcIter.main calling? #!/usr/bin/env python3 from __future__ import absolute_import from sfmutils.warc_iter import BaseWarcIter from da...
[ "No it doesn't call the __init__ method automatically, it must be that TwitterStreamWarcIter.main calls the main function defined in the superclass BaseWarcIter which code you haven't provided. TwitterStreamWarcIter inherits this function and it is called by the piece of code TwitterStreamWarcIter.main(TwitterStrea...
[ 1 ]
[]
[]
[ "object_oriented_analysis", "python", "python_class" ]
stackoverflow_0074236886_object_oriented_analysis_python_python_class.txt
Q: return coefficients from Pipeline object in sklearn I've fit a Pipeline object with RandomizedSearchCV pipe_sgd = Pipeline([('scl', StandardScaler()), ('clf', SGDClassifier(n_jobs=-1))]) param_dist_sgd = {'clf__loss': ['log'], 'clf__penalty': [None, 'l1', 'l2', 'elasticnet'], ...
return coefficients from Pipeline object in sklearn
I've fit a Pipeline object with RandomizedSearchCV pipe_sgd = Pipeline([('scl', StandardScaler()), ('clf', SGDClassifier(n_jobs=-1))]) param_dist_sgd = {'clf__loss': ['log'], 'clf__penalty': [None, 'l1', 'l2', 'elasticnet'], 'clf__alpha': np.linspace(0.15, 0.35), ...
[ "You can always use the names you assigned to them while making the pipeline by using the named_steps dict.\nscaler = sgd_randomized_pipe.best_estimator_.named_steps['scl']\nclassifier = sgd_randomized_pipe.best_estimator_.named_steps['clf']\n\nand then access all the attributes like coef_, intercept_ etc. which ar...
[ 45, 14, 3, 0 ]
[]
[]
[ "cross_validation", "machine_learning", "python", "scikit_learn", "scikit_learn_pipeline" ]
stackoverflow_0043856280_cross_validation_machine_learning_python_scikit_learn_scikit_learn_pipeline.txt
Q: Python module not found even though "Requirement Already satisfied in Pip" writing some python in OS X, and it's saying several packages I installed with pip "ImportError: no module named requests" When running pip install requests > sudo -H pip install requests Requirement already satisfied: requests in /usr/lo...
Python module not found even though "Requirement Already satisfied in Pip"
writing some python in OS X, and it's saying several packages I installed with pip "ImportError: no module named requests" When running pip install requests > sudo -H pip install requests Requirement already satisfied: requests in /usr/local/lib/python2.7/site-packages Requirement already satisfied: certifi>=2017.4....
[ "Run in command prompt.\npip list\n\nCheck what version you have installed on your system if you have an old version.\nTry to uninstall the package...\npip uninstall requests\n\nTry after to install it:\npip install requests\n\nYou can also test if pip does not do the job.\neasy_install requests\n\n", "In my case...
[ 21, 15, 10, 8, 6, 4, 2, 1, 0, 0, 0 ]
[]
[]
[ "pip", "python", "python_requests" ]
stackoverflow_0045345377_pip_python_python_requests.txt
Q: Pass arguments to executable in Python I am using os.startfile('C:\\test\\sample.exe') to launch the application. I don't want to know the application’s exit status and I just want to launch the exe. I need to pass the argument to that exe like 'C:\\test\\sample.exe' -color Please suggest a method to run this in ...
Pass arguments to executable in Python
I am using os.startfile('C:\\test\\sample.exe') to launch the application. I don't want to know the application’s exit status and I just want to launch the exe. I need to pass the argument to that exe like 'C:\\test\\sample.exe' -color Please suggest a method to run this in Python.
[ "You should use the subprocess module instead of os.startfile or os.system in every case that I'm aware of.\nimport subprocess\nsubprocess.Popen([r'C:\\test\\sample.exe', '-color'])\n\nYou could, as @Hackaholic suggests in the comments, do\nimport os\nos.system(r'C:\\test\\sample.exe -color')\n\nBut this is no simp...
[ 9, 0 ]
[]
[]
[ "python" ]
stackoverflow_0026680647_python.txt
Q: I have issue at install scikit-image with python 3.11 what should I do? Good evening everyone, I have an issue with scikit-image while installing this package I installed python 3.11 on windows 11 pip install scikit-image I got these issues as below in the screenshot got previous issue EDIT: I installed Microsoft...
I have issue at install scikit-image with python 3.11 what should I do?
Good evening everyone, I have an issue with scikit-image while installing this package I installed python 3.11 on windows 11 pip install scikit-image I got these issues as below in the screenshot got previous issue EDIT: I installed Microsoft C++ 14 but I got another issue at the below screenshot enter image descripti...
[ "The issue is that no wheels are available for scikit-image for Python 3.11\nPython libraries can have code that is not written in Python (like C, C++, FORTRAN, Rust, ...) and in order to use those, you need to compile that code for your version of Python, your OS and CPU architecture.\nFortunately, Python offers a...
[ 3 ]
[]
[]
[ "python", "scikit_image" ]
stackoverflow_0074229470_python_scikit_image.txt
Q: Webhook listener with FastAPI raises 422 Unprocessable Entity error I have a webhook listener that uses APIRouter to desginate the route for the application on the server. The app should receive a POST request (expecting data in JSON format) and log this to the console. However, I am getting consistent redirects. ...
Webhook listener with FastAPI raises 422 Unprocessable Entity error
I have a webhook listener that uses APIRouter to desginate the route for the application on the server. The app should receive a POST request (expecting data in JSON format) and log this to the console. However, I am getting consistent redirects. I have attempted the following with curl: curl -X 'POST' \ 'http://127.0....
[ "You called your dict “data” in your curl , should be called “body”.\n", "You used data as the field name for your body, whereas in your Pydantic model you define this as body. Hence, the error about body value is not a valid dict. The requet's body should instead look like this:\n{\n \"body\": {\"UK\":\"test\"}...
[ 0, 0 ]
[]
[]
[ "fastapi", "json", "python", "webhooks" ]
stackoverflow_0074235378_fastapi_json_python_webhooks.txt
Q: converting geotiff to datarame and preserving lat/lon in columns I downloaded a geotiff from here: https://www.nass.usda.gov/Research_and_Science/Crop_Progress_Gridded_Layers/index.php (file also available: https://drive.google.com/file/d/1XcfEw-CZgVFE2NJytu4B1yBvjWydF-Tm/view?usp=sharing) Looking at one of the we...
converting geotiff to datarame and preserving lat/lon in columns
I downloaded a geotiff from here: https://www.nass.usda.gov/Research_and_Science/Crop_Progress_Gridded_Layers/index.php (file also available: https://drive.google.com/file/d/1XcfEw-CZgVFE2NJytu4B1yBvjWydF-Tm/view?usp=sharing) Looking at one of the weeks in 2021, I'd like to convert the geotiff to a data frame so I have...
[ "Credit to Jose from the GIS community:\nimport rioxarray\nimport pandas as pd\n\nda = rioxarray.open_rasterio(fl, masked=True)\nda = da.rio.reproject(\"EPSG:4326\")\ndf = da[0].to_pandas()\ndf['y'] = df.index\ndf = pd.melt(df, id_vars='y')\n\nhttps://gis.stackexchange.com/questions/443801/add-lat-and-lon-to-dataar...
[ 0 ]
[]
[]
[ "geotiff", "python", "python_xarray", "rasterio" ]
stackoverflow_0074208825_geotiff_python_python_xarray_rasterio.txt
Q: SQLAlchemy Filtering on Third Degree Relationship I'm using SQL alchemy as part of a budgeting tool with the following classes. I'm trying to filter Transactions by whether they are or not in a Budget. For that to occur a Transaction must be in a Category that has a Budget Item and the Transaction Date must fall w...
SQLAlchemy Filtering on Third Degree Relationship
I'm using SQL alchemy as part of a budgeting tool with the following classes. I'm trying to filter Transactions by whether they are or not in a Budget. For that to occur a Transaction must be in a Category that has a Budget Item and the Transaction Date must fall within the Budget's Start and End Dates associated to th...
[ "I think you can query for transactions without a budget like this:\nsession.query(Transaction).filter(Budget.is(None)).all()\n\n" ]
[ 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0074235859_python_sql_sqlalchemy.txt
Q: RoadtripView.put() missing 1 required positional argument: 'pk' I will try to explain my problem in English, because in fact I speak rather French. I have a little problem and it's been 5 hours now that I can't solve it. I wrote three functions GET, POST and PUT. the first two work well but the PUT has a problem. ...
RoadtripView.put() missing 1 required positional argument: 'pk'
I will try to explain my problem in English, because in fact I speak rather French. I have a little problem and it's been 5 hours now that I can't solve it. I wrote three functions GET, POST and PUT. the first two work well but the PUT has a problem. I am looking to update my Roadtrip table. I send you my codes # Resea...
[ "Change\n def put(self,request,id,pk,*args,**kwargs):\n\n\nto\n def put(self,request,id,*args,**kwargs): # remove pk\n\nI also suggest that you change id to pk everywhere.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074236869_python.txt
Q: Automatically generate API reference for all subpackages / modules I am using mkdocs with the mkdocstrings plugin to generate the documentation of my Python package. My package is organized in a standard fashion - setup.py - mkdocs.yaml - docs/ - mypackage/ - __init__.py - module1.py - module2.py - subpack...
Automatically generate API reference for all subpackages / modules
I am using mkdocs with the mkdocstrings plugin to generate the documentation of my Python package. My package is organized in a standard fashion - setup.py - mkdocs.yaml - docs/ - mypackage/ - __init__.py - module1.py - module2.py - subpackage1/ - __init__.py - submodule1.py - submodule2.py - [.....
[ "Ah, it's because by default submodules are not rendered. Try setting the show_submodules option to true. Globally:\nplugins:\n- mkdocstrings:\n handlers:\n python:\n options:\n show_submodules: true\n\nLocally:\n::: mypackage\n options:\n show_submodules: true\n\n" ]
[ 1 ]
[]
[]
[ "docstring", "mkdocs", "python" ]
stackoverflow_0074209148_docstring_mkdocs_python.txt
Q: How to read a specific colum value and also n - 1 from data fram I have some set of data in csv format. whereas I have to find total sale amount difference from yesterday and today sales. so could you please explain to access same in a columns date sales value diff 10-oct-22 100 0 11-oct-22 120 20 12-oct-22 10...
How to read a specific colum value and also n - 1 from data fram
I have some set of data in csv format. whereas I have to find total sale amount difference from yesterday and today sales. so could you please explain to access same in a columns date sales value diff 10-oct-22 100 0 11-oct-22 120 20 12-oct-22 105 -15 How get get date and sales value from pandas datafra...
[ "something like this (?):\nimport pandas as pd\nfrom datetime import datetime\n\ndf = pd.DataFrame({'date': [datetime(2022, 10, 10), datetime(2022, 10, 11), datetime(2022, 10, 12)], 'sales value': [100, 120, 105]})\n\ndf['diff'] = df['sales value'].diff().fillna(0)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074237028_dataframe_pandas_python.txt
Q: Python- Need to search a list for adjacent duplicate values and replace the adjacent this is an example list: mylist = [0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1] I need to search the list for adjacent 0 until no zeros are adjacent. My needed output- newlist = [0,x,1,0,1,0,x,x,1,0,x,x,x,1,0,x,x,1,0,1,0,x,1] ...
Python- Need to search a list for adjacent duplicate values and replace the adjacent
this is an example list: mylist = [0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1] I need to search the list for adjacent 0 until no zeros are adjacent. My needed output- newlist = [0,x,1,0,1,0,x,x,1,0,x,x,x,1,0,x,x,1,0,1,0,x,1] so I retain a single zero at its correct index, but replace its adjacents with "x". I am n...
[ "Zip the list together with a lagged copy of itself and use a list comprehension to produce the new list:\nnewlist = [\"x\" if a == b == 0 else b for a, b in zip([None] + mylist, mylist)]\n\nI understood from your question that you are only looking for duplicate zeroes. But if you want to replace all duplicates, ju...
[ 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074236738_list_python.txt
Q: Replace values in a string type pandas Series with lists I need to remap a column of strings with other strings, but some strings are related to more than one other string, so I need to fit multiple values in to some elements in the resulting column. I assumed I would do that with a list, so the column of strings ...
Replace values in a string type pandas Series with lists
I need to remap a column of strings with other strings, but some strings are related to more than one other string, so I need to fit multiple values in to some elements in the resulting column. I assumed I would do that with a list, so the column of strings would be converted into a column of lists of strings of length...
[ "Let's try Series.map\ndf['mapped_column'] = df['embark_town'].map(mapping)\n\n", "Use map function instead. df['embark_town'].map(mapping)\nimport seaborn as sns\n\ndf = sns.load_dataset('titanic').iloc[:5]\n\nmapping = {\n 'Southampton': ['A', 'B'],\n 'Cherbourg': ['C']\n}\n\ndf[\"embark_town\"] = df[\"em...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "pandas", "python" ]
stackoverflow_0074237175_dictionary_list_pandas_python.txt
Q: SQLAlchemy Alembic Migration generate SQL scripts at revision step with --autogenerate We use SQLAlchemy + Alembic to generate migrations as python code (default behaviour for Alembic). We want to move from python to SQL scripts as it provides more control over the generated scripts. It seems the command revision ...
SQLAlchemy Alembic Migration generate SQL scripts at revision step with --autogenerate
We use SQLAlchemy + Alembic to generate migrations as python code (default behaviour for Alembic). We want to move from python to SQL scripts as it provides more control over the generated scripts. It seems the command revision --autogenerate doesn't work with --sql option. We don't want to use updgrade --sql option as...
[ "I've not seen a way to autogenerate new migrations as SQL, but we also wanted to keep our migrations in SQL and handle it this way:\nWe store each migration as \"forward\" and \"backward\" SQL files, with a timestamp and the revision in the name (the timestamp was added simply because we prefer the revisions to be...
[ 0 ]
[]
[]
[ "alembic", "python", "sqlalchemy" ]
stackoverflow_0073644632_alembic_python_sqlalchemy.txt
Q: python function to transform list of Python dictionaries Input: [{'item': 'milk', 'inventory': 1}, {'item': 'eggs', 'inventory': 0}, \ {'item': 'bread', 'inventory': 6}, {'item': 'sugar', 'inventory': 12}] Expected Output: [{'item': 'milk', 'inventory_level': 'Low'}, {'item': 'eggs', 'inventory_level': 'None'}, \...
python function to transform list of Python dictionaries
Input: [{'item': 'milk', 'inventory': 1}, {'item': 'eggs', 'inventory': 0}, \ {'item': 'bread', 'inventory': 6}, {'item': 'sugar', 'inventory': 12}] Expected Output: [{'item': 'milk', 'inventory_level': 'Low'}, {'item': 'eggs', 'inventory_level': 'None'}, \ {'item': 'bread', 'inventory_level': 'Normal'}, {'item': 'sug...
[ "This will transform your input list of Python dictionaries. Note: there is no JSON here.\nAlso note that this is destructive. If you want non-destructive version then take a copy of your input list and work on that.\ndata = [\n {'item': 'milk', 'inventory': 1},\n {'item': 'eggs', 'inventory': 0},\n {'item...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074236656_python.txt
Q: Conditionally Set Values Greater Than 0 To 1 I have a dataframe that looks like this, with many more date columns AUTHOR 2022-07-01 2022-10-14 2022-10-15 ..... 0 Kathrine 0.0 7.0 0.0 1 Catherine 0.0 13.0 17.0...
Conditionally Set Values Greater Than 0 To 1
I have a dataframe that looks like this, with many more date columns AUTHOR 2022-07-01 2022-10-14 2022-10-15 ..... 0 Kathrine 0.0 7.0 0.0 1 Catherine 0.0 13.0 17.0 2 Amanda Jane 0.0 0.0 ...
[ "You can select the date column first then mask on these columns\ncols = df.drop(columns='AUTHOR').columns\n# or\ncols = df.filter(regex='\\d{4}-\\d{2}-\\d{2}').columns\n# or\ncols = df.select_dtypes(include='number').columns\n\ndf[cols] = df[cols].mask(df[cols] != 0, 1)\n\nprint(df)\n\n AUTHOR 2022-07-01 ...
[ 4, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074237051_pandas_python.txt
Q: Python Coding difficulty arising with while and if loop I am new to python coding and i need help with a question ,i am not able to understand where i am doing wrong, can you all please help me with it. If you help me understand this would quite helpful for me. Question is that i need to return the grades of 2 stu...
Python Coding difficulty arising with while and if loop
I am new to python coding and i need help with a question ,i am not able to understand where i am doing wrong, can you all please help me with it. If you help me understand this would quite helpful for me. Question is that i need to return the grades of 2 students by their average score, problem is that the custom inpu...
[ "you could take the sum of each list by accessing each one:\nyou can access nested lists just like lst[0], this will give you [60,20,2,30,56] then you can make a quick sum by using an already builtin function called sum().\nso you would end up like this sum(lst[0]) => 168\nand then you could also calculate the leng...
[ 1, 1, 1, 0 ]
[ " Gra=[]\n\n for grade_list in students_marks: \n total = sum(grade_list)\n number = len(grade_list) \n av = total/number\n \n if av >=90:\n Grades='A+'\n elif av >=80 and av <90:\n Grades='A'\n elif av >=70 and av <90:\n Grades='B'\n elif av >=60 and...
[ -1 ]
[ "python", "python_3.x", "python_requests" ]
stackoverflow_0063557331_python_python_3.x_python_requests.txt
Q: Pylance: unexpected type inference for a union of two list types Assume x has type list[int] | list[str], that is, it is either a list containing only ints or a list containing only strings. Then set(x) is either a set containing only ints, or a set containing only strings, so I would expect it to have the type se...
Pylance: unexpected type inference for a union of two list types
Assume x has type list[int] | list[str], that is, it is either a list containing only ints or a list containing only strings. Then set(x) is either a set containing only ints, or a set containing only strings, so I would expect it to have the type set[int] | set[str]. However, Pylance infers the type set[int | str], wh...
[ "Use a constrained generic type variable: (PEP 484)\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", str, int)\n\ndef my_set(x: list[T]) -> set[T]:\n return set(x)\n\n\na = my_set([1, 2, 3])\nb = my_set([\"x\", \"y\", \"z\"])\n\nreveal_type(a) # inferred by `mypy` as `set[int]`\nreveal_type(b) # inferred by `...
[ 3 ]
[]
[]
[ "pylance", "python", "python_3.x", "python_typing" ]
stackoverflow_0074237229_pylance_python_python_3.x_python_typing.txt
Q: How can I host the folder's content for anyone to access and have my device act as a server while it's running? I'm trying to share a folder for anyone to access while running the code by making my local machine act as a server PORT = 8000 DIRECTORY = "/content/sample_data" class Handler(http.server.SimpleHTTPRequ...
How can I host the folder's content for anyone to access and have my device act as a server while it's running?
I'm trying to share a folder for anyone to access while running the code by making my local machine act as a server PORT = 8000 DIRECTORY = "/content/sample_data" class Handler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory=DIRECTORY, **kwargs) ...
[ "Open a terminal, move to the directory that you want to give access to and run:\npython -m http.server 8000\n\nYou will have a local server running on the port 8000.\nIf you don't have a public ip address you can use ngrok to get one:\nInstall ngrok, open another terminal and run\nngrok http 8000\n\nNow anyone can...
[ 0 ]
[]
[]
[ "python", "python_3.x", "simplehttpserver", "socketserver" ]
stackoverflow_0074237243_python_python_3.x_simplehttpserver_socketserver.txt
Q: Scraping href links in Python using BeautifulSoup I am trying to scrape the links that are stored in the href values from this website: https://www.fotmob.com/teams/8676/fixtures/wycombe-wanderers?page=1 I tried the following code: url = "https://www.fotmob.com/teams/8676/fixtures/wycombe-wanderers?page=1" r = re...
Scraping href links in Python using BeautifulSoup
I am trying to scrape the links that are stored in the href values from this website: https://www.fotmob.com/teams/8676/fixtures/wycombe-wanderers?page=1 I tried the following code: url = "https://www.fotmob.com/teams/8676/fixtures/wycombe-wanderers?page=1" r = requests.get(url) html_doc = r.content soup = BeautifulSo...
[ "The required data is loaded dynamically by JavaScript that's why you are getting empty output because bs4 can't render JS but they are using API and you can extract data from API url instead.\nimport requests\n\napi_url= 'https://www.fotmob.com/api/teams?id=8676&timezone=Asia%2FDhaka&ccode3=BGD'\nheaders={\n 'u...
[ 2 ]
[]
[]
[ "beautifulsoup", "href", "python", "web_scraping" ]
stackoverflow_0074237139_beautifulsoup_href_python_web_scraping.txt
Q: BeautifulSoup find extract info to cusom-made list I have 3 different type ofhtml snippets which are part of a bigger part as follows: <html> <body> <span _ngcontent-dna-c199="" class="font-weight-bold"> <span _ngcontent-dna-c199="" class="ng-star-inserted"> <span _ngcontent-dna-c199="" translate=""> ...
BeautifulSoup find extract info to cusom-made list
I have 3 different type ofhtml snippets which are part of a bigger part as follows: <html> <body> <span _ngcontent-dna-c199="" class="font-weight-bold"> <span _ngcontent-dna-c199="" class="ng-star-inserted"> <span _ngcontent-dna-c199="" translate=""> issue_number </span> 4 Näköispainos </span>...
[ "You could search for each part individually:\ndef bs2customList(soup): \n fwb = soup.find(\"span\", class_=\"font-weight-bold\")\n\n #fdesc = [] if fwb is None else [( #(text, filter1, filter2, filter3)\n #d.get_text(strip=True), d.parent.get('class', []), d.parent.get('translate'), len(d.parent.selec...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074235245_beautifulsoup_html_python_web_scraping.txt
Q: AWS SSO - List users assigned with an aws account I have the list of all AWS accounts in my organization. I need to list the users present in each account via API. Through the documentation List account assigments, I can list only passing as parameters account + permission set. I wanted it to list all users, just ...
AWS SSO - List users assigned with an aws account
I have the list of all AWS accounts in my organization. I need to list the users present in each account via API. Through the documentation List account assigments, I can list only passing as parameters account + permission set. I wanted it to list all users, just like when I click on the account via console, as shown ...
[ "The way I managed to do it was as follows:\n\nList all organization accounts\nFor each account, list all permission sets\nWith the account id and permission set, you can list users\n\nYou need to perform this process on all accounts and group users by account. It's a little tedious but it's the only way I found.\n...
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_cli", "aws_sso", "boto3", "python" ]
stackoverflow_0074199533_amazon_web_services_aws_cli_aws_sso_boto3_python.txt
Q: OSU, Download links open beatmap page instead of downloading the beatmap file Noticed that the beatmap packages that are available officially in OSU have 98% songs I don't care for to play. Same with the unofficial mega packs you can find that have 20gigs of songs on a per year basis 2011,2012,2013,2013,etc.. I di...
OSU, Download links open beatmap page instead of downloading the beatmap file
Noticed that the beatmap packages that are available officially in OSU have 98% songs I don't care for to play. Same with the unofficial mega packs you can find that have 20gigs of songs on a per year basis 2011,2012,2013,2013,etc.. I did find that the "most favourites" page in osu: https://osu.ppy.sh/beatmapsets?sort=...
[ "def read_excel():\nimport pandas as pd\ndf = pd.read_excel('book.xlsx') # Get all the urls from the excel\nmylist = df['urls'].tolist() #urls is the column name\nprint(mylist) # will print all the urls\n\n# now loop through each url & perform actions.\nfor url in mylist:\n options = webdriver.ChromeOptions()\n ...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0071817457_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: vectorizing custom python function with numpy array Not sure if that is the correct terminology. Basically trying to take a black and white image and first transform it such that all the white pixels that border black-pixels remain white, else turn black. That part of the program works fine, and is done in find_ed...
vectorizing custom python function with numpy array
Not sure if that is the correct terminology. Basically trying to take a black and white image and first transform it such that all the white pixels that border black-pixels remain white, else turn black. That part of the program works fine, and is done in find_edges. Next I need to calculate the distance from each elem...
[ "You can use KDTree to compute distances fast.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.ndimage import binary_erosion\nfrom scipy.spatial import KDTree\n\n\ndef find_edges(img):\n img_np = np.array(img)\n\n kernel = np.ones((3,3))\n edges = img_np - binary_erosion(img_np, kernel)*...
[ 1, 0 ]
[]
[]
[ "arrays", "image_processing", "numpy", "python", "vectorization" ]
stackoverflow_0074232186_arrays_image_processing_numpy_python_vectorization.txt
Q: Evaluate an expression and do something in the same line in python Is there a way to evaluate an expression in python and break from a loop in the same time? Easiest example to explain what I have in mind: while True: if bar == 'baz': foo = bar == 'baz' break But that's programmerhorror and I ...
Evaluate an expression and do something in the same line in python
Is there a way to evaluate an expression in python and break from a loop in the same time? Easiest example to explain what I have in mind: while True: if bar == 'baz': foo = bar == 'baz' break But that's programmerhorror and I wanted to do something along the lines (maybe with lambda function?): wh...
[ "add your condition into the while clause itself:\nwhile bar != 'baz':\n # do something\n continue\n\n# now bar = 'baz'\nfoo = bar\n\n", "To extend @C.Nivs answer for the updated question where you want to have foo be a boolean than do:\nfoo = False\nwhile not foo:\n foo = bar == \"baz\"\n\nOr if you are...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074237202_python.txt
Q: Trying to use GridSearchCV returning error: Check the list of available parameters with `estimator.get_params().keys()` I'm trying to build a Voting Ensemble model, with a data transformation pipeline. I still need to put the transformation of the response variable into the pipeline. I'm trying to use GridSearchCV...
Trying to use GridSearchCV returning error: Check the list of available parameters with `estimator.get_params().keys()`
I'm trying to build a Voting Ensemble model, with a data transformation pipeline. I still need to put the transformation of the response variable into the pipeline. I'm trying to use GridSearchCV to evaluate the best parameters for each algorithm, but when I try to run the last code block, I get an error. dummy= pd.get...
[ "Always, please post the stack trace of the error for people to understand\nThere are multiple mistakes in your code,\n\nYou are creating Pipeline Object using varible_transformer, where are you fitting it?\nWhat is X and y?\n\nSolution:\n\nSeparate X-> input features needed for training and y-> the output variable...
[ 1 ]
[]
[]
[ "gridsearchcv", "pipeline", "python" ]
stackoverflow_0074227499_gridsearchcv_pipeline_python.txt
Q: How do I set Ansible python interpreter on for remote Windows host? Ansible fails to find a python interpreter on my remote Windows host. To try to avoid this problem, I want to dynamically tell Ansible where the interpreter on the remote host is. Here is the code I have tried: --- - name: My playbook hosts: all...
How do I set Ansible python interpreter on for remote Windows host?
Ansible fails to find a python interpreter on my remote Windows host. To try to avoid this problem, I want to dynamically tell Ansible where the interpreter on the remote host is. Here is the code I have tried: --- - name: My playbook hosts: all tasks: - name: Verify python installed win_shell: python --vers...
[ "I don't know if you solved this problem (I think that you can't).\nI came here with the same question and later I found this from the official Ansible documentation:\n\nCan I run Python modules on Windows hosts? No\n\n(You are reading the latest (stable) community version of the Ansible documentation.)\n\n\nSo I t...
[ 0 ]
[]
[]
[ "ansible", "python", "windows" ]
stackoverflow_0072438794_ansible_python_windows.txt
Q: How many times can you divide 24**36 by 2 until it becomes imprecise? How many times can you divide 24**36 by 2 until it becomes imprecise? I had this question on one of my quizzes in a python course, and I'm curious as to what the correct answer is. (It's already submitted so no cheating here) I wrote this small ...
How many times can you divide 24**36 by 2 until it becomes imprecise?
How many times can you divide 24**36 by 2 until it becomes imprecise? I had this question on one of my quizzes in a python course, and I'm curious as to what the correct answer is. (It's already submitted so no cheating here) I wrote this small bit of code in python to calculate how many times you can evenly divide the...
[ "Never ever use floating point arithmetics for integer values, specialy in Python! In other languages, you may have to use multiprecision library for large values, but Python integer are multiprecision integers...\nNow 24 ** 36 = (3 * 2**3) ** 36 = (3 ** 36) * (2 ** 108)\nSo you can divide it 108 times by 2, and yo...
[ 2, 1, 0 ]
[]
[]
[ "floating_point", "precision", "python" ]
stackoverflow_0074237146_floating_point_precision_python.txt
Q: How to predict next number from sequence of number with tf model.predict? Trying to make prediction of the next number but it didn't work well. I have a list of 500 numbers : [..., x, x, 3, 2, 1, 7, 2, 0, 3], i want to make prediction model with those 500 numbers to give me the possible 501 number. I tried making ...
How to predict next number from sequence of number with tf model.predict?
Trying to make prediction of the next number but it didn't work well. I have a list of 500 numbers : [..., x, x, 3, 2, 1, 7, 2, 0, 3], i want to make prediction model with those 500 numbers to give me the possible 501 number. I tried making model example with this code, it didn't go as expected with the example of 1 to...
[ "To solve this kind of problem your model should be more complicated. Relationship between input value and target value are not linear (according to the example) so current model which looks like input_value x weight + bias barely can find a good solution.\nI would suggest you to use something like this:\nmodel = t...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074216783_keras_python_tensorflow.txt
Q: Dataclass to dict when using slots If I use a regular dataclass I can get a dict with @dataclass class Cat: fur: bool meow: int Cat(True, 3).__dict__ But it doesn't work when using __slots__. What is the most efficient solution to use instead? @dataclass class Cat: __slots___ = ['fur', 'meow'] fur: b...
Dataclass to dict when using slots
If I use a regular dataclass I can get a dict with @dataclass class Cat: fur: bool meow: int Cat(True, 3).__dict__ But it doesn't work when using __slots__. What is the most efficient solution to use instead? @dataclass class Cat: __slots___ = ['fur', 'meow'] fur: bool meow: int # Doesn't work: Cat(Tr...
[ "Using python 3.10 here\nI agree with juanpa.arrivillaga. __dict__ is the actual namespace of the instance and you can use dataclasses.asdict() to create a dict and JSON string.\nHere's how you can do it:\nimport json\nfrom dataclasses import dataclass, asdict\n\n\n@dataclass\nclass Cat:\n __slots___ = ('fur', '...
[ 0, 0 ]
[]
[]
[ "dictionary", "python", "slots" ]
stackoverflow_0068218081_dictionary_python_slots.txt
Q: String Conversion of Selected Columns Based on a Condition I'm fairly new to Python and have been studying it for financial data manipulation. I have a dataframe with strings representing millions (MM) of dollars of Free Cash Flow: FCF (t) FCF (t-1) FCF (t-2) FCF (t-3) FCF (t-4) FCF (t-5) FCF (t-6) ...
String Conversion of Selected Columns Based on a Condition
I'm fairly new to Python and have been studying it for financial data manipulation. I have a dataframe with strings representing millions (MM) of dollars of Free Cash Flow: FCF (t) FCF (t-1) FCF (t-2) FCF (t-3) FCF (t-4) FCF (t-5) FCF (t-6) Total Assets LTM 1006 0 0 0 0 0 0 0 378MM 1007...
[ "Considering that your Dataframe has only values with MM and B, I created a function that first splits each element of the column \"value\" by either MM or B and takes the first element that is the number part, and saves it in another list.\nThis list now replaces the Column value entirely\ndef parse_currency(df):\...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074237393_dataframe_pandas_python.txt
Q: __init__() missing 1 error while Adding a Discrete Colorbar to a ContourPlot I was trying to replicate the Contour Plot: for a new set of interpolated data found on interpolated.nc I got the error: TypeError Traceback (most recent call last) Input In [552], in <cell line: 48>() ...
__init__() missing 1 error while Adding a Discrete Colorbar to a ContourPlot
I was trying to replicate the Contour Plot: for a new set of interpolated data found on interpolated.nc I got the error: TypeError Traceback (most recent call last) Input In [552], in <cell line: 48>() 43 plt.contourf(to_np(lons), to_np(lats), to_np(dr_nested2), 10, 44 ...
[ "Instead of\nax = plt.axes(projection=crs.PlateCarree())\n\nIt should be this;\nax = plt.axes(transform=crs.PlateCarree())\n\n" ]
[ 1 ]
[]
[]
[ "colorbar", "jupyter_notebook", "matplotlib", "python", "python_xarray" ]
stackoverflow_0074154984_colorbar_jupyter_notebook_matplotlib_python_python_xarray.txt
Q: How to align the LabelFrames to left on tkinter? I am new to tkinter and learning to organize the frames in tkinter. In the following code, I have created 3 label frames. The frames are not aligned as per my requirements and I would like to get help organizing them cleanly. Required =========== By default it gives...
How to align the LabelFrames to left on tkinter?
I am new to tkinter and learning to organize the frames in tkinter. In the following code, I have created 3 label frames. The frames are not aligned as per my requirements and I would like to get help organizing them cleanly. Required =========== By default it gives me following layout LabelFrame1 L...
[ "For greater clarity, first draw on a piece of paper what you want to place in the window. Like this:\n\nAnd you will see that you need to stretch tk.LabelFrame(f, text='Calculator') over several cells ( columnspan=3).\nimport tkinter as tk\nfrom tkinter import ttk, messagebox\n\n# variables\npadding = dict(padx=20...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074236956_python_tkinter.txt
Q: if input in list, select next item For instance, this is the list: exchange_list = ['coin', 'quarter', 'dime', 'penny', 'buck', 'bitcoin'] exchanger = input("Please give the input of a money currency that you'd like to exchange") How do I make it so that if my input for instance is 'penny' that it selects the ne...
if input in list, select next item
For instance, this is the list: exchange_list = ['coin', 'quarter', 'dime', 'penny', 'buck', 'bitcoin'] exchanger = input("Please give the input of a money currency that you'd like to exchange") How do I make it so that if my input for instance is 'penny' that it selects the next item in the list (in this case 'buck'...
[ "You can do:\nindex = (exchange_list.index(exchanger) + 1) % len(exchange_list)\n\nprint(exchange_list[index])\n\n", "exchange_list = ['coin', 'quarter', 'dime', 'penny', 'buck', 'bitcoin']\n\nexchanger = str(input(\"Please give the input of a money currency that you'd like to exchange: \"))\nfoo = exchange_list....
[ 0, 0, 0, 0 ]
[]
[]
[ "cycle", "input", "list", "next", "python" ]
stackoverflow_0074237407_cycle_input_list_next_python.txt
Q: Importing methods from built-in class for use in custom class - Python I created a class with extended methods for the built-in 'str' class, but I want the user to be able to use those normal built-in methods for strings as well as my extra methods. How would I do this without having to manually code each method a...
Importing methods from built-in class for use in custom class - Python
I created a class with extended methods for the built-in 'str' class, but I want the user to be able to use those normal built-in methods for strings as well as my extra methods. How would I do this without having to manually code each method already in the 'str' class? class StringMethods: """ StringMethods cl...
[ "Here is a class that inherits from str() and is extended with your functions.\nclass StringMethod(str):\n\"\"\"\nStringMethods class:\n\nA class inheriting from the built in python str class\nbut with extended methods for string analysis, password checking etc.\n\"\"\"\n\ndef contains(self, char: str) -> bool:\n ...
[ 2 ]
[]
[]
[ "class", "methods", "python", "string" ]
stackoverflow_0074237043_class_methods_python_string.txt
Q: Python logging to stdout and log file I am fairly new in python and starting to get into the logging module. I would like to have the message logged into a log file and outputting to the console. The code below prints out the message to console but how can I get all the message to be log in a file? Logger object d...
Python logging to stdout and log file
I am fairly new in python and starting to get into the logging module. I would like to have the message logged into a log file and outputting to the console. The code below prints out the message to console but how can I get all the message to be log in a file? Logger object does not have a function call (basicConfig(f...
[ "You just need to add another handler, like a logging.FileHandler\nfh = logging.FileHandler(r'/path/to/log.txt')\nlogger.addHandler(fh)\n\n", "Expanding on @Brendan's answer.\nYour logger currently outputs to the console using a StreamHandler.\nBy adding a FileHandler, you can log to a file.\nEach handler instanc...
[ 20, 10, 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0040858658_logging_python.txt
Q: How to edit data in a CSV file? I'm trying to change someone's name in a Pandas data frame. I've tried using this code, but it just adds to the current name: def rename(self): id = '1' person = (df.loc[df['id'] == id]) print(person) newName = 'tom' df.loc[df['id'] == id, ['name']] = df['name'] ...
How to edit data in a CSV file?
I'm trying to change someone's name in a Pandas data frame. I've tried using this code, but it just adds to the current name: def rename(self): id = '1' person = (df.loc[df['id'] == id]) print(person) newName = 'tom' df.loc[df['id'] == id, ['name']] = df['name'] - df['name'] + newName Input: id na...
[ "Hi this is an if statement in pandas\nyou can use either:\ndf.loc[df.id == 1, 'name'] = 'tom'\n\nor,\ndf.loc[df.name == 'bob', 'name'] = 'tom'\n\nor,\ndf.loc[(df.id == 1) & (df.name == 'bob'), 'name'] = 'tom'\n\nyou can also try to make a dictionary:\nname_change = {'old_name':'new_name'}\ndf['name'] = df.name.rep...
[ 2, 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074237600_csv_dataframe_pandas_python.txt
Q: How to do OCR for multi page using (Python + AWS Textract + Lambda) I used the code (python + AWS textract + lambda) below and The OCR success to get response for the pdf with one page But when I test with more than one page pdf it doesn't work need advice to OCR for multipage pdf client = boto3.client("textra...
How to do OCR for multi page using (Python + AWS Textract + Lambda)
I used the code (python + AWS textract + lambda) below and The OCR success to get response for the pdf with one page But when I test with more than one page pdf it doesn't work need advice to OCR for multipage pdf client = boto3.client("textract") response = client.analyze_document( Document={ ...
[ "Multipage PDFs are only supported by the asynchronous API. So you need to use\nclient.start_document_analysis which will return a job id that you can use to fetch the results \"later\". You can pass an SNS topic which will be triggered once the processing is over allowing for a workflow like:\nCall Amazon Textract...
[ 1 ]
[]
[]
[ "amazon_textract", "amazon_web_services", "aws_lambda", "boto3", "python" ]
stackoverflow_0074218500_amazon_textract_amazon_web_services_aws_lambda_boto3_python.txt
Q: cartopy: Why isn't my circle moving along the great circle path? I'm having trouble using cartopy ... I have some locations (mainly changing in lat) and I want to draw some circles along the this great circle path. Here's the code import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy import ...
cartopy: Why isn't my circle moving along the great circle path?
I'm having trouble using cartopy ... I have some locations (mainly changing in lat) and I want to draw some circles along the this great circle path. Here's the code import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy import numpy as np import matplotlib.pyplot as plt import matplotlib.patches...
[ "Thanks for rewriting the example, that clears things up!\nI think the key point is that you need to convert the x/y coordinates that you use for the Circle as well, or vice versa keep the radius also in lat/lon (probably close but not identical). Now you mix and match, where the radius is based on the Orthographic...
[ 1, 0 ]
[]
[]
[ "cartopy", "matplotlib", "python" ]
stackoverflow_0074196575_cartopy_matplotlib_python.txt
Q: How to manually specify HEX colors in categorial scatter plot using Plotly express? I am trying to change the colors to my scatter plot using hex codes. I need to assign the following hex color codes to my 3 categories: "#581D74", "#4BA8B6" and "A7C673" This is the code i have used: For now I used a discrete palle...
How to manually specify HEX colors in categorial scatter plot using Plotly express?
I am trying to change the colors to my scatter plot using hex codes. I need to assign the following hex color codes to my 3 categories: "#581D74", "#4BA8B6" and "A7C673" This is the code i have used: For now I used a discrete pallette available on Plotly express fig9 = px.scatter(df, x="ApplicantIncome", y="LoanAmount"...
[ "Use the hex color codes in a list as follows:\nimport pandas as pd\nimport plotly.express as px\n\ndf = px.data.gapminder().query(\"year == 2007\")\n\nfig = px.bar(df, y=\"continent\", x=\"pop\", color=\"continent\", orientation=\"h\", hover_name=\"country\",\n color_discrete_sequence=[\"#581D74\", \"#...
[ 0 ]
[]
[]
[ "hex", "plotly", "python", "scatter_plot" ]
stackoverflow_0074233532_hex_plotly_python_scatter_plot.txt
Q: Invalid hex encoding in query string im currently working on a DJango search with multiple query_params, since im using Sentry i found out that sometimes there's an issue triggered when you search for example something with percentages: "100% natural" "100% unique" "50% blah blah blah" Sentry: Unhandled Invalid h...
Invalid hex encoding in query string
im currently working on a DJango search with multiple query_params, since im using Sentry i found out that sometimes there's an issue triggered when you search for example something with percentages: "100% natural" "100% unique" "50% blah blah blah" Sentry: Unhandled Invalid hex encoding in query string. This is mark...
[ "There is a function for url decoding your data. space is not the only possible encoded chars...\nfrom urllib.parse import unquote\n\nquery = request.query_params.get(\"query\")\nquery = unquote(query) if query else None\n\n\n" ]
[ 0 ]
[]
[]
[ "django", "parameters", "python", "search" ]
stackoverflow_0074237649_django_parameters_python_search.txt
Q: What does conda do when "solving environment" Whenever I run conda install/remove/update <package>, it tells me it's "Solving environment" for some time before telling me the list of things it's going to download/install/update. Presumably it's looking for dependencies for <package>, but why does it sometimes remo...
What does conda do when "solving environment"
Whenever I run conda install/remove/update <package>, it tells me it's "Solving environment" for some time before telling me the list of things it's going to download/install/update. Presumably it's looking for dependencies for <package>, but why does it sometimes remove packages after doing this operation? For example...
[ "You can add --debug option to the conda command and see the output from console(or terminal). For example, type conda update --debug numpy.\nFrom the output, we can see that the client requests repodata.json from channel list and do some computation locally in the Solving Environment Step.\n", "As a side note on...
[ 54, 9, 4, 2, 2 ]
[]
[]
[ "anaconda", "conda", "package_managers", "python", "updates" ]
stackoverflow_0051753988_anaconda_conda_package_managers_python_updates.txt
Q: Why does plot of RFECV grid scores split into 5 lines? I'm trying to plot the CV score for recursive feature selection for a wine quality data set. I can't work out why my plot ends up splitting out into 5 lines... My expectation is that it will be 1 line showing the change in CV score for a number of selected fea...
Why does plot of RFECV grid scores split into 5 lines?
I'm trying to plot the CV score for recursive feature selection for a wine quality data set. I can't work out why my plot ends up splitting out into 5 lines... My expectation is that it will be 1 line showing the change in CV score for a number of selected features. rfe.grid_scores_ comes out as a list of lists... I've...
[ "The reason why your plot splits into 5 lines is because your target variable, y, has 5 distinct values: 3, 4, 5, 6, and 7. These are the quality ratings of the wine. When you use RepeatedStratifiedKFold as your cross-validation strategy, it preserves the proportion of each class in each fold. This means that each ...
[ 0, 0 ]
[]
[]
[ "feature_selection", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0074236324_feature_selection_machine_learning_python_scikit_learn.txt
Q: Django-Extra-Views: Inlines child model gets author none. How do I set it the same as the parent? I have been spinning my wheels on this issue for a day or two. I have django web application that has 3 models users/models.py: from django.db import models from django.db.models.signals import post_save from django....
Django-Extra-Views: Inlines child model gets author none. How do I set it the same as the parent?
I have been spinning my wheels on this issue for a day or two. I have django web application that has 3 models users/models.py: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User # Create your models here. class ...
[ "Welp, I've looked at the source code and tried to figure it out.. It's really abstract and a lot of inheritance\nThis would be my best guess:\n def forms_valid(self, form, inlines):\n user = ExtendedUser.objects.get(user=self.request.user)\n form.instance.customerauthor = user\n for i in inl...
[ 0 ]
[]
[]
[ "django", "django_class_based_views", "python" ]
stackoverflow_0074112378_django_django_class_based_views_python.txt
Q: Tweepy authentication failed Tweepy API Request to twitter return me Twitter error response: status code=401. This is my actual code: def func(): tweets = list(tweepy.Cursor( api.search, "{0}".format("COVID-19"), lang="en",tweet_mode='extended', count=5).items(7)) Tweet_outpt = [] for i in twee...
Tweepy authentication failed
Tweepy API Request to twitter return me Twitter error response: status code=401. This is my actual code: def func(): tweets = list(tweepy.Cursor( api.search, "{0}".format("COVID-19"), lang="en",tweet_mode='extended', count=5).items(7)) Tweet_outpt = [] for i in tweets: text = i.full_text ...
[ "Code 401 is an authentication error, please make sure you're using the correct tokens.\nTweepy uses different syntax depending on if you're using Twitter's API V1 or V2.\nIf you're using V2 use the bearer token to set up your Client object.\nclient = tweepy.Client(bearer_token=(\"token\"))\n\njust replacing the \"...
[ 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0074237772_python_tweepy_twitter.txt
Q: How to get current time in a specific timezone? I am using the datetime module as follows to get the current time: datetime.now().strftime('%I:%M:%S %p') And this gives me the current time but in UTC. How can I get the current time in CST ? Can I do that without using other external libraries or is it easier to...
How to get current time in a specific timezone?
I am using the datetime module as follows to get the current time: datetime.now().strftime('%I:%M:%S %p') And this gives me the current time but in UTC. How can I get the current time in CST ? Can I do that without using other external libraries or is it easier to use something else? Any help is appreciated!
[ "It might be tricky without an external library, so i suggest you use the pytz package\npip install pytz\n\nAnd with help from here you could try something like below\nfrom datetime import datetime\nfrom pytz import timezone\n\nnow_time = datetime.now(timezone('America/Chicago'))\nprint(now_time.strftime('%I:%M:%S ...
[ 3, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0053747385_python_python_3.x.txt
Q: printing list object with appended element not works - python I have written a code to get list from tuple and append a number to it. I have read other posts about this, and know that list.append returns None, and None would be printed. But in my code, how can I append the new value? Thank you. from itertools impo...
printing list object with appended element not works - python
I have written a code to get list from tuple and append a number to it. I have read other posts about this, and know that list.append returns None, and None would be printed. But in my code, how can I append the new value? Thank you. from itertools import combinations steps = [1,2,3,4,5,6,7,8] for i in range(7, 8): ...
[ "As you said in your question you know that list.append() returns None, therefore you are currently setting tmp_subset to the value returned by append(). So all you need to do is separate your line tmp_subset = list(subset).append(1) into:\ntmp_subset = list(subset)\ntmp_subset.append(1)\n\n", "Don't use append i...
[ 1, 0 ]
[]
[]
[ "append", "list", "python", "python_3.x", "tuples" ]
stackoverflow_0074237800_append_list_python_python_3.x_tuples.txt
Q: Trying to implement a linear search on an ordered array for a specific number(n) but return statement keeps returning nothing I am trying to perform a linear search on an ordered array for a specific number. If the number is found, the algorithm must return its index. If we reach an element that is greater than th...
Trying to implement a linear search on an ordered array for a specific number(n) but return statement keeps returning nothing
I am trying to perform a linear search on an ordered array for a specific number. If the number is found, the algorithm must return its index. If we reach an element that is greater than the number, the algorithm should break. Lastly, if the number is not in the array print None. When I run the code, it returns no outp...
[ "A couple things:\n\nYou should be checking if array[el] == number\nreturn None outside of the IF statement, otherwise it will return None when el == 0\n\n", "I hope this code helps you out!\n def LinearSearch(array, n, k):\n for j in range(0,n):\n if (array[j] == k):\n return j\n retur...
[ 0, 0 ]
[ "def linear_search(array, number):\n for el in range(len(array)):\n if array[el] == number:\n return el\n return None\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0074237685_python.txt
Q: Is there a way to draw borders around a figure in Plotly? I have the following bar chart. I would like to put it around a border. Does anyone know how to do it? data = {'Programming Languages': ['Python', 'C#', 'Java', 'Ruby', 'C++', 'C', 'JavaScript', 'PHP', 'TypeScript', 'Haskell', 'Closure'...
Is there a way to draw borders around a figure in Plotly?
I have the following bar chart. I would like to put it around a border. Does anyone know how to do it? data = {'Programming Languages': ['Python', 'C#', 'Java', 'Ruby', 'C++', 'C', 'JavaScript', 'PHP', 'TypeScript', 'Haskell', 'Closure', 'Kotlin'], 'Responses': [12,11,10,5,3,2,2,1,1,1,1,1]}...
[ "fig.update_xaxes(showline=True,\n linewidth=1,\n linecolor='black',\n mirror=True)\n\nfig.update_yaxes(showline=True,\n linewidth=1,\n linecolor='black',\n mirror=True)\n\nfig.show()\n\n\n" ]
[ 1 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074237517_plotly_python.txt
Q: How to navigate through FastAPI routes by clicking on HTML button in Jinja2 Templates? I have a FastAPI app with some routes working fine if I move around them manually (by changing the /<path> in the browser's address bar). For example, this is one of them: @task.get('/tasks', response_model=list[Task], tags=["Ta...
How to navigate through FastAPI routes by clicking on HTML button in Jinja2 Templates?
I have a FastAPI app with some routes working fine if I move around them manually (by changing the /<path> in the browser's address bar). For example, this is one of them: @task.get('/tasks', response_model=list[Task], tags=["Tasks"]) def find_all_tasks(): print("\n[*] Showing all Tasks\n") return tasksEntity(c...
[ "Frontend\nYou can use the url_for() function, for example:\n<a href=\"{{ url_for('find_all_tasks') }}\">Click me</a>\n\nor\n<button onclick=\"location.href='{{ url_for('find_all_tasks') }}';\">Click me</button>\n\nor\n<input type=\"button\" onclick=\"location.href='{{ url_for('find_all_tasks') }}';\" value=\"Click...
[ 1, 0 ]
[]
[]
[ "fastapi", "html", "jinja2", "python", "starlette" ]
stackoverflow_0074237542_fastapi_html_jinja2_python_starlette.txt
Q: pandas to_numeric(…, downcast='float') losing precision Downcasting pandas dataframe (by columns) from float64 to float32 results in losing precision even though largest(9.761140e+02) and smallest (0.000000e+00) element is suitable for float32. Dataset is pretty large, 55 million rows times 12 columns. This is the...
pandas to_numeric(…, downcast='float') losing precision
Downcasting pandas dataframe (by columns) from float64 to float32 results in losing precision even though largest(9.761140e+02) and smallest (0.000000e+00) element is suitable for float32. Dataset is pretty large, 55 million rows times 12 columns. This is the mean of the particular column without downcasting (1.343987e...
[ "This was a pretty interesting question. I tested several dataframes starting from 1 million records to 55 million, the same size as yours, keeping min, max value similar to the ones you have.\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx, y = [], []\nfor idx, num in enumerate(range...
[ 4, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "precision", "python" ]
stackoverflow_0061309590_dataframe_numpy_pandas_precision_python.txt
Q: Python: convert my_list = [ '[2,2]', '[0,3]' ] to my_list = [ [2,2], [0,3] ] I have the following list: my_list = [ '[2,2]', '[0,3]' ] I want to convert it into my_list = [ [2,2], [0,3] ] Is there any easy way to do this in Python? A: my_list = [eval(x) for x in my_list] But beware: eval() is a potentially da...
Python: convert my_list = [ '[2,2]', '[0,3]' ] to my_list = [ [2,2], [0,3] ]
I have the following list: my_list = [ '[2,2]', '[0,3]' ] I want to convert it into my_list = [ [2,2], [0,3] ] Is there any easy way to do this in Python?
[ "my_list = [eval(x) for x in my_list]\n\nBut beware: eval() is a potentially dangerous function, always validate its input.\n", "You can use ast.literal_eval.\nimport ast\nmy_list = [ '[2,2]', '[0,3]' ]\nres = list(map(ast.literal_eval, my_list))\nprint(res)\n\nOutput:\n[[2, 2], [0, 3]]\n\nYou can read these:\n\n...
[ 1, 1, 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074237967_list_python_python_3.x.txt
Q: Django Rest Framework: allow a serializer field to be created, but not edited Right now, DRF's read_only argument on a Serializer constructor means you can neither create nor update the field, while the write_only argument on a Serializer constructor allows the field to be created OR updated, but prevents the fiel...
Django Rest Framework: allow a serializer field to be created, but not edited
Right now, DRF's read_only argument on a Serializer constructor means you can neither create nor update the field, while the write_only argument on a Serializer constructor allows the field to be created OR updated, but prevents the field from being output when serializing the representation. Is there any (elegant) way...
[ "class TodoModifySerializer(ModelSerializer):\n\n def to_internal_value(self, data):\n data = super(TodoModifySerializer, self).to_internal_value(data)\n if self.instance:\n # update\n for x in self.create_only_fields:\n data.pop(x)\n return data\n\n c...
[ 7, 3, 1, 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0053028241_django_django_rest_framework_python_python_3.x.txt
Q: How to print a variable into selenium find_element? into the text area how can i print a variable into the find_element? i want to put my storaged info on the text camp of my chrome, but i can't link the find_element with my variable "rota1" from PyQt5 import QtCore, QtGui, QtWidgets import sys import selenium...
How to print a variable into selenium find_element? into the text area
how can i print a variable into the find_element? i want to put my storaged info on the text camp of my chrome, but i can't link the find_element with my variable "rota1" from PyQt5 import QtCore, QtGui, QtWidgets import sys import selenium from selenium import webdriver from webdriver_manager.chrome import ChromeD...
[ "You can pass those variables into function declaration and use it in the 'send_keys':\ndef clicked(var_1, var_2):\n \n servico = Service(ChromeDriverManager().install())\n navegador = webdriver.Chrome(service=servico)\n navegador.get(\"https://www.google.com.br/maps/dir/...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074237802_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: In python, how can i get the multiplication of array elements using recursion? I want to get the multiplication of array elements using recursion. arr is array, and n is length of the array. if arr=[1, 2, 3], n=3, answer is 6. I tried this, but error occurred. def multiply(arr, n): if n == 0: return ar...
In python, how can i get the multiplication of array elements using recursion?
I want to get the multiplication of array elements using recursion. arr is array, and n is length of the array. if arr=[1, 2, 3], n=3, answer is 6. I tried this, but error occurred. def multiply(arr, n): if n == 0: return arr else: return arr[n] * \ multyply(arr[n - 1]) please he...
[ "You should implement it like this\ndef mul(arr):\n if not arr:\n return 1\n return arr[0] * mul(arr[1:])\n\n", "Your approach is close. Try change n to count up and the exit condition to check when n exceeds the length of arr -\ndef multiply(arr, n = 0):\n if n >= len(arr):\n return 1\n else:\n...
[ 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074234528_python_recursion.txt
Q: Reading .txt file into pandas with empty entries in several columns I am trying to parse the txt file into readable pandas format. See this sample .txt file. Arsenal 123 UK Barcelona 456 Marc-Andre Ter Stegen ES Chelsea 789 Ceasr Azpilicueta UK from this .txt ...
Reading .txt file into pandas with empty entries in several columns
I am trying to parse the txt file into readable pandas format. See this sample .txt file. Arsenal 123 UK Barcelona 456 Marc-Andre Ter Stegen ES Chelsea 789 Ceasr Azpilicueta UK from this .txt file, the file clearly stated three columns despite a name is missing in ...
[ "you can use read_fwf (fix width format) to read in the file\n# to read in a dataframe\ndf=pd.read_fwf(r'csv2.txt', header=None) \ndf\n\n 0 1 2 3\n0 Arsenal 123 NaN UK\n1 Barcelona 456 Marc-Andre Ter Stegen ES\n2 Chelsea 789 ...
[ 1 ]
[]
[]
[ "pandas", "python", "split", "txt" ]
stackoverflow_0074238024_pandas_python_split_txt.txt
Q: Getting out of a while loop using input i am preparing a function to user to guess a random number generated by computer. The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number. In the end the, the user should be asked if he wants to play again or not. Ev...
Getting out of a while loop using input
i am preparing a function to user to guess a random number generated by computer. The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number. In the end the, the user should be asked if he wants to play again or not. Everything is working excepts this last part, b...
[ "The condition evaluation is always True, hence you get into the loop again.\nwhile playagain not in ['y', 'n']:\n ...\n\nwould satisfy your input check\nAlso, your continue/break condition is only evaluated if the while loop condition is met (i.e., the input was not correct)\n", "It looks like you are continui...
[ 0, 0 ]
[]
[]
[ "input", "python", "while_loop" ]
stackoverflow_0074238014_input_python_while_loop.txt
Q: Algorithm Improvement: Calculate signed change in heading I am trying to implement an algorithm to calculate the signed change in direction between two vectors. Here, I define the signed change in heading to be the smallest angle that needs to be added or subtracted from the angle of a given vector to meet the ang...
Algorithm Improvement: Calculate signed change in heading
I am trying to implement an algorithm to calculate the signed change in direction between two vectors. Here, I define the signed change in heading to be the smallest angle that needs to be added or subtracted from the angle of a given vector to meet the angle of another vector. I have a naive implementation, but I was...
[ "I would use atan2(Ax * By - Ay * Bx, Ax * Bx + Ay * By).\n" ]
[ 1 ]
[]
[]
[ "algorithm", "geometry", "python" ]
stackoverflow_0074238136_algorithm_geometry_python.txt
Q: calculating Gini coefficient in Python/numpy i'm calculating Gini coefficient (similar to: Python - Gini coefficient calculation using Numpy) but i get an odd result. for a uniform distribution sampled from np.random.rand(), the Gini coefficient is 0.3 but I would have expected it to be close to 0 (perfect equalit...
calculating Gini coefficient in Python/numpy
i'm calculating Gini coefficient (similar to: Python - Gini coefficient calculation using Numpy) but i get an odd result. for a uniform distribution sampled from np.random.rand(), the Gini coefficient is 0.3 but I would have expected it to be close to 0 (perfect equality). what is going wrong here? def G(v): bins =...
[ "This is to be expected. A random sample from a uniform distribution does not result in uniform values (i.e. values that are all relatively close to each other). With a little calculus, it can be shown that the expected value (in the statistical sense) of the Gini coefficient of a sample from the uniform distribu...
[ 36, 16, 6, 2, 1, 1, 0 ]
[]
[]
[ "numpy", "python", "statistics" ]
stackoverflow_0039512260_numpy_python_statistics.txt
Q: Converting Python Speech Recognition Audio Frame data to a numpy array that can be processed by Whisper? I'm using the speech recognition Python library to record audio bytes from my microphone in mono at 16khz but I want to use the new Whisper library that accepts NumPy arrays, spectrograms, and file paths. Writi...
Converting Python Speech Recognition Audio Frame data to a numpy array that can be processed by Whisper?
I'm using the speech recognition Python library to record audio bytes from my microphone in mono at 16khz but I want to use the new Whisper library that accepts NumPy arrays, spectrograms, and file paths. Writing to a file takes too long so I'd like to directly convert the data to an array to pass it to Whisper.
[ "try librosa library\nlibrosa.load(path, *, sr=22050, mono=True, offset=0.0, duration=None, dtype=<class 'numpy.float32'>, res_type='soxr_hq')\n\nlink\nlibrosa load function\n", "Here is a solution to your problem:\nAssuming your code goes like\nwith sr.Microphone(device_index=device_index, sample_rate=16000) as ...
[ 0, 0 ]
[]
[]
[ "audio", "openai_whisper", "python", "speech_recognition" ]
stackoverflow_0073981594_audio_openai_whisper_python_speech_recognition.txt
Q: loop + slice/split np array and store to another array i am basically new to python and tried my first selenium project. I've learned a lot through this board, but i can't find a solution for my current problem. I got an array from reading an excel sheet that looks like this: order number customer name custom...
loop + slice/split np array and store to another array
i am basically new to python and tried my first selenium project. I've learned a lot through this board, but i can't find a solution for my current problem. I got an array from reading an excel sheet that looks like this: order number customer name customer no. article 48000100 supplierx 1 articl...
[ "You could use some pandas groupby to solve this issue.\narr = np.array([[\"48000100\",\"48000101\",\"48000101\",\"48000102\"],\n [\"supplierx\",\"suppliery\",\"suppliery\",\"supplierz\"],\n [\"1\",\"2\",\"2\",\"3\"],\n [\"article1\", \"article2\", \"article3\", \"art...
[ 0 ]
[]
[]
[ "arrays", "loops", "python" ]
stackoverflow_0074236149_arrays_loops_python.txt
Q: About Microsoft turning off IMAP protocol communication. When I use imaplib in python I get this error: b'LOGIN failed' My sample code block; import imaplib try: userName = "test@abc.com" passwd = "***" SMTP = "outlook.office365.com" Port = "993" imapSession = imaplib.IMAP4_SSL(SMTP, Port) ...
About Microsoft turning off IMAP protocol communication. When I use imaplib in python I get this error: b'LOGIN failed'
My sample code block; import imaplib try: userName = "test@abc.com" passwd = "***" SMTP = "outlook.office365.com" Port = "993" imapSession = imaplib.IMAP4_SSL(SMTP, Port) imapSession.login(userName, passwd) except Exception as e: print(e) Return: error: b'LOGIN failed.' I'm sure my email...
[ "They are not shгtting down IMAP4. They are disabling Basic Authentication - you need to use OAuth.\nSee https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth\n" ]
[ 0 ]
[]
[]
[ "authentication", "imaplib", "outlook", "python" ]
stackoverflow_0074234660_authentication_imaplib_outlook_python.txt
Q: How to center plots in matplotlib and put a photo in it? I've two frames as you can see on the picture. I want to automatically center this two figures and put in a photo. But I failed in the first part. My code is: fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows = 2, ncols = 2) # Axes 1 ax1 = plt.subplot2grid((...
How to center plots in matplotlib and put a photo in it?
I've two frames as you can see on the picture. I want to automatically center this two figures and put in a photo. But I failed in the first part. My code is: fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows = 2, ncols = 2) # Axes 1 ax1 = plt.subplot2grid((3, 3), (0, 0)) #ax1.set_title[['[0,0]'] # Axes 2 ax2 = plt.s...
[ "Assuming that you don't want the ratio of the displayed length of x- and y-axes of the subplots in the first row of the figure to change, we can use plt.subplot to get the expected result by creating a finer resolution of row by having more columns accessible to plot a particular subplot:\nimport matplotlib.pyplot...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074236819_matplotlib_python.txt
Q: Plot line-chart with vertical histogram for each timestep I am trying to plot a line chart that shows the mean value for each point in time in a dataset (say you observe 100 datapoints for each day and plot the mean for each day) - this part is easy. What I cannot figure out to do is how to add the distribution of...
Plot line-chart with vertical histogram for each timestep
I am trying to plot a line chart that shows the mean value for each point in time in a dataset (say you observe 100 datapoints for each day and plot the mean for each day) - this part is easy. What I cannot figure out to do is how to add the distribution of observed values as a vertical histogram for each timestep. Bec...
[ "I'm not really sure what you're going for, but is something like this what you're after? Of course something isn't correct about the placement of the curves, but perhaps it's close-ish to what you want.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import gaussian_kde\n\nx = np.random.rand...
[ 1 ]
[]
[]
[ "distribution", "matplotlib", "python", "seaborn" ]
stackoverflow_0074237418_distribution_matplotlib_python_seaborn.txt
Q: New mamba environment force torch CPU and I don't know why When creating a new mamba (conda) environment, I only get Pytorch's CPU package. Does anyone know how to ensure/force the GPU version? Even if, the first thing I installed is cudatoolkit it keeps getting the CPU package. I tried with version 11.6 and 11.3,...
New mamba environment force torch CPU and I don't know why
When creating a new mamba (conda) environment, I only get Pytorch's CPU package. Does anyone know how to ensure/force the GPU version? Even if, the first thing I installed is cudatoolkit it keeps getting the CPU package. I tried with version 11.6 and 11.3, nothing changed. This is the command I used: mamba install pyto...
[ "The command you use is the one officially recommended by PyTorch documentation.\nFailure seems to be down to a new version of Pytorch (1.13) having appeared on conda-forge recently and the GPU version seems to have some dependency problems (https://anaconda.org/pytorch/pytorch/files).\nUnfortunately, there does no...
[ 1 ]
[]
[]
[ "conda", "gpu", "mamba", "python", "pytorch" ]
stackoverflow_0074234628_conda_gpu_mamba_python_pytorch.txt
Q: How to map a list of elements to a Dataframe I have a list of locations, extracted from geocoders. I want to map these locations to their respective Postal codes in DataFrame. location = ['country', 'city', 'state', 'postal-code'] My data frame looks like this: ID postal code 1 1111 2 2222 3 ...
How to map a list of elements to a Dataframe
I have a list of locations, extracted from geocoders. I want to map these locations to their respective Postal codes in DataFrame. location = ['country', 'city', 'state', 'postal-code'] My data frame looks like this: ID postal code 1 1111 2 2222 3 3333 4 4444 5 5555 I want something ...
[ "Try df apply() method like this:\ndf[['country', 'city', 'state', 'postal-code']] = df['postal code'].astype(str).apply(lambda x: pd.Series([x[0], x[1], x[2], x[3]]))\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074236525_dataframe_pandas_python_python_3.x.txt
Q: How to fix a nextcord.errors.ApplicationInvokeError I am investigating why I am getting this error with my Python Discord bot. I'm using Python in VScode with the Nextcord library. It works a bit and them throws this error: Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object ...
How to fix a nextcord.errors.ApplicationInvokeError
I am investigating why I am getting this error with my Python Discord bot. I'm using Python in VScode with the Nextcord library. It works a bit and them throws this error: Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x000002379C4C7730>: Traceback (most recent call last)...
[ "\"Unknown interaction\" pretty much always means you are taking too long to respond.\nDiscord allows 3 seconds to respond. If you want to extend that, you can use await interaction.response.defer() at the beginning of the function to show \"bot is thinking\" for up to 15 minutes to allow you time to respond.\nSee ...
[ 0 ]
[]
[]
[ "bots", "discord", "nextcord", "python" ]
stackoverflow_0074214588_bots_discord_nextcord_python.txt
Q: Alternative to passing Greater Than sign as an argument My function : def check(list,num): check if there is list[x] > list[0]+num # in case num is positive OR if there is list[x] < list[0]+num # in case num is negative So I can send 50 to check if we are up 50, or -50 to check if we are down 50. The only ...
Alternative to passing Greater Than sign as an argument
My function : def check(list,num): check if there is list[x] > list[0]+num # in case num is positive OR if there is list[x] < list[0]+num # in case num is negative So I can send 50 to check if we are up 50, or -50 to check if we are down 50. The only way I see to do this is ugly : for x in list: if num > ...
[ "If you are trying to pass the comparison function as an argument you can use the operator module\nimport operator\noperator.lt # <\noperator.gt # >\noperator.le # <=\noperator.ge # >=\n\nIn your case you could refactor to\ndef function(comparison):\n for x in values:\n if comparison(num, 0) and compari...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074237591_python.txt
Q: One liner to restructure/nest a dictionary I'm wondering if in Python3 there is a one liner that can turn: in_dict = { ("ID1", "TEXT_A"): "TIMESTAMP_X", ("ID1", "TEXT_B"): "TIMESTAMP_Y", ("ID2", "TEXT_C"): "TIMESTAMP_X", ("ID3", "TEXT_E"): "TIMESTAMP_Y", } into out_dict = { "ID1": [ {"...
One liner to restructure/nest a dictionary
I'm wondering if in Python3 there is a one liner that can turn: in_dict = { ("ID1", "TEXT_A"): "TIMESTAMP_X", ("ID1", "TEXT_B"): "TIMESTAMP_Y", ("ID2", "TEXT_C"): "TIMESTAMP_X", ("ID3", "TEXT_E"): "TIMESTAMP_Y", } into out_dict = { "ID1": [ {"TEXT_A": "TIMESTAMP_X"}, {"TEXT_B": "TI...
[ "One way of doing this is using groupby if keys of dictionary are in sorted manner as in your case\nfrom itertools import groupby\nin_dict = {\n (\"ID1\", \"TEXT_A\"): \"TIMESTAMP_X\",\n (\"ID1\", \"TEXT_B\"): \"TIMESTAMP_Y\",\n (\"ID2\", \"TEXT_C\"): \"TIMESTAMP_X\",\n (\"ID3\", \"TEXT_E\"): \"TIMESTAM...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074195968_python_python_3.x.txt
Q: hiding secret key in django project on github after uploading project I uploaded my django project on github and I have a lot of commits on my project. I don't want to delete my project and reupload it again. what is the easiest way to hide secret key after uploading project to github and after a lot of commits? ...
hiding secret key in django project on github after uploading project
I uploaded my django project on github and I have a lot of commits on my project. I don't want to delete my project and reupload it again. what is the easiest way to hide secret key after uploading project to github and after a lot of commits?
[ "In the same directory where manage.py is, create a file whose name is .env, and put inside it:\nSECRET_KEY = '....your secret key ....' # --- the one indicated in your settings.py, cut an paste it here\n\nwhere SECRET_KEY = '....your secret key ....' is the one indicated in your settings.py. So cut this line from ...
[ 29, 1 ]
[]
[]
[ "django", "github", "python", "secret_key" ]
stackoverflow_0064208678_django_github_python_secret_key.txt
Q: Functional programming in Python Functional programming is one of the programming paradigms in Python. It treats computation as the evaluation of mathematical functions and avoids state and mutable data. I am trying to understand how Python incorporates functional programming. Consider the following factorial prog...
Functional programming in Python
Functional programming is one of the programming paradigms in Python. It treats computation as the evaluation of mathematical functions and avoids state and mutable data. I am trying to understand how Python incorporates functional programming. Consider the following factorial program (factorial.py): def factorial(n, t...
[ "The example is correct for functional programming. And a good example of what not to do in Python because it is inefficient and doesn't scale. Python doesn't have any tail-call optimisation, so recursive calls should not be used solely to avoid imperative loops. If you really start programming in this style in P...
[ 3, 0, 0 ]
[ "Basics\nFunctional programming is a paradigm where we use only expressions and no statements. Statements do something like an if, whereas expressions evaluate mathematical stuff. We try to avoid mutability (values getting changed), since we only want pure functions. Pure functions don't have side effects, meaning ...
[ -1 ]
[ "functional_programming", "python" ]
stackoverflow_0024949635_functional_programming_python.txt
Q: How to redirect request with data to another url in Flask I have a Flask app that redirects the requests to different urls checking their availability first. The target URLs do not belong to the same Flask app. I am already able to redirect to the available url, but I am having problems trying to pass the data tha...
How to redirect request with data to another url in Flask
I have a Flask app that redirects the requests to different urls checking their availability first. The target URLs do not belong to the same Flask app. I am already able to redirect to the available url, but I am having problems trying to pass the data that came in the original request. I am working with this code: @a...
[ "The main problem I can see is in these two lines\n data = json.loads(resp.content)\n if data != 'pong':\n\njson.loads(x) runs an error when x is not a valid json string. If the expected value for data really is pong, then an error like this one will be thrown at that point:\n\nThen if \"pong\" is really ...
[ 0 ]
[]
[]
[ "flask", "python", "redirect" ]
stackoverflow_0074237908_flask_python_redirect.txt
Q: Altair changes order of legend when saving data to disk vs. storing data in the plot Consider the following dataframe created with the code snipped attached at the end of this question: A B C 0 1.624345 -0.611756 2 1 -1.072969 0.865408 1 2 1.744812 -0.761207 2 3 -0.24...
Altair changes order of legend when saving data to disk vs. storing data in the plot
Consider the following dataframe created with the code snipped attached at the end of this question: A B C 0 1.624345 -0.611756 2 1 -1.072969 0.865408 1 2 1.744812 -0.761207 2 3 -0.249370 1.462108 2 4 -0.322417 -0.384054 11 5 -1.099891 -0.172428 1 6 0.04...
[ "This seems like a weird bug. But I managed to find a workaround. The trick is to use transform_filter by passing possible values of C one at a time.\ndef csv_dir(data, data_dir=\"altairdata\") -> None:\n os.makedirs(data_dir, exist_ok=True)\n return pipe(data, alt.to_csv(filename=data_dir + \"/{prefix} -{has...
[ 2 ]
[]
[]
[ "altair", "python" ]
stackoverflow_0074206324_altair_python.txt
Q: How to solve error about "subcommand is required but not givern"? Hi guys im trying to run the code clone from github on AWS. But when I want to train the model, I see such error message. Can anyone help to solve it? Thanks a lot I followed the instruction in README file but failed at the "train bttr model using g...
How to solve error about "subcommand is required but not givern"?
Hi guys im trying to run the code clone from github on AWS. But when I want to train the model, I see such error message. Can anyone help to solve it? Thanks a lot I followed the instruction in README file but failed at the "train bttr model using gpu" step.
[ "The solution is mostly there in the help message, though it can be a bit obscure if you're new to Python / argparse.\nThe help message is telling you that you need to use one of the subcommands in your command invocation: fit, validate, test, predict, tune.\nSo something like this:\npython train.py train --config ...
[ 0 ]
[]
[]
[ "amazon_web_services", "error_handling", "python", "training_data" ]
stackoverflow_0074238502_amazon_web_services_error_handling_python_training_data.txt
Q: PyOpenGL program doesn't show cube? I'm trying to draw a 3D cube using Python and its packages, pygame, numpy, PyOpenGL, and PyOpenGL_accelerate. The 3D cube also rotates to other directions when I press the arrow buttons. For example, it rotates to right when I press the right arrow. First, I've tried it on other...
PyOpenGL program doesn't show cube?
I'm trying to draw a 3D cube using Python and its packages, pygame, numpy, PyOpenGL, and PyOpenGL_accelerate. The 3D cube also rotates to other directions when I press the arrow buttons. For example, it rotates to right when I press the right arrow. First, I've tried it on other PC and it runs perfectly. But then, I've...
[ "You have to update the display after drawing the cube. Call pygame.display.flip() after glEnd(). You need to redraw the cube in each frame and change the rotation matrix in each frame. It is a matter of Indentation. The indentation of the application loop is wrong.\nimport pygame\nfrom pygame.locals import *\n\nfr...
[ 1 ]
[]
[]
[ "numpy", "opengl", "pygame", "pyopengl", "python" ]
stackoverflow_0074237478_numpy_opengl_pygame_pyopengl_python.txt
Q: I am a first time python/django user trying to test a nested serializer and getting 'TypeError: Direct assignment to the reverse side of a relatedset' I am trying to write a test to show that I can serialize a customer and pass the subscriptions that the customer has subscribed for currently just one subscription ...
I am a first time python/django user trying to test a nested serializer and getting 'TypeError: Direct assignment to the reverse side of a relatedset'
I am trying to write a test to show that I can serialize a customer and pass the subscriptions that the customer has subscribed for currently just one subscription but I do believe that what I have would work for multiple subscriptions. This is my first time doing anything in python and I do not know the inner workings...
[ "You cannot assign subscriptions directly in Customer.objects.create function - you need to set it separately.\nIf you remove 'subscriptions' from self.customer_attributes it should work.\nThen you can update the subscription via\nSubscription.objects.filter(id=self.subscription_id).update(customers=self.customer)\...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074238670_django_python.txt
Q: Is there any method to change filename of the TimedRotatingFileHandler for the "future-created" file in the dictConfig written in JSON? I would like to change the .suffix for the TimedRotatingFileHandler for the "future-created" file in dictConfig written in json. Is there any suggestion on how to do that? JSON fi...
Is there any method to change filename of the TimedRotatingFileHandler for the "future-created" file in the dictConfig written in JSON?
I would like to change the .suffix for the TimedRotatingFileHandler for the "future-created" file in dictConfig written in json. Is there any suggestion on how to do that? JSON file code: { "version": 1, "disable_existing_loggers": true, "formatters": { "simple": { "format": "%(asctime)s-%(levelname)s-%...
[ "Create your own TimedRotatingFileHandler class and define your namer method as you like:\nimport logging.handlers\nfrom datetime import date, timedelta\n\n\nclass MyTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):\n def __init__(self, filename, when='midnight', interval=1, backupCount=3):\n ...
[ 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0066979966_logging_python.txt
Q: This relates to Multiple if statements in python I am a beginner level python student. This is a code challenge in a udemy program related to Multiple if statements add_pepperoni ="Y" extra_cheese="Y" pizza_price =15 if add_pepperoni =="Y": pizza_price +=2 if extra_cheese =="Y": pizza_price +=1 ...
This relates to Multiple if statements in python
I am a beginner level python student. This is a code challenge in a udemy program related to Multiple if statements add_pepperoni ="Y" extra_cheese="Y" pizza_price =15 if add_pepperoni =="Y": pizza_price +=2 if extra_cheese =="Y": pizza_price +=1 else: print(f"final price is{pizza_price}")...
[ "I assume you want to be able to print the correct price, regardless of the combinations chosen by the customer: pepperoni, no extra cheese; no pepperoni, extra cheese, etc. The snag in your code (and mxthng's) is that the 'extra_cheese' 'if' statement has been nested in the 'add_pepperoni' 'if' statement. When nes...
[ 1, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074230355_if_statement_python.txt
Q: How to make while loop work inbetween time interval? I am trying to create a nested while loop which should be working in hours 02:20 - 21:50, butI can't figure out the boolean expression which would fulfill the condition. while True: now = datetime.datetime.now() print((now.hour >= 2 and now.minute >= 20)...
How to make while loop work inbetween time interval?
I am trying to create a nested while loop which should be working in hours 02:20 - 21:50, butI can't figure out the boolean expression which would fulfill the condition. while True: now = datetime.datetime.now() print((now.hour >= 2 and now.minute >= 20), (now.hour <= 21 and now.minute <= 49)) while (now.ho...
[ "now = datetime.datetime.now()\nswitch = !(2 <= now.hour <= 21) : True ? (20 <= now.minute <= 49)\nwhile (2 <= now.hour <= 21) and switch:\n now = datetime.datetime.now()\n\n", "Here is an example how to do it. I used the .replace() method of the datetime object to prevent setting the datetime objects' day, mo...
[ 1, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074238062_datetime_python.txt
Q: Populate Django pdf after submition from user input I've done the HTML as well as the pdf blank file for my web framework, but when it comes to the submission POST, I cannot seem to get it to work. Its supposed that once you press the submit it will save the user input to the blank pdf created, to later through a ...
Populate Django pdf after submition from user input
I've done the HTML as well as the pdf blank file for my web framework, but when it comes to the submission POST, I cannot seem to get it to work. Its supposed that once you press the submit it will save the user input to the blank pdf created, to later through a button (which is already created and functional, but down...
[ "In your views.py you are not adding any lines to your PDF\n lines =[\n \n ]\n for line in lines:\n textob.textLine(line)\n\nYou have to use the request.POST data to construct the lines you like to have in your PDF file.\nWe can't help you any further, as we do not know what t...
[ 0, 0, 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074199216_django_html_python.txt
Q: how can we explain id() built-in function output structure? a = 5 id(a) As you know,output is; 1936111069616 I know that this is a memory address reference of "a" variable linked between variable name and object heap and stack memory on ram in decimal format but i haven't found anything about the detailed defini...
how can we explain id() built-in function output structure?
a = 5 id(a) As you know,output is; 1936111069616 I know that this is a memory address reference of "a" variable linked between variable name and object heap and stack memory on ram in decimal format but i haven't found anything about the detailed definition of this address. If we wanted to write a user-defined functi...
[ "The documentation explains id as much as it can be explained:\n\nReturn the “identity” of an object. This is an integer which is\nguaranteed to be unique and constant for this object during its\nlifetime. Two objects with non-overlapping lifetimes may have the same\nid() value.\n\nThat's it. It's an integer with n...
[ 1, 0 ]
[]
[]
[ "built_in", "memory_management", "python", "variables" ]
stackoverflow_0074238083_built_in_memory_management_python_variables.txt
Q: How do i install pygame on python 3.11.0 it's showing the following error Whenever i try to install pygame, it says it has error: subprocess-exited-with-error python setup.py egg_info did not run successfully. exit code 1 A: pip install pygame --pre This should fix it for now. You can upgrade to the normal versi...
How do i install pygame on python 3.11.0 it's showing the following error
Whenever i try to install pygame, it says it has error: subprocess-exited-with-error python setup.py egg_info did not run successfully. exit code 1
[ "pip install pygame --pre This should fix it for now. You can upgrade to the normal version once it launches\n" ]
[ 4 ]
[]
[]
[ "pygame", "python", "python_3.11" ]
stackoverflow_0074238684_pygame_python_python_3.11.txt
Q: Why does subplot_mosaic show an Error: 'Figure' object has no attribute 'subplot_mosaic' I've a problem with "subplot_mosaic" because Spyder can't find it. Could it be because of the version? The Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gs # Subplot_Mosaic layout = [...
Why does subplot_mosaic show an Error: 'Figure' object has no attribute 'subplot_mosaic'
I've a problem with "subplot_mosaic" because Spyder can't find it. Could it be because of the version? The Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gs # Subplot_Mosaic layout = [["logo", "text"],["bar", "bar"]] fig = plt.figure(figsize = (5,5)) ax_dict = fig.subplot_mos...
[ "Updating the version to: Maptlotlib 3.6.1 solved the problem!\nThanks to: @BigBen\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074238189_matplotlib_python.txt
Q: Ursina, how to change font in dropdownbutton I wish to change font or width in dropdownbutton in ursina, any help? cheer. My simple dropdownbutton is the following from ursina import * # Import the ursina engine from ursina.prefabs.dropdown_menu import DropdownMenu, DropdownMenuButton app = Urs...
Ursina, how to change font in dropdownbutton
I wish to change font or width in dropdownbutton in ursina, any help? cheer. My simple dropdownbutton is the following from ursina import * # Import the ursina engine from ursina.prefabs.dropdown_menu import DropdownMenu, DropdownMenuButton app = Ursina() # Initialise your U...
[ "I found to myself a way to change the font and wish to share it, I feel that there is a more efficient way but anyway:\nStep 1: copy the font file in the current ursina directory.\nStep 2: use text_entity.font attribute.\nHere a working example:\nfrom ursina import * # Import the ursina engine\n...
[ 0 ]
[]
[]
[ "python", "ursina", "user_interface" ]
stackoverflow_0074198653_python_ursina_user_interface.txt
Q: django:django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet I got stuck on a process when I wanted to deploy a django project on the server today. When I run python manage.py runserver on server, the terminal shows me this: Traceback (most recent call last): File "manage.py", line 10, in <module> ...
django:django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I got stuck on a process when I wanted to deploy a django project on the server today. When I run python manage.py runserver on server, the terminal shows me this: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages...
[ "This could well be an issue with your Django settings. For example, I just had specified in LOGGING a filename in a non-existent directory. As soon as I changed it to an existing directory, the issue was resolved.\n", "I ran into this issue today. There was an app in INSTALLED_APPS that didn't exist. Once it was...
[ 22, 13, 5, 2, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0033186413_django_python.txt