content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to map apply_async exception to args given to apply_async function In my code I pass arguments (and the function to execute :-) to pool.apply_async. Later, if the function causes an exception, is there an elegant solution to map the arguments to the exception? from multiprocessing import Pool import dill def ...
How to map apply_async exception to args given to apply_async function
In my code I pass arguments (and the function to execute :-) to pool.apply_async. Later, if the function causes an exception, is there an elegant solution to map the arguments to the exception? from multiprocessing import Pool import dill def test(): with Pool(processes=5) as pool: results = [] fo...
[ "I see two solutions\nKeep together append( [result, run, test] )\nand later unpack it for result, run, test in results:\nfor run, test in self.run_queue:\n result = _apply_async(pool, self._prepare_and_run_test, args=(run, test))\n results.append( [result, run, test] )\n\nfor result, run, test in results:\n ...
[ 1 ]
[]
[]
[ "pool", "python" ]
stackoverflow_0074144088_pool_python.txt
Q: Customised data summary table I am attempting to create a data summary table that has three columns. One of which shows the attribute's name, one of which shows the most frequently occurring attribute-value, and the other shows the count of that most frequently occurring value. I have the following data: data = {"...
Customised data summary table
I am attempting to create a data summary table that has three columns. One of which shows the attribute's name, one of which shows the most frequently occurring attribute-value, and the other shows the count of that most frequently occurring value. I have the following data: data = {"Sex":["M", "M", "F", "F", "F", "F",...
[ "If you're looping through a DataFrame, you're probably doing it wrong.\n# Use `mode` to get the most frequent of each column.\nmost_frequent = df.mode().squeeze().rename('Most Frequently Occurring Value')\n\n# Get the counts of those with a mask.\ncounts = df[df.eq(most_frequent)].count().rename('Count')\n\n# Comb...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074147692_pandas_python.txt
Q: Failing to add constant numbers to data frames - NaN NaN NaN NaN I am trying to add some constant values to a data frame. I have successfully done multiplication, but now addition does not work. This works: df_C2H_TT_y1['DURATION_H'] = df_C2H_TT_y1['DURATION_H'] * 0.95 This does not work: TT_Base = pd.DataFrame()...
Failing to add constant numbers to data frames - NaN NaN NaN NaN
I am trying to add some constant values to a data frame. I have successfully done multiplication, but now addition does not work. This works: df_C2H_TT_y1['DURATION_H'] = df_C2H_TT_y1['DURATION_H'] * 0.95 This does not work: TT_Base = pd.DataFrame() TT_Base["TT"] = (0.05 + A2C_TT_x2['DURATION_H']) + 0.25 + df_C2H_TT_y...
[ "you should try df.values. Hope it should work.\nTT_Base = pd.DataFrame()\nTT_Base[\"Base_TT\"] = 0.05 + A2C_TT_x2['DURATION_H'].values + 0.25 + df_C2H_TT_y1['DURATION_H'].values + 0.58333333333333333333333333333333\nTT_Base\n\n", "Your code has no problem from outside. But it will only work if certain conditions...
[ 1, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "python_3.x" ]
stackoverflow_0074147593_dataframe_jupyter_notebook_pandas_python_python_3.x.txt
Q: I can't install PyQt5-tools I am trying to install PyQt5-tools but I'm having trouble with it. I'm getting the error that you can see below: Collecting pyqt5-tools Using cached pyqt5_tools-5.15.4.3.2-py3-none-any.whl (29 kB) Collecting pyqt5==5.15.4 Using cached PyQt5-5.15.4.tar.gz (3.3 MB) Installing build depend...
I can't install PyQt5-tools
I am trying to install PyQt5-tools but I'm having trouble with it. I'm getting the error that you can see below: Collecting pyqt5-tools Using cached pyqt5_tools-5.15.4.3.2-py3-none-any.whl (29 kB) Collecting pyqt5==5.15.4 Using cached PyQt5-5.15.4.tar.gz (3.3 MB) Installing build dependencies ... done Getting requireme...
[ "I had the same problem, when I researched, I saw that if you are using 3.10 version in python, pyqt5-tools cannot be installed in this version, I recommend you to install 3.9 version\n" ]
[ 0 ]
[]
[]
[ "pyqt5", "python", "pyuic" ]
stackoverflow_0072901537_pyqt5_python_pyuic.txt
Q: how would I create this list? A function that creates a list of 'a' random integers in the range of 'a' to (a+b) and then prints that list inside the function. The function returns a list of integers, taken from the list it initially created, that are multiple of b. print out the list that the function returns. th...
how would I create this list?
A function that creates a list of 'a' random integers in the range of 'a' to (a+b) and then prints that list inside the function. The function returns a list of integers, taken from the list it initially created, that are multiple of b. print out the list that the function returns. this is what I came up with, but its ...
[]
[]
[ "from random import randint\n\ndef RandInts( a, b ):\n c = [ randint( a, a + b ) for idx in range( 0, amount_nums_you_want_to_create ) ]\n print( c )\n d = [ num for num in c if num % b == 0 ]\n return d\n\n" ]
[ -1 ]
[ "integer", "list", "python" ]
stackoverflow_0074147739_integer_list_python.txt
Q: How Can I Add my Nested List to Pandas DataFrame as a row ? (Best way) I have an nested list like that; [[1,2,3,...,48], [96,97,98,...,144], [145,...,192]] --> means always list of length in inside is 48 and I have empty pandas dataframe like that (I wrote nan values ​​to show better.); one two three ... forty-...
How Can I Add my Nested List to Pandas DataFrame as a row ? (Best way)
I have an nested list like that; [[1,2,3,...,48], [96,97,98,...,144], [145,...,192]] --> means always list of length in inside is 48 and I have empty pandas dataframe like that (I wrote nan values ​​to show better.); one two three ... forty-eight 0 NaN NaN NaN ... NaN I want add nested list element (which is...
[ "The best way is to create directly DataFrame:\nimport pandas as pd\n\ndata = [ \n [1,2,3], \n [4,5,6], \n [7,8,9] \n]\n\ndf = pd.DataFrame(data, columns=['one', 'two', 'three'])\n\nprint(df)\n\nResult:\n one two three\n0 1 2 3\n1 4 5 6\n2 7 8 9\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074147309_dataframe_pandas_python.txt
Q: My Python Interpreter is not using the correct interpreter. I have reinstalled the Python extention and deactivated the Activate Integrated Terminal This is my interpreter path ("C:\Users\smuss\AppData\Local\Programs\Python\Python38\python.exe"). Within this path are all my packages. The interpreter goes to anothe...
My Python Interpreter is not using the correct interpreter. I have reinstalled the Python extention and deactivated the Activate Integrated Terminal
This is my interpreter path ("C:\Users\smuss\AppData\Local\Programs\Python\Python38\python.exe"). Within this path are all my packages. The interpreter goes to another interpreter which is "C:\Program Files\Inkscape\bin\python.exe" which doesnt contain all my packages. def checkPythonInterpreter(): print(sys.exe...
[ "Pleasure to meet you.\nHave you tried choose python interpreter in vscode?\n\nUse shortcuts \"Ctrl+Shift+P\" and type \"Python: Select Interpreter\"\n\n\n\nChoose the correct interpreter which you want.\n\n\n" ]
[ 0 ]
[]
[]
[ "interpreter", "python", "visual_studio_code" ]
stackoverflow_0074147051_interpreter_python_visual_studio_code.txt
Q: Template matching with updating templates from previous detection I am trying to write a code where after matching with a given template, the detected part of that frame becomes the template for the next frame. temp = "image.png" while True: try: _, frame = cap.read() copy = frame.copy() w,h=temp.shape[:-1] ...
Template matching with updating templates from previous detection
I am trying to write a code where after matching with a given template, the detected part of that frame becomes the template for the next frame. temp = "image.png" while True: try: _, frame = cap.read() copy = frame.copy() w,h=temp.shape[:-1] res=cv2.matchTemplate(frame,temp,cv2.TM_CCOEFF_NORMED) ...
[ "You can find x,y,w,h of the matched image with cv2.minMaxLoc()\nimport cv2\n\nsrc = cv2.imread(\"source.png\", cv2.IMREAD_GRAYSCALE)\ntemplit = cv2.imread(\"initial_template.png\", cv2.IMREAD_GRAYSCALE)\n\nresult = cv2.matchTemplate(src, templit, cv2.TM_SQDIFF_NORMED)\n\nminVal, maxVal, minLoc, maxLoc = cv2.minMax...
[ 0 ]
[]
[]
[ "opencv", "python", "template_matching" ]
stackoverflow_0074142524_opencv_python_template_matching.txt
Q: Adding pandas series on end of each pandas dataframe's row I've had issues finding a concise way to append a series to each row of a dataframe, with the series labels becoming new columns in the df. All the values will be the same on each of the dataframes' rows, which is desired. I can get the effect by doing the...
Adding pandas series on end of each pandas dataframe's row
I've had issues finding a concise way to append a series to each row of a dataframe, with the series labels becoming new columns in the df. All the values will be the same on each of the dataframes' rows, which is desired. I can get the effect by doing the following: df["new_col_A"] = ser["new_col_A"] ..... df["new_col...
[ "Given:\n# df\n\n A B\n0 1 2\n1 1 3\n2 4 6\n\n# ser\n\nC a\nD b\ndtype: object\n\nDoing:\ndf[ser.index] = ser\nprint(df)\n\nOutput:\n A B C D\n0 1 2 a b\n1 1 3 a b\n2 4 6 a b\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074147617_pandas_python.txt
Q: There is a problem with the writing of regular expressions. If there is a problem with the following writing, how can I modify it self.parameters[['设备机型', 'DeviceType', 'T6-800'], ['顶升抱闸', 'LiftBreak', '1'], ['电机方向', 'MotorDir', '1']] self.text("[10-20 10:15:44][2584][para_config_cmd][000] DeviceType:800 [10-20 1...
There is a problem with the writing of regular expressions. If there is a problem with the following writing, how can I modify it
self.parameters[['设备机型', 'DeviceType', 'T6-800'], ['顶升抱闸', 'LiftBreak', '1'], ['电机方向', 'MotorDir', '1']] self.text("[10-20 10:15:44][2584][para_config_cmd][000] DeviceType:800 [10-20 10:15:44][2584][para_config_cmd][001] RobotID:613 [10-20 10:15:44][2584][para_config_cmd][002] LiftBreak:1 [10-20 10:15:45][2584][para_c...
[ "self references removed, but this list comprehension returns what you're looking for.\nimport re\nparameters = [['设备机型', 'DeviceType', 'T6-800'], ['顶升抱闸', 'LiftBreak', '1'], ['电机方向', 'MotorDir', '1']]\ntext = (\"\"\"\n[10-20 10:15:44][2584][para_config_cmd][000] DeviceType:800\n[10-20 10:15:44][2584][para_config_c...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074147766_python.txt
Q: Gitbash Hangs on 'python' Command I was recently running a python test program in gitbash. It looks like this: COST_OF_FRISBEE = 15 num_frisbees = int(input("How many frisbees do you want? ")) result = COST_OF_FRISBEE * num_frisbees print("The total cost is " + str(result)) and is saved in a file called hw4.py. U...
Gitbash Hangs on 'python' Command
I was recently running a python test program in gitbash. It looks like this: COST_OF_FRISBEE = 15 num_frisbees = int(input("How many frisbees do you want? ")) result = COST_OF_FRISBEE * num_frisbees print("The total cost is " + str(result)) and is saved in a file called hw4.py. Unfortunately, when I run the program wi...
[ "Since there is no error in your code, that would point towards a problem with your python install.\nA Cross Referenced article to Super User: Git-Bash not running Python3 as expected, hanging issues\nGives advice on using winpty to create an alias that will run python in winpty instead of gitbash.\nin gitbash star...
[ 1 ]
[]
[]
[ "git_bash", "python" ]
stackoverflow_0074147890_git_bash_python.txt
Q: How do you give a date range then have that daterange be appended to the dataframe? I know how to generate a daterange using this code: pd.date_range(start='2022-10-16', end='2022-10-19') How do I get the daterange result above and loop through every locations in the below dataframe? +----------+ | Location | +---...
How do you give a date range then have that daterange be appended to the dataframe?
I know how to generate a daterange using this code: pd.date_range(start='2022-10-16', end='2022-10-19') How do I get the daterange result above and loop through every locations in the below dataframe? +----------+ | Location | +----------+ | A | | B | | C | +----------+ This is the result I want. ...
[ "You can cross join your date range and dataframe to get your desired result:\ndate_range = (pd.date_range(start='2022-10-16', end='2022-10-19')\n .rename('Date')\n .to_series())\n\ndf = df.merge(date_range, 'cross')\nprint(df)\n\nOutput:\n Location Date\n0 A 2022-10-16...
[ 3, 1 ]
[]
[]
[ "date_range", "pandas", "python" ]
stackoverflow_0074147873_date_range_pandas_python.txt
Q: Python subprocess check output not working I'm trying to run my test_script.py in main_script.py with subprocess. test_script.py is a siple sum program, and main_script.py should call it with 2 arguments, and catch output. Here is the code: test_script.py a = int(input()) b = int(input()) print(a+b) main_script....
Python subprocess check output not working
I'm trying to run my test_script.py in main_script.py with subprocess. test_script.py is a siple sum program, and main_script.py should call it with 2 arguments, and catch output. Here is the code: test_script.py a = int(input()) b = int(input()) print(a+b) main_script.py import subprocess subprocess.check_output(['p...
[ "Actually the subprocess check output command only returns the value. So, you need a variable to store it in. So you can try this:\nresult = subprocess.check_output(\"python test_script.py\", \n stderr=subprocess.STDOUT, shell=True)\nprint(result)\n\n", "All parts of argument must a string. Do the following inste...
[ 1, 0, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0033959540_python_subprocess.txt
Q: ImproperlyConfigured("Error loading psycopg2 module: %s" % e) Currently on MacOS Monterey working with Django 4.0 and Python 3.10.0. After running the command python3 manage.py runserver I get this error ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Err...
ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
Currently on MacOS Monterey working with Django 4.0 and Python 3.10.0. After running the command python3 manage.py runserver I get this error ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/tonyingle/.local/share/vi...
[ "Of course I figure it out right after I post the question, but here is what I did that worked for me.\nbrew install postgresql\n\npip install psycopg2-binary --force-reinstall --no-cache-dir\n\nApple M1: install psycopg2 package Symbol not found: _PQbackendPID\n", "I was running psycopg2 version 2.9.1. I updated...
[ 14, 1 ]
[]
[]
[ "django", "psycopg2", "python" ]
stackoverflow_0070637715_django_psycopg2_python.txt
Q: Python Can't Connect to Kernel My Jupyter Notebook will say connecting to kernel before not being able to make a connection. To correct this I run. python -m pip --proxy http://my_proxy_chain install --upgrade notebook But while installing that, while it's collecting pywinpty>=1.1.0, I get: ERROR: No matching dis...
Python Can't Connect to Kernel
My Jupyter Notebook will say connecting to kernel before not being able to make a connection. To correct this I run. python -m pip --proxy http://my_proxy_chain install --upgrade notebook But while installing that, while it's collecting pywinpty>=1.1.0, I get: ERROR: No matching distribution found for maturin<0.13,>=0...
[ "Try these steps;\ncreate new environment using venv or conda env create -name <YOUR_ENV_NAME>\ninstall dependancies. (You can even use pip install -r requirements.txt\nfor the jupyter kernel setup;\npip3 install jupyter ipykernel\npython3 -m ipykernel install --user --name=new_kernel\n\nnew_kernel is the name of t...
[ 0 ]
[]
[]
[ "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0074147768_jupyter_jupyter_notebook_python.txt
Q: OpenSearch Getting Run Execution Times I am doing research on AWS OpenSearch and one of the things I'm trying to measure is run times or execution times for different queries andindex commands. For example how long does it take to perform an action such as a query search, create index, delete index? Right now I am...
OpenSearch Getting Run Execution Times
I am doing research on AWS OpenSearch and one of the things I'm trying to measure is run times or execution times for different queries andindex commands. For example how long does it take to perform an action such as a query search, create index, delete index? Right now I am using the awswrangler Python library for in...
[ "I was able to resolve this by using the python requests library and looking at the \"took\" value in the response, which is the time it took to run the query in ms. Here is the code I used to get this working:\nsample_sql_query = \"SELECT * FROM <index_name> LIMIT 5\"\n\nsql_result = requests.post(\"<opensearch_d...
[ 0 ]
[]
[]
[ "amazon_opensearch", "amazon_web_services", "opensearch", "pandas", "python" ]
stackoverflow_0074128175_amazon_opensearch_amazon_web_services_opensearch_pandas_python.txt
Q: Is there a way to trick a lambda command to execute three functions in tkinter? I basically have a lot of different canvases that are all consequent to the other in order to create a game-like study guide. I wrote all canvases in functions given that it is schoolwork and with the click of every button the current ...
Is there a way to trick a lambda command to execute three functions in tkinter?
I basically have a lot of different canvases that are all consequent to the other in order to create a game-like study guide. I wrote all canvases in functions given that it is schoolwork and with the click of every button the current canvas ereases and it jumps to the next canvas called by a function. My issue is that...
[ "Lambda functions are nice for doing quick and simple things, but when you start wanting to do more complex functions it is typically best to just define a function the normal way using def. You can still defined your function inside of the parent function if you wish.\ndef make_two_functions():\n\n lambda_summe...
[ 0 ]
[]
[]
[ "lambda", "python", "thonny", "tkinter" ]
stackoverflow_0074147918_lambda_python_thonny_tkinter.txt
Q: Can we give pyautogui permission to I/O (Mouse and keyboard) in Chromebooks? I am using a Chromebook to code python. I made a script which makes it so that it looks up something in google. This is the current code: import pyautogui as pag import time time.sleep(3) pag.typewrite('is that a tomato?', interval=0.03)...
Can we give pyautogui permission to I/O (Mouse and keyboard) in Chromebooks?
I am using a Chromebook to code python. I made a script which makes it so that it looks up something in google. This is the current code: import pyautogui as pag import time time.sleep(3) pag.typewrite('is that a tomato?', interval=0.03) pag.press('enter') print('Working code.') If I run this program in Visual Studio...
[ "I just tested it, and it works in a limited way.\nKeyboard: Does not work in Chrome tabs, only in others(like linux apps)\nMouse: There are many errors.\n" ]
[ 0 ]
[]
[]
[ "chromebook", "google_chrome_os", "io", "pyautogui", "python" ]
stackoverflow_0071762666_chromebook_google_chrome_os_io_pyautogui_python.txt
Q: In Pandas df, apply function skiping NaN Confianza 2.0 4.0 7.0 NaN Expected Output: Confianza Baja Media Alta NaN In a pandas DataFrame, I want to apply this function for a column but skip NaN def condiciones(df5): if ( df5['Confianza'] > 4 ): return "Alta" elif (df5['Confianza'] == 4 ):...
In Pandas df, apply function skiping NaN
Confianza 2.0 4.0 7.0 NaN Expected Output: Confianza Baja Media Alta NaN In a pandas DataFrame, I want to apply this function for a column but skip NaN def condiciones(df5): if ( df5['Confianza'] > 4 ): return "Alta" elif (df5['Confianza'] == 4 ): return "Medi...
[ "import numpy as np\nimport pandas as pd\ndf = pd.DataFrame({\"Confianza\": [2.0, 4.0, 7.0, None]})\n\ndef condiciones(row):\n if (row[\"Confianza\"] is None) or (np.isnan(row[\"Confianza\"])):\n return np.nan\n elif (row[\"Confianza\"] > 4):\n return \"Alta\"\n elif (row[\"Confianza\"] == 4)...
[ 2, 1, 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074147965_group_by_pandas_python.txt
Q: how to make it can shows the calculation process? n =78 def subtracts_sum(n): sum = 0 while n > 0: number = n%10 sum = sum+number n = int(n/10) return sum subtracts_sum(n) n - subtracts_sum(n) This is what I wrote, and the output is 63. However, I want to make it have a cal...
how to make it can shows the calculation process?
n =78 def subtracts_sum(n): sum = 0 while n > 0: number = n%10 sum = sum+number n = int(n/10) return sum subtracts_sum(n) n - subtracts_sum(n) This is what I wrote, and the output is 63. However, I want to make it have a calculation process, like 78-(7+8) = 63. Can somebody help...
[ "You need to work on it like a string, in python every string works like a list, and you can call any parts of the string by using a[x:y:z]\nJust follow the code and you're good to go\ndef subtracts_sum(n):\n sum = 0\n while n > 0:\n number = n%10\n sum = sum+number\n n = int(n/10)\n r...
[ 0 ]
[]
[]
[ "calculation", "loops", "process", "python", "while_loop" ]
stackoverflow_0074147737_calculation_loops_process_python_while_loop.txt
Q: save separated ndarray predictions as csv file dans=pd.read_csv('ans.csv', header=0) dataa=dans for x in dataa['ideas']: token=tokenizer.texts_to_matrix([x], mode='tfidf') c=model.predict(np.array(token)) #cc=model.predict_classes(token) cc=np.argmax(c,axis=1) xc=encoder.inverse_transform(cc) ...
save separated ndarray predictions as csv file
dans=pd.read_csv('ans.csv', header=0) dataa=dans for x in dataa['ideas']: token=tokenizer.texts_to_matrix([x], mode='tfidf') c=model.predict(np.array(token)) #cc=model.predict_classes(token) cc=np.argmax(c,axis=1) xc=encoder.inverse_transform(cc) print((xc)) I want save the results of xc in a ...
[ "dans=pd.read_csv('ans.csv', header=0)\nresults = dans['A_COLUMN_NAME']\nresults['Prediction'] = 0\nidx = 0\ndataa=dans\nfor x in dataa['ideas']:\n token=tokenizer.texts_to_matrix([x], mode='tfidf')\n c=model.predict(np.array(token))\n #cc=model.predict_classes(token)\n cc=np.argmax(c,axis=1)\n xc=en...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074147456_python.txt
Q: Django ORM Get first row for each group I want to be able to get the first row of each group of id & type, I'll give and example : Type Id terms data_signed is_agreed ---------------------------------------- BUY 1 31 20-01-01 Y BUY 1 12 19-01-01 Y BUY 3 99 20...
Django ORM Get first row for each group
I want to be able to get the first row of each group of id & type, I'll give and example : Type Id terms data_signed is_agreed ---------------------------------------- BUY 1 31 20-01-01 Y BUY 1 12 19-01-01 Y BUY 3 99 20-01-01 N SELL 2 42 19-01-01...
[ "What's the desired order within each group? It's not consistent in your example. Without this it's impossible to determine which in the table is \"the first\":\nHowever, if you can decide on a third field to order by, then you could use window functions which sqlite and postgresql both support. This example suppos...
[ 4 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0073940537_django_python_sql.txt
Q: Rename images with ground truth values and image name I have a folder with named images (inside images folder it contains 150 folders and each folder contains 10,000 images) along with gt.txt. The single gt.txt is lying with images folder and contains the all images name with ground truth value. The structure of g...
Rename images with ground truth values and image name
I have a folder with named images (inside images folder it contains 150 folders and each folder contains 10,000 images) along with gt.txt. The single gt.txt is lying with images folder and contains the all images name with ground truth value. The structure of gt.txt is like images/0/0.jpg 참자녀사무실. I would like to rena...
[ "I think you can do like this:\n\nread the gt.txt, read the file, use split get raw name raw_name and the part of real name img_name;\nuse {}_{}.format(img_name, raw_name) to compose a new filename;\nuse a for loop to rename all image, you can use os.rename to do this.\n\nupdate:\nmy experience is that not use any ...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074147764_python_python_3.x.txt
Q: filter dataframe value in pandas Hi I was trying to extract only the no's from a columns in my df with this code: (df['hello']=='No') But it changes the values from the df and put it like a boolean values, I just want to value_count in that column the No's, but I'm not sure what I'm doing wrong. A: Assume you a...
filter dataframe value in pandas
Hi I was trying to extract only the no's from a columns in my df with this code: (df['hello']=='No') But it changes the values from the df and put it like a boolean values, I just want to value_count in that column the No's, but I'm not sure what I'm doing wrong.
[ "Assume you are using pandas.DataFrame, if you want to get the subset of df rows with 'hello' column value 'No', use:\ndf[df['hello']=='No']\n\nIf you only want the column 'hello':\ndf['hello'][df['hello']=='No']\n\n", "If you would like count\n(df['hello']=='No').sum()\n\nMore like value_counts\ndf['hello'].valu...
[ 1, 1, 1, 0 ]
[]
[]
[ "filtering", "numpy", "pandas", "python" ]
stackoverflow_0074147994_filtering_numpy_pandas_python.txt
Q: Python: remove read-only access Windows to copy and paste files I have tried many methods, some from How to remove read-only attrib directory with Python in Windows? but none work. Still getting the WinError Access Denied message. Simply need to access a file location, remove it, then put a different file in that ...
Python: remove read-only access Windows to copy and paste files
I have tried many methods, some from How to remove read-only attrib directory with Python in Windows? but none work. Still getting the WinError Access Denied message. Simply need to access a file location, remove it, then put a different file in that folder.
[ "Easiest way to do this is using OS library and execute commands in shell, but in big projects, especially commercial ones, It's going to be a security bug =)\nto use it, just import the OS library and use it like os.system('command').\nThis function let you run any commands in most Operating Systems\nIn your case,...
[ 0 ]
[]
[]
[ "python", "readonly", "windows" ]
stackoverflow_0074148055_python_readonly_windows.txt
Q: Python, About UnboundLocalError occurring in the if or for statement An error occurred during the process of utilizing the notion API. I want to categorize the titles separately and make them look good, but my code can't find the variable 'title'. ERR: UnboundLocalError: local variable 'title' referenced before a...
Python, About UnboundLocalError occurring in the if or for statement
An error occurred during the process of utilizing the notion API. I want to categorize the titles separately and make them look good, but my code can't find the variable 'title'. ERR: UnboundLocalError: local variable 'title' referenced before assignment import requests, json def read_database(database_id, token): ...
[ "actually UnboundLocalError error is self-exploratory.\nif you trace your code closely enough :\nif \"title\" in i:\n title = i\n print(title)\n\nif this condition is not satisfied, your variable title will not get declared.\nwhile your print statement : print(f\"The title type is {title} here.\") is outside ...
[ 1, 0, 0 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0074145335_python_scope.txt
Q: How can I sort with values if equal sort by a number String I have an list of lists, each have a String (index 0) and a Value(index 1) the string has an number in it, example a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3] I want to sort it based on, firstly, the value, so the higher value goes first...
How can I sort with values if equal sort by a number String
I have an list of lists, each have a String (index 0) and a Value(index 1) the string has an number in it, example a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3] I want to sort it based on, firstly, the value, so the higher value goes first and if there is equal value between two arrays, sort with the di...
[ "We can try doing the following 2D sort with the help of a lambda function:\na = [[\"Test 1\", 5],[\"Test 2\", 3],[\"Test 3\", 1], [\"Test 4\",3]]\na.sort(key=lambda row: (row[1], -int(row[0].split()[1])), reverse=True)\nprint(a) # [['Test 1', 5], ['Test 2', 3], ['Test 4', 3], ['Test 3', 1]]\n\nThe sort first orde...
[ 0 ]
[ "\nReturn a new result:\nsorted(a, key=lambda x: (-x[1], int(x[0].split()[1])))\n\nChange a itself:\na.sort(key=lambda x: (-x[1], int(x[0].split()[1])))\n\n\nlambda function generates a tuple. indicates the sort function that firstly bases on the Value(index 1) with a larger go first, and if in a tie then bases on ...
[ -1 ]
[ "python" ]
stackoverflow_0074148105_python.txt
Q: Export part of data filed - MongoDB I'm using MongoDB Compass to export my data as csv file, but I have only the choice to select which field I want and not elements in a specific field. MongoDB export data: Actually, I'm interested to save only the "scores" for object "0,1,2". Here a ScreenShot from MongDB Compa...
Export part of data filed - MongoDB
I'm using MongoDB Compass to export my data as csv file, but I have only the choice to select which field I want and not elements in a specific field. MongoDB export data: Actually, I'm interested to save only the "scores" for object "0,1,2". Here a ScreenShot from MongDB Compas: It is something that I should deal wi...
[ "One option could be to \"rewrite\" \"scoreTable\" so that there are a maximum of 3 elements in the \"scores\" array and then \"$out\" to a new collection that can be exported in full.\ndb.devicescores.aggregate([\n {\n \"$set\": {\n \"scoreTable\": {\n \"$map\": {\n \"input\": \"$scoreTabl...
[ 0 ]
[]
[]
[ "csv", "dataframe", "mongodb", "python" ]
stackoverflow_0074143734_csv_dataframe_mongodb_python.txt
Q: Add a common argument to all the methods in a class I have three methods in a class, class A: def func_1(self, a: int, b: int): print(a, b) def func_2(self, a: int, c: int): print(a, c) def func_3(self, a: int, d: int): print(a, d) I want to avoid repeating a: int again and again, is there a way...
Add a common argument to all the methods in a class
I have three methods in a class, class A: def func_1(self, a: int, b: int): print(a, b) def func_2(self, a: int, c: int): print(a, c) def func_3(self, a: int, d: int): print(a, d) I want to avoid repeating a: int again and again, is there a way I could add a as a parameter with type annotation int to...
[]
[]
[ "Yes, this is possible using the init method in a class object. It's a constructor function.\nclass A:\n def __init__(self, a: int, b: int) -> None:\n self.a = a\n self.b = b\n\n def add(self) -> int:\n return self.a + self.b\n\n" ]
[ -1 ]
[ "arguments", "python" ]
stackoverflow_0074147945_arguments_python.txt
Q: Django - mix two annotated values into one with a Case/When make the performance getting slow on many elements In get_queryset function inside a viewset I buid a queryset that needs to list a big amount of "Course" but with annotating some counts of a children model "CoursePerson". It could have like 10000 "Course...
Django - mix two annotated values into one with a Case/When make the performance getting slow on many elements
In get_queryset function inside a viewset I buid a queryset that needs to list a big amount of "Course" but with annotating some counts of a children model "CoursePerson". It could have like 10000 "Course" objects with in total ~5 millions of "CoursePerson" objects. I would like to annotate "interact_count" by taking a...
[ "You just want to use the Count function here, not subqueries. You can pass it filter kwargs to fine tune how you count the related models you're counting. Your Case/When + subqueries can be replaced by a more complex filter using Q objects passed to the Count function.\nI think this should work:\nphishing_and_sms_...
[ 0 ]
[]
[]
[ "case", "django", "python" ]
stackoverflow_0074142076_case_django_python.txt
Q: If statement in list dynamic creation colors = [ (i % 2 == 0)? "W" else "B" for i in range(4000)] The above is an invalid python syntax. But you get the goal, colors should be ["W", "B", "W",...] 4000 times. If there a way to achieve this in a single line in python ? A: You were close. You just didn't have the ...
If statement in list dynamic creation
colors = [ (i % 2 == 0)? "W" else "B" for i in range(4000)] The above is an invalid python syntax. But you get the goal, colors should be ["W", "B", "W",...] 4000 times. If there a way to achieve this in a single line in python ?
[ "You were close. You just didn't have the syntax quite right. Here's what you want:\ncolors = [ \"W\" if (i % 2 == 0) else \"B\" for i in range(4000)]\n\nResult:\n['W', 'B', 'W', 'B', 'W', 'B', 'W', 'B' ....\n\nIf you are going to iterate over the colors rather than really needing them all at once in an in-memory ...
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074148183_list_python_python_3.x.txt
Q: Conversion - beginner I have a hard time doing the arithmetic statement Convert the tuple, "Third" to an array. Double all the elements in "Third" Add the elements in this array to the elements in "Fourth". To do this, use only 1 arithmetic statement. Store this result as "Fifth" and print it. Hint Answer should l...
Conversion - beginner
I have a hard time doing the arithmetic statement Convert the tuple, "Third" to an array. Double all the elements in "Third" Add the elements in this array to the elements in "Fourth". To do this, use only 1 arithmetic statement. Store this result as "Fifth" and print it. Hint Answer should look like this: Fifth = 2*(_...
[ "The numpy.ndarray type (docs) supports addition using the + operator. However, in your example my guess is that 2*arr + fourth will not produce the result you are looking for because fourth is of shape (7,1) while arr is of shape (7,), so arr + fourth would be of shape (7,7).\nThere are multiple ways to get fourth...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074148106_arrays_numpy_python.txt
Q: Father and Daughter Accounts - Error Detection In the company I work for, we have a business rule, where each customer account can be within or linked to another account. For example, company A owns company B, hence we call company A the parent of company B and therefore company B is the daughter of company A. Thi...
Father and Daughter Accounts - Error Detection
In the company I work for, we have a business rule, where each customer account can be within or linked to another account. For example, company A owns company B, hence we call company A the parent of company B and therefore company B is the daughter of company A. This relationship must follow the following rules: Eac...
[ "# Valid parents are Account IDs with itself as Parent Account ID\nvalid_parents = df.loc[df[\"ID Acc\"] == df[\"ID Parent Acc\"], \"ID Acc\"]\n\n# Violators are those whose parents NOT in the valid_parents series\ndf[~df[\"ID Parent Acc\"].isin(valid_parents)]\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074144697_pandas_python.txt
Q: In xonsh how can I receive from a pipe to a python expression? In the xonsh shell how can I receive from a pipe to a python expression? Example with a find command as pipe provider: find $WORKON_HOME -name pyvenv.cfg -print | for p in <stdin>: $(ls -dl @(p)) The for p in <stdin>: is obviously pseudo code. What do...
In xonsh how can I receive from a pipe to a python expression?
In the xonsh shell how can I receive from a pipe to a python expression? Example with a find command as pipe provider: find $WORKON_HOME -name pyvenv.cfg -print | for p in <stdin>: $(ls -dl @(p)) The for p in <stdin>: is obviously pseudo code. What do I have to replace it with? Note: In bash I would use a construct l...
[ "The easiest way to pipe input into a Python expression is to use a function that is a callable alias, which happens to accept a stdin file-like object. For example, \ndef func(args, stdin=None):\n for line in stdin:\n ls -dl @(line.strip())\n\nfind $WORKON_HOME -name pyvenv.cfg -print | @(func)\n\nOf cou...
[ 3, 0 ]
[]
[]
[ "bash", "python", "xonsh" ]
stackoverflow_0053119083_bash_python_xonsh.txt
Q: is there any way that I can lessen the line of this code grade = float(input("Input: ")) if grade <= 60 or grade > 100: print ("Invalid Grade") elif grade > 60 and grade <= 74.9: print ("failing grade") else: print ("Passed!") A: Number of conditions you have will give this minimal number of if-el...
is there any way that I can lessen the line of this code
grade = float(input("Input: ")) if grade <= 60 or grade > 100: print ("Invalid Grade") elif grade > 60 and grade <= 74.9: print ("failing grade") else: print ("Passed!")
[ "Number of conditions you have will give this minimal number of if-else block. But you can try complex conditional one liner like this\ngrade = float(input(\"Input: \"))\ns = \"Invalid Grade\" if grade <= 60 or grade > 100 else (\"failing grade\" if grade > 60 and grade <= 74.9 else \"Passed!\")\nprint(s)\n\n" ]
[ 1 ]
[ "You can use a list of remarks with a calculated index based on the number of tiers the input grade clears. Use a modulo of 3 to make the highest tier fall back to index 0 for an invalid grade. With this approach, your code would be more easily scalable when there is a need to increase the number of tiers:\ngrade =...
[ -1, -1 ]
[ "python" ]
stackoverflow_0074147949_python.txt
Q: Use while loop with continue statement to print all letters except 'p' and 'r'. a = 'happyfriday' I am learning how to use while loop for the continue statement and trying to print all letters except 'p' and 'r' in a string: a = 'happyfriday' I tried several ways but unable to figure out, my current version is: a=...
Use while loop with continue statement to print all letters except 'p' and 'r'. a = 'happyfriday'
I am learning how to use while loop for the continue statement and trying to print all letters except 'p' and 'r' in a string: a = 'happyfriday' I tried several ways but unable to figure out, my current version is: a= 'happyfriday' while True: if a == "g": continue if a =="o": continue print(a) ...
[ "Try this, what you need to loop through is string a\na = 'happyfriday'\nindex = 0\nwhile index < len(a):\n if (value := a[index]) in (\"p\", \"r\"):\n index += 1\n continue\n else:\n print(value)\n index += 1\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074147696_python_python_3.x.txt
Q: Use the classic Python IDLE theme in Visual Studio Code? How can I set the original Python IDLE colors in Visual Studio Code? This could be a very useful question for readers. I read that you need to edit the Json file, but I don't know what to write to it. I would use this with white background theme: Variables &...
Use the classic Python IDLE theme in Visual Studio Code?
How can I set the original Python IDLE colors in Visual Studio Code? This could be a very useful question for readers. I read that you need to edit the Json file, but I don't know what to write to it. I would use this with white background theme: Variables & Data: #000000 Strings: #00aa00 Functions (for example len(), ...
[ "The picture shows how to open it. You can also use shortcuts \"Ctrl+K Ctrl+T\" to open it.\n\n\nFor me, the classic color is the dark+ in the options.\nYou can also set it in your settings.json or try some theme extensions.\nFor example:\n\"workbench.colorCustomizations\": {\n \"statusBar.background\" : \"#0000...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "themes", "visual_studio_code" ]
stackoverflow_0074147908_python_python_3.x_themes_visual_studio_code.txt
Q: How to create and return a Zarr file from xarray Dataset? How would I go about creating and return a file new_zarr.zarr from a xarray Dataset? I know xarray.Dataset.to_zarr() exists but this returns a ZarrStore and I must return a bytes-like object. I have tried using the tempfile module but am unsure how to proce...
How to create and return a Zarr file from xarray Dataset?
How would I go about creating and return a file new_zarr.zarr from a xarray Dataset? I know xarray.Dataset.to_zarr() exists but this returns a ZarrStore and I must return a bytes-like object. I have tried using the tempfile module but am unsure how to proceed, how would I write an xarray.Dataset to a bytes-like object ...
[ "Zarr supports multiple storage backends (DirectoryStore, ZipStore, etc.). If you are looking for a single file object, it sounds like the ZipStore is what you want.\nimport xarray as xr\nimport zarr\n\nds = xr.tutorial.open_dataset('air_temperature')\nstore = zarr.storage.ZipStore('./new_zarr.zip')\nds.to_zarr(sto...
[ 1 ]
[]
[]
[ "file", "geospatial", "python", "python_xarray", "zarr" ]
stackoverflow_0074127357_file_geospatial_python_python_xarray_zarr.txt
Q: How do I catch a psycopg2.errors.UniqueViolation error in a Python (Flask) app? I have a small Python web app (written in Flask) that uses sqlalchemy to persist data to the database. When I try to insert a duplicate row, an exception is raised, something like this: (psycopg2.errors.UniqueViolation) duplicate key ...
How do I catch a psycopg2.errors.UniqueViolation error in a Python (Flask) app?
I have a small Python web app (written in Flask) that uses sqlalchemy to persist data to the database. When I try to insert a duplicate row, an exception is raised, something like this: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "uix_my_column" I would like to wrap the exception ...
[ "The error that you have posted in your question isn't the error that has been raised. The full error message is:\nsqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint \"model_name_key\"\n\nThe key part being the SQLAlchemy error which you've chosen to omit...
[ 41, 16, 10, 6, 0, 0, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0058740043_python_sqlalchemy.txt
Q: Altair: Converting Y-Axis to % Format in Global Configuration (vs Local Config) I need my Y-axis labels to be in the '%' format. I know how to do this with local configuration: line1 = alt.Chart(source).mark_line( ).encode( x='Date:T', y=alt.Y('value:Q', title="Some Title", axis=alt.Axis(format='%')), ) ...
Altair: Converting Y-Axis to % Format in Global Configuration (vs Local Config)
I need my Y-axis labels to be in the '%' format. I know how to do this with local configuration: line1 = alt.Chart(source).mark_line( ).encode( x='Date:T', y=alt.Y('value:Q', title="Some Title", axis=alt.Axis(format='%')), ) line1 In the above example, the "axis=alt.Axis(format='%')" argument converts the a...
[ "You can use chart.configure(numberFormat='%'). For example:\nimport altair as alt\nimport pandas as pd\nimport numpy as np\n\nsource = pd.DataFrame({\n 'Date': pd.date_range('2021-01-01', freq='D', periods=7),\n 'value': np.linspace(0, 1, 7),\n})\n\nalt.Chart(source).mark_line().encode(\n x='Date:T', \n ...
[ 2, 0 ]
[]
[]
[ "altair", "data_visualization", "python", "vega_lite" ]
stackoverflow_0065668046_altair_data_visualization_python_vega_lite.txt
Q: matching 2 dataframes in pandas If I have 2 dataframes in pandas like below but 2 dataframes don't have same columns, only few columns are same. df1 no datas1 datas2 datas3 datas4 0 a b a a 1 b c b b 2 d b c a df2 no datas1 datas2 datas3 data4 data 5 d...
matching 2 dataframes in pandas
If I have 2 dataframes in pandas like below but 2 dataframes don't have same columns, only few columns are same. df1 no datas1 datas2 datas3 datas4 0 a b a a 1 b c b b 2 d b c a df2 no datas1 datas2 datas3 data4 data 5 data6 0 c a a a ...
[ "You can do this - first run equals method and if True then print that dataframes match, otherwise use compare method and then calculate the percentage of rows that matched between dfs:\nimport pandas as pd\n\ndf1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})\ndf2 = pd.DataFrame({'a': [2, 2, 3], 'b': [4, 5, 7]})...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074148442_pandas_python.txt
Q: Packet sequence number wrong - got 1 expected 0 Getting the below error in MariaDb and its causing timeout issue : Debugged it with removing skip-name-resolve, granting privileges to user@localhost, and in pyton create_engine used pool_pre_ping = True and pool_recycle=3600 but nothing seems to solve the issue. Mar...
Packet sequence number wrong - got 1 expected 0
Getting the below error in MariaDb and its causing timeout issue : Debugged it with removing skip-name-resolve, granting privileges to user@localhost, and in pyton create_engine used pool_pre_ping = True and pool_recycle=3600 but nothing seems to solve the issue. MariaDb version is 10.4.20 and Python is 3.9.Its not a m...
[ "Used poolclass=NullPool in create_engine.\nThis has fixed the Packet Sequence error in this case.The app does not stop with Packet Sequence error anymore.\n" ]
[ 0 ]
[]
[]
[ "mariadb", "mariadb_10.4", "python", "python_3.x", "sqlalchemy" ]
stackoverflow_0071611802_mariadb_mariadb_10.4_python_python_3.x_sqlalchemy.txt
Q: What's wrong for the error of Time Limit Exceeded on leetcode 53. Maximum Subarray? My code is below for leetcode 53.Maximum Subarray, but one test case is not passed. How can I fix my current code to prevent Time Limit Exceeded? class Solution(object): def maxSubArray(self, nums): """ :type nu...
What's wrong for the error of Time Limit Exceeded on leetcode 53. Maximum Subarray?
My code is below for leetcode 53.Maximum Subarray, but one test case is not passed. How can I fix my current code to prevent Time Limit Exceeded? class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ result = nums[0] array_len ...
[ "I think you can use some algorihm function to reduce your time complexity;lick max() in c++.\nYou can use iteration to solut it.\n", "You are getting TLE because your solution's runtime is O(n^2). The time complexity can be reduced by two ways. Either you need to use divide and conquer approach which has O(nlogn...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0059728698_python_python_3.x.txt
Q: Derive consumption from existing column (Pandas) Data client total avail used date charles 5000 5000 0 2/1/2022 charles 8000 5000 3000 2/1/2022 charles 500 500 0 3/1/2022 cara 1000 100 900 3/1/2022 cara 2000 50 1550 2/1/2022...
Derive consumption from existing column (Pandas)
Data client total avail used date charles 5000 5000 0 2/1/2022 charles 8000 5000 3000 2/1/2022 charles 500 500 0 3/1/2022 cara 1000 100 900 3/1/2022 cara 2000 50 1550 2/1/2022 cara 500 0 500 2/1/2022 cara...
[ "You aren't using a correct aggregation function. You should be using sum on both your \"used\" and \"total\" columns:\ndf = pd.DataFrame(\n {\n 'client': ['charles', 'charles', 'charles', 'cara', 'cara', 'cara', 'cara'],\n 'total': [5000, 8000, 500, 1000, 2000, 500, 100],\n 'used': [0, 3000...
[ 3 ]
[]
[]
[ "group_by", "numpy", "pandas", "python" ]
stackoverflow_0074148524_group_by_numpy_pandas_python.txt
Q: Create gradient image in numpy for LUT (Look Up Tables) What I'm trying to achieve: lookup tables to create duotone effect also called false color. Say I have two colours: pure red and pure green provided in hex format ff0000 and 00ff00 respectively. We know its essentially (255, 0, 0) and (0, 255, 0). I need to c...
Create gradient image in numpy for LUT (Look Up Tables)
What I'm trying to achieve: lookup tables to create duotone effect also called false color. Say I have two colours: pure red and pure green provided in hex format ff0000 and 00ff00 respectively. We know its essentially (255, 0, 0) and (0, 255, 0). I need to create a 256x1 gradient image in numpy with red and green at b...
[ "From here modifying to give numpy arrays\ndef hex_to_rgb(hex):\n hex = hex.lstrip('#')\n hlen = len(hex)\n return np.array([int(hex[i:i+hlen//3], 16) for i in range(0, hlen, hlen//3)])\n\nThen the numpy part:\ndef gradient(hex1, hex2):\n np1 = hex_to_rgb(hex1)\n np2 = hex_to_rgb(hex2)\n return...
[ 1, 0 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0064680907_numpy_opencv_python.txt
Q: Assertion error with uppercase / lower case not working (Python) I've been studying the Python textbook "Automate the boring stuff" and doing fine but this task has really stumped me. Been trying to do it for days, but can't get it right. Worst part is, I'm sure it's something kinda simple. What would you conside...
Assertion error with uppercase / lower case not working (Python)
I've been studying the Python textbook "Automate the boring stuff" and doing fine but this task has really stumped me. Been trying to do it for days, but can't get it right. Worst part is, I'm sure it's something kinda simple. What would you consider the best answer? Thank you. Write an assert statement that triggers ...
[ "assert eggs.lower() != bacon.lower()\n\n" ]
[ 0 ]
[]
[]
[ "assertion", "lowercase", "python", "uppercase" ]
stackoverflow_0074148604_assertion_lowercase_python_uppercase.txt
Q: AttributeError: 'tuple' object has no attribute 'startswith' in pyspark This is the command I use: test=rdd.filter(lambda line:line.startsWith("I")) test.take(2) Of course, rdd was already made and it worked fine. But test did not work and showing the below the error. This question can look sily but I am unfamil...
AttributeError: 'tuple' object has no attribute 'startswith' in pyspark
This is the command I use: test=rdd.filter(lambda line:line.startsWith("I")) test.take(2) Of course, rdd was already made and it worked fine. But test did not work and showing the below the error. This question can look sily but I am unfamiliar with Pyspark. I got this error in pyspark through the virtual machine. Do...
[ "From the error, it looks like the rdd is not RDD[String] but RDD[Tuple] and since you are trying to apply startswith which is a python string function, it fails.\nYou can try something like this:\ntest = rdd.filter(lambda line: line[0][0].startsWith(\"I\"))\nThe above will filter your RDD and return records whose ...
[ 0, 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0049808613_apache_spark_pyspark_python.txt
Q: Python for shiny, How to access input id that gernerated by iteration? I am new in python for shiny.I have create text input ui from iteration that number of iteration come from user input(in example code it is 5 times).But I can not access their ID because in shiny it must call 'input.<ID>()' and deny by python i...
Python for shiny, How to access input id that gernerated by iteration?
I am new in python for shiny.I have create text input ui from iteration that number of iteration come from user input(in example code it is 5 times).But I can not access their ID because in shiny it must call 'input.<ID>()' and deny by python input() method.Anyone can solve this. from shiny import App, ui, reactive, re...
[ "The shiny team already answer me.\nUse \"input['input_1']()\" instead of \"input.input_1()\" and it's OK.Thank you.\n" ]
[ 2 ]
[]
[]
[ "javascript", "py_shiny", "python", "python_3.x", "shiny" ]
stackoverflow_0074140129_javascript_py_shiny_python_python_3.x_shiny.txt
Q: Implementation of stable_sort in python In c++ there is a function stable_sort() function (It preserves the order ) .Is there any function in python like this ? A: list.sort() is stable. From the documentation: The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the re...
Implementation of stable_sort in python
In c++ there is a function stable_sort() function (It preserves the order ) .Is there any function in python like this ?
[ "list.sort() is stable. From the documentation:\n\nThe sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).\n\n" ]
[ 2 ]
[]
[]
[ "c++", "python", "stable_sort" ]
stackoverflow_0074148653_c++_python_stable_sort.txt
Q: Explode data in Python I have data in the table which I wanted to explode Input: | Col 1 | Col 2 | Col 3 | | -------- | ---------|---------| | [A,B,C,D]| Value 1 | Value 2 | Expected Output: The 'col 1' is exploded in the combination the [A,B,C,D]. The values 'col 1' can vary in length also the values ar...
Explode data in Python
I have data in the table which I wanted to explode Input: | Col 1 | Col 2 | Col 3 | | -------- | ---------|---------| | [A,B,C,D]| Value 1 | Value 2 | Expected Output: The 'col 1' is exploded in the combination the [A,B,C,D]. The values 'col 1' can vary in length also the values are dynamic | Col 1 | Col 2...
[ "Let's use itertools.combinations on Col 1 column then explode\nimport itertools\n\ndf['Col 1'] = df['Col 1'].apply(lambda lst: list(itertools.combinations(lst, 2)))\nout = df.explode('Col 1', ignore_index=True)\n\nprint(out)\n\n Col 1 Col 2 Col 3\n0 (A, B) Value 1 Value 2\n1 (A, C) Value 1 Value 2\n...
[ 2 ]
[]
[]
[ "pandas", "pandas_explode", "python" ]
stackoverflow_0074148589_pandas_pandas_explode_python.txt
Q: How to keep the same dict value while filling the nans in pandas Assume we have the dict having the median values of the features: infereddict = {sepalwidth : -0.03999432052319804, sepalheight :-0.08741807979521529, petalwitdh: -0.049475134763957505} while we fill the nans in datafarame with the dict , it change...
How to keep the same dict value while filling the nans in pandas
Assume we have the dict having the median values of the features: infereddict = {sepalwidth : -0.03999432052319804, sepalheight :-0.08741807979521529, petalwitdh: -0.049475134763957505} while we fill the nans in datafarame with the dict , it changes the value and gives below output sepalwidth -3.999432e-02 sepalh...
[ "Pandas is displaying the numbers in scientific notation. The values are equal to each other, it's just a different way of displaying numbers.\nSome examples of comparing the two and converting between two formats\n>>> # You can directly check that they're equal to each other\n>>> -0.039994 == -3.9994e-2\nTrue\n>>>...
[ 0 ]
[]
[]
[ "dictionary", "fillna", "pandas", "python" ]
stackoverflow_0074148327_dictionary_fillna_pandas_python.txt
Q: "database is locked" in SQLite3 and Python after SELECT and Loop this is my first post in Stackoverflow.com This is the process I'm following: Make a connection to dB Make a query to the dB to check if the register exists If the register does NOT exist iterate over a loop Add the registers in the dB My code: con...
"database is locked" in SQLite3 and Python after SELECT and Loop
this is my first post in Stackoverflow.com This is the process I'm following: Make a connection to dB Make a query to the dB to check if the register exists If the register does NOT exist iterate over a loop Add the registers in the dB My code: conn = sqlite3.connect('serps.db') c = conn.cursor() # 1) Make the query...
[ "SQLite is meant to be a lightweight database, and thus can't support a high level of concurrency. OperationalError: database is locked errors indicate that your application is experiencing more concurrency than sqlite can handle in default configuration. This error means that one thread or process has an exclusive...
[ 0, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074148712_python_sqlite.txt
Q: OpenAI Gym LunarLander execution considerably slowed down for an unknown reason I have been playing around with the OpenAI Gym LunarLander testing a DQN neural network. I had gotten to a point where it was slowly learning. Since I had started with the CartPole problem which was solved in a couple of minutes/episod...
OpenAI Gym LunarLander execution considerably slowed down for an unknown reason
I have been playing around with the OpenAI Gym LunarLander testing a DQN neural network. I had gotten to a point where it was slowly learning. Since I had started with the CartPole problem which was solved in a couple of minutes/episodes, I initially thought that the LunarLander would function at a similar speed but it...
[ "The batch size is whats causing your execution to slow down. If you increase it, your render will go faster. However, if you do so, you will end up doing less steps by episode.\n" ]
[ 3 ]
[]
[]
[ "dqn", "keras", "neural_network", "python", "q_learning" ]
stackoverflow_0061370115_dqn_keras_neural_network_python_q_learning.txt
Q: Buffer Overflow in strcpy(): return address of system() has a \x00 byte. (return-to-libc) I'm currently learning about a return-to-libc method to bypass the non-executable stack countermeasure. The return address I'm trying to overflow on the stack is the libc system() function's address but it contains a Null Ter...
Buffer Overflow in strcpy(): return address of system() has a \x00 byte. (return-to-libc)
I'm currently learning about a return-to-libc method to bypass the non-executable stack countermeasure. The return address I'm trying to overflow on the stack is the libc system() function's address but it contains a Null Termination byte at the end which stop the strcpy() function from copying any further into a buffe...
[ "\nNow that I'm pretty sure that the error was because of the NULL Byte\n\nYes: strcpy() will stop when it finds the NUL byte (note, it's different from NULL, which is not a byte).\n\nI would like to know if there is a way to bypass that without using a completely different method?\n\nOn my system, disassembly of t...
[ 1 ]
[]
[]
[ "buffer_overflow", "c", "libc", "python", "stack" ]
stackoverflow_0074147054_buffer_overflow_c_libc_python_stack.txt
Q: How to terminate Colab session programmatically? To save consumed compute units in Colab (as there's an option) to pay as you go, how to terminate / shut down Colab session using a code programmatically? A: Use the following function from google.colab import runtime runtime.unassign() It will delete the current...
How to terminate Colab session programmatically?
To save consumed compute units in Colab (as there's an option) to pay as you go, how to terminate / shut down Colab session using a code programmatically?
[ "Use the following function\nfrom google.colab import runtime\nruntime.unassign()\n\nIt will delete the currently connected runtime and disconnect the notebook.\nIt's announced here.\n" ]
[ 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074148849_google_colaboratory_python.txt
Q: Printing a domain that does not exist Is there a way where I can print out that the domain does not exist instead of giving me an error like this ConnectionError: HTTPSConnectionPool(host='www.enroll.connect.web.co.id', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection...
Printing a domain that does not exist
Is there a way where I can print out that the domain does not exist instead of giving me an error like this ConnectionError: HTTPSConnectionPool(host='www.enroll.connect.web.co.id', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f4f558003d0>:...
[ "Use Exception Handling:\ncode:\nimport requests\n\ntry:\n request = requests.get('https://www.enroll.connect.web.co.id')\n if request.status_code == 200:\n print('Web site exists')\nexcept : \n print('Web site does not exist')\n\n", "In this case I prefer to use an exception and just bypass...
[ 1, 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074148799_jupyter_notebook_python.txt
Q: Why does this for each loop repeat infinitely when an if else is inside? I'm observing some very strange behavior of a for each loop. When the if/else blocks are present, an infinite loop results. However, when they are commented out, and only the print(motif) remains in the loop, the expected behavior results, lo...
Why does this for each loop repeat infinitely when an if else is inside?
I'm observing some very strange behavior of a for each loop. When the if/else blocks are present, an infinite loop results. However, when they are commented out, and only the print(motif) remains in the loop, the expected behavior results, looping through the list 4 times. I should mention the the motif_seqs list was a...
[ "You are adding items to the list in your else statement. Since your condition always fails, it moves to the else branch which adds items to the list and makes it so that the list never ends.\n", "Since your condition if motif == \"homopolymer\": always fails, it goes to else block. And in else block you are appe...
[ 0, 0 ]
[]
[]
[ "generator", "infinite_loop", "iterator", "list", "python" ]
stackoverflow_0074148811_generator_infinite_loop_iterator_list_python.txt
Q: How do I plot the frequency of an event overtime with pandas?I I was trying to plot some data from a pandas dataframe. My table contains 10000ish films and for each of them two info: the year it got published, and a rating from 0 to 3. I am having a hard time trying to plot a graph with the pandas library that sho...
How do I plot the frequency of an event overtime with pandas?I
I was trying to plot some data from a pandas dataframe. My table contains 10000ish films and for each of them two info: the year it got published, and a rating from 0 to 3. I am having a hard time trying to plot a graph with the pandas library that shows the number of films that received a particular rating (3 in my ca...
[ "You can filter by rating and use Series.value_counts:\ns = data.loc[data['rating'].eq(3), 'year'].value_counts()\n\nBut there is many years of films:\nprint (len(s))\n108\n\nSo for plot I filter only counts greatwer like 30, it is 40 years here:\nprint (s.gt(30).sum())\n40\n\nSo filter again and plot:\ns[s.gt(30)]...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_requests" ]
stackoverflow_0074148788_dataframe_pandas_python_python_requests.txt
Q: In my python code, the lines are mixed up I didn't finish a program in python, then two days later I came back to it and found this. Does anyone know how this could have happened? I was coding in Sublime Text matrix.append(int(a[count_a])) matrix.append(int(vectors[j][i])) ...
In my python code, the lines are mixed up
I didn't finish a program in python, then two days later I came back to it and found this. Does anyone know how this could have happened? I was coding in Sublime Text matrix.append(int(a[count_a])) matrix.append(int(vectors[j][i])) print(a[count_a], end="") ...
[ "Ooh... maybe I accidentally pressed CTRL + A and f9...\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074148791_python.txt
Q: AES key (string) input, unable to be converted to corresponding byte sequences correctly My python program takes a AES key as input. For example, \xee~\xb0\x94Lh\x9fn\r?\x18\xdf\xa4_7I\xf7\xd8T?\x13\xd0\xbd4\x8eQ\x9b\x89\xa4c\xf9\xf1 This string input must now be converted back to a byte sequences, so that the ke...
AES key (string) input, unable to be converted to corresponding byte sequences correctly
My python program takes a AES key as input. For example, \xee~\xb0\x94Lh\x9fn\r?\x18\xdf\xa4_7I\xf7\xd8T?\x13\xd0\xbd4\x8eQ\x9b\x89\xa4c\xf9\xf1 This string input must now be converted back to a byte sequences, so that the key can be used in decryption. aes_key = str.encode(user_input) # user_input being the key is st...
[ "After some guesswork of what your input might be, I got the following:\ninput_string = \"\\\\xee~\\\\xb0\\\\x94Lh\\\\x9fn\\\\r?\\\\x18\\\\xdf\\\\xa4_7I\\\\xf7\\\\xd8T?\\\\x13\\\\xd0\\\\xbd4\\\\x8eQ\\\\x9b\\\\x89\\\\xa4c\\\\xf9\\\\xf1\"\n\nprint(input_string) \n# \\xee~\\xb0\\x94Lh\\x9fn\\r?\\x18\\xdf\\xa4_7I\\xf7\...
[ 0 ]
[]
[]
[ "aes", "byte", "python", "string" ]
stackoverflow_0074148699_aes_byte_python_string.txt
Q: groupby two columns take highest sum (Pandas) Looking to see which client has the highest price sum for the month of February. 2/1/2022 Data client box Price date charles AA 5,000 2/1/2022 charles AA 5,050 2/1/2022 charles AA 5,075 2/1/2022 cara BB 25,116 2/1/2022 cara BB 5,154 2/1/2022 lu ...
groupby two columns take highest sum (Pandas)
Looking to see which client has the highest price sum for the month of February. 2/1/2022 Data client box Price date charles AA 5,000 2/1/2022 charles AA 5,050 2/1/2022 charles AA 5,075 2/1/2022 cara BB 25,116 2/1/2022 cara BB 5,154 2/1/2022 lu CC 0 2/1/2022 max DD 10,000 3/1/20...
[ "idxmax will return the index of the maximum value—which you can then use to look up the row you want. Be aware that in the case that two customers are tied for the highest price, it will return only the first occurence.\nExample:\n(\n df\n # Fist filter to only Februrary\n .loc[lambda df_: df_[\"date\"].d...
[ 1, 1, 1, 1 ]
[]
[]
[ "group_by", "numpy", "pandas", "python" ]
stackoverflow_0074148435_group_by_numpy_pandas_python.txt
Q: Pandas Installation on PyPy I've seen a number of questions here referring to particular package installations on PyPy and have tried a number of them. However, I haven't found a suitable answer to my question. So, the point is the following: I am trying to install pandas on pypy (under Linux OS). I have followed ...
Pandas Installation on PyPy
I've seen a number of questions here referring to particular package installations on PyPy and have tried a number of them. However, I haven't found a suitable answer to my question. So, the point is the following: I am trying to install pandas on pypy (under Linux OS). I have followed the below steps: conda create -n ...
[ "The recommended way to use scientific python (pandas, scipy, ...) with PyPy 3.8 and 3.9 is via conda, You can get started with\n$ conda create -c conda-forge -n my-pypy-env pypy python=3.8\n$ conda activate my-pypy-env\n$ conda install -c conda-forge pandas\n\nNote that until HPy becomes used in cython, you should...
[ 0 ]
[]
[]
[ "linux", "pandas", "pip", "pypy", "python" ]
stackoverflow_0074112832_linux_pandas_pip_pypy_python.txt
Q: The code worked a week ago, why is there now an error? I'm using python with the 'Spyder IDE' Wrote this code a week ago and when I open the file after a week, the code is giving me an indentation error. The code is meant to take a six-digit number inputted from the user and put it through a few tests using if/els...
The code worked a week ago, why is there now an error?
I'm using python with the 'Spyder IDE' Wrote this code a week ago and when I open the file after a week, the code is giving me an indentation error. The code is meant to take a six-digit number inputted from the user and put it through a few tests using if/else and match statements. import numpy as np code = input('Pl...
[ "It works fine for me. My guess is maybe there's a hidden space or something there? I'd just delete those two lines (35-36) and re-type them and see if you get the same error.\n", "You probably have a mix of tabs and spaces. Erase each indent and replace them with four spaces. The standard shown in the style guid...
[ 1, 1 ]
[]
[]
[ "python", "python_3.10", "spyder" ]
stackoverflow_0074148895_python_python_3.10_spyder.txt
Q: How to merge multiple word file into one word file according to the content For example, there are 3 word files (Name: word_1, word_2, word_3), and I would like to merge all the content into word_1. Before merge: Content in word_1: 1.1.1 Hello World testing text 111 1.1.2 Hello America testing text 22...
How to merge multiple word file into one word file according to the content
For example, there are 3 word files (Name: word_1, word_2, word_3), and I would like to merge all the content into word_1. Before merge: Content in word_1: 1.1.1 Hello World testing text 111 1.1.2 Hello America testing text 222 1.1.3 Hello USA 1.1.4 Hello Korea 1.1.5 Hello Japan Content in word_2: 1....
[ "Using regex and some string manipulation\na = \"\"\"Content in word_1:\n1.1.1 Hello World\n testing text 111\n\n1.1.2 Hello America\n testing text 222\n\n1.1.3 Hello USA\n\n\n1.1.4 Hello Korea\n\n\n1.1.5 Hello Japan\"\"\"\n\nb = \"\"\"Content in word_2:\n1.1.3 Hello USA\n testing text 333\n\n1.1.4 H...
[ 0 ]
[]
[]
[ "ms_word", "python", "vba" ]
stackoverflow_0074148701_ms_word_python_vba.txt
Q: why does my conda deactivate doesn't work? I am having troubles with my conda installation on a cluster. It seems that i can't deactivate any of my environments. it goes so far, that i have to close my terminal because it froze. I am working on multiple server with a common home directory, so i can access the same...
why does my conda deactivate doesn't work?
I am having troubles with my conda installation on a cluster. It seems that i can't deactivate any of my environments. it goes so far, that i have to close my terminal because it froze. I am working on multiple server with a common home directory, so i can access the same conda installation from different servers. Inte...
[ "thanks to @merv I could easily solve the problem.\nRunning conda init bash and restarting the terminal seems to clean something and now it works as well.\nI can see again my prompt and the environments are closing again.\nyeroslaviz@hpcl8001:~$ conda init bash\nmodified /fs/home/yeroslaviz/miniconda3/condabin...
[ 3 ]
[]
[]
[ "conda", "environment", "python" ]
stackoverflow_0074134920_conda_environment_python.txt
Q: google admin api - client_secrets error I was playing around with google admin api and put the example code together with a little modification. I set things up correctly on the google end, but when I run the script it kept giving me errors. Below is my code in python: from __future__ import print_function from...
google admin api - client_secrets error
I was playing around with google admin api and put the example code together with a little modification. I set things up correctly on the google end, but when I run the script it kept giving me errors. Below is my code in python: from __future__ import print_function from apiclient.discovery import build from httpli...
[ "The issue I've found is with the name of Google's OAuth 2.0 client IDs. For your client ID, the name must EXACTLY be Google Sheets API Quickstart, or else the \"client_secret\" won't be populated in the client_secret.json when you download it from Google. \nAlternatively, you could manually add a property under th...
[ 1, 1 ]
[ "Download the client_secret.json again. There is a problem with that file.\nYou can use this link for a small tutorial to get your client_secret.\n" ]
[ -1 ]
[ "google_api", "google_api_client", "google_api_python_client", "python", "python_2.7" ]
stackoverflow_0040205446_google_api_google_api_client_google_api_python_client_python_python_2.7.txt
Q: Django, Is there a way to access additional custom fields to the default user model in the serializer? I am trying to send current user information through an API endpoint. I am using the Django default user model, and adding additional fields through inline. (Please refer to the code below) I am wondering if ther...
Django, Is there a way to access additional custom fields to the default user model in the serializer?
I am trying to send current user information through an API endpoint. I am using the Django default user model, and adding additional fields through inline. (Please refer to the code below) I am wondering if there is a way that I can access the newly added fields in the User serializer? I tried a lot of ways to include...
[ "We can do it using 2 ways:\n1. Represent it using another serializers:\nclass AccountSerializer(ModelSerializer):\n class Meta:\n model = Account\n fields = (\"gender_identity\", \"sexual_orientation\")\n\n\nclass UserSerializer(ModelSerializer):\n account = AccountSerializer(read_only=True)\n\...
[ 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_users", "python" ]
stackoverflow_0074148275_django_django_models_django_rest_framework_django_users_python.txt
Q: Python - Rock, Paper, Scissors. Function and win counter I want to try and make it so that the player plays the game 3 times. For each round of the game, it prints whether the player wins, loses, or draws. The function seems to be working, however, the if and elif statements do not. For some reason only the else s...
Python - Rock, Paper, Scissors. Function and win counter
I want to try and make it so that the player plays the game 3 times. For each round of the game, it prints whether the player wins, loses, or draws. The function seems to be working, however, the if and elif statements do not. For some reason only the else statement works. I also don't know how to implement the return...
[ "import random\n\ndef main():\n gameInput = ['1', '2', '3']\n win=0\n for attempt in range(1,4):\n pc = int(input('Enter 1(rock), 2(paper), or 3(scissor): '))\n npc = int(random.choice(gameInput))\n win = play_game(pc,npc)+win\n #end of loop body\n print(f'You played three ti...
[ 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0074148343_python_windows.txt
Q: Debugging AWS Lambda (Python) Locally in VS Code with out using SAM-CLI I'm trying to debug AWS lambda (python) function created using container image locally on VSCode. I don't want to use SAM CLI as my Directory structure don't contain template.yml. Is there a way to debug the code in VSCode while running the co...
Debugging AWS Lambda (Python) Locally in VS Code with out using SAM-CLI
I'm trying to debug AWS lambda (python) function created using container image locally on VSCode. I don't want to use SAM CLI as my Directory structure don't contain template.yml. Is there a way to debug the code in VSCode while running the container from the image for AWS Lambda?
[ "I refer to this page which can help.\nAdd the following code to your launch.json:\nWindows:\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \".NET Core Launch (console)\",\n \"type\": \"coreclr\",\n \"request\": \"launch\",\n \"preLaunch...
[ 0 ]
[]
[]
[ "aws_lambda", "container_image", "debugging", "python", "visual_studio_code" ]
stackoverflow_0074147758_aws_lambda_container_image_debugging_python_visual_studio_code.txt
Q: PIL.Image vs skimage.io: When to use each, and which (if one) is prefered over the other in general? I have been using Image for opening and getting pixel info, and have read things like "PIL is the future and blabla..", but I have seen that skimage is extensively used. Which one should I use for general image pr...
PIL.Image vs skimage.io: When to use each, and which (if one) is prefered over the other in general?
I have been using Image for opening and getting pixel info, and have read things like "PIL is the future and blabla..", but I have seen that skimage is extensively used. Which one should I use for general image processing? I would feel more comfortable with this question answered..
[ "In general it is safe to say that Pillow (install this rather than PIL as Pillow is maintained) is the one to go for if you are manipulating Image->Image as this is its main focus.\nHowever, if you are reading an image for manipulation by other science kit based tools, such as machine learning, then go for skimage...
[ 0 ]
[]
[]
[ "image_processing", "package", "python" ]
stackoverflow_0043723214_image_processing_package_python.txt
Q: Create new column in a dataframe based on group by and other conditions I have a data frame where you can have either one row or two rows by id. I need to create two new columns where for each id group if we have one row only. We determine the values based on the condition on one column 'type'. If there are two ro...
Create new column in a dataframe based on group by and other conditions
I have a data frame where you can have either one row or two rows by id. I need to create two new columns where for each id group if we have one row only. We determine the values based on the condition on one column 'type'. If there are two rows, the values of the new columns depend on the conditions on 'type' and get ...
[ "One approach could be as follows:\n\nUse df.groupby to create a df with first and last indices for all groups in column id (here assigned to g).\nNow, for both didx and puidx, we use Series.map to assign either -1 or -10.\nNext, we chain Series.where combined with Series.duplicated. For, didx we check ~df.id.dupli...
[ 1 ]
[]
[]
[ "apply", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074148540_apply_dataframe_group_by_pandas_python.txt
Q: how to create an app with in app inside a Django project? How that app can be registered to setting py file? *project- New.app-app want to add an app inside app 1.how to register this to the setting.py file? what are the things I should be worried once I have an app with in an app? A: To create an app in Django...
how to create an app with in app inside a Django project? How that app can be registered to setting py file?
*project- New.app-app want to add an app inside app 1.how to register this to the setting.py file? what are the things I should be worried once I have an app with in an app?
[ "To create an app in Django do this:\nFirst, navigate to project folder in terminal or cmd and run above command:\npython manage.py startapp appname #This will create an app inside Django project\n\nSecond, after create app:\nIn settings.py file:\nadd your app in INSTALLED_APP:\nex:\nINSTALLED_APPs = [\n 'appname...
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074135206_django_django_templates_python.txt
Q: Unable to install python on fedora server So I am trying to install python on my fedora 36 server using wget https://www.python.org/ftp/python/3.10.8/Python-3.10.8.tgz but when I run the code it says Error: The certificate of 'www.python.org' is not trusted I am using wget btw A: See wget help: --no-check-cer...
Unable to install python on fedora server
So I am trying to install python on my fedora 36 server using wget https://www.python.org/ftp/python/3.10.8/Python-3.10.8.tgz but when I run the code it says Error: The certificate of 'www.python.org' is not trusted I am using wget btw
[ "See wget help:\n\n--no-check-certificate\nDon't check the server certificate against the available certificate authorities. Also don't require the URL host name to\nmatch the common name presented by the certificate.\nAs of Wget 1.10, the default is to verify the server's certificate against the recognized certif...
[ 0 ]
[]
[]
[ "fedora", "linux", "python" ]
stackoverflow_0074149113_fedora_linux_python.txt
Q: How can I write every loop result from SQL in python? Here is my code. In the excel file, it should have 4 tables, including date = 1/3,1/7,1/14,1/21. I have run the query, it showed 4 results. However, when I wrote to the excel, the file only has one table, which was date = 1/3. I'm wondering how can I correct th...
How can I write every loop result from SQL in python?
Here is my code. In the excel file, it should have 4 tables, including date = 1/3,1/7,1/14,1/21. I have run the query, it showed 4 results. However, when I wrote to the excel, the file only has one table, which was date = 1/3. I'm wondering how can I correct this, thanks! import pyodbc import pandas as pd ...
[ "I solved it! Put while outside the SQL query, as the following.\nimport pyodbc \nimport pandas as pd\nfrom datetime import datetime,timedelta\n\ncnxn = pyodbc.connect('DRIVER=xx; SERVER=xx; DATABASE=xx; UID=xx; PWD=xx;MARS_Connection=yes')\n\ncursor = cnxn.cursor()\nstart = datetime.strptime('2022-01-03','%Y-%m-%d...
[ 0 ]
[ "You made need to use a for loop on the actual object to loop through what was returned. Let me know if this helps.\nwriter = pd.ExcelWriter('test1.xlsx')\nfor x in df:\n df.to_excel(writer, sheet_name='test000')\nwriter.save()\n\n" ]
[ -1 ]
[ "loops", "python", "sql" ]
stackoverflow_0074120839_loops_python_sql.txt
Q: How can I use parenthesis while using the (?P...) regular expression? I want to specify something from the expression after the (?P<name>...) like: (?P<name>\d.+([a-z])) but it is not allowing me. Is there a way to use the (?P<name>...) expression with parenthesis? Sample text: 197.109.77.178 - kertzmann3129 [21/...
How can I use parenthesis while using the (?P...) regular expression?
I want to specify something from the expression after the (?P<name>...) like: (?P<name>\d.+([a-z])) but it is not allowing me. Is there a way to use the (?P<name>...) expression with parenthesis? Sample text: 197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] "DELETE /virtual/solutions/target/web+services HTT...
[ "use pattern (.*?) to match anything inside brackets.\nimport re\n\nregex = r'\\[(.*?)\\]'\n\ntext = '''197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] \"DELETE /virtual/solutions/target/web+services HTTP/2.0\" 203 26554\n156.127.178.177 - okuneva5222 [21/Jun/2019:15:45:27 -0700] \"DELETE /interactive/t...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074148890_python_regex.txt
Q: Python Txt File Replacement - 'str' object does not support item assignment Suppose I have a txt file like below 3 113.12747240513697 -1.0352096627496632 14.963682795503324 3 10.892386778099667 10.556798857881242 2.017821533523687 2 15.532838824289408 11.761144702842378 -5.862336401808785 2 10.892386778099667 1...
Python Txt File Replacement - 'str' object does not support item assignment
Suppose I have a txt file like below 3 113.12747240513697 -1.0352096627496632 14.963682795503324 3 10.892386778099667 10.556798857881242 2.017821533523687 2 15.532838824289408 11.761144702842378 -5.862336401808785 2 10.892386778099667 10.556798857881242 2.017821533523687 2 15.532838824289408 11.761144702842378 -5.8...
[ "Strings in Python are immutable.\nYou can create a new modified line2 and then write it out.\nwith open(traintypesdata) as f:\n for line in f:\n first_char = '0' if line[0] == '2' else \\\n '1' if line[0] == '3' else \\\n '2' if line[0] == '5' else \\\n line[0]\n...
[ 2 ]
[]
[]
[ "python", "txt" ]
stackoverflow_0074149324_python_txt.txt
Q: Pandas: How to multiply a index with value in a multi-index series? I have a series as below, Name id A 1 10 2 20 3 30 . . . . B 1 100 2 200 3 300 . . I wanted to do something below, pd.cut(series...
Pandas: How to multiply a index with value in a multi-index series?
I have a series as below, Name id A 1 10 2 20 3 30 . . . . B 1 100 2 200 3 300 . . I wanted to do something below, pd.cut(series.id * series.value, bins=10) How can I do this in a performant way?
[ "Combine Series.mul with Index.get_level_values:\ns.mul(s.index.get_level_values('id'))\n# `get_level_values` works both with \"names\" (i.e. `id`) and \"index\" (i.e. `1`)\n\nName id\nA 1 10\n 2 40\n 3 90\nB 1 100\n 2 400\n 3 900\ndtype: int64\n\nSo, you can ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074149214_pandas_python.txt
Q: Transform "4CA2CACA" to "CCCCACCACA" I have already tried this (as somebody told me on another question): import re def decode(txt): list = [] for cnt, char in re.findall(r"([\d*])([^d])", txt): list.extend((char * (int(cnt) if cnt else 1))) list = "".join(list) return list Example...
Transform "4CA2CACA" to "CCCCACCACA"
I have already tried this (as somebody told me on another question): import re def decode(txt): list = [] for cnt, char in re.findall(r"([\d*])([^d])", txt): list.extend((char * (int(cnt) if cnt else 1))) list = "".join(list) return list Example: print(decode("2CACA2CACA3CACACA3CAC")) ...
[ "re.sub can take a named function or lambda as its second argument, and you can use this to accomplish your goal. Using this approach you simply don't do any substitution when a letter does not have a number in front of it.\ndef decode(s):\n return re.sub(r'(\\d+)([a-zA-Z])', \n lambda m: m.group(2)...
[ 2, 0, 0, -3 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0074083090_python_python_re.txt
Q: Call a function in all API endpoints with decorator? I was wondering if there was a way to ensure some function was called in all Flask API endpoints without manually calling the function? This is to prevent repetition in making sure the functions get called, and to avoid mistakes of accidentally forgetting to cal...
Call a function in all API endpoints with decorator?
I was wondering if there was a way to ensure some function was called in all Flask API endpoints without manually calling the function? This is to prevent repetition in making sure the functions get called, and to avoid mistakes of accidentally forgetting to call it. Maybe with a library or decorator? def do_something(...
[ "You can use app.before_request\nFrom the doc\nbefore_request(f)\n\nRegister a function to run before each request.\nFor example, this can be used to open a database connection, or to load the logged in user from the session.\n\nexample:\n@app.before_request\ndef load_user():\n if \"user_id\" in session:\n ...
[ 1 ]
[]
[]
[ "api", "decorator", "flask", "python", "python_decorators" ]
stackoverflow_0074147717_api_decorator_flask_python_python_decorators.txt
Q: Get Application layer Protocol in dpkt I have to get the name of all the different protocols from PCAP files. Basically, I have to parse it. I researched a bit and was informed that dpkt is very efficient for this. I am writing the script in python and below is the code - def inet_to_str(inet): # First try ipv4 a...
Get Application layer Protocol in dpkt
I have to get the name of all the different protocols from PCAP files. Basically, I have to parse it. I researched a bit and was informed that dpkt is very efficient for this. I am writing the script in python and below is the code - def inet_to_str(inet): # First try ipv4 and then ipv6 try: return socket.inet_nto...
[ "You can look at the ports of the transport layer packets. This way you can figure out which application layer protocol is being used. Here is a link to the ports numbers and the application layer protocol that uses it: https://en.wikibooks.org/wiki/A-level_Computing/AQA/Paper_2/Fundamentals_of_communication_and_ne...
[ 0 ]
[]
[]
[ "dpkt", "networking", "parsing", "pcap", "python" ]
stackoverflow_0074091369_dpkt_networking_parsing_pcap_python.txt
Q: Exception has occurred: AttributeError 'int' object has no attribute 'shape' when calling dqn.fit() I'm trying to create a dqn agent for a space invaders environment and I keep getting this attribute error when I try to run the program, the error pops up at the dqn.fit() line. It seems that in memory.py observatio...
Exception has occurred: AttributeError 'int' object has no attribute 'shape' when calling dqn.fit()
I'm trying to create a dqn agent for a space invaders environment and I keep getting this attribute error when I try to run the program, the error pops up at the dqn.fit() line. It seems that in memory.py observations.shape in zeroed_observation cant find 'shape'. Ive installed tensorflow-cpu, gym, gym[atari], keras-rl...
[ "I'm having the same issue (following this tutorial: https://youtu.be/hCeJeq8U0lo). Just following the error, my best guess is something is up with Python version, keras, gym or even tensorflow, as seems to often be the case with these tutorials from even a year ago.\nFor instance, in the tutorial, he's using Pytho...
[ 1, 0 ]
[]
[]
[ "keras", "machine_learning", "python", "reinforcement_learning", "tensorflow" ]
stackoverflow_0074132742_keras_machine_learning_python_reinforcement_learning_tensorflow.txt
Q: Training DL model on slurm and it's getting slow my school started to let their student use GPU server. So I'm training DL model through slurm. salloc -p p3 -J chem_proj --mincpus=16 --mem=64G --time=2-00:00:00 --gres=gpu:a40:1 srun --pty bash I got resources by using above line. (got 16 cpus, 64GB, one A40 gpu f...
Training DL model on slurm and it's getting slow
my school started to let their student use GPU server. So I'm training DL model through slurm. salloc -p p3 -J chem_proj --mincpus=16 --mem=64G --time=2-00:00:00 --gres=gpu:a40:1 srun --pty bash I got resources by using above line. (got 16 cpus, 64GB, one A40 gpu for 2 days). And I launched my jupyter sessions with th...
[ "This might be a memory (RAM) issue. Have you checked the RAM usage during the second epoch? Could you try reducing the memory allocation (--mem=32G)?\nSomething similar happened to me when I was training a pytorch-based model with a data generator which didn't explicitly delete training data from previous epochs. ...
[ 0, 0 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "pytorch", "slurm" ]
stackoverflow_0073604488_deep_learning_machine_learning_python_pytorch_slurm.txt
Q: How to extract text without tags (between br)? I am trying to store headings and paragraphs into different arrays, i can't manage with text between <br>. Here's my HTML code and python below: <p><strong>W Ognisku</strong><br>W londyńskim Ognisku Polskim odbyło się spotkanie z brytyjskim historykiem<br><br><strong>...
How to extract text without tags (between br)?
I am trying to store headings and paragraphs into different arrays, i can't manage with text between <br>. Here's my HTML code and python below: <p><strong>W Ognisku</strong><br>W londyńskim Ognisku Polskim odbyło się spotkanie z brytyjskim historykiem<br><br><strong>10 lat polskiej szkoły sobotniej Copernicus </strong...
[ "from bs4 import BeautifulSoup\nhtml = \"\"\"<html>\n <body>\n <p>\n <strong>\n W Ognisku\n </strong>\n <br/>\n W londyńskim Ognisku Polskim odbyło się spotkanie z brytyjskim historykiem\n <br/>\n <br/>\n <strong>\n 10 lat polskiej szkoły sobotniej Copernicus\n </strong>\n <br/>\n W Wielk...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_docx", "web_scraping" ]
stackoverflow_0074147313_beautifulsoup_html_python_python_docx_web_scraping.txt
Q: How to display all label values in matplotlib I have two lists, when I plot with the following code, the x axis only shows up to 12 (max is 15). May I know how can I show all of the values in x list to the x axis? Thanks in advance. x = [4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3] y = [10,20,30,40,50,60,70,80,90,100,1...
How to display all label values in matplotlib
I have two lists, when I plot with the following code, the x axis only shows up to 12 (max is 15). May I know how can I show all of the values in x list to the x axis? Thanks in advance. x = [4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3] y = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160] fig = plt.figure() ax1 = fi...
[ "The issue here is that the number of ticks -set automatically - isn’t the same as the number of points in your plot.\nTo resolve this, set the number of ticks:\nax1.set_xticks(np.arange(len(x)))\n\nBefore the ax1.set_xticklabels(x) call.\n", "or better\nax.xaxis.set_major_locator(ticker.MultipleLocator(1))\nax.y...
[ 81, 0 ]
[]
[]
[ "axis_labels", "graph", "matplotlib", "python" ]
stackoverflow_0026131822_axis_labels_graph_matplotlib_python.txt
Q: Reverse Linked Lists recursively (not grasping the head.next.next part) I have seen solutions to the reverse linked lists recursively but I dont understand the head.next.next part. Can someone explain this to me. This is leetcode 206 problem. # Definition for singly-linked list. # class ListNode: # def __init_...
Reverse Linked Lists recursively (not grasping the head.next.next part)
I have seen solutions to the reverse linked lists recursively but I dont understand the head.next.next part. Can someone explain this to me. This is leetcode 206 problem. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = nex...
[ "The recursive function will never reach the last value in the list and hence not throw an error. During recursion, the function takes in the node pointed by head.next, not the head itself. Hence the stopping condition is actually checking the condition: (if not head.next or not head.next.next).\nAnother way of loo...
[ 0, 0, 0 ]
[]
[]
[ "linked_list", "python", "recursion" ]
stackoverflow_0074147590_linked_list_python_recursion.txt
Q: Python error WindowsError(5, 'Access is denied.' I am new to python and am trying to run a prewritten program but keep recieving an error here is the whole error. Traceback (most recent call last): File "C:\source\python\pill.py", line 29, in <module> ser.open() File "C:\Python27\lib\site-packages\serial\ser...
Python error WindowsError(5, 'Access is denied.'
I am new to python and am trying to run a prewritten program but keep recieving an error here is the whole error. Traceback (most recent call last): File "C:\source\python\pill.py", line 29, in <module> ser.open() File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open raise SerialExce...
[ "You may have another program using the COM port, for example a test program like firmata_test.exe that our course work told use to use.\nOne course module told us to run that program, which is a Windows executable that opens the COM port and monitors the various pins on the board and lets us toggle their state Hig...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0033621086_python.txt
Q: while trying to use xlsxwriter worksheet.data_validation() I get the error message: 'Worksheet' object has no attribute 'data_validation' I'm trying to edit an excel file by writing some values to excel cells with openpyxl, the problem I ran into was that all my drop down lists (data validation) are now gone. so I...
while trying to use xlsxwriter worksheet.data_validation() I get the error message: 'Worksheet' object has no attribute 'data_validation'
I'm trying to edit an excel file by writing some values to excel cells with openpyxl, the problem I ran into was that all my drop down lists (data validation) are now gone. so I am trying to set them up again after writing, using worksheet.data_validation() but for some reason, pycharm doesnt recognizes it. sheet1.data...
[ "With Row/Column notation you must specify all four cells in the range: (first_row, first_col, last_row, last_col).\nhttps://xlsxwriter.readthedocs.io/working_with_data_validation.html\n" ]
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0072372799_excel_openpyxl_python.txt
Q: matplotlib different values for y function I need to make plot for: this function or this I made plots before with this code: x = np.arange(-5, 5, 0.1) y1 = np.tanh(x) plt.plot(x,y1) but how to make something like this? if(x <= 0): y4 = 0 else: y4 = x gives valueerror:The truth value of an array with mo...
matplotlib different values for y function
I need to make plot for: this function or this I made plots before with this code: x = np.arange(-5, 5, 0.1) y1 = np.tanh(x) plt.plot(x,y1) but how to make something like this? if(x <= 0): y4 = 0 else: y4 = x gives valueerror:The truth value of an array with more than one element is ambiguous. Use a.any() or...
[ "Try this iterate over the array and apply the function:\ndef relu(x):\n if(x <= 0):\n y4 = 0\n else:\n y4 = x\n return y4\n\nx = np.arange(-5, 5, 0.1)\narray_for = np.array([relu(element) for element in x])\nplt.plot(array_for)\n\n\nalternatively, you can use numpy.vectorize or another solut...
[ 0, 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0074144744_matplotlib_numpy_python.txt
Q: why the plotly map is empty? What am I doing wrong that this code returns the partially empty map like this? ideally to have locations = 'zip' column instead of fips link to the data file uszips.csv import pandas as pd import plotly.express as px from urllib.request import urlopen import json with urlopen('https:...
why the plotly map is empty?
What am I doing wrong that this code returns the partially empty map like this? ideally to have locations = 'zip' column instead of fips link to the data file uszips.csv import pandas as pd import plotly.express as px from urllib.request import urlopen import json with urlopen('https://raw.githubusercontent.com/plotly...
[ "Find a US map, I found that Mesa County in Co state is not shown,\nand check its fips in uszips.csv, is 8077:\ndf1 = df[df[\"State\"]==\"CO\"]\ndf1[\"Mesa\" == df[\"City\"]]\n\nRegionID SizeRank zip fips StateName State City Metro CountyName 9/30/2022\n25162 93837 27031 71853 8077 CO ...
[ 1 ]
[]
[]
[ "plotly", "python", "python_3.x" ]
stackoverflow_0074148217_plotly_python_python_3.x.txt
Q: How to correct name weight not define error I am learning python by printing the output line by line from this tutorial https://towardsdatascience.com/convolution-neural-network-for-image-processing-using-keras-dc3429056306 and find out what does each line do. At the last line of code I facing error weight not def...
How to correct name weight not define error
I am learning python by printing the output line by line from this tutorial https://towardsdatascience.com/convolution-neural-network-for-image-processing-using-keras-dc3429056306 and find out what does each line do. At the last line of code I facing error weight not define but it seem the code is running fine without ...
[ "The error is due to an indentation issue. The last line needs to be executed inside the constructor init for it to recognize the weight argument. The code should look like this:\n import numpy as np\n import torch\n import torch.nn as nn\n import torch.nn.functional as fn\n \n filter_vals = np.array([[-1, -1, 1, 2...
[ 0 ]
[]
[]
[ "conv_neural_network", "python", "pytorch" ]
stackoverflow_0074149565_conv_neural_network_python_pytorch.txt
Q: Filling out fields using selenium (poor html here) I am trying to accomplish the following things: Input my email Click submit If "check again later" close, rinse and repeat until the other message appears "you are in!" Here's the code I have so far: PATH = "D:\Program Files (x86)\chromedriver.exe" email = "yada...
Filling out fields using selenium (poor html here)
I am trying to accomplish the following things: Input my email Click submit If "check again later" close, rinse and repeat until the other message appears "you are in!" Here's the code I have so far: PATH = "D:\Program Files (x86)\chromedriver.exe" email = "yada@yada" option = webdriver.ChromeOptions() option.add_ar...
[ "For the first point, about the error message - Selenium is saying that it can't find the target element you're looking for - Sometimes this is due to your script executing before the page has fully loaded.\nTo your second point about the iframe - You'll want to switch the driver to the iframe first, then use the s...
[ 1 ]
[]
[]
[ "html", "python", "selenium" ]
stackoverflow_0074148518_html_python_selenium.txt
Q: mean per group in a fragmented dataset this is actually an extension of my previous question, but I was requested to put it as a separate question Rolling average on previous dates per group I have the following dataset: Name Loc Site Date Total Alex Italy A 12.31.2020 30 Alex Italy B 1...
mean per group in a fragmented dataset
this is actually an extension of my previous question, but I was requested to put it as a separate question Rolling average on previous dates per group I have the following dataset: Name Loc Site Date Total Alex Italy A 12.31.2020 30 Alex Italy B 12.31.2020 20 Alex Italy B 12.30.2020...
[ "Use custom lambda function in GroupBy.transform with replace match values to NaNs and create averages by numpy.nanmean:\ndf['Date'] = pd.to_datetime(df['Date'])\n\n\ndef f(x):\n arr = x.index.to_numpy()\n s = x.to_numpy()\n prev = arr - pd.Timedelta(5, 'day')\n return np.nanmean(np.where((arr[:, None] ...
[ 1 ]
[]
[]
[ "group_by", "pandas", "python", "time_series" ]
stackoverflow_0074141450_group_by_pandas_python_time_series.txt
Q: Performance improvement for calculating the powerset of a list of integers I am trying to compute the powerset of a list of prime numbers. I have already done some research and the prefered way of doing this seems to be using a line like itertools.chain.from_iterable(itertools.combinations(primes, r) for r in rang...
Performance improvement for calculating the powerset of a list of integers
I am trying to compute the powerset of a list of prime numbers. I have already done some research and the prefered way of doing this seems to be using a line like itertools.chain.from_iterable(itertools.combinations(primes, r) for r in range(2, len(primes) + 1)) and then iterating over all combinations to get the produ...
[ "The solution to this problem was to create a pointer array, which crawls through the prime array until the product of the pointed primes gets too high. The needed helper functions can be implemented like this:\ndef calcProductOfPointers(pointerArray, dataArray):\n prod = 1\n for pointer in pointerArray:\n ...
[ 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074141814_math_python.txt
Q: How to dynamically resize a Matplotlib figure when embedded in a custom QtWidget with QtDesigner and PySide6? I am facing the following issue: I have constructed my project as follow: ¬project ¬ uis (contains all guis and widgets) ¬ python scripts I have designed a GUI with QtDesigner and used a...
How to dynamically resize a Matplotlib figure when embedded in a custom QtWidget with QtDesigner and PySide6?
I am facing the following issue: I have constructed my project as follow: ¬project ¬ uis (contains all guis and widgets) ¬ python scripts I have designed a GUI with QtDesigner and used a QWidget to embed a matplolib pyplot. I first tried to promote a custom MplWidget (in a mplwidget.py module), but d...
[ "Solved, I went back to the widget promotion and added the full path of the mplwidget.py module as the header in the Qtdesigner.\nThe code generation now generate the line :\nfrom project.uis.mplwidget import MplWidget\nThere is no more need to overwrite the QWidget (because it has been promoted)\nand the Matplotl...
[ 1 ]
[]
[]
[ "matplotlib", "pyside6", "python", "qtwidgets" ]
stackoverflow_0074142238_matplotlib_pyside6_python_qtwidgets.txt
Q: How to use scrapy to crawl the details page? How can I use scrapy to crawl the details page? Not the list page. The link is https://ssr1.scrape.center import scrapy from scrapytutorial.items import ScrapytutorialItem class FirstprojectSpider(scrapy.Spider): name = 'firstproject' allowed_domains = ['scra...
How to use scrapy to crawl the details page?
How can I use scrapy to crawl the details page? Not the list page. The link is https://ssr1.scrape.center import scrapy from scrapytutorial.items import ScrapytutorialItem class FirstprojectSpider(scrapy.Spider): name = 'firstproject' allowed_domains = ['scrape.com', 'baidu.com'] start_urls = ['https:/...
[ "\nYou never said what was the problem, you just posted your code. Next time read how to ask carefully, and attach both your code, the error it produces, and ask a (not too general) question.\nDecide how to do the pagination, you tried to handle it both in the start_requests method and in parse method.\nYour xpath ...
[ 2 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074148868_python_scrapy.txt
Q: Why am I getting two different answers with quaternion-vector multiplication I am trying to multiply a quaternion with a vector following the formula q * v * q_conjugate(q) I found in this thread. When I run the following code in Python, I get an output that looks correct. However, when I run the code again I get ...
Why am I getting two different answers with quaternion-vector multiplication
I am trying to multiply a quaternion with a vector following the formula q * v * q_conjugate(q) I found in this thread. When I run the following code in Python, I get an output that looks correct. However, when I run the code again I get another output. How can that be? Hope you can help! def q_conjugate(q): w, x, ...
[ "Easy answere. Use pyquaternion to rotate the vector. The correct answere should be output 1.\nfrom pyquaternion import Quaternion\nQuaternion([0.921369, 0.027301, 0.049432, -0.384565]).conjugate.rotate([-0.122545--0.004102, -0.214168-0.19796, -0.010722--0.017395])\n\n" ]
[ 1 ]
[]
[]
[ "python", "quaternions", "vector_multiplication" ]
stackoverflow_0074139783_python_quaternions_vector_multiplication.txt
Q: Quadrant Plot in Python Missing Middle Cross Lines I have the following code: import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import seaborn as sns #the data data = pd.DataFrame({ 'label': ['Luis', 'Sara', 'Jeroen', 'Sophie', 'Florence', 'Simeon', 'Lambert', 'Rahu...
Quadrant Plot in Python Missing Middle Cross Lines
I have the following code: import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import seaborn as sns #the data data = pd.DataFrame({ 'label': ['Luis', 'Sara', 'Jeroen', 'Sophie', 'Florence', 'Simeon', 'Lambert', 'Rahul', 'Peter', 'John'], 'Data Culture': [0, 5, 10, 15,...
[ "Please update the packages since the code is creating expected figure with:\nPandas: 1.4.1\nnumpy: 1.23.4\nmatplotlib: 3.5.1\nseaborn: 0.11.2\nPlotly: 5.10.0\n\nFigure generated by the code shared in the question:\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074149620_matplotlib_pandas_python_seaborn.txt
Q: Using classes, functions or other objects from an installed package I successfully installed this package using pip C:\Users\>pip install functional-dependencies Collecting functional-dependencies Downloading functional_dependencies-1.3.0-py2.py3-none-any.whl (33 kB) Installing collected packages: functional-dep...
Using classes, functions or other objects from an installed package
I successfully installed this package using pip C:\Users\>pip install functional-dependencies Collecting functional-dependencies Downloading functional_dependencies-1.3.0-py2.py3-none-any.whl (33 kB) Installing collected packages: functional-dependencies Successfully installed functional-dependencies-1.3.0 which sho...
[ "Although this is a very basic question, just because the official documentation does not include full working examples, I will provide an answer here.\nYou have already installed the module functional-dependencies. To use it, you'll need to know the module name to use to import. This is written in the first line o...
[ 4 ]
[]
[]
[ "python", "python_packaging" ]
stackoverflow_0073999200_python_python_packaging.txt
Q: when n is greater than 20 it prints 'weird', but it should print 'not weird' N = 24 if N/2 == 0: if N in range(2, 5): print('Not Weird') if N in range(6, 20): print('Weird') if N > 20: print('Not Weird') if N/2 != 0: print('Weird') I want to work it like this: If N is odd, ...
when n is greater than 20 it prints 'weird', but it should print 'not weird'
N = 24 if N/2 == 0: if N in range(2, 5): print('Not Weird') if N in range(6, 20): print('Weird') if N > 20: print('Not Weird') if N/2 != 0: print('Weird') I want to work it like this: If N is odd, print Weird If N is even and in the inclusive range of 2 to 6, print Not Weird If ...
[ "You need to use mod operator to check if the number is odd or not.\nif N % 2 == 0:\n # do something\nelse:\n # do the other\n\n", "The expression N/2 == 0 will only be true when N is zero, you want the modulo operator:\nif N % 2 == 0:\n\nAlso, the expression range(a, b) gives you an inclusive range of a th...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0061037851_python_python_3.x.txt
Q: Python ignore DataFrame rows after non-null value I have such DataFrame: date unique_id order_id 0 2022-09-20 111 NULL 1 2022-09-10 111 NULL 2 2022-08-10 111 2660a139 3 2022-08-08 111 NULL 4 2022-08-07 111 NULL 5 2022-08-04 222 NU...
Python ignore DataFrame rows after non-null value
I have such DataFrame: date unique_id order_id 0 2022-09-20 111 NULL 1 2022-09-10 111 NULL 2 2022-08-10 111 2660a139 3 2022-08-08 111 NULL 4 2022-08-07 111 NULL 5 2022-08-04 222 NULL 6 2022-07-31 222 e61d1e7d 7 2022-07-20 ...
[ "Use GroupBy.cummax with Series.notna:\ndf = df[df['order_id'].notna().groupby(df['unique_id']).cummax()]\n#laternative\n#df = df[df['order_id'].ne('NULL').groupby(df['unique_id']).cummax()]\nprint (df)\n date unique_id order_id\n2 2022-08-10 111 2660a139\n3 2022-08-08 111 NaN\n4 2...
[ 2 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074149882_dataframe_numpy_pandas_python.txt