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: Using Ordinal Variables as categories in XGBoost Python I am trying to train a multi-class classifier using XGBoost. Data contains 4 independent variables which are ordinal in nature. I want to use these variables as is because they are encoded. The data looks like below Column name Values target ['high', 'mediu...
Using Ordinal Variables as categories in XGBoost Python
I am trying to train a multi-class classifier using XGBoost. Data contains 4 independent variables which are ordinal in nature. I want to use these variables as is because they are encoded. The data looks like below Column name Values target ['high', 'medium', 'low'] feature_1 Values ranging from 1-5 featur...
[ "If you want them treated as ordinal, then just make the column type int: xgboost will make splits as though they were continuous, which preserves the ordered nature.\n", "You are almost there!\nBased on XGBoost Documentation, you need to set enable_categorical=True and the supported tree methods are gpu_hist, ap...
[ 1, 0 ]
[]
[]
[ "classification", "data_preprocessing", "pandas", "python", "xgboost" ]
stackoverflow_0074478807_classification_data_preprocessing_pandas_python_xgboost.txt
Q: Side-by-side Labels in StackLayout: Why is second label missing? (kivy, python) How can I display two labels side-by-side in a Kivy StackLayout? Consider the following code #!/usr/bin/env python3 from kivy.uix.button import Button from kivy.lang import Builder from kivy.app import App KV = """ StackLayout: o...
Side-by-side Labels in StackLayout: Why is second label missing? (kivy, python)
How can I display two labels side-by-side in a Kivy StackLayout? Consider the following code #!/usr/bin/env python3 from kivy.uix.button import Button from kivy.lang import Builder from kivy.app import App KV = """ StackLayout: orientation: 'lr-tb' Label: text: "Hello" Label: text: "Worl...
[ "To make this work as expected, you have to:\n\noverride size_hint to None and\nset the size of the widget to its texture_size (which is the actual pixels needed to render the font -- but you may actually want to pad this with some pixels)\n\nFor example\n#!/usr/bin/env python3\n\nfrom kivy.uix.button import Button...
[ 2 ]
[]
[]
[ "kivy", "kivy_language", "layout", "python", "stacklayout" ]
stackoverflow_0074480862_kivy_kivy_language_layout_python_stacklayout.txt
Q: How to check if tuple having a list or dictionary is empty I have a tuple: details = ({}, []) As there is no data in the following tuple I want to return a null response. For this I am writing: if not details: return Response({}) else: print "Not null" But this does not seem to work as it is always g...
How to check if tuple having a list or dictionary is empty
I have a tuple: details = ({}, []) As there is no data in the following tuple I want to return a null response. For this I am writing: if not details: return Response({}) else: print "Not null" But this does not seem to work as it is always going in the else part and printing not null. I am new to python....
[ "\nNote: if you write:\nif <expr>:\n pass\n\nthen Python will not check that <expr> == True, it will evaluate the truthiness of the <expr>. Objects have some sort of defined \"truthiness\" value. The truthiness of True and False are respectively True and False. For None, the truthiness is False, for numbers usua...
[ 11, 0 ]
[]
[]
[ "list", "python", "python_2.7", "tuples" ]
stackoverflow_0048660923_list_python_python_2.7_tuples.txt
Q: Optuna, recover original study name to load .db file I created a study to optimize a model with Optuna, which produced a .db file with the same name as the study_name. The problem is that I'm trying to load the results by using: study = optuna.create_study(study_name=study_name, sto...
Optuna, recover original study name to load .db file
I created a study to optimize a model with Optuna, which produced a .db file with the same name as the study_name. The problem is that I'm trying to load the results by using: study = optuna.create_study(study_name=study_name, storage=f"sqlite:///{results_folder}/results.db", ...
[ "Yep! The db file is query-able. Study names are stored in a table called \"studies\", so you can use your database interface of choice to query that table. However, if you're storing multiple study results in this one db file, you'll need to be able to remember which of the study names you find is actually the one...
[ 1 ]
[]
[]
[ "optuna", "python" ]
stackoverflow_0073556231_optuna_python.txt
Q: fast api stopping after a while on google cloud vm I have a ML model with fast api wrapper running on google cloud VM, it runs fine when ssh terminal is open. but once I close the terminal it runs for 10 more minutes maybe and then the api returns 502 bad gate way I'm using nginx with this config server{listen 80...
fast api stopping after a while on google cloud vm
I have a ML model with fast api wrapper running on google cloud VM, it runs fine when ssh terminal is open. but once I close the terminal it runs for 10 more minutes maybe and then the api returns 502 bad gate way I'm using nginx with this config server{listen 80; server_name: public ip; location /{proxy_pass http://1...
[ "When you close the SSH terminal session, the applications that you started will be killed. Use a program such as tmux, screen, etc. to create sessions that you can attach to and detach from.\nHowever, since you are using Nginx, there are better methods of managing applications that are being proxied. For developme...
[ 0 ]
[]
[]
[ "fastapi", "google_cloud_platform", "nginx", "python", "python_3.x" ]
stackoverflow_0074481058_fastapi_google_cloud_platform_nginx_python_python_3.x.txt
Q: Video Recording with mss in python I'm capturing my screen using OpenCV on windows. It works fine but I have heard mss is much faster than PIL. I have seen this code in a youtube video but am unable to figure out how to save the frames to a .wav file or similar from mss import mss import cv2 from PIL import Image ...
Video Recording with mss in python
I'm capturing my screen using OpenCV on windows. It works fine but I have heard mss is much faster than PIL. I have seen this code in a youtube video but am unable to figure out how to save the frames to a .wav file or similar from mss import mss import cv2 from PIL import Image import numpy as np from time import time...
[ "Here is a basic example to get you started:\nimport cv2\nimport numpy as np\nimport mss\nfrom time import time\n\nwidth = 640\nheight = 400\nfps = 25\nframe_delta = 1 / fps\n\n# part of the screen to capture\nmonitor = {\"top\": 10, \"left\": 10, \"width\": width, \"height\": height}\n\n# open video writer\nvideo ...
[ 0 ]
[]
[]
[ "opencv", "python", "recording" ]
stackoverflow_0074365876_opencv_python_recording.txt
Q: Python: JSON File Format not printing out correctly I'm trying to develop a parser that extracts data from a json formatted file, but when I was testing out trying to read the file and output its contents it doesn't print the data properly. Disclaimer this is my first time working on json so please go easy. Here a...
Python: JSON File Format not printing out correctly
I'm trying to develop a parser that extracts data from a json formatted file, but when I was testing out trying to read the file and output its contents it doesn't print the data properly. Disclaimer this is my first time working on json so please go easy. Here are the contents of the file (it's quite dense so I'm only...
[ "Your code iterates over each job, and then prints that job, one per line. There's only one job in your example file, so you get one line of output.\nWhy would you expect the print statement to drop some of the data?\nThose subkeys are available, exactly as you expect:\nfor job in data['jobs']:\n # job is now the ...
[ 0 ]
[]
[]
[ "file", "format", "json", "printing", "python" ]
stackoverflow_0074482380_file_format_json_printing_python.txt
Q: Hello everyone! I am begginer in programming and I decide to write some small programming. And and as usually happens with beginners, I have a problem My goal in this program is that when the user entered data, it was written from the dictionary. And in my case, only the last entered by the user is recorded in the...
Hello everyone! I am begginer in programming and I decide to write some small programming. And and as usually happens with beginners, I have a problem
My goal in this program is that when the user entered data, it was written from the dictionary. And in my case, only the last entered by the user is recorded in the dictionary and displayed on the screen. I apologize in advance for not writing comments. The program is stupid, but I still want to know what wrong. dictio...
[ "from collections import defaultdict\ndictionary = defaultdict(list)\n\n\ndef make_album(artist_name, album_title, number_of_songs_in_album=None):\n all_info_here = {'artist_name': artist_name, 'album_title': album_title}\n if number_of_songs_in_album:\n all_info_here['number_of_songs_in_album'] = numb...
[ 0 ]
[]
[]
[ "linux", "pycharm", "python", "windows" ]
stackoverflow_0074482341_linux_pycharm_python_windows.txt
Q: Is there a way to be notified when a cell finishes execution in VSCode Jupyter Notebook? I'm using Jupyter Notebook on VSCode and would like to be notified when a cell finishes execution. I searched and was not able to find any extension for this task. Is there a way to get this working? A: You could play a soun...
Is there a way to be notified when a cell finishes execution in VSCode Jupyter Notebook?
I'm using Jupyter Notebook on VSCode and would like to be notified when a cell finishes execution. I searched and was not able to find any extension for this task. Is there a way to get this working?
[ "You could play a sound at the end of your Section after your code finishes. :-P\nfrom playsound import playsound\nplaysound('/path/to/note.wav') # .wav file\nplaysound('/path/to/note.mp3') # .mp3 file\n\nIt's a way of creating an audio alert, if that suits your needs. You can borrow one of the audio alerts that co...
[ 2, 2, 2 ]
[]
[]
[ "jupyter_notebook", "python", "python_3.x", "visual_studio_code" ]
stackoverflow_0071317132_jupyter_notebook_python_python_3.x_visual_studio_code.txt
Q: What is an "instance method"? From 3. Data model: Instance methods An instance method object combines a class, a class instance and any callable object (normally a user-defined function). If it is a definition, what does it mean? If it is not a definition, what is the definition of an "instance method"? Is an "in...
What is an "instance method"?
From 3. Data model: Instance methods An instance method object combines a class, a class instance and any callable object (normally a user-defined function). If it is a definition, what does it mean? If it is not a definition, what is the definition of an "instance method"? Is an "instance method" the same concept of ...
[ ">>> class Foo:\n... def im_a_method(self):\n... pass\n... \n>>> x = Foo()\n>>> x.im_a_method\n<bound method Foo.im_a_method of <__main__.Foo object at 0x7f4f1993dd30>>\n\nTada! That's an instance method object. It's the thing you get when you retrieve a method of an object, before you call it.\n", "W...
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0046230482_python_python_3.x.txt
Q: How can I put data from api to django I have stored some data in python and now I want to display it in django how can I do that? animeUrl = "https://api.jikan.moe/v4/top/anime" animeResponse = requests.get(animeUrl).json() def topAnime(): for idx, video in enumerate(animeResponse['data']): animeUrl ...
How can I put data from api to django
I have stored some data in python and now I want to display it in django how can I do that? animeUrl = "https://api.jikan.moe/v4/top/anime" animeResponse = requests.get(animeUrl).json() def topAnime(): for idx, video in enumerate(animeResponse['data']): animeUrl = video['url'] title = video['titl...
[ "The question is answered here :\nHow to pass data to a template in Django?\nIn order to display data in django from url to html files there are two ways\nMethod 1: Rendering the template along with the data\nDjango Templates\nHow to use it in the project : Render Html Pages in django\nYou can easily set up the jin...
[ 0, 0 ]
[]
[]
[ "api", "django", "python" ]
stackoverflow_0074481937_api_django_python.txt
Q: How to generate __init__.py in all subdirectories of current directory in cmake? I use an out-of-tree builds with CMake. I have a CMake custom command that generates *_pb2.py files from proto-files. Since proto-files may reside in an unknown number of subdirectories (package namespace), like $SRC/package1/package2...
How to generate __init__.py in all subdirectories of current directory in cmake?
I use an out-of-tree builds with CMake. I have a CMake custom command that generates *_pb2.py files from proto-files. Since proto-files may reside in an unknown number of subdirectories (package namespace), like $SRC/package1/package2/file.proto, then the build directory will contain something like $BLD/package1/packag...
[ "If you are working under a *NIX os (including mac) you could use the shell find command like:\nROOT=\"./\"\nfor DIR in $(find $ROOT -type d); do\n touch $DIR/__init__.py\ndone\n\nor with a python script:\nfrom os.path import isdir, walk, join\n\nroot = \"/path/to/project\"\nfinit = '__init__.py'\ndef visitor(ar...
[ 6, 2, 1 ]
[]
[]
[ "cmake", "protocol_buffers", "python" ]
stackoverflow_0011449117_cmake_protocol_buffers_python.txt
Q: `ResourceExhaustedError: Graph execution error` when trying to train tensorflow model using model.fit() A few days back, I got the same error at 12th epoch. This time, it happens at the 1st. I have no idea why that is happening as I did not make any changes to the model. I only normalized the input to give X_train...
`ResourceExhaustedError: Graph execution error` when trying to train tensorflow model using model.fit()
A few days back, I got the same error at 12th epoch. This time, it happens at the 1st. I have no idea why that is happening as I did not make any changes to the model. I only normalized the input to give X_train.max() as 1 after scaling like it should be. Does it have something to do with patch size? Should I reduce it...
[ "I had the same error as you ,it's a resource exhausted problem, resolved by just reducing batch_size value(I had a Model which try to learn from dataset of big images I reduce it's value from 32 to 16) .and it's worked fine\n", "Just by looking at your SS from nvidia-smi command, it seems like your GPU is not be...
[ 2, 0 ]
[]
[]
[ "google_colaboratory", "python", "tensorflow" ]
stackoverflow_0072122939_google_colaboratory_python_tensorflow.txt
Q: More concise way of filling blocks of NaN values with CAGR between beginning and ending periods with Pandas Sample data: data = {'year':[2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020], 'revenue' : [100, np.nan, np.nan, 108, 118, np.nan, np.nan, np.nan, 127, 135]} df = pd.DataFrame(data).set_in...
More concise way of filling blocks of NaN values with CAGR between beginning and ending periods with Pandas
Sample data: data = {'year':[2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020], 'revenue' : [100, np.nan, np.nan, 108, 118, np.nan, np.nan, np.nan, 127, 135]} df = pd.DataFrame(data).set_index('year') df Output: revenue year 2011 100.0 2012 NaN 2013 NaN 2014 108.0 2015 118....
[ "You are trying to interpolate data in your DataFrame. From what I understand, you want to apply a kind of exponential growth rate between each date.\nAs pandas does not have direct exponential interpolation, an idea would be to first apply a log (understand it as natural logarithm, or ln in maths) function to your...
[ 0 ]
[]
[]
[ "dataframe", "fillna", "pandas", "python" ]
stackoverflow_0074480937_dataframe_fillna_pandas_python.txt
Q: pytest-django Use env vars in settings.py I have an api in Django that uses quite a few environment variables. The idea is to add pytest-django to test all its functionalities (I know it would have been smarter to build the tests together with the project). Currently it is in the manage.py file where I load the en...
pytest-django Use env vars in settings.py
I have an api in Django that uses quite a few environment variables. The idea is to add pytest-django to test all its functionalities (I know it would have been smarter to build the tests together with the project). Currently it is in the manage.py file where I load the environment variables as follows: def main(): ...
[ "I was having the same issue. The suggestion of calling dotenv.read_dotenv() from pytest_sessionstart() in conftest.py did not work for me. I also tried the pytest-dotenv library that was linked. It made pytest work, but broke my manage.py module (due to a namespace conflict between django-dotenv [which my manage.p...
[ 1 ]
[]
[]
[ "django", "pytest", "pytest_django", "python" ]
stackoverflow_0073021144_django_pytest_pytest_django_python.txt
Q: Split function returning NaN for non matching patterns in pandas I am getting NaN for non mathcing pattern w.r.t to split in pandas. Source Data: Attr [ABC].[xyz] CDE Code Used: df['Extr_Attr'] = np.where((df.Attr.str.contains('.')),df['Attr'].str.split('.',1).str[1], df.Attr) This returns NaN for ...
Split function returning NaN for non matching patterns in pandas
I am getting NaN for non mathcing pattern w.r.t to split in pandas. Source Data: Attr [ABC].[xyz] CDE Code Used: df['Extr_Attr'] = np.where((df.Attr.str.contains('.')),df['Attr'].str.split('.',1).str[1], df.Attr) This returns NaN for data that does not have a match of '.' in source data. Expected outp...
[ "Assuming you want the last chunk after a dot (if any, else the full string).\nIf you want to split, use rsplit and slice the last item:\ndf['Extr_Attr'] = df['Attr'].str.rsplit('.', 1).str[-1]\n\nOr more efficiently, with extract (get all non-. characters at the end of the string):\ndf['Extr_Attr'] = df['Attr'].st...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074482602_pandas_python.txt
Q: Django : Can't import 'module'. Check that module AppConfig.name is correct Might look like an already answered question, actually here you have the same problem (kind of) i had. My problem is, it's just a trick, one line, no explanation (and still it's different but the solution given works, and that's part of my...
Django : Can't import 'module'. Check that module AppConfig.name is correct
Might look like an already answered question, actually here you have the same problem (kind of) i had. My problem is, it's just a trick, one line, no explanation (and still it's different but the solution given works, and that's part of my problem). Here's my project structure, simplified: manage.py compfactu/---settin...
[ "According to the documentation, AppConfig.name is a full python path to the application.\n\nAppConfig.name\nFull Python path to the application, e.g. 'django.contrib.admin'.\nThis attribute defines which application the configuration applies to.\n It must be set in all AppConfig subclasses.\nIt must be unique acr...
[ 131, 0 ]
[]
[]
[ "django", "python", "python_3.x" ]
stackoverflow_0046177499_django_python_python_3.x.txt
Q: How do i make my discord.py bot pick an random line in a .txt file and reply to a message Ok so i am making a gen bot for me and my friends and i wanted to know how do i make my bot reply to the message with a account from a .txt file that i put in the folder with the bot please help me thank you i tried ` import ...
How do i make my discord.py bot pick an random line in a .txt file and reply to a message
Ok so i am making a gen bot for me and my friends and i wanted to know how do i make my bot reply to the message with a account from a .txt file that i put in the folder with the bot please help me thank you i tried ` import random @client.command() async def color(ctx): responses = ['red', 'blue'...
[ "You could add something like this to your code:\nimport random\n\n\ndef readTxtLines(filename):\n with open(filename, \"r\") as f:\n lines = f.readlines()\n return lines\n\n\ndef getRandomLine(lines):\n return random.choice(lines).strip()\n\n\nprint(getRandomLine(readTxtLines(\"test.txt\")))\n\n", ...
[ 0, 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074438914_bots_discord_discord.py_python.txt
Q: Select rows between multiple values for all columns in a dataframe I am trying to select multiple values between a range fom all rows per each column and plot them all-together. The values in the dataframe are between 0 and 100. I want to select a range of values between 0 to 10 for all rows of one column, and the...
Select rows between multiple values for all columns in a dataframe
I am trying to select multiple values between a range fom all rows per each column and plot them all-together. The values in the dataframe are between 0 and 100. I want to select a range of values between 0 to 10 for all rows of one column, and then repeat that iteration every 10 values until 100 (e.g.: values between ...
[ "Try :\ndf_1 = df[(df['A']>0) & (df['A']<10)]\n\nYou will get :\n>>> df_1\n\n A B C D E F G H I J\n43 5 91 98 63 55 32 6 79 28 18\n47 3 88 62 6 52 21 16 64 33 60\n50 8 43 84 6 8 6 70 93 0 95\n65 5 24 7 80 89 92 70 65 12 44\n78 2 99 15 14 ...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074481753_pandas_python.txt
Q: I can read from local file in py spark but i can't write data frame in local file df.write.csv("sdf") " 21/07/24 15:27:23 ERROR FileFormatWriter: Aborting job a9914f88-3ab9-480a-984f-33d0e598c0fc. java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z at org....
I can read from local file in py spark but i can't write data frame in local file
df.write.csv("sdf") " 21/07/24 15:27:23 ERROR FileFormatWriter: Aborting job a9914f88-3ab9-480a-984f-33d0e598c0fc. java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method) at org.apache.hadoop...
[ "Apart from getting winutils.exe and setting the hadoop_home.\nPlease check if you have hadoop.dll binary in your bin or not.\nIf not there then download it from the github repo.\nhttps://github.com/cdarlint/winutils/blob/master/hadoop-3.2.1/bin/hadoop.dll\nIt worked for me.\n", "For PySpark 3.3.1, Win10, Java 18...
[ 1, 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0068509434_apache_spark_pyspark_python.txt
Q: Break Python Functions into Other Files So to keep it simple I just want to be able to reference the function in C from A and I'm not sure how to do this in python without directly referencing c which I don't want to do a.py references b.py b.py references c.py c.py has a function in it called foo I want to cal...
Break Python Functions into Other Files
So to keep it simple I just want to be able to reference the function in C from A and I'm not sure how to do this in python without directly referencing c which I don't want to do a.py references b.py b.py references c.py c.py has a function in it called foo I want to call foo from a.py but for abstraction purposes...
[ "So not the most ideal solution but it appears if I create a member for each sub file in b.py it will allow me to access it from a.py\nIt would look something like this\nc.py\ndef call_me_c():\n print(\"It works from c\")\n\nb.py\nimport c\ncfile = c\n\na.py\nimport b\nb.cfile.call_me_c()\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074482785_python.txt
Q: How to unstack a dataset to a certain dataframe? I have a dataset like this data = {'weight': ['NaN',2,3,4,'NaN',6,7,8,9,'NaN',11,12,13,14,15], 'MI': ['NaN', 21, 19, 18, 'NaN',16,15,14,13,'NaN',11,10,9,8,7]} df = pd.DataFrame(data, index= ['group1', "gene1", "gene2", 'gene3', 'group2'...
How to unstack a dataset to a certain dataframe?
I have a dataset like this data = {'weight': ['NaN',2,3,4,'NaN',6,7,8,9,'NaN',11,12,13,14,15], 'MI': ['NaN', 21, 19, 18, 'NaN',16,15,14,13,'NaN',11,10,9,8,7]} df = pd.DataFrame(data, index= ['group1', "gene1", "gene2", 'gene3', 'group2', "gene1", 'gene21', 'gene4', 'gene7', 'group3', ...
[ "You can use:\nm = df['weight'].ne('NaN')\n\n(df[m]\n .set_index((~m).cumsum()[m], append=True)['MI']\n .unstack('weight', fill_value=0.1)\n .add_prefix('group')\n )\n\nVariant with pivot:\nm = df['weight'].ne('NaN')\n\n(df.assign(col=(~m).cumsum())\n .loc[m]\n .pivot(columns='col', values='MI')\n .fill...
[ 4, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074481613_pandas_python.txt
Q: How can I deal with unwanted numbers in my dataframe where I only want date format? In my dataframe I have a column called Competencia where only dates in the format YYYY-MM-DD should be. But I just found out that I have a couple of zeros and suddenly and a number like for example 11. Which shouldnt be in it. The ...
How can I deal with unwanted numbers in my dataframe where I only want date format?
In my dataframe I have a column called Competencia where only dates in the format YYYY-MM-DD should be. But I just found out that I have a couple of zeros and suddenly and a number like for example 11. Which shouldnt be in it. The Column Competencia has currently the Dtype OBJECT. I normally created a new column called...
[ "Something along the lines of this if I remember rightly - doing from memory\ndf30_new['COMPETENCIA_TRIMMED'] = df30_new['COMPETENCIA'].apply(lambda x: x if type(x) is datetime else None, axis=1)\nMaybe check the datatype of one of the correct values for this to work as expected.\nCheck out apply in the pandas docs...
[ 0 ]
[]
[]
[ "datetime", "dtype", "object", "pandas", "python" ]
stackoverflow_0074482804_datetime_dtype_object_pandas_python.txt
Q: How to convert negative strings in float numbers in pandas? I have a series of negative strings in my dataset. I'd like to convert them into negative floats, but get the ValueError: could not convert string to float: '-'. I suppose there is a problem with the enconding format, so I tried to replace - with the Uni...
How to convert negative strings in float numbers in pandas?
I have a series of negative strings in my dataset. I'd like to convert them into negative floats, but get the ValueError: could not convert string to float: '-'. I suppose there is a problem with the enconding format, so I tried to replace - with the Unicode - hyphen, but got the same error anyway. I've tried to repla...
[ "The issue is that there is at least one '-' value. That's it, just a hyphen with no figure after it.\nYou can do this:\nimport numpy as np\n\ndf['Lat.'] = df['Lat.'].replace('-',np.nan)\n\nThen this will work:\ndf['Lat.'] = df['Lat.'].astype(float)\n\n", "in case you still get an error you can use pd.to_numeric ...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0060748254_pandas_python.txt
Q: Download the attachment only from the from latest outlook email using Python? I am trying to download and save the outlook email attachment from the most recent email in a folder. I have a code that downloads all of the attachment from a outlook folder and saves it. Any help is appreciated. from pathlib import Pat...
Download the attachment only from the from latest outlook email using Python?
I am trying to download and save the outlook email attachment from the most recent email in a folder. I have a code that downloads all of the attachment from a outlook folder and saves it. Any help is appreciated. from pathlib import Path import win32com.client output_dir = Path.home()/r"Documents\Test" output_dir.mkd...
[ "\nI am trying to download and save the outlook email attachment from the most recent email in a folder.\n\nTo get the most recent item from the folder you need to sort the collection first by using the Sort method in the following way (VBA):\nmessages = inbox.Items\nmessages.Sort(\"[RecievedTime]\", false) \nmessa...
[ 0 ]
[]
[]
[ "email_attachments", "office_automation", "outlook", "python", "pywin32" ]
stackoverflow_0074471096_email_attachments_office_automation_outlook_python_pywin32.txt
Q: How to read a csv file into a multidimensional list in Python I'm trying to read a csv file into a multidimensional list with 52 rows and 7 columns. Currently it's only displaying me the last line as 52 rows of the csv file. I am pretty sure there is something wrong in my readfile function but I couldn't figure it...
How to read a csv file into a multidimensional list in Python
I'm trying to read a csv file into a multidimensional list with 52 rows and 7 columns. Currently it's only displaying me the last line as 52 rows of the csv file. I am pretty sure there is something wrong in my readfile function but I couldn't figure it out where I'm making the mistake. Here is my code: rows = 52 cols ...
[ "Use the built-in csv module:\nimport csv\nfrom pprint import pprint\n\nwith open('input.csv', newline='') as f:\n reader = csv.reader(f)\n data = [[int(x) for x in line] for line in reader]\n\npprint(data)\n\nOutput:\n[[0, 0, 30, 2, 21, 13, 23],\n [29, 3, 29, 30, 7, 8, 25],\n [26, 5, 26, 13, 4, 13, 4],\n [22...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074482853_python.txt
Q: How to change color of data points on a scatter plot according to an age range? !(https://i.stack.imgur.com/FX1vB.png) !(https://i.stack.imgur.com/mGajr.png) Hello everyone, I am very new to Python so bear with me. I am sure this is an easy answer. Above is my scatter plot, with GOLF Data from Kaggle. The X variab...
How to change color of data points on a scatter plot according to an age range?
!(https://i.stack.imgur.com/FX1vB.png) !(https://i.stack.imgur.com/mGajr.png) Hello everyone, I am very new to Python so bear with me. I am sure this is an easy answer. Above is my scatter plot, with GOLF Data from Kaggle. The X variable is Fairway Hit% and the Y variable is Average Driving Distance. I can see there is...
[ "import pandas as pd\ndf = pd.DataFrame({'Age': [18, 22, 26,36, 47,78]})\nYOUNG = df[(df['Age']>=20) & (df['Age']<=29)]\nYOUNG\n\nOr if the type of Age is string,\nimport pandas as pd\ndf = pd.DataFrame({'Age': ['18', '22', '26', '36', '47', '78']})\ndf['Age'] = df['Age'].astype('int64')\nYOUNG = df[(df['Age']>=20)...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python", "scatter_plot" ]
stackoverflow_0074483044_matplotlib_pandas_python_scatter_plot.txt
Q: Extract FQDNS from a text file using python I am trying to create a python script that downloads text files from a list of URLs and then concatenates them into a single file. This is what I have: import urllib import urllib.request import re with open("blocklist_urls.txt", "r") as a: urls = a.readlines() ret...
Extract FQDNS from a text file using python
I am trying to create a python script that downloads text files from a list of URLs and then concatenates them into a single file. This is what I have: import urllib import urllib.request import re with open("blocklist_urls.txt", "r") as a: urls = a.readlines() retrieved_pages = [] for url in urls: retrieved_...
[ "The simplest way is probably to use the IANA database of Top Level Domain (.com, .org, .net, ...). With this list, create a regex pattern to find all strings that match something like '*.tld':\n# Additional import\nimport re\n\n# Get TLD database\nresp = urllib.request.urlopen('http://data.iana.org/TLD/tlds-alpha-...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069144646_python.txt
Q: Cannot create .exe with pyinstaller from .py with torchaudio (CPU): AttributeError: '_OpNamespace' 'torchaudio' object has no attribute 'cuda_version' I have a .py script that uses torchaudio (without GPU) to process some sound in Windows. To distribute it, I've used pyinstaller to turn it into a .exe. You can rep...
Cannot create .exe with pyinstaller from .py with torchaudio (CPU): AttributeError: '_OpNamespace' 'torchaudio' object has no attribute 'cuda_version'
I have a .py script that uses torchaudio (without GPU) to process some sound in Windows. To distribute it, I've used pyinstaller to turn it into a .exe. You can reproduce the issue with this simple script: import torchaudio import time if __name__ == '__main__': t = torchaudio.transforms time.sleep(3) prin...
[ "I was able to make the script work. Here are the steps I took to get it to run.\n\nCreate a new empty directory and pasted your script in as main.py\n\npy -m venv venv && venv\\scripts\\activate && py -m pip install --upgrade pip pyinstaller\n\npip install torchaudio==0.13.0 torch==1.13.0 numpy=1.22.4 sounddevice...
[ 1 ]
[]
[]
[ "pyinstaller", "python", "torch", "torchaudio" ]
stackoverflow_0074451478_pyinstaller_python_torch_torchaudio.txt
Q: Add data to DataFrame by function thats my function: import pandas as pd shopping_list = pd.DataFrame() shopping_list = shopping_list.assign(Order=0, Type=0, Price=0, Quantity=0) def add_item(order: str, type_transaction: str, price: float, quantity: int, shopping_list=shopping_list): new_item_data = pd.Data...
Add data to DataFrame by function
thats my function: import pandas as pd shopping_list = pd.DataFrame() shopping_list = shopping_list.assign(Order=0, Type=0, Price=0, Quantity=0) def add_item(order: str, type_transaction: str, price: float, quantity: int, shopping_list=shopping_list): new_item_data = pd.DataFrame({"Order": [order], ...
[ "Here with some changes to make things work:\nimport pandas as pd\n\nshopping_list = pd.DataFrame()\nshopping_list = shopping_list.assign(Order=0, Type=0, Price=0, Quantity=0)\n\n\ndef add_item(order: str, type_transaction: str, price: float, quantity: int, shopping_list=shopping_list):\n new_item_data = pd.Data...
[ 1, 1 ]
[]
[]
[ "concatenation", "dataframe", "python" ]
stackoverflow_0074482457_concatenation_dataframe_python.txt
Q: No module named _cffi_backend I have Python 2.6 in my Linux rhel-5. I have installed pip and required CFFI packages. When I try to run a sample CFFI program: ffi = FFI() it says: File "/usr/lib/python2.6/site-packages/cffi/api.py", line 56, in __init__ import _cffi_backend as backend ImportError: No module na...
No module named _cffi_backend
I have Python 2.6 in my Linux rhel-5. I have installed pip and required CFFI packages. When I try to run a sample CFFI program: ffi = FFI() it says: File "/usr/lib/python2.6/site-packages/cffi/api.py", line 56, in __init__ import _cffi_backend as backend ImportError: No module named _cffi_backend What could be th...
[ "For python2.x use following command:\npython -m pip install cffi\n\nfor python3.x\npython3 -m pip install cffi\n\n", "I needed to uninstall and install it again:\nsudo pip uninstall cryptography\n\nsudo pip uninstall paramiko\n\nthen install pagamiko again\nsudo pip install paramiko\n\nand it start to work for m...
[ 55, 19, 12, 9, 6, 5, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_2.6", "python_cffi" ]
stackoverflow_0034370962_python_python_2.6_python_cffi.txt
Q: Expected Expression Error in my Python script I'm on Visual Studio trying to update my Itch Quiz Game and when I tried to test an Else function that follows with a print function it said I had an Expected Expression error. I tried to fix it but it didn't work. Please help Heres my code import time print("Math Gam...
Expected Expression Error in my Python script
I'm on Visual Studio trying to update my Itch Quiz Game and when I tried to test an Else function that follows with a print function it said I had an Expected Expression error. I tried to fix it but it didn't work. Please help Heres my code import time print("Math Game") print("") score = 0 #intro print("Welcom...
[ "The main issue is that the body of the if-else statement in Question 1 is empty. You need to have at least one line of code inside every if/else statement. If nothing should be done, you can use the keyword pass:\nif answer1 == \"4\":\n # ...\n score += 1 # this should go here, when answer1=='4', right?\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074483073_python.txt
Q: QtMultimedia is not currently supported on this platform or compiler. PyInstaller I'm using PyInstaller v5.6.2. I prescribe pyinstaller mp3pyqt6.py, after which I add the necessary files to mp3pyqt6.spec, updating the pyinstaller mp3pyqt6.spec command. The console that comes with the application says: could not lo...
QtMultimedia is not currently supported on this platform or compiler. PyInstaller
I'm using PyInstaller v5.6.2. I prescribe pyinstaller mp3pyqt6.py, after which I add the necessary files to mp3pyqt6.spec, updating the pyinstaller mp3pyqt6.spec command. The console that comes with the application says: could not load multimedia backend "" QtMultimedia is not currently supported on this platform or co...
[ "I got it to work, and these are the steps I took to get it to run and compile.\n\nCreate a new directory and paste your script inside of it as main.py.\npy -m venv venv && venv\\scripts\\activate\npy -m pip install --upgrade pip pyinstaller PyQt6\npyinstaller -F main.py\nGo into the venv\\Lib\\site-packages folder...
[ 0 ]
[]
[]
[ "pyinstaller", "pyqt6", "python" ]
stackoverflow_0074415173_pyinstaller_pyqt6_python.txt
Q: Python ParseError Document is empty I'm lost. You won't be able to run the code because of existing files in the directory. Does anyone know why this occurs? Below is the code and the executed error. It runs up to 1900 before stopping. Why 1900? I've run it 5 times, and it's always 1900. I would understand the iss...
Python ParseError Document is empty
I'm lost. You won't be able to run the code because of existing files in the directory. Does anyone know why this occurs? Below is the code and the executed error. It runs up to 1900 before stopping. Why 1900? I've run it 5 times, and it's always 1900. I would understand the issue more if it crashed immediately, but it...
[ "I'm working on the same project and ran into the same issue.\nAfter running this code, I found 3 empty box scores:\nfor b in box_scores:\n if os.path.getsize(b) == 0: # check for empty files\n print(b)\n\nI removed the 3 empty files using the following list comprehension:\nbox_scores = [b for b in box_sc...
[ 0 ]
[]
[]
[ "pandas", "parsing", "python" ]
stackoverflow_0074176923_pandas_parsing_python.txt
Q: How to cast String float to Float in PySpark? I have the following PySpark dataframe: df = spark.createDataFrame( [ ('31,2', 'foo'), ('33,1', 'bar'), ], ['cost', 'label'] ) I need to cast the ´cost´ column to float. I do it as follows: df = df.withColumn('cost', df.cost.cast('float')) ...
How to cast String float to Float in PySpark?
I have the following PySpark dataframe: df = spark.createDataFrame( [ ('31,2', 'foo'), ('33,1', 'bar'), ], ['cost', 'label'] ) I need to cast the ´cost´ column to float. I do it as follows: df = df.withColumn('cost', df.cost.cast('float')) However, as I result I get null values instead of ...
[ "This should work for you.\ndf = (df.withColumn('cost', F.regexp_replace(df.cost, ',', '.')\n .withColumn('cost', df.cost.cast('float')))\n\n\n", "I think a simple lambda expression should take care of most things.\n df.loc[:, 'cost'] = df.cost.apply(lambda x: float(x.replace(',', '.')))\n\n" ]
[ 2, 1 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074481067_pyspark_python.txt
Q: How to use model.fit generator I have this variable #Data Preprocessing train_datagen = ImageDataGenerator(rescale=1.0/255) train_generator = train_datagen.flow_from_directory(directory=images_train,target_size=(1024,1024),class_mode='categorical',batch_size=32) val_datagen = ImageDataGenerator(rescale=1.0/255) v...
How to use model.fit generator
I have this variable #Data Preprocessing train_datagen = ImageDataGenerator(rescale=1.0/255) train_generator = train_datagen.flow_from_directory(directory=images_train,target_size=(1024,1024),class_mode='categorical',batch_size=32) val_datagen = ImageDataGenerator(rescale=1.0/255) val_generator = train_datagen.flow_fr...
[ "before calling model.fit(x, y) please compile it first by:\nmodel.compile()\n\nRef:\nhttps://keras.io/api/models/model_training_apis/\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tf.keras" ]
stackoverflow_0074482746_keras_python_tf.keras.txt
Q: Does pytest support multiprocessing.set_start_method? The doc of multiprocessing.set_start_method note that: Note that this should be called at most once, and it should be protected inside the if name == 'main' clause of the main module. However, if I put multiprocessing.set_start_method('spawn') in a pytest mod...
Does pytest support multiprocessing.set_start_method?
The doc of multiprocessing.set_start_method note that: Note that this should be called at most once, and it should be protected inside the if name == 'main' clause of the main module. However, if I put multiprocessing.set_start_method('spawn') in a pytest module fixture, I do not know will does it work perfectly.
[ "Indeed, as stated in the documentation, you will be in trouble if you try to call multiprocessing.set_start_method() from multiple unit tests functions. Moreover, this will affect your whole program and may interoperate badly with the entire tests suit.\nHowever, there exists a workaround which is described in the...
[ 0, 0 ]
[]
[]
[ "pytest", "python", "python_multiprocessing" ]
stackoverflow_0052921309_pytest_python_python_multiprocessing.txt
Q: Phone number parser producing undesirable white space phone_number = int(input()) line_number =phone_number % 10000 area_code_prefix = phone_number //10000 area_code =area_code_prefix // 1000 prefix =area_code_prefix % 1000 print('(',area_code,')',prefix,'-',line_number) and I can't figure out how to fix it. I'v...
Phone number parser producing undesirable white space
phone_number = int(input()) line_number =phone_number % 10000 area_code_prefix = phone_number //10000 area_code =area_code_prefix // 1000 prefix =area_code_prefix % 1000 print('(',area_code,')',prefix,'-',line_number) and I can't figure out how to fix it. I've already tried a few different str.() types to try to solv...
[ "Simple fix: ',' produces a white space\n\nphone_number = int(input(\"Enter phone number\"))\nline_number =phone_number % 10000\narea_code_prefix = phone_number //10000\narea_code =area_code_prefix // 1000\nprefix =area_code_prefix % 1000\n\nprint('('+str(area_code)+')'+str(prefix)+'-'+str(line_number))\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074483149_python.txt
Q: How to extract edges from polydata as connected features? I have a polydata structure and its extracted edges but computed with extract_feature_edges function as unconnected cells (separated lines). Is it possible to connect those cells (lines) from their common points and then get the different features (lands, i...
How to extract edges from polydata as connected features?
I have a polydata structure and its extracted edges but computed with extract_feature_edges function as unconnected cells (separated lines). Is it possible to connect those cells (lines) from their common points and then get the different features (lands, islands such as what you can see in the image - Antartica, Austr...
[ "Here is a solution using vtk.vtkStripper() to join contiguous segments into polylines.\nSee thread from https://discourse.vtk.org/t/get-a-continuous-line-from-a-polydata-structure/9864\nimport pyvista as pv\nimport vtk\nimport random\n\n! wget -q -nc https://thredds-su.ipsl.fr/thredds/fileServer/ipsl_thredds/brock...
[ 0, 0 ]
[]
[]
[ "python", "pyvista", "vtk" ]
stackoverflow_0074467727_python_pyvista_vtk.txt
Q: I am trying to convert a string from a list into an integer without losing the decimal places I want to convert a string to integer without rounding. For example s = "99.7" x = s(int(float(s)) Output: 99 But I want the output to be 99.7 I was thinking of just adding all the strings to a list and somehow converti...
I am trying to convert a string from a list into an integer without losing the decimal places
I want to convert a string to integer without rounding. For example s = "99.7" x = s(int(float(s)) Output: 99 But I want the output to be 99.7 I was thinking of just adding all the strings to a list and somehow converting the list to an integer but I am not sure how to do that or how to even do it individually. Desir...
[ "An integer in python can not have a floating point. To show this you should use\nfloat(x)\n\nThis will prevent any rounding.\n" ]
[ 1 ]
[]
[]
[ "decimal", "integer", "list", "python", "string" ]
stackoverflow_0074483183_decimal_integer_list_python_string.txt
Q: Scrapy [scrapy.core.scraper] ERROR: Error processing I am trying to scrape some data from a website using scrapy. I am scraping the data using these lines of code: ` def parse(self, response): data = json.loads(response.body) flat = FlatItem() for item in data["_embedded"]["estates"]: flat['fla...
Scrapy [scrapy.core.scraper] ERROR: Error processing
I am trying to scrape some data from a website using scrapy. I am scraping the data using these lines of code: ` def parse(self, response): data = json.loads(response.body) flat = FlatItem() for item in data["_embedded"]["estates"]: flat['flat'] = item['price'] yield flat ` and the FlatItem...
[ "What is probably happening is that one of your items has a None value and postgresql doesn't accept None as a value.\nTry changing your pipeline process_item() to this:\ndef process_item(self, item, spider):\n print(item)\n print(item[\"flat\"])\n if item[\"flat\"]:\n self.current.execute(\n ...
[ 0 ]
[]
[]
[ "postgresql", "python", "scrapy" ]
stackoverflow_0074474061_postgresql_python_scrapy.txt
Q: How to fix "could not find or load the Qt platform plugin windows" while using Matplotlib in PyCharm I am getting the error "could not find or load the Qt platform plugin windows" while using matplotlib in PyCharm. How can I solve this? A: I had the same problem with Anaconda3 4.2.0 and 4.3.0.1 (64-bit). When I ...
How to fix "could not find or load the Qt platform plugin windows" while using Matplotlib in PyCharm
I am getting the error "could not find or load the Qt platform plugin windows" while using matplotlib in PyCharm. How can I solve this?
[ "I had the same problem with Anaconda3 4.2.0 and 4.3.0.1 (64-bit). When I tried to run a simple program that uses matplotlib, I got this error message:\nThis application failed to start because it could not find or load the Qt platform plugin \"windows\"\n\nReinstalling the application may fix this problem.\n\nRein...
[ 57, 27, 27, 20, 20, 17, 15, 12, 7, 4, 3, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "In my case, I had multiple combined problems in order to make PyQt5 run on Windows, see DLL load failed when importing PyQt5\n", "I had the same issue with Qt 5.9 example btscanner.exe. What works in my case is:\n\nCreate a folder where is btscanner.exe ( my is c:\\temp\\BlueTouth )\nRun from command prompt wind...
[ -1, -1, -2 ]
[ "pycharm", "python", "python_3.x" ]
stackoverflow_0041994485_pycharm_python_python_3.x.txt
Q: Stick the dataframe rows and column in one row+ replace the nan values with the day before or after I have a df and I want to stick the values of it. At first I want to select the specific time, and replace the Nan values with the same in the day before. Here is a simple example: I only want to choose the values ...
Stick the dataframe rows and column in one row+ replace the nan values with the day before or after
I have a df and I want to stick the values of it. At first I want to select the specific time, and replace the Nan values with the same in the day before. Here is a simple example: I only want to choose the values in 2020, I want to stick its value based on the time, and also replace the nan value same as day before. ...
[ "I don't know what the output is supposed to be but i think this should do at least part of what you're trying to do\ndf['day'] = pd.to_datetime(df['day'], format='%Y-%m-%d')\ndf = df.sort_values(by=['day'])\n\nfilter_2020 = df['day'].dt.year == 2020\nval_cols = df.filter(like='value_').columns\n\ndf.loc[filter_202...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074480636_dataframe_pandas_python.txt
Q: trying to zip datetime64[D], getting Error : too many values to unpack (expected 2) I am trying to zip 3 iterators - list of high temperature values , list of low temperature values and a date index of dtype = datetime64[D]. I am using vs code. here is my code: date_index = np.arange('2015-01-01','2016-01-01', dty...
trying to zip datetime64[D], getting Error : too many values to unpack (expected 2)
I am trying to zip 3 iterators - list of high temperature values , list of low temperature values and a date index of dtype = datetime64[D]. I am using vs code. here is my code: date_index = np.arange('2015-01-01','2016-01-01', dtype='datetime64[D]') (dates_high,break_high) = [(x,a) for a, b, x in zip(high, tmax, date...
[ "Here's a simple example like your problem line:\nIn [580]: [(a,b) for a,b,c in zip([1,2,3,4],[5,6,7,8],[9,10,11,12])]\nOut[580]: [(1, 5), (2, 6), (3, 7), (4, 8)]\n\nTell me how it's supposed to unpack that into two variable? There are 4 items in the list.\nYou don't need to zip to get the elements of the respecti...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "zip" ]
stackoverflow_0074481786_numpy_pandas_python_zip.txt
Q: Python logging - different logs from every instance of one class Is there any way in python to get other logs from every instance of one class without necessitiy of modifying existing logs? import logging log = logging.getLogger("my_module") class MyClass: def __init__(self, name): self.name = name ...
Python logging - different logs from every instance of one class
Is there any way in python to get other logs from every instance of one class without necessitiy of modifying existing logs? import logging log = logging.getLogger("my_module") class MyClass: def __init__(self, name): self.name = name def function(self): log.debug("My log!") c1 = MyClass("fir...
[ "You can fairly easily set up a different logger with a different name for each instance:\nclass MyClass:\n def __init__(self, name):\n self.name = name\n self.log = logging.getLogger(f'{__name__}.{type(self).__name__}.{name}')\n\n def function(self):\n self.log.debug(\"My log!\")\n\nIf y...
[ 0 ]
[]
[]
[ "logging", "python", "python_3.x" ]
stackoverflow_0074483210_logging_python_python_3.x.txt
Q: Using dictionary to calculate totals from a text file in python Below is a sample input file: A,B,C Location:London A, 46 B, 93 C, 32 A, 48 Location:Amsterdam A, 83 B, 21 C, 92 B, 39 Location:Paris A, 29 B, 91 C, 10 The output should be as follows: name_set = { A, B, C } location_set = {London, Amsterdam, Pari...
Using dictionary to calculate totals from a text file in python
Below is a sample input file: A,B,C Location:London A, 46 B, 93 C, 32 A, 48 Location:Amsterdam A, 83 B, 21 C, 92 B, 39 Location:Paris A, 29 B, 91 C, 10 The output should be as follows: name_set = { A, B, C } location_set = {London, Amsterdam, Paris} Generate a dictonary that maps name to total: dic = {A: 206, B: 2...
[ "Create a dictionary with the names as the keys and 0 for the values, and increment the appropriate value as you read the file.\nuserfile = \"input.txt\"\nlocations = set()\nwith open(userfile) as f:\n names = dict.fromkeys(next(f).strip().split(\",\"), 0)\n location = \"\"\n for line in f:\n if lin...
[ 2 ]
[]
[]
[ "dictionary", "file", "python", "set" ]
stackoverflow_0074483206_dictionary_file_python_set.txt
Q: reroute terminal to interface of the application I have built a small desktop application which edits data(.ags format) and then saves to selected folder. Before i had an issue that, i could run it as python file, but it would crash when I make it .exe. I figured out the problem. The reason was that, particular li...
reroute terminal to interface of the application
I have built a small desktop application which edits data(.ags format) and then saves to selected folder. Before i had an issue that, i could run it as python file, but it would crash when I make it .exe. I figured out the problem. The reason was that, particular line of code tries to prints to terminal, but .exe did n...
[ "By default pyinstaller compiles executables in console mode... which means that unless you tell it otherwise when the application is run outside of the command line, e.g. by double clicking the .exe a console window will always appear.\nTo avoid this simply use the windowed mode of pyinstaller with the -w flag wh...
[ 0 ]
[]
[]
[ "exe", "pyinstaller", "pysimplegui", "python", "terminal" ]
stackoverflow_0074479039_exe_pyinstaller_pysimplegui_python_terminal.txt
Q: pd.read_csv: delimiter = '\t' and header=None not compatible I have this line of code: df = pd.read_csv('some_file.txt',engine ='python', delimiter = '\t', header=None, encoding="utf-16") I'm using those txt files quiet often in my lab, one of our machines gives them as output. If I only use th...
pd.read_csv: delimiter = '\t' and header=None not compatible
I have this line of code: df = pd.read_csv('some_file.txt',engine ='python', delimiter = '\t', header=None, encoding="utf-16") I'm using those txt files quiet often in my lab, one of our machines gives them as output. If I only use the delimiter I get a nice table, but with the first element as head...
[ "Assuming all the files have the same structure and you only want the data; skip the first four rows, don't use the last three rows, whitespace delimiter, no header, python engine.\n>>> df = pd.read_csv(csv,skiprows=4,skipfooter=3,header=None,delim_whitespace=True,engine='python')\n>>> df\n 0 1 2 ...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074480594_dataframe_pandas_python.txt
Q: Retrieving identity of most recent insert in Oracle DB 12c I'd like to have returned to me (via cx_oracle in python) the value of the Identity that's created for a row that I'm inserting. I think I can figure out the python bit on my own, if someone could please state how to modify my SQL statement to get the ID ...
Retrieving identity of most recent insert in Oracle DB 12c
I'd like to have returned to me (via cx_oracle in python) the value of the Identity that's created for a row that I'm inserting. I think I can figure out the python bit on my own, if someone could please state how to modify my SQL statement to get the ID of the newly-created row. I have a table that's created with som...
[ "Taking what user2502422 said above and adding the python bit:\nnewest_id_wrapper = cursor.var(cx_Oracle.STRING)\nsql_params = { \"newest_id_sql_param\" : newest_id_wrapper }\nsql = \"insert into hypervisor ( name ) values ('my hypervisor') \" + \\ \n \"returning id into :python_var\"\ncursor.execu...
[ 12, 7, 4, 1, 0 ]
[]
[]
[ "oracle", "oracle12c", "python" ]
stackoverflow_0035327135_oracle_oracle12c_python.txt
Q: how to make input not case sensitive so i recently started my coding journey and am a freshman computer science student and i decided to do a side project where i input a country and it tells me the continent uknow for fun, although when i write the input it dosnt work and i think it has to do with it being case s...
how to make input not case sensitive
so i recently started my coding journey and am a freshman computer science student and i decided to do a side project where i input a country and it tells me the continent uknow for fun, although when i write the input it dosnt work and i think it has to do with it being case sensitive. pls help here's the code i curre...
[ "When you write the following\nif country.upper() in countries_in_africa:\n print('country is in africa')\n\nYou're searching for an all-caps string. Casing is important as you've noted. To get around it you can also convert all strings in countries_in_africa to uppercase.\nEither do it manually when you define ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074483304_python.txt
Q: Write a function that, given natural numbers n, m, determines the smallest natural number k such that n^k >= m, in time O(log k) I can do it in only O(k) time can someone be that kind to help me. I can not use build in functions. def potnr(a, b): rez = 1 while b>0: if b%2: rez = rez * a...
Write a function that, given natural numbers n, m, determines the smallest natural number k such that n^k >= m, in time O(log k)
I can do it in only O(k) time can someone be that kind to help me. I can not use build in functions. def potnr(a, b): rez = 1 while b>0: if b%2: rez = rez * a b = b // 2 a = a * a return rez def liczba(n, m): k = 1 while potnr(n, k) < m: k += 1 ...
[ "n^k >= m if and only if k >= log m base n\nSince log m base n = log m / log n, this is as simple as:\nfrom math import log, ceil\ndef smallest_k(n, m):\n return ceil(log(m)/log(n))\n\nThis runs in O(1) time.\n", "This one should work (I just fixed the value of k returned, for there was no guarantee it was the...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074482502_python.txt
Q: Django - Pagination test When moving a test from a separate class to a class with other tests, it starts showing 4 posts on the second page instead of 3. If range is changed to 12 it shows 2 posts. Please suggest what is the problem. def test_correct_page_context_guest_client(self): posts = [Post(text=f'Тесто...
Django - Pagination test
When moving a test from a separate class to a class with other tests, it starts showing 4 posts on the second page instead of 3. If range is changed to 12 it shows 2 posts. Please suggest what is the problem. def test_correct_page_context_guest_client(self): posts = [Post(text=f'Тестовый текст {i}', ...
[ "I added Post created in SetUpClass to SetUp and deleted it before pagination test with self.post.delete() command\n" ]
[ 0 ]
[]
[]
[ "django", "python", "python_3.x" ]
stackoverflow_0074482153_django_python_python_3.x.txt
Q: How to use new Spark Context I am currently running a jupyter notebook on GCP dataproc and hoping to increase the memory available via my config: I first stopped my spark context: import pyspark sc = spark.sparkContext sc.stop() Waited until running the next code block so sc.stop() can finish conf = pyspark.Spar...
How to use new Spark Context
I am currently running a jupyter notebook on GCP dataproc and hoping to increase the memory available via my config: I first stopped my spark context: import pyspark sc = spark.sparkContext sc.stop() Waited until running the next code block so sc.stop() can finish conf = pyspark.SparkConf().setAll([('spark.driver.max...
[ "You've created a SparkContext, not a new SparkSession.\nYou will need to use spark = SparkSession.builder.config(key, value).getOrCreate() after stopping the context.\nAlternatively (recommended) You should also be able to set PYSPARK_SUBMIT_ARGS='-c spark.driver.maxResultSize=8g' in the Notebook's environment var...
[ 1 ]
[]
[]
[ "apache_spark", "dataproc", "google_cloud_platform", "pyspark", "python" ]
stackoverflow_0074483399_apache_spark_dataproc_google_cloud_platform_pyspark_python.txt
Q: Split list into N lists, and assign each list to a worker in multithreading I'm writing a script that takes N records from a table, and processes the said records via multithreading. Previously I simply used Order by RAND() in my SQL statement within each worker definition, and hoped that there would be no duplica...
Split list into N lists, and assign each list to a worker in multithreading
I'm writing a script that takes N records from a table, and processes the said records via multithreading. Previously I simply used Order by RAND() in my SQL statement within each worker definition, and hoped that there would be no duplicates. This sort of works (deduping is done later), however, I would like to make m...
[ "Two things:\nFirst, take a look at the Queue object. You don't even need to split the lists apart yourself this way. It's used for splitting a collection of objects between multiple threads (there's also a multi-process varient, which is where I'm getting to). The docs contain very good examples that fit your requ...
[ 4, 1, 0 ]
[]
[]
[ "list", "multithreading", "python" ]
stackoverflow_0047900922_list_multithreading_python.txt
Q: I can't print my entire csv file in python on OnlineGDB I'm trying to print a csv file on OnlineGDB. However, when I do, I can only print the first and last column and 5 rows. It also prints [5 rows X 6 columns] at the very end. Although this is not terrible, my csv file contains over a thousand rows and 6 columns...
I can't print my entire csv file in python on OnlineGDB
I'm trying to print a csv file on OnlineGDB. However, when I do, I can only print the first and last column and 5 rows. It also prints [5 rows X 6 columns] at the very end. Although this is not terrible, my csv file contains over a thousand rows and 6 columns. Is there anyway I can print the entirety of my csv file? He...
[ "you can use a pandas function to show all columns\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\nI hope this helps!\n" ]
[ 0 ]
[]
[]
[ "csv", "file", "printing", "python" ]
stackoverflow_0074483402_csv_file_printing_python.txt
Q: Tell Python that two sympy symbols are related by a complex conjugate My Problem I am using Sympy v. 1.11.1 on (Jupyter Notebook) Python v. 3.8.5. I am dealing with a large Hessian, where terms such as these appear: Pi+ and Pi- are complex Sympy symbols. However, one is the complex conjugate of the other, that is...
Tell Python that two sympy symbols are related by a complex conjugate
My Problem I am using Sympy v. 1.11.1 on (Jupyter Notebook) Python v. 3.8.5. I am dealing with a large Hessian, where terms such as these appear: Pi+ and Pi- are complex Sympy symbols. However, one is the complex conjugate of the other, that is conjugate(Pi+) = Pi- and vice versa. This means that the product Pi+ * Pi-...
[ "Given one and the other, try replacing one with conjugate(other):\n>>> one = x; other = y\n>>> p = one*other; q = p.subs(one, conjugate(other); im(q),re(q)\n(Abs(y)**2, 0)\n\nIf you want to get back the original symbol after the simplifications wrought by the first replacement, follow up with a second replacement:...
[ 1 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0074482997_python_sympy.txt
Q: how to define python generic classes I have a class: T = TypeVar('T') class Stack(Generic[T]): def __init__(self) -> None: self.items: list[T] = [] def push(self, item: T) -> None: self.items.append(item) def pop(self) -> T: return self.items.pop() def empty(self) -> boo...
how to define python generic classes
I have a class: T = TypeVar('T') class Stack(Generic[T]): def __init__(self) -> None: self.items: list[T] = [] def push(self, item: T) -> None: self.items.append(item) def pop(self) -> T: return self.items.pop() def empty(self) -> bool: return not self.items but I c...
[ "Type checking vs runtime\nAfter writing this, I finally understood @Alexander point in first comment: whatever you write in annotations, it does not affect runtime, and your code is executed in the same way (sorry, I missed that you're looking just not from type checking perspective). This is core principle of pyt...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_typing" ]
stackoverflow_0074472798_python_python_3.x_python_typing.txt
Q: GEKKO error in model expression with array of variables and intermediates I am trying to use GEKKO for fitting and function parameters estimation. I need to use arrays of variables and arrays of intermediate-type variables because of changing number of parameters to fit. And got an error I think in a model. apm so...
GEKKO error in model expression with array of variables and intermediates
I am trying to use GEKKO for fitting and function parameters estimation. I need to use arrays of variables and arrays of intermediate-type variables because of changing number of parameters to fit. And got an error I think in a model. apm some_ip_here_gk_model14 <br><pre> -----------------------------------------------...
[ "Intermediates are not defined with m.Array() because they are defined with the m.Intermediate() method. Try using an empty list instead:\nG = [None]*num_pulses_in_window\nd = [None]*num_pulses_in_window\nf = [None]*num_pulses_in_window\n\nFor troubleshooting, open the run folder with model.open_folder() and inspec...
[ 0 ]
[]
[]
[ "curve_fitting", "gekko", "python" ]
stackoverflow_0074482108_curve_fitting_gekko_python.txt
Q: Loop to remove string in selected dataframe column header I wonder if it is possible to create a loop to remove strings in dataframe column. I have multiple dataframes which look like the structure below. df = pd.DataFrame({ 'xyz CODE': [1,2,3,3,4, 5,6,7,7,8], 'a': [4, 5, 3, 1, 2, 20, 10, 40, 50, 30], ...
Loop to remove string in selected dataframe column header
I wonder if it is possible to create a loop to remove strings in dataframe column. I have multiple dataframes which look like the structure below. df = pd.DataFrame({ 'xyz CODE': [1,2,3,3,4, 5,6,7,7,8], 'a': [4, 5, 3, 1, 2, 20, 10, 40, 50, 30], 'b': [20, 10, 40, 50, 30, 4, 5, 3, 1, 2], 'c': [25, 20, 5, ...
[ "Try to use DataFrame.rename:\ndf = df.rename(columns={df.columns[0]: df.columns[0].replace(\" CODE\", \"\")})\nprint(df)\n\nPrints:\n xyz a b c\n0 1 4 20 25\n1 2 5 10 20\n2 3 3 40 5\n3 3 1 50 15\n4 4 2 30 10\n5 5 20 4 25\n6 6 10 5 20\n7 7 40 3 5\n8 ...
[ 1, 0 ]
[]
[]
[ "loops", "pandas", "python", "python_3.x" ]
stackoverflow_0074483455_loops_pandas_python_python_3.x.txt
Q: Minimizing rows with a merge/squish in Pandas DataFrame with Multiple indexes With a DataFrame like, import pandas as pd import numpy as np df = pd.DataFrame({ 'id_1': [33,33,33,33,22,22,88,100], 'id_2': [64,64,64,64,12,12,77,100], 'col_1': [np.nan, 'dog', np.nan, 'kangaroo', np.nan, np.nan, np.nan, ...
Minimizing rows with a merge/squish in Pandas DataFrame with Multiple indexes
With a DataFrame like, import pandas as pd import numpy as np df = pd.DataFrame({ 'id_1': [33,33,33,33,22,22,88,100], 'id_2': [64,64,64,64,12,12,77,100], 'col_1': [np.nan, 'dog', np.nan, 'kangaroo', np.nan, np.nan, np.nan, np.nan], 'col_2': ['bike', 'car', np.nan, np.nan, 'train', np.nan, 'horse', np....
[ "# melt (wide to long) on id_1, id_2 and sort the values\n# this brings the NaN to the top\n\ndf2=df.melt(id_vars=['id_1', 'id_2'], var_name='col').sort_values(['id_1', 'id_2','col', 'value'])\n\n# create a seq, to make the keys unique and pivot\ndf3=(df2.assign(seq=df2.groupby(['id_1','id_2','col' ]).cumcount())\n...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074478461_dataframe_pandas_python.txt
Q: Python Higher order-function with varying arguments I am trying to write a higher-order function that takes a varying amount of arguments. For instance something like this def higher(fnc, args): print(f"Calling function {fnc}") fnc(argv) def one_arg(only_arg): print(f"Here is the only arg {only}") de...
Python Higher order-function with varying arguments
I am trying to write a higher-order function that takes a varying amount of arguments. For instance something like this def higher(fnc, args): print(f"Calling function {fnc}") fnc(argv) def one_arg(only_arg): print(f"Here is the only arg {only}") def two_arg(first, second): print(f"Here is the first {...
[ "you can just use * to define multiple args.\ndef higher(fnc, *args):\n print(f\"Calling function {fnc}\")\n fnc(*args)\n\ndef one_arg(only_arg):\n print(f\"Here is the only arg {only_arg}\")\n\ndef two_arg(first, second):\n print(f\"Here is the first {first} And here is the second {second}\")\n\nhigher...
[ 1, 0 ]
[]
[]
[ "higher_order_functions", "python", "python_3.x" ]
stackoverflow_0074483499_higher_order_functions_python_python_3.x.txt
Q: How to split text into columns? I want to split these ascii characters into 4 columns so it will look more convenient.. Uploaded a picture as an example.. for i in range(1,121): a = chr(i) print(str(i)+". "+str(a)) I have tried the .format or split(), but they don't seem to work as intended A: Because p...
How to split text into columns?
I want to split these ascii characters into 4 columns so it will look more convenient.. Uploaded a picture as an example.. for i in range(1,121): a = chr(i) print(str(i)+". "+str(a)) I have tried the .format or split(), but they don't seem to work as intended
[ "Because print prints line-by-line, we're going to have to figure out which characters go on the same line, and then format those into a string. Since some characters are not printable, we'll have to replace them, especially characters like \"\\n\" and \"\\t\", which would break our formatting. Luckily, python prov...
[ 2, 0 ]
[]
[]
[ "ascii", "python" ]
stackoverflow_0074483371_ascii_python.txt
Q: extract a specific table from web page I want to extract the first table of this page https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=1318605 For the second table of the page I use the id of the table url=f'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=1318605' response = requests.get(url) we...
extract a specific table from web page
I want to extract the first table of this page https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=1318605 For the second table of the page I use the id of the table url=f'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=1318605' response = requests.get(url) web = response.content soup = BeautifulSoup(we...
[ "Try:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=1318605\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\n# select correct table\ntable = soup.select_one(\"table:not(:has(table)):has(a:-soup-contai...
[ 1 ]
[]
[]
[ "beautifulsoup", "pandas", "python" ]
stackoverflow_0074483513_beautifulsoup_pandas_python.txt
Q: Looping through dataframe rows and compare them I am working with a huge dataframe and I want to loop through rows and compare them. If Value and DATE are the same in different rows I would like to merge them doing some statistics, eg, minimum of minimums etc.. Value MIN MAX MEAN STD DATE 0 -24...
Looping through dataframe rows and compare them
I am working with a huge dataframe and I want to loop through rows and compare them. If Value and DATE are the same in different rows I would like to merge them doing some statistics, eg, minimum of minimums etc.. Value MIN MAX MEAN STD DATE 0 -2460 -454 -1413.1 254.8 20181223 1 -2361 61...
[ "This is pretty easy.\ndf = pandas.read_clipboard(sep='\\\\s+')\ndf\n\ndf.groupby(['Value'])['MIN'].min()\n\n\ndf.groupby(['Value'])[['MIN','MAX','MEAN','STD']].min()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "if_statement", "loops", "python" ]
stackoverflow_0061122128_dataframe_if_statement_loops_python.txt
Q: jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 553305856 bytes. BufferAssignment OOM I'm getting this error when running a jax script on multiple GPU. jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 553305856 bytes. ...
jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 553305856 bytes. BufferAssignment OOM
I'm getting this error when running a jax script on multiple GPU. jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 553305856 bytes. BufferAssignment OOM Are there things I can do to solve this?
[ "This seems to have worked for me.\nos.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"]=\"false\"\nos.environ[\"XLA_PYTHON_CLIENT_MEM_FRACTION\"]=\".XX\"\nos.environ[\"XLA_PYTHON_CLIENT_ALLOCATOR\"]=\"platform\"\n\nhttps://jax.readthedocs.io/en/latest/gpu_memory_allocation.html\n" ]
[ 0 ]
[]
[]
[ "gpu", "jax", "python", "tensorflow" ]
stackoverflow_0074143812_gpu_jax_python_tensorflow.txt
Q: How can I artificially nest schemas in Marshmallow? In Marshmallow, is there a way to pass the current object to a Nested field in order to produce artificially nested serializations? For example, consider this object that I'm serializing: example = Example( name="Foo", address="301 Elm Street", city="...
How can I artificially nest schemas in Marshmallow?
In Marshmallow, is there a way to pass the current object to a Nested field in order to produce artificially nested serializations? For example, consider this object that I'm serializing: example = Example( name="Foo", address="301 Elm Street", city="Kalamazoo", state="MI", ) I want to produce JSON for...
[ "I managed to figure out a solution that allows me to preserve introspection and use only built-in fields; it's a little odd, though. I modified ExampleSchema to include a @pre_dump hook that adds a self-referential attribute, and pointed the field at that:\nclass ExampleSchema:\n name = fields.String()\n add...
[ 4, 1, 0 ]
[]
[]
[ "marshmallow", "python", "serialization" ]
stackoverflow_0051951669_marshmallow_python_serialization.txt
Q: How to extract the text from (bs4.element.Tag) How can I extract the "Data Engineer" text from <a class="jobTitle-link" href="/job/Data-Engineer/861664201/">Data Engineer</a> Sample Code should be fine. A: const text = document.querySelector(".jobTitle-link").innerText; console.log(text); <a class="jobTitle-lin...
How to extract the text from (bs4.element.Tag)
How can I extract the "Data Engineer" text from <a class="jobTitle-link" href="/job/Data-Engineer/861664201/">Data Engineer</a> Sample Code should be fine.
[ "\n\nconst text = document.querySelector(\".jobTitle-link\").innerText;\nconsole.log(text);\n<a class=\"jobTitle-link\" href=\"/job/Data-Engineer/861664201/\">Data Engineer</a>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "alfresco_webscripts", "html", "jupyter", "python", "web_scraping" ]
stackoverflow_0074483323_alfresco_webscripts_html_jupyter_python_web_scraping.txt
Q: Adding input variables to plot title/legend in Python I would like to display the current value of a parameter used to plot a certain function in the plot title/legend/annotated text. As a simple example, let's take a straight line: import numpy import matplotlib.pyplot as plt def line(m,c): x = numpy.linspace...
Adding input variables to plot title/legend in Python
I would like to display the current value of a parameter used to plot a certain function in the plot title/legend/annotated text. As a simple example, let's take a straight line: import numpy import matplotlib.pyplot as plt def line(m,c): x = numpy.linspace(0,1) y = m*x+c plt.plot(x,y) plt.text(0.1, 2.8, "...
[ "Use string formatting with the .format() method:\nplt.text(0.1, 2.8, \"The gradient is {}, the intercept is {}\".format(m, c))\n\nWhere m and c are the variables you want to substitute in. \nYou can directly write the variables like this in Python 3.6+ if you prefix the string with an f whcih denotes a formatted s...
[ 8, 3, 0 ]
[]
[]
[ "legend", "matplotlib", "python", "text" ]
stackoverflow_0051812323_legend_matplotlib_python_text.txt
Q: Trying to concatenate a string with a int but the min() command is there and is causing mayhem Im trying to do something for a school project and have the code ask the users for some numbers then print the smallest from the bunch.The main issue with this is that i have to put a string with the print so that the gr...
Trying to concatenate a string with a int but the min() command is there and is causing mayhem
Im trying to do something for a school project and have the code ask the users for some numbers then print the smallest from the bunch.The main issue with this is that i have to put a string with the print so that the grading system gives a 100.Im not sure on how to do that with my knowledge.Here is my code- num1=int(i...
[ "Hello @NindeBonic in order to show the Smallest number, you need to delete the \"Smallest\" string that you are trying to concat, instead use:\nnum1 = int(input(\"Enter a number: \"))\nnum2 = int(input(\"Enter a number: \"))\nnum3 = int(input(\"Enter a number: \"))\n\n# print the minumum of the three numbers\nprin...
[ 1 ]
[ "num1=int(input(\"Enter a number: \"))\nnum2=int(input(\"Enter a number: \"))\nnum3=int(input(\"Enter a number: \"))\nprint(\"Smallest: \" + str(min(num1 , num2 , num3)))\n\n", "You have the \"min\" in the wrong spot, it should be after the text:\nprint(\"Smallest:\", min(num1 , num2 , num3))\n" ]
[ -1, -2 ]
[ "python" ]
stackoverflow_0074483465_python.txt
Q: I want to know python gekko optimization solve I am currently using Python. However, I am struggling with one error. This is the tool I have made so far. from gekko import GEKKO import numpy as np m = GEKKO(remote=False) m.options.SOLVER = 1 hour = 24 Num_EV = 1 ...
I want to know python gekko optimization solve
I am currently using Python. However, I am struggling with one error. This is the tool I have made so far. from gekko import GEKKO import numpy as np m = GEKKO(remote=False) m.options.SOLVER = 1 hour = 24 Num_EV = 1 p_i =m.Array(m.Var,(hour,Num_EV)) TOU = ...
[ "There are a few problems with the model that can be observed by opening the model file in the run directory. Use m.open_folder() and open the gk_model0.apm file with a text editor. Here are some of the equations that indicate that there is a problem with the formulation:\nTrue\nv50>=v50\nv51>=v51\nv52>=v52\nv53>=v...
[ 0 ]
[]
[]
[ "gekko", "nonlinear_optimization", "optimization", "python" ]
stackoverflow_0074416838_gekko_nonlinear_optimization_optimization_python.txt
Q: How can I visualize single image with only one convolutional layer and one pooling layers? I wrote this sample code to show only a single image after passing it to my model. The model should have only one convolutional layer and one pooling layer. Or in another way, how can I visualize a single image by passing it...
How can I visualize single image with only one convolutional layer and one pooling layers?
I wrote this sample code to show only a single image after passing it to my model. The model should have only one convolutional layer and one pooling layer. Or in another way, how can I visualize a single image by passing it to a simple neural network that has one convolutional and one pooling layer? import torch impor...
[ "The input to the CNN needs to be of the torch.Tensor type. You can do this by applying the transform directly on the PIL image, as:\ndata = torchvision.transforms.functional.to_tensor(image)\n\nor\ntransform = torchvision.transforms.ToTensor() # can be composed with other transforms if necessary\ndata = transform(...
[ 1, 1 ]
[]
[]
[ "conv_neural_network", "deep_learning", "python", "pytorch" ]
stackoverflow_0074452216_conv_neural_network_deep_learning_python_pytorch.txt
Q: How to find circle faster than by Hough Transform in python opencv I’m trying to make Hough Transform find a circle faster or find another function that can do it faster. (i do not need to stick to open cv, but it needs to be opensource) I need to get centerpoint and radius. My use case: I have a square picture...
How to find circle faster than by Hough Transform in python opencv
I’m trying to make Hough Transform find a circle faster or find another function that can do it faster. (i do not need to stick to open cv, but it needs to be opensource) I need to get centerpoint and radius. My use case: I have a square picture in grayscale, 4 aruco markers in the corners(detected earlier), and a ...
[ "I didn't have much success with the method I suggested in the comments so I tried a different approach:\n#!/usr/bin/env python3\n\nimport cv2\n\n# Load image in greyscale\nim = cv2.imread('J65Xt.jpg', cv2.IMREAD_GRAYSCALE)\n\n# Define region of interest to exclude corner markers and reduce processing time\nROI = i...
[ 1 ]
[]
[]
[ "hough_transform", "opencv", "python" ]
stackoverflow_0074438250_hough_transform_opencv_python.txt
Q: python loop function in cs description: Python can loop functions in eachother. can cS loop function too? Example python: def func(): x=input(">") func() Example c# expected: namespace f {class f{ static void main(string[] args){ void stuff() { Console.readLine() stuff() } ...
python loop function in cs
description: Python can loop functions in eachother. can cS loop function too? Example python: def func(): x=input(">") func() Example c# expected: namespace f {class f{ static void main(string[] args){ void stuff() { Console.readLine() stuff() } } }} i dont think its possibl...
[ "I'm not familiar with C# but hopefully this page can help Recursive Function C#\nWhat you're trying to make is called a recursive function\n", "Every modern language supports recursion. The problem in your example was you had a nested function, which C# doesn't do. You'd write it like this:\nnamespace f {\n c...
[ 1, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0074483652_c#_python.txt
Q: Bbox For Image Grabbing So , I'm Trying To Make A Automated App Actually , i'm making it for Dino Web Game Everything Is Fine , But ! Colors Array's Number Will Not Change , I Think It is Boxing Problem Can You Guide Me With Correct Values In This Box ? from PIL import ImageGrab, ImageOps from webbrowser import op...
Bbox For Image Grabbing
So , I'm Trying To Make A Automated App Actually , i'm making it for Dino Web Game Everything Is Fine , But ! Colors Array's Number Will Not Change , I Think It is Boxing Problem Can You Guide Me With Correct Values In This Box ? from PIL import ImageGrab, ImageOps from webbrowser import open_new_tab as new from pyauto...
[ "If you just want to pixel match a certain rgb value in a certain x,y position then you can use pyautogui.pixelMatchesColor(x, y, (r, g, b)) which is perfect for this situation\nSo in your code (keep in mind you will have to change the x,y values):\nwhile True:\n #if at x 497 and y 524 the pixel matches your rgb...
[ 1 ]
[]
[]
[ "numpy", "pyautogui", "python", "python_imaging_library", "webbrowser_control" ]
stackoverflow_0074474813_numpy_pyautogui_python_python_imaging_library_webbrowser_control.txt
Q: Filling NaN values with rolling mean of the previous non-NaN values I have recently come across a case where I would like to replace NaN values with the rolling mean of the previous non-NaN values in such a way that each newly generated rolling mean is then considered a non-NaN and is used for the next NaN. This i...
Filling NaN values with rolling mean of the previous non-NaN values
I have recently come across a case where I would like to replace NaN values with the rolling mean of the previous non-NaN values in such a way that each newly generated rolling mean is then considered a non-NaN and is used for the next NaN. This is the sample data set: df = pd.DataFrame({'col1': [1, 3, 4, 5, 6, np.NaN,...
[ "for i in df.index:\n if np.isnan(df[\"col1\"][i]):\n df[\"col1\"][i] = (df[\"col1\"][i - 1] + df[\"col1\"][i - 2]) / 2\n\nThis can be a start using for loop, it will fail if the first 2 values of the dataframe are NAN\n" ]
[ 2 ]
[]
[]
[ "pandas", "python", "reduce" ]
stackoverflow_0074482996_pandas_python_reduce.txt
Q: Getting EOF error but running my code in Thonny produces no errors I'm learning python and one of my labs required me to: Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include th...
Getting EOF error but running my code in Thonny produces no errors
I'm learning python and one of my labs required me to: Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's, if the number of times t...
[ "Thank you Mr. Roberts the number of inputs was the issue. I had to create a single input and pull what I needed from that single line. My code ended up being:\nstring = input()\n\nchar = string[0]\n\nphrase = string[1:]\n\ncount = 0\n\nfor i in phrase:\n \nif i == char:\n \ncount +=1\n\nAll good now.\n" ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074483609_python.txt
Q: conda activate fails (results in IndexError: list index out of range) I have a fresh copy of Ubuntu 22.04 that I'm running in a Hyper-V virtual machine in Windows 11 Pro. I just installed Anaconda from anaconda.com. Everything seems fine (I've also added Conda to the path.) I created a new environment using: conda...
conda activate fails (results in IndexError: list index out of range)
I have a fresh copy of Ubuntu 22.04 that I'm running in a Hyper-V virtual machine in Windows 11 Pro. I just installed Anaconda from anaconda.com. Everything seems fine (I've also added Conda to the path.) I created a new environment using: conda create --name proto202211 Environment is created successfully and conda te...
[ "I found the solution to this problem. After installing anaconda I manually edited my PATH using:\necho \"export PATH=$PATH:/home/nate/anaconda3/bin\">> ~/.bashrc\nThis was a bad idea. I removed that line from .bashrc using gedit, restarted bash, and now I can switch environments.\nI got the idea to try this from t...
[ 0 ]
[]
[]
[ "anaconda", "conda", "linux", "python", "ubuntu" ]
stackoverflow_0074478348_anaconda_conda_linux_python_ubuntu.txt
Q: beginner python on looping back to the start of my simple number guessing game This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock: import random Player_Name = input("Wha...
beginner python on looping back to the start of my simple number guessing game
This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock: import random Player_Name = input("What is your name?\n") print(f"Hello {Player_Name}!\n") random_num = random.randint(1,...
[ "Honestly, there are many ways to do what you want. But using your code as base, this is one possible solution.\nimport random\n\n\nPlayer_Name = input(\"What is your name?\\n\")\nprint(f\"Hello {Player_Name}!\\n\")\nrandom_num = random.randint(1, 10)\n\n\n\ndef number_game():\n guess = int(input(\"What is the n...
[ 1, 0 ]
[]
[]
[ "integer", "loops", "python", "random" ]
stackoverflow_0074483670_integer_loops_python_random.txt
Q: How to extract all nested tags and their content with BeautifulSoup? I'm trying to pull out all nested <option> tags and their values using BeautifulSoup in Python. The first block of code provides the desired Unicode-type result (more than 60 pages of output). Part of the HTML tree is included below. Please note...
How to extract all nested tags and their content with BeautifulSoup?
I'm trying to pull out all nested <option> tags and their values using BeautifulSoup in Python. The first block of code provides the desired Unicode-type result (more than 60 pages of output). Part of the HTML tree is included below. Please note that the desired <option> tags are nested. Issue: The second block of code...
[ "I noticed that the part of the HTML you want to process is in a comment block, which means the BeautifulSoup cannot process the content.\n<!-- 3/23/06 <img src=\" -->\n\nTry the code below to see all the comments,\nimport requests\nfrom bs4 import BeautifulSoup, Comment\n\ndef main(base_url):\n response = reques...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x" ]
stackoverflow_0074483202_beautifulsoup_python_python_3.x.txt
Q: Flask and sqlalchemy: Receiving a "can't adapt type 'ABCMeta'" error when posting to database When I try to create a new user in the database I receive an error that reads sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'ABCMeta' I've seen similar responses to this error here, but I a...
Flask and sqlalchemy: Receiving a "can't adapt type 'ABCMeta'" error when posting to database
When I try to create a new user in the database I receive an error that reads sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'ABCMeta' I've seen similar responses to this error here, but I am unsure of what this error is telling me. Would anyone be able to give me clarity on what this err...
[ "It appears the password value you are trying to save is not a string, as the typing of the password column suggests you intended, but a class -- specifically, the class passlib.handlers.pbkdf2.pbkdf2_sha256. I think maybe you meant to call that class when you were setting the value of password (i.e., do this: pass...
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0072440229_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Python question using Monte carlo simulation and for loops This is the problem: Simulate the average of rolling two dice. This is the code I have so far: from random import seed, randint def simulate(): """ Roll two dice and return their sum """ dice_1 = randint(1,6) dice_2 = randint(1,6) ...
Python question using Monte carlo simulation and for loops
This is the problem: Simulate the average of rolling two dice. This is the code I have so far: from random import seed, randint def simulate(): """ Roll two dice and return their sum """ dice_1 = randint(1,6) dice_2 = randint(1,6) sum = dice_1 + dice_2 ### Main seed(0) total = 0 # Use...
[ "I didn't get exactly what you want to do, but is this enough for you ?\nfrom random import seed, randint\n\ndef simulate():\n \"\"\"\n Roll two dice and return their sum\n \"\"\"\n\n\n dice_1 = randint(1,6)\n dice_2 = randint(1,6)\n sum = dice_1 + dice_2\n # Add A return statement to get your...
[ 0 ]
[]
[]
[ "montecarlo", "python" ]
stackoverflow_0074483826_montecarlo_python.txt
Q: The function takes a string as a parameter. If the string is anything but "Arizona" you return the string passed in as an argument I don't know why it still printing Arizona, and not raising a ValueError.The function also needs to be able to take Arizona in any case mix for example "ArIzOna" in the argument. def r...
The function takes a string as a parameter. If the string is anything but "Arizona" you return the string passed in as an argument
I don't know why it still printing Arizona, and not raising a ValueError.The function also needs to be able to take Arizona in any case mix for example "ArIzOna" in the argument. def raising_arizona(string): try: print(string) return True except: if string.upper() == 'Arizona' or string...
[ "The \"try...except statement first runs the code in the try: section, and if it doesn't raise any exceptions (doesn't have an error) then it will skip over the except: section.\nSo, in you case, you are trying to print the passed argument and returning true. Neither of these lines throw an error, so the except sec...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074483770_python.txt
Q: Finding the indexes of an array If i have an array like this a = np.array([[False, False, False, False, False, False, False, False, False, False],[False, False, False, False, False, False, False, False, False, False],[False, False, False, True, True, False, False, False, False, False], I tried np.random.choice ...
Finding the indexes of an array
If i have an array like this a = np.array([[False, False, False, False, False, False, False, False, False, False],[False, False, False, False, False, False, False, False, False, False],[False, False, False, True, True, False, False, False, False, False], I tried np.random.choice but it doesnt work for 1_D arrays :(
[ "A possible solution is to loop through different indexes until you find a match\nE.g.\n\nimport random\nindex_0 = 0\nindex_1 = 0\nfound = False\nwhile not found:\n temp_i0 = random.randint(len(array))\n temp_i1 = random.randint(len(array[0]))\n if array[temp_i0][temp_i1]:\n index_0 = temp_i0\n inde...
[ 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074483572_numpy_python.txt
Q: What does asyncio.create_task actually do? I'm trying to understand how does asyncio.create_task actually work. Suppose I have following code: import asyncio import time async def delayer(): await asyncio.sleep(1) async def messenger(): await asyncio.sleep(1) return "A Message" async def main(): ...
What does asyncio.create_task actually do?
I'm trying to understand how does asyncio.create_task actually work. Suppose I have following code: import asyncio import time async def delayer(): await asyncio.sleep(1) async def messenger(): await asyncio.sleep(1) return "A Message" async def main(): message = await messenger() await delayer()...
[ "Perhaps it will help to think in the following way.\nYou cannot understand what await does until you understand what an event loop is. This line:\nasyncio.run(main())\n\ncreates and executes an event loop, which is basically an infinite loop with some methods for allowing an exit - a \"semi-infinite\" loop, so to...
[ 1 ]
[]
[]
[ "coroutine", "python", "python_asyncio" ]
stackoverflow_0074480673_coroutine_python_python_asyncio.txt
Q: Code for TensorFlow's EfficientNet preprocess_input()? I am using EfficientNet and I want to remove TensorFlow dependencies from my code, and for this I want to make preprocess_input on my own. from tensorflow.keras.applications.efficientnet import preprocess_input Can anyone tell me how to write preprocess_input...
Code for TensorFlow's EfficientNet preprocess_input()?
I am using EfficientNet and I want to remove TensorFlow dependencies from my code, and for this I want to make preprocess_input on my own. from tensorflow.keras.applications.efficientnet import preprocess_input Can anyone tell me how to write preprocess_input function of efficientnet without using TensorFlow? def prep...
[ "Efficient net model expect the images to have pixels in the range from 0 to 255 so if your images have pixels in that range you do not need to preprocess the input\n" ]
[ 1 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074472305_keras_python_tensorflow.txt
Q: save the pillow img result, and without vector line just the pure picture Purpose: (python) save the pillow img result, and without vector line just the pure picture I'm making the picture RGB/HSV (0~255) make img color I accidentally save the mask one , I want to save plt.show output (the one after filter the m...
save the pillow img result, and without vector line just the pure picture
Purpose: (python) save the pillow img result, and without vector line just the pure picture I'm making the picture RGB/HSV (0~255) make img color I accidentally save the mask one , I want to save plt.show output (the one after filter the mask) here is the pic link: https://imgur.com/a/eYVqHA9 and my script: ( is simp...
[ "you mention you used plt.imsave\nthe plt.savefig should work\nthe working script will be:\nfrom PIL import Image\nimport pytesseract\nimport cv2 \nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.pyplot as plt\n\npath_01 = \"/home/student_joy/desktop/output_02/\"\nout...
[ 0 ]
[]
[]
[ "matplotlib", "python", "python_imaging_library" ]
stackoverflow_0074473059_matplotlib_python_python_imaging_library.txt
Q: AttributeError: module 'matplotlib.pyplot' has no attribute 'xlabel' I read all the similar questions about this error, they are either spelling mistakes or importing the matplotlib.pyplot as plt wrong. My code is as follows. import matplotlib.pyplot as plt import matplotlib %matplotlib inline plt.hist(raw_data['...
AttributeError: module 'matplotlib.pyplot' has no attribute 'xlabel'
I read all the similar questions about this error, they are either spelling mistakes or importing the matplotlib.pyplot as plt wrong. My code is as follows. import matplotlib.pyplot as plt import matplotlib %matplotlib inline plt.hist(raw_data['smoker'], bins=3, color='gray') plt.xlabel('Smoker') plt.show() I'm not s...
[ "I am using matplotlib version 3.5.2 and it works\nYou can try with this command:\npip install matplotlib==3.5.2 \n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074483898_matplotlib_python.txt
Q: How do I get os.environ to list environment variables of my system, not a user? For context, I am trying to run code that tries to read an environment variable and spits an error: _PySpin.SpinnakerException: Spinnaker: System instance cannot be acquired. Could not load producer. Make sure that the environment vari...
How do I get os.environ to list environment variables of my system, not a user?
For context, I am trying to run code that tries to read an environment variable and spits an error: _PySpin.SpinnakerException: Spinnaker: System instance cannot be acquired. Could not load producer. Make sure that the environment variable FLIR_GENTL64_CTI_VS140 exists, and points to the location of the file FLIR_GenTL...
[ "Well, the problem is fixed. os.environ now prints out the environment variables found in windows system properties->advanced->environment variables.\nI am only guessing, but I think that restarting my windows machine fixed this issue. I deleted my conda environment. I uninstalled the Spinnaker SDK and then reinsta...
[ 0 ]
[]
[]
[ "environment_variables", "flir", "python", "spinnaker" ]
stackoverflow_0074483730_environment_variables_flir_python_spinnaker.txt
Q: Can I query elasticsearch inside spark map method? I can query elasticsearch from spark like this: spark.read.format( "es" ).options( **{ "es.index.auto.create": "true", 'es.resource': index_name, 'es.nodes.wan.only': 'true', 'es.nodes': elasticsearch_host, 'es.port'...
Can I query elasticsearch inside spark map method?
I can query elasticsearch from spark like this: spark.read.format( "es" ).options( **{ "es.index.auto.create": "true", 'es.resource': index_name, 'es.nodes.wan.only': 'true', 'es.nodes': elasticsearch_host, 'es.port': elasticsearch_port, 'es.net.http.auth.user': e...
[ "I fixed this problem by myself yesterday. The solution is relatively simple.\ndf.rdd.map(\n lambda x: ElasticSearch().search(index=index, query={\"match\": {\"name\": x[1]}})\n)\n\nyes, just new an object of ElasticSearch() will works.\nIf you encountered obstacles in this step such as Connection Error or etc. ...
[ 0 ]
[]
[]
[ "elasticsearch", "pyspark", "python" ]
stackoverflow_0074473030_elasticsearch_pyspark_python.txt
Q: How can I groupby row with multi-column with pandas? I'm beginner of pandas so I have a question below. There's a lot of answers about groupby rows but I can't find the answer what I want. anyway my datatable is below. COLUMN1 COLUMN2 COLUMN3 0 APPLE RED JOHN, JANE 1 BANANA YELLOW SMITH...
How can I groupby row with multi-column with pandas?
I'm beginner of pandas so I have a question below. There's a lot of answers about groupby rows but I can't find the answer what I want. anyway my datatable is below. COLUMN1 COLUMN2 COLUMN3 0 APPLE RED JOHN, JANE 1 BANANA YELLOW SMITH 1 BANANA YELLOW EMILY 2 GRAPE VIOLET JES...
[ "import pandas as pd\ndf = pd.DataFrame({'col1': ['Apple', 'Banana', 'Banana', 'Grape', 'Grape', 'Grape', 'Apple'], 'col2': ['Red', 'Yellow', 'Yellow', 'Violet', 'Violet', 'Purple', 'Red'], 'col3':['John, Jane', 'Smith', 'Emily', 'Jecica', 'Reira', 'Joe', 'Rio']})\ndf2 = df.groupby(['col1', 'col2'])['col3'].apply(l...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074483651_pandas_python.txt
Q: how can I store more objects from another class in other classes Field I've been looking for my problem in Django documentation and couldn't find solution. My problem is that in Api Pannel I cannot insert more objects from "ActorsAndDirectors" class into "cast" Field in "Movie" class. I can only insert one. How to...
how can I store more objects from another class in other classes Field
I've been looking for my problem in Django documentation and couldn't find solution. My problem is that in Api Pannel I cannot insert more objects from "ActorsAndDirectors" class into "cast" Field in "Movie" class. I can only insert one. How to transfrom cast field so I could insert multiple objects from "ActorsAndDire...
[ "What you are looking for is a Many to Many relation. Where many actors and directors can participate in many different movies.\nI would like to complement that when querying the database its slower to look for strings. Maybe you should check this choices option for your ActorsAndDirectors role field.\nThis would h...
[ 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074483636_django_django_models_django_rest_framework_python.txt
Q: Adding a list to df and getting Error invalid __array_struct__ Hi so I have a list of 54000 items, some of which say None. I want to add this list as a column to a df that has 54000 rows as well. I think I need to add a N/A to the empty rows but I can't seem to do that. This one gives me: Error invalid _array_stru...
Adding a list to df and getting Error invalid __array_struct__
Hi so I have a list of 54000 items, some of which say None. I want to add this list as a column to a df that has 54000 rows as well. I think I need to add a N/A to the empty rows but I can't seem to do that. This one gives me: Error invalid _array_struct_ df.insert(loc = 0, column = 'name', value = ...
[ "What you are describing should be as easy as making the list an additional column in the dataframe:\ndf['new_name'] = the_list\n\nUnless there's something very unusual with the list.\nBtw I'm assuming you are using a different name for the list than 'list', and this is just an example. If you aren't, you've either...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074483951_pandas_python.txt
Q: Is there any quick way to do the following in sql or python? I have a dataset of size 1TB containing 3 columns and about 20 billion rows. I would like to split this data in some random order into two sub datas in approximately 80/20 chunks. However, the two data should be non-overlapping meaning no entry in one c...
Is there any quick way to do the following in sql or python?
I have a dataset of size 1TB containing 3 columns and about 20 billion rows. I would like to split this data in some random order into two sub datas in approximately 80/20 chunks. However, the two data should be non-overlapping meaning no entry in one chunk should appear in another chunk. An entry in one column of one...
[]
[]
[ "You can just iterate over the file and randomly assign rows to sub-data-1 and sub-data-2 according to the proportions you've laid out.\nimport random\nwith open('large_file', 'r') as lf, \nopen('s1', 'w') as s1, open('s2', 'w') as s2:\n for line in lf:\n if random.random() < 0.8:\n s1.write(li...
[ -1 ]
[ "python", "sql" ]
stackoverflow_0074483972_python_sql.txt
Q: How can I connect myremotesql to Python? I tried to connect RemoteMySql as a host with PyMySql, it neither shows an error nor does it work. The code is below: db = pymysql.connect( host="remotemysql.com",user="USER", password="PASSWORD",db="DBNAME") cur = db.cursor() cur.execute("INSERT INTO `users` (ID, n...
How can I connect myremotesql to Python?
I tried to connect RemoteMySql as a host with PyMySql, it neither shows an error nor does it work. The code is below: db = pymysql.connect( host="remotemysql.com",user="USER", password="PASSWORD",db="DBNAME") cur = db.cursor() cur.execute("INSERT INTO `users` (ID, name, password,email) VALUES (93454623021,'Jeff...
[ "This source code is correct.\nAt issue is: \"does the client have TCP connectivity to the server?\".\nIt's easy to check.\nUse any one of these commands.\n$ ncat remotemysql.com 3306\nL\n8.0.13-4???3E>Z/l8Q?????hC+!h&CsNmysql_native_password\n^C\n$\n$ telnet remotemysql.com 3306\nTrying 37.59.55.185...\nConnected ...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074481975_mysql_python.txt
Q: Print parameter value if it exists for all class methods I have a class I wrote where a majority (but not all) of its methods take in an int parameter foo: class MyClass: def fun_one(self, foo: int): pass def fun_two(self, foo: int, flu: int): pass def fun_three(self, flu: str, foo: i...
Print parameter value if it exists for all class methods
I have a class I wrote where a majority (but not all) of its methods take in an int parameter foo: class MyClass: def fun_one(self, foo: int): pass def fun_two(self, foo: int, flu: int): pass def fun_three(self, flu: str, foo: int): pass def fun_four(self): pass Is th...
[ "You could add this to every method:\nif 'foo' in locals():\n print(foo)\n\n", "As a note to people in the future, I ended up using a regex script to do this. In VS Code's find/replace, I used the following:\n\nSearch: (def.*foo: int.*\\n)\nReplace: $1 print(foo)\\n\n\n(I'm sure there's a more efficient...
[ 0, 0 ]
[]
[]
[ "parameters", "python" ]
stackoverflow_0074482117_parameters_python.txt
Q: Align an array of traces in python I have an array of traces that are look like this : Really small low part then a big High part and ended with low part again. I want to be able to align all those traces ... as close as I can (so the changes from low to high and the opposite will be at the same indexes). I tried...
Align an array of traces in python
I have an array of traces that are look like this : Really small low part then a big High part and ended with low part again. I want to be able to align all those traces ... as close as I can (so the changes from low to high and the opposite will be at the same indexes). I tried to use cross-correlation but that gave ...
[ "I know this is kind of an old question, but I'll answer it anyway for future people interested. The way I solved this problem was by taking a section of the signal from one array and cross-correlating the other arrays with the section. I chose the max correlation and subtracted the max index of the subarray to get...
[ 0 ]
[]
[]
[ "numpy", "python", "sequence_alignment", "signals" ]
stackoverflow_0059492958_numpy_python_sequence_alignment_signals.txt
Q: Passing a dictionary to aggregate function in Python - Alternative Way? I have a bit of an odd issue - the following code works in Jupyter Notebook but it does not work in Databricks: df = df.set_index('date') groups = ['ABC', 'XYZ'] df_grouped = df.groupby(groups) df_grouped = df_grouped.resample('Q') df_group...
Passing a dictionary to aggregate function in Python - Alternative Way?
I have a bit of an odd issue - the following code works in Jupyter Notebook but it does not work in Databricks: df = df.set_index('date') groups = ['ABC', 'XYZ'] df_grouped = df.groupby(groups) df_grouped = df_grouped.resample('Q') df_grouped_agg = dict( sum_area=('shop_area', 'sum'), total_count=('name', 'c...
[ "For anyone who has this problem in the future (especially with Databricks for some reason) here's a workaround:\nBasically, replace:\ndf_grouped_agg = dict(\n sum_area=('shop_area', 'sum'),\n total_count=('name', 'count'),\n sum_total_1=('total_cost_customer', 'sum'),\n sum_total_2=('total_cost_item', ...
[ 0 ]
[]
[]
[ "aggregate", "databricks", "dictionary", "python" ]
stackoverflow_0074470344_aggregate_databricks_dictionary_python.txt
Q: Django rest filter by serializermethodfield with custom filter As declared in question title, i got task to filter results by field not presented in model but calculated by serializer. The model: class Recipe(models.Model): tags = models.ManyToManyField( Tag, related_name='recipe_tags' ) ...
Django rest filter by serializermethodfield with custom filter
As declared in question title, i got task to filter results by field not presented in model but calculated by serializer. The model: class Recipe(models.Model): tags = models.ManyToManyField( Tag, related_name='recipe_tags' ) author = models.ForeignKey( User, on_delete=models...
[ "We can use queryset annotate:\nfrom django.db import models\nfrom rest_framework import serializers\n\nclass RecipeViewSet(ModelViewSet):\n def get_queryset(self):\n user = self.request.user\n user_id = user.id if not user.is_anonymous else None\n return Recipe.objects.all().annotate(\n ...
[ 1 ]
[]
[]
[ "django", "django_filter", "django_rest_framework", "python" ]
stackoverflow_0074477101_django_django_filter_django_rest_framework_python.txt
Q: Aliasing commands in Python Argparse I'd like some of my argparse commands to have an alias. For example, let's say I have the command mycli test --true posarg. In this example, mycli is the name of the program (the parent parser), test is a subcommand (subparser parser), --true is a boolean flag argument, and pos...
Aliasing commands in Python Argparse
I'd like some of my argparse commands to have an alias. For example, let's say I have the command mycli test --true posarg. In this example, mycli is the name of the program (the parent parser), test is a subcommand (subparser parser), --true is a boolean flag argument, and posarg is a positional argument. I would like...
[ "Not an alias in the sense that you define one command that refers to another, but you can define two separate subcommands that achieve the same result. One has an option --true; the other has a positional argument with the same name.\nimport argparse\n\np = argparse.ArgumentParser()\nsp = p.add_subparsers()\np1 = ...
[ 0 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0074483693_argparse_python.txt
Q: How to connect to an existing firefox instance using selenium(python) Is there any way to open a Firefox browser and then connect to it using selenium? I know this is possible on chrome by launching it in the command line and using --remote-debugging-port argument like this: import subprocess from selenium import ...
How to connect to an existing firefox instance using selenium(python)
Is there any way to open a Firefox browser and then connect to it using selenium? I know this is possible on chrome by launching it in the command line and using --remote-debugging-port argument like this: import subprocess from selenium import webdriver from selenium.webdriver.chrome.options import Options subproces...
[ "CMD:\nC:\\Program Files\\Mozilla Firefox\\\n\nfirefox.exe -marionette -start-debugger-server 2828 //only use 2828\n\nPython Script:\nfrom selenium import webdriver\n\ndriver = webdriver.Firefox(executable_path = \"YOUR GECKODRIVER PATH\", service_args = ['--marionette-port', '2828', '--connect-existing'] )\n\npage...
[ 2, 1, 1 ]
[]
[]
[ "firefox", "geckodriver", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0072331816_firefox_geckodriver_python_selenium_selenium_webdriver.txt