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: JSON format inside record in csv file - convert to column Python This is my data. Inside the column - 'device' and 'geonetwork' store the data as a dict or json format. I would like to create new columns based on data from that columns, fore example -> new column should be 'browser','browserversion', 'continent' a...
JSON format inside record in csv file - convert to column Python
This is my data. Inside the column - 'device' and 'geonetwork' store the data as a dict or json format. I would like to create new columns based on data from that columns, fore example -> new column should be 'browser','browserversion', 'continent' and so on. I have tried a lot of solutions, but it dosen't work. enter ...
[ "enter image description here\nOn the attached picture first new column name is highlited. It is json file\nimport csv\nimport json\n\n\ndef csv_to_json(csvFilePath, jsonFilePath):\n jsonArray = []\n\n # read csv file\n with open(csvFilePath, encoding='utf-8') as csvf:\n csvReader = csv.DictReader(c...
[ 0 ]
[]
[]
[ "arrays", "csv", "dataframe", "json", "python" ]
stackoverflow_0074485676_arrays_csv_dataframe_json_python.txt
Q: Resolving bottleneck on database connection in Dataflow pipeline We have a Dataflow streaming job that consumes messages in Pubsub, do some transformations, and perform DML (INSERT, UPDATE, DELETE) on a CloudSQL Postgres instance. We observed that the bottleneck is in the database. The code is written in Python an...
Resolving bottleneck on database connection in Dataflow pipeline
We have a Dataflow streaming job that consumes messages in Pubsub, do some transformations, and perform DML (INSERT, UPDATE, DELETE) on a CloudSQL Postgres instance. We observed that the bottleneck is in the database. The code is written in Python and uses SQLAlchemy as the library to interface with Postgres Common iss...
[ "You should try to batch the call to your database. The pseudocode would look like this (taken from the beam programming guide)\nclass BufferDoFn(DoFn):\n BUFFER = BagStateSpec('buffer', EventCoder())\n IS_TIMER_SET = ReadModifyWriteStateSpec('is_timer_set', BooleanCoder())\n OUTPUT = TimerSpec('output', TimeDom...
[ 2 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "google_cloud_sql", "python", "sqlalchemy" ]
stackoverflow_0074476994_apache_beam_google_cloud_dataflow_google_cloud_sql_python_sqlalchemy.txt
Q: Sniffing network traffic with scapy, get "Could not activate the pcap handler" I try to sniff network adapter(TP-LINK, 0bda:b711) with python3 , But I get an OSError: Could not activate the pcap handler from scapy.all import * from scapy.config import conf from scapy.layers.dot11 import Dot11 conf.use_pcap = True...
Sniffing network traffic with scapy, get "Could not activate the pcap handler"
I try to sniff network adapter(TP-LINK, 0bda:b711) with python3 , But I get an OSError: Could not activate the pcap handler from scapy.all import * from scapy.config import conf from scapy.layers.dot11 import Dot11 conf.use_pcap = True def callBack(pkg): if pkg.haslayer(Dot11): if pkg.type == 0 and pkg....
[ "If you posted issue #1136 on the libpcap issues list, then you presumably somehow managed to determine that pcap_activate() returned PCAP_ERROR. If you did that by modifying the Scapy code, try modifying it further to, if pcap_activate() returns PCAP_ERROR, report the result of pcap_geterr(), in order to try to f...
[ 0 ]
[]
[]
[ "linux", "python", "wifi" ]
stackoverflow_0074336825_linux_python_wifi.txt
Q: Is there a way to run Python scripts client side in the browser using a front end framework like react? Introduction There are so many cool and useful python scripts/programs out there, that aren't living up to their potential, in my opinion. Because all of these are executed locally in the command line, they aren...
Is there a way to run Python scripts client side in the browser using a front end framework like react?
Introduction There are so many cool and useful python scripts/programs out there, that aren't living up to their potential, in my opinion. Because all of these are executed locally in the command line, they aren't very user friendly and not very accessible to the normal person. I wanted to create a site that could run ...
[ "I have not used this tool yet myself, but Brython boasts this functionality. I will be looking into using this myself, as this is something I've been looking forward to utilizing.\n", "I'm personally a fan of Transcrypt and use it myself to create full React applications that are programmed with Python instead o...
[ 1, 0, 0 ]
[]
[]
[ "api", "client_side", "javascript", "python", "reactjs" ]
stackoverflow_0070900950_api_client_side_javascript_python_reactjs.txt
Q: How to get text from commandline with python I need to read out the text from a cmd prompt window (which updates every second) in my Python program. I'm using Windows 7. Anyone have an idea how to do this? edit: I didn’t explain it very well. The cmd prompt is already open and I need to read out everything it pri...
How to get text from commandline with python
I need to read out the text from a cmd prompt window (which updates every second) in my Python program. I'm using Windows 7. Anyone have an idea how to do this? edit: I didn’t explain it very well. The cmd prompt is already open and I need to read out everything it prints. I have to "link" my Python program to the com...
[ "You should read :module-subprocess \n>>> subprocess.check_output([\"echo\", \"Hello World!\"])\n'Hello World!\\n'\n\n", "Have you tried sys.argv ?.\nimport sys\nprint sys.argv[1:]\n\nThe first argument will be your file name.\n", "Just do subprocess.check_output()\nimport subprocess\ncommand = \"dir\"\noutput ...
[ 1, 0, 0 ]
[]
[]
[ "cmd", "python", "windows" ]
stackoverflow_0022197322_cmd_python_windows.txt
Q: run python script from within html in the browser This is a python inside html question. I have been looking for some time and have come across this code that embeds python inside a webpage (html). I have tested it and it works. Here is the code: The code script is saved as *.html and opens (and runs) in the brows...
run python script from within html in the browser
This is a python inside html question. I have been looking for some time and have come across this code that embeds python inside a webpage (html). I have tested it and it works. Here is the code: The code script is saved as *.html and opens (and runs) in the browser. <!DOCTYPE html> <head> <script type="module" src="h...
[ "I think you should learn flask or Django \\\nthe solution here FLASK can be helpful\n", "Pyodide is a solution for embedding python inside a webpage.\n", "Now it can be achievable by using PyScript. You can use the import statements inside the <py-script> tag.\nLive Demo :\n\n\n<link rel=\"stylesheet\" href=\"...
[ 0, 0, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0071636540_html_python.txt
Q: Selenium: Go URL's "up" is there a way to go urls endings up? For an example : driver.get("Example.com/1") then driver.get("Example.com/2") then driver.get("Example.com/3") and again and again. Until it is at 69. I tried googling, but I didn't found anything. A: Just use range for that: for i in range(1, 70): ...
Selenium: Go URL's "up"
is there a way to go urls endings up? For an example : driver.get("Example.com/1") then driver.get("Example.com/2") then driver.get("Example.com/3") and again and again. Until it is at 69. I tried googling, but I didn't found anything.
[ "Just use range for that:\nfor i in range(1, 70):\n driver.get(f'example/{i}')\n # Do what you want\n driver.quit()\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074485633_python_selenium_selenium_chromedriver.txt
Q: How to convert list into row using pandas if the name and there value is stored in one list Analyte_line 0 NaN 1 [['Urea', 3.0, '3', ''], ['Creatinine', 3.0, '... 2 [['Total Protein', '', '6', ''], ['Albumin', '... 3 ...
How to convert list into row using pandas if the name and there value is stored in one list
Analyte_line 0 NaN 1 [['Urea', 3.0, '3', ''], ['Creatinine', 3.0, '... 2 [['Total Protein', '', '6', ''], ['Albumin', '... 3 [['HGB', '', '18', ''], ['RBC', '', '1', ''], ... 4 [['Total Protein', '', '23', ''], ['Albu...
[ "You can use:\nout = (df\n .set_index(0).T.astype(str)\n .agg(lambda s: ','.join(x for x in s if x))\n .to_frame().T\n)\n\nOr:\nout = pd.DataFrame.from_dict({0: {k: ','.join(x for x in map(str, l) if x)\n for k, *l in data}}, orient='index')\n\nOutput:\n Urea Creatinine Uric Acid...
[ 1 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074486198_csv_dataframe_pandas_python.txt
Q: Is it possible to run python code in a web browser? My code below is a pandas dataframe, I've tried transcypt and flask to view this code in my browser, but have had errors. Any help would be greatly appreciated. import pandas as pd columns = ['cap', 'title', 'price'] df = pd.read_csv('asdawhiskey.csv', names=col...
Is it possible to run python code in a web browser?
My code below is a pandas dataframe, I've tried transcypt and flask to view this code in my browser, but have had errors. Any help would be greatly appreciated. import pandas as pd columns = ['cap', 'title', 'price'] df = pd.read_csv('asdawhiskey.csv', names=columns) items = df[df['cap'] == '70cl'] print(items.to_ht...
[ "Try Streamlit. https://streamlit.io\nYou don't have to write a single line of html\nimport streamlit as st\nimport pandas as pd\n\ncolumns = ['cap', 'title', 'price']\ndf = pd.read_csv('asdawhiskey.csv', names=columns)\n\nitems = df[df['cap'] == '70cl']\n\nst.write(items)\n\nThen run streamlit run example.py\n", ...
[ 3, 0 ]
[]
[]
[ "html", "pandas", "python" ]
stackoverflow_0062942057_html_pandas_python.txt
Q: No symbols loaded for c++ in mixed debugging (from Python) I have a large project where the major part computation heavy stuff is written in c++ and the "glue code" and the start script is written in Python. The code has been compiled with the VS 2017 compiler (V141) and Python 3.7.0-32bit for a few years now and ...
No symbols loaded for c++ in mixed debugging (from Python)
I have a large project where the major part computation heavy stuff is written in c++ and the "glue code" and the start script is written in Python. The code has been compiled with the VS 2017 compiler (V141) and Python 3.7.0-32bit for a few years now and I want to upgrade to V143 and Python 3.10-64, I can build and ru...
[ "Woho! I finally figured it out. The issue was connected to the venv. Running from the global Python works but if you need to run it from a venv you need to create it with --symlinks like this C:\\Python310-64\\python.exe -m venv venv --symlinks. You also need to run this command as administrator in the cmd or fro...
[ 2 ]
[]
[]
[ "c++", "debugging", "python", "visual_studio", "windows" ]
stackoverflow_0074190153_c++_debugging_python_visual_studio_windows.txt
Q: Add names to a list without splitting in Python I'm trying to create a program where a user copy pastes a list of names seperated by spaces & python saves it as a list. However, while using list.extend it splits every name into alphabets. How can I fix it so it saves each name as a string. How can I solve it. A: ...
Add names to a list without splitting in Python
I'm trying to create a program where a user copy pastes a list of names seperated by spaces & python saves it as a list. However, while using list.extend it splits every name into alphabets. How can I fix it so it saves each name as a string. How can I solve it.
[ "You could use regex:\nimport re\ninput = \"program where a user copy pastes a list of names seperated\"\noutput = re.split(\" \", input)\n\nResult:\n['program', 'where', 'a', 'user', 'copy', 'pastes', 'a', 'list', 'of', 'names', 'seperated']\n\n", "Python strings have the split function, that split by white spac...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074486054_list_python.txt
Q: PyQT drag and drop to reorder items Im trying to make a small app that would help me rename pictures. Since i want to manually order them, i had the idea to simply show a window with thumbnails inside in a grid ( or small scale images, doesnt matter ), and then drag and drop reorder them as i see fit. Afterwards i...
PyQT drag and drop to reorder items
Im trying to make a small app that would help me rename pictures. Since i want to manually order them, i had the idea to simply show a window with thumbnails inside in a grid ( or small scale images, doesnt matter ), and then drag and drop reorder them as i see fit. Afterwards its just click a button and they get prope...
[ "After ekhumoro hint, i was able to solve it.\nHeres a sample code that reads the current folder of its files, shows them as \"thumbnails\", and allows reordering.\n#!/usr/bin/python\n\nimport sys, os\nfrom PyQt5.QtWidgets import (QListWidget, QWidget, QMessageBox,\n QApplication, QVBoxL...
[ 0 ]
[]
[]
[ "pyqt", "python", "user_interface" ]
stackoverflow_0074474875_pyqt_python_user_interface.txt
Q: Unable to locate or select a select element from dropdown menu with Selenium - element not visible edited: [https://www.bellsofsteel.us/checkout/][1] I'm unable to locate or select an option from a drop-down menu using selenium. I'm attempting to get the various taxes and shipping for an item, by iterating throug...
Unable to locate or select a select element from dropdown menu with Selenium - element not visible
edited: [https://www.bellsofsteel.us/checkout/][1] I'm unable to locate or select an option from a drop-down menu using selenium. I'm attempting to get the various taxes and shipping for an item, by iterating through a list with cities, states and zip codes The HTML for the select element is as follows: <span class="w...
[ "That dropdown is not a 'Select' type element, it is a 'ul' type element, so you can't use Select.\nIn the checkout page, add the below code and try:\n# scrolling to the element - 'First name' label\nfirst_name_label = driver.find_element(By.XPATH, \".//label[@for='billing_first_name']\")\ndriver.execute_script(\"a...
[ 0 ]
[]
[]
[ "drop_down_menu", "ironwebscraper", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074470588_drop_down_menu_ironwebscraper_python_selenium_selenium_webdriver.txt
Q: How to improve this pandas code "Dropping of nuisance columns in DataFrame reductions (with 'numeric_only=None') is deprecated" I have a CSV with more than 500.000 results with a lot of duplicates, I'm creating a new dataframe with unique values and trying to find the min value of a date. I have this code here tha...
How to improve this pandas code "Dropping of nuisance columns in DataFrame reductions (with 'numeric_only=None') is deprecated"
I have a CSV with more than 500.000 results with a lot of duplicates, I'm creating a new dataframe with unique values and trying to find the min value of a date. I have this code here that works but takes way to much time to load. How can I improve this? for i in range(len(df_leads)): df_leads.loc[i,'Created Date']...
[ "\nI'm creating a new dataframe with unique values and trying to find the min value of a date.\nThe second df comes from doing the unique of df['customer_lead_id']\n\nInstead of that, we can drop_duplicates in a DataFrame after we sort_values of the date - this will keep the first occurrence, i. e. the min value:\n...
[ 0 ]
[]
[]
[ "optimization", "pandas", "python" ]
stackoverflow_0074474798_optimization_pandas_python.txt
Q: How to find if a value unique to first data frame when comparing to another data frame For example, I have 2 dataframes with 2 columns: df1 df2 AAA BBB AAA KKK BBB CCC BBB LLL CCC FFF CCC FFF DDD None None None I want to spot whats on df1 is not in df2, then th...
How to find if a value unique to first data frame when comparing to another data frame
For example, I have 2 dataframes with 2 columns: df1 df2 AAA BBB AAA KKK BBB CCC BBB LLL CCC FFF CCC FFF DDD None None None I want to spot whats on df1 is not in df2, then the result is DDD (exclude None). How can I achieve this?
[ "import pandas as pd\n\ndf1 = pd.DataFrame([['AAA', 'BBB'], ['BBB', 'CCC'], ['CCC', 'FFF'], ['DDD', None]])\ndf2 = pd.DataFrame([['AAA', 'KKK'], ['BBB', 'LLL'], ['CCC', 'FFF'], [None, None]])\n\ndf1_uniq = []\ndf2_uniq = []\nfor col in df1.columns:\n for string in df1[col].unique():\n df1_uniq.append(string)\nf...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074485939_dataframe_pandas_python.txt
Q: Getting text from multiple webpages(Pagination) in selenium python I wanted to extract text from multiple pages. Currently, I am able to extract data from the first page but I want to append and go to muliple pages and extract the data from pagination. I have written this simple code which extracts data from the f...
Getting text from multiple webpages(Pagination) in selenium python
I wanted to extract text from multiple pages. Currently, I am able to extract data from the first page but I want to append and go to muliple pages and extract the data from pagination. I have written this simple code which extracts data from the first page. I am not able to extract the data from multiple pages which i...
[ "You have provided the code just for the previous page button. I guess you need to go to the next page until next page exists. As I don't know what site we are talking about I can only guess its behavior. So I'm assuming the button 'next' disappears when no next page exists. If so, it can be done like this:\nelemen...
[ 0 ]
[]
[]
[ "automation", "pagination", "python", "selenium" ]
stackoverflow_0074485737_automation_pagination_python_selenium.txt
Q: My else statement doesn't work. What is wrong? So in the if-statement, I want to print a message if the player doesn't input the correct things. The problem is that when I start up the code and type something random, it jumps to the first if where it checks yes and moves on. It even replied to the next function fo...
My else statement doesn't work. What is wrong?
So in the if-statement, I want to print a message if the player doesn't input the correct things. The problem is that when I start up the code and type something random, it jumps to the first if where it checks yes and moves on. It even replied to the next function for me. Is there a way to fix this? import time yes_n...
[ "You need to change:\nif cmd == \"yes\" or \"y\"\n\nto\nif cmd == \"yes\" or cmd == \"y\"\n\n..and similarly in other parts of your code.\nIf cmd == 'no' then this test would be True because a non-empty string is truthy.\nAn alternative construct could be:\nif cmd in {'yes', 'y'}\n\n", "change as following:\nif c...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074486393_python.txt
Q: How to detect figures in a paper news image in Python? So i have this project in Python (Computer Vision), which is seperating text from figures of an image (like a paper news image). My question is what's the best way to detect those figures in the paper ? (in Python). Paper image example : Paper . Haven't try an...
How to detect figures in a paper news image in Python?
So i have this project in Python (Computer Vision), which is seperating text from figures of an image (like a paper news image). My question is what's the best way to detect those figures in the paper ? (in Python). Paper image example : Paper . Haven't try anything. I have no idea ..
[ "I found layout-parser python toolkit which is very helpful for your project.\nLayout Parser is a unified toolkit for Deep Learning Based Document Image Analysis.\nWith the help of Deep Learning, layoutparser supports the analysis very complex documents and processing of the hierarchical structure in the layouts.\n...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "computer_vision", "document_layout_analysis", "image_processing", "object_detection", "python" ]
stackoverflow_0074485252_computer_vision_document_layout_analysis_image_processing_object_detection_python.txt
Q: Find non-numeric values in pandas dataframe column I got a a column in a dataframe that contains numbers and strings. So I replaced the strings by numbers via df.column.replace(["A", "B", "C", "D"], [1, 2, 3, 4], inplace=True). But the column is still dtype "object". I can not sort the column (TypeError error: '<'...
Find non-numeric values in pandas dataframe column
I got a a column in a dataframe that contains numbers and strings. So I replaced the strings by numbers via df.column.replace(["A", "B", "C", "D"], [1, 2, 3, 4], inplace=True). But the column is still dtype "object". I can not sort the column (TypeError error: '<' not supported between instances of 'str' and 'int'). No...
[ "You can use pd.to_numeric with something like:\ndf['column'] = pd.to_numeric(df['column'], errors='coerce')\n\nFor the errors argument you have few option, see reference documentation here\n", "Expanding on Francesco's answer, it's possible to create a mask of non-numeric values and identify unique instances to ...
[ 0, 0, -1 ]
[]
[]
[ "dataframe", "dtype", "pandas", "python", "python_3.x" ]
stackoverflow_0062376326_dataframe_dtype_pandas_python_python_3.x.txt
Q: Custom methods for a Pandas DataFrame I'd like to write custom functions that I can call on my pd.DataFrame df using the df.method() notation. For instance, def my_pd_method(df: pd.DataFrame, col: str)->pd.DataFrame: '''apply my_function to df[col] of df''' df_copy = df.copy(deep = True) df_copy[col]...
Custom methods for a Pandas DataFrame
I'd like to write custom functions that I can call on my pd.DataFrame df using the df.method() notation. For instance, def my_pd_method(df: pd.DataFrame, col: str)->pd.DataFrame: '''apply my_function to df[col] of df''' df_copy = df.copy(deep = True) df_copy[col] = df_copy[col].apply(lambda x: my_function...
[ "Your best shot is to use inheritance i.e to create your own custom class that inherits from pandas DataFrame class.\nExample:\nclass CustomDataFrame(pd.DataFrame):\n def my_method(self, col):\n df_copy = self.copy(deep = True)\n df_copy[col] = df_copy[col].apply(lambda x: my_function(x), axis = 1)...
[ 2 ]
[]
[]
[ "dataframe", "methods", "oop", "pandas", "python" ]
stackoverflow_0074485623_dataframe_methods_oop_pandas_python.txt
Q: find Coordinates on a 3D hexgon Coordinates of the hexagon [Hexagon](https://i.stack.imgur.com/tww83.png) Now I want to add coordinates between these coordinates such that these 8 coordinates 27 coordinates as shownenter image description here an find the new coordinates too I tried to make a code but not working ...
find Coordinates on a 3D hexgon
Coordinates of the hexagon [Hexagon](https://i.stack.imgur.com/tww83.png) Now I want to add coordinates between these coordinates such that these 8 coordinates 27 coordinates as shownenter image description here an find the new coordinates too I tried to make a code but not working much well xi = [-1.0, 0.0, 1.0] ele_a...
[ "Hard code it: let a, b, c, d, e, f, g, h be the eight points. Then add the averages of\n(a, b), (b, c), (c, d), (d, a), (d, e), (e, f), (g, h), (h, d), (a, d), (b, e), (c, f), (d, h), (a, b, c, d), (a, d, b, e), (e, f, g, h), (b, e, c, f), (c, f, d, h), (d, h, a, d), (a, b, c, d, e, f, g).\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074486559_python.txt
Q: What is the most efficient option to implement a C based library into my python code? I have a moderate amount of experience in python and a little experience in C++ and c#. I am currently doing an optimization challenge where I am gated by efficiency, and am hoping to use a C library in python to increase efficie...
What is the most efficient option to implement a C based library into my python code?
I have a moderate amount of experience in python and a little experience in C++ and c#. I am currently doing an optimization challenge where I am gated by efficiency, and am hoping to use a C library in python to increase efficiency. I have no experience using C in python, but I won't need to marshall many variables. I...
[ "In general, you can't write your C code inline within your Python file. Instead, you need to create a separate C program which can get compiled into a library which defines a function that can be imported by Python.\nThis article appears to have reasonable instructions.\n", "Better way to do this will be create ...
[ 0, 0 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0074467742_c_python_python_c_api.txt
Q: Send email in Python Now, as the Lesser secure apps feature in Gmail has been disabled, I am trying to find alternatives for email sending. I am trying freemail.hu as an alternative which supports SMTP protocol, but any other suggestion is highly welcome. According to the web page, the data for SMTP are the follow...
Send email in Python
Now, as the Lesser secure apps feature in Gmail has been disabled, I am trying to find alternatives for email sending. I am trying freemail.hu as an alternative which supports SMTP protocol, but any other suggestion is highly welcome. According to the web page, the data for SMTP are the following: Server name: smtp.fr...
[ "For Gmail the App Passwords as described on page https://support.google.com/mail/answer/185833 works well. The 2 step verification should be turned on, and then a 16 character long random password can be generated on the App passwords section.\n" ]
[ 0 ]
[]
[]
[ "python", "smtplib" ]
stackoverflow_0074395874_python_smtplib.txt
Q: Python - Sort Dictionary Key Alphabetically while sorting Value list elements by length I have a Dictionary here: test_dict = {'gfg': ['One', 'six', 'three'], 'is': ['seven', 'eight', 'nine'], 'best': ['ten', 'six']} I tried: for i in range(len(test_dict)): values = lis...
Python - Sort Dictionary Key Alphabetically while sorting Value list elements by length
I have a Dictionary here: test_dict = {'gfg': ['One', 'six', 'three'], 'is': ['seven', 'eight', 'nine'], 'best': ['ten', 'six']} I tried: for i in range(len(test_dict)): values = list(test_dict.values()) keys = list(test_dict) value_sorted_lis...
[ "Sorting keys alphabetically and values by length.\nnew_dict = {}\nfor key in sorted(test_dict.keys()):\n sorted_values = sorted(test_dict[key], key=len)\n new_dict[key] = sorted_values\nprint(new_dict)\n\n", "dict preserves insertion order since 3.7.\n\nChanged in version 3.7: Dictionary order is guarantee...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "function", "list", "python", "sorting" ]
stackoverflow_0074485945_dictionary_function_list_python_sorting.txt
Q: --proto_path passed empty directory name I'm trying to compile a proto file with the following command: protoc -I=. --python_out=. ./message.proto --proto_path=. But I'm getting this error: --proto_path passed empty directory name. (Use "." for current directory.) What to do? A: You should remove = in -I=. an...
--proto_path passed empty directory name
I'm trying to compile a proto file with the following command: protoc -I=. --python_out=. ./message.proto --proto_path=. But I'm getting this error: --proto_path passed empty directory name. (Use "." for current directory.) What to do?
[ "You should remove = in -I=. and also remove --proto_path=. flag\n", "The command works for me.\n\nNOTE -I == --proto_path so using both with the same value is redundant\n\nOne 'wrinkle' with protoc is that the protobuf files must be encapsulated by a proto_path.\nSo, in your case, the current directory must cont...
[ 8, 0, 0 ]
[]
[]
[ "proto", "protocol_buffers", "python" ]
stackoverflow_0064048132_proto_protocol_buffers_python.txt
Q: Visual Studio Code Python refuses to write to file I'm trying to have a program output data to a JSON file, but VS code or Python itself seems to have a problem with that. Specifically, I'm trying to output this(Tlist and Slist are lists of integers): output = {"Time": Tlist, "Space": Slist} json_data = json.dumps...
Visual Studio Code Python refuses to write to file
I'm trying to have a program output data to a JSON file, but VS code or Python itself seems to have a problem with that. Specifically, I'm trying to output this(Tlist and Slist are lists of integers): output = {"Time": Tlist, "Space": Slist} json_data = json.dumps(output, indent=4) with open("sortsOutput.json", "a") as...
[ "\nout = file.open(\"blah.txt\", \"w\")\n\nIn your second example, it seems that you don't need file.. open() is a built-in method of Python.\nYou can use out = open(\"blah.txt\", \"w\") directly.\nAt the same time, this problem seems to have nothing to do with vscode.\nI think this problem is more likely due to th...
[ 0, 0 ]
[]
[]
[ "file_io", "python", "visual_studio_code" ]
stackoverflow_0074140974_file_io_python_visual_studio_code.txt
Q: Distutils build include C++ library with setup I'm trying to link glfw to my C++ python extension but I can't do it without cmake. Here is how I did it in cmake: cmake_minimum_required(VERSION 3.0) project(Test) add_subdirectory(lib/glfw) add_executable(Test py_extend.cpp) target_include_directories(Test PRIVAT...
Distutils build include C++ library with setup
I'm trying to link glfw to my C++ python extension but I can't do it without cmake. Here is how I did it in cmake: cmake_minimum_required(VERSION 3.0) project(Test) add_subdirectory(lib/glfw) add_executable(Test py_extend.cpp) target_include_directories(Test PRIVATE ${OPENGL_INCLUDE_DIR} ) target_link_librarie...
[ "I did it by changing to setuptools (I should change to it since distutils will be depricated soon.) and writing it like this:\nfrom setuptools import setup, Extension\n\nmodule1 = Extension('nerveblox_test',\n sources = ['py_extend.cpp', 'src/nerveblox_VM.cpp'],\n include_dirs...
[ 0 ]
[]
[]
[ "c++", "cmake", "distutils", "python" ]
stackoverflow_0074486430_c++_cmake_distutils_python.txt
Q: Fetch not receiving headers JS from Flask send_file() I'm writing a full stack app. I have a python backend using flask that sends a file and a Vue client that receives. Its been working fine up until the point when I try to send the filename over using a Content-Disposition header. On the backend I've tried: retu...
Fetch not receiving headers JS from Flask send_file()
I'm writing a full stack app. I have a python backend using flask that sends a file and a Vue client that receives. Its been working fine up until the point when I try to send the filename over using a Content-Disposition header. On the backend I've tried: return send_file(base_path + filename, as_attachment=True, down...
[ "Research\nIn the interest of logging the solution I found and helping out anyone in the future who may be interested in knowing the answer here's what I discovered:\n\n\n\nThere is a restriction to access response headers when you are using Fetch API over CORS.\n\nhttps://stackoverflow.com/a/44816592/20342081\nSo,...
[ 0 ]
[]
[]
[ "fetch_api", "flask", "javascript", "python", "vue.js" ]
stackoverflow_0074473164_fetch_api_flask_javascript_python_vue.js.txt
Q: AuthorizationPermissionMismatch when copy blobs across different storage accounts I am using below code to copy blob across different storage accounts, but it fails with the below error src_blob = '{0}/{1}?{2}'.format('source_url',b_name,'sp=rw&st=2022-11-17T20:44:03Z&se=2022-12-31T04:44:03Z&spr=https&sv=2021-06-0...
AuthorizationPermissionMismatch when copy blobs across different storage accounts
I am using below code to copy blob across different storage accounts, but it fails with the below error src_blob = '{0}/{1}?{2}'.format('source_url',b_name,'sp=rw&st=2022-11-17T20:44:03Z&se=2022-12-31T04:44:03Z&spr=https&sv=2021-06-08&sr=c&sig=ZXRe2FptVF5ArRM%2BKDAkLboCN%2FfaD9Mx38yZGWhnps0%3D') destinatio...
[ "I tried in my environment and successfully copied blob from one storage account to another storage account.\nCode:\nfrom azure.storage.blob import BlobServiceClient\n\nb_name=\"sample1.pdf\"\n\nsrc_blob = '{0}/{1}?{2}'.format('https://venkat123.blob.core.windows.net/test',b_name,'sp=r&st=2022-11-18T07:46:10Z&se...
[ 1 ]
[]
[]
[ "azure_blob_storage", "azure_python_sdk", "azure_storage", "python" ]
stackoverflow_0074485713_azure_blob_storage_azure_python_sdk_azure_storage_python.txt
Q: Vscode Unittests not discovered when using conda environment with mamba installed I am trying to use tests in vscode. When I am on the default interpreter in /usr/bin/python3 I have no problem and my simple tests are discovered. However when I select the conda interpreter the tests disappear and if I configure the...
Vscode Unittests not discovered when using conda environment with mamba installed
I am trying to use tests in vscode. When I am on the default interpreter in /usr/bin/python3 I have no problem and my simple tests are discovered. However when I select the conda interpreter the tests disappear and if I configure the tests again they won't appear. This is the python output when I try to discover tests ...
[ "Just in case anyone else finds this and has this problem\nI had installed mamba directly into my conda environments instead of into the base environment and recreating those environments. The mamba installation instructions specifically warns against installing mamba into anywhere other than the base environment. ...
[ 1, 0 ]
[]
[]
[ "python", "unit_testing", "visual_studio_code" ]
stackoverflow_0072508876_python_unit_testing_visual_studio_code.txt
Q: Scraping a table from html using python and beautifulsoup I am trying to scrape data from a table in a government website, I have tried to watch some tutorials but so far to no avail (coding dummy over here!!!) I would like to get a .csv file out of the tables they have containing the date, the type of event, and ...
Scraping a table from html using python and beautifulsoup
I am trying to scrape data from a table in a government website, I have tried to watch some tutorials but so far to no avail (coding dummy over here!!!) I would like to get a .csv file out of the tables they have containing the date, the type of event, and the adopted measures for a project. I leave here the website if...
[ "Make your life easier and just use pandas to parse the tables and dump the data to a .csv file.\nFor example, this gets you all the tables, merges them, and spits out a .csv file:\nimport pandas as pd\nimport requests\n\nurl = \"https://www.inspq.qc.ca/covid-19/donnees/ligne-du-temps\"\ntables = pd.read_html(reque...
[ 0 ]
[]
[]
[ "beautifulsoup", "google_colaboratory", "python", "web_scraping" ]
stackoverflow_0074483452_beautifulsoup_google_colaboratory_python_web_scraping.txt
Q: How to train real-time LSTM with input and output of varying length? I have the data of banner clicks by minute. I have the following data: hour, minute, and was the banner clicked by someone in that minute. There are some other features (I omitted them in the example dataframe). I need to predict will be any clic...
How to train real-time LSTM with input and output of varying length?
I have the data of banner clicks by minute. I have the following data: hour, minute, and was the banner clicked by someone in that minute. There are some other features (I omitted them in the example dataframe). I need to predict will be any clicks on banner for all following minutes of this hour. For example I have da...
[ "An RNN (or LSTM) will return an output for every input, as well as the final hidden state (and cell state for LSTM). So one possible solution: Pad your input of future minutes with with a different token and use an embedding layer with 3 embeddings (0, 1, 2 where 2 represents unseen value). For example, at timeste...
[ 1 ]
[]
[]
[ "deep_learning", "lstm", "python", "pytorch", "recurrent_neural_network" ]
stackoverflow_0074482446_deep_learning_lstm_python_pytorch_recurrent_neural_network.txt
Q: layoutparser has no attribute Detectron2LayoutModel Im working on a projet where I need to extract informations from resume in pdf format, the problem is when I use libraries like pdfminer ect sometimes the text extracted is not the good result because it gets lines overlapped with other lines from another box of ...
layoutparser has no attribute Detectron2LayoutModel
Im working on a projet where I need to extract informations from resume in pdf format, the problem is when I use libraries like pdfminer ect sometimes the text extracted is not the good result because it gets lines overlapped with other lines from another box of text, thats why I thought of using layout parser first be...
[ "Actually the attribute Detectron2LayoutModel can be accessed only inside models:\nmodel = lp.models.Detectron2LayoutModel('lp://PubLayNet/mask_rcnn_X_101_32x8d_FPN_3x/config',\n extra_config=[\"MODEL.ROI_HEADS.SCORE_THRESH_TEST\", 0.5],\n label_map={0...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0072572315_python.txt
Q: Python Threading consumer being called before producer I wrote a simple python program to understand threading. This program has no thread blocking logic like time.sleep(x) but still I don't understand how possibly can consumer thread be called before producer thread. Producer -> appends a numeric value to list Co...
Python Threading consumer being called before producer
I wrote a simple python program to understand threading. This program has no thread blocking logic like time.sleep(x) but still I don't understand how possibly can consumer thread be called before producer thread. Producer -> appends a numeric value to list Consumer -> gets/prints the numeric value from this list. How ...
[ "This is a race condition, and if the list was bigger and there were more elements in it you would only print the elements that were in the list the moment the second thread started, which is only a portion of the list.\nPrinting is also buffered so it doesn't happen at the order in which you call print, the actual...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074470184_multithreading_python.txt
Q: read excel with pandas hiii guys i'am new in python and pandas. i have some questions about this tutorial page from pandas https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-indexing-with-hierarchical-index how to get a list of loc A B C first second...
read excel with pandas
hiii guys i'am new in python and pandas. i have some questions about this tutorial page from pandas https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-indexing-with-hierarchical-index how to get a list of loc A B C first second ...
[ "try this\ndf.index.unique(level=0)\nreturns\nIndex(['bar', 'baz', 'foo', 'qux'], dtype='object', name='first')\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074486041_pandas_python.txt
Q: Pandas - Pivot Table based on Column A while ensuring order in Column B Given the following data frame containing three columns: Text Line_Number Value 521998135749 15 Pamphlet 2716253485 15 Local SRM 15 Info ...
Pandas - Pivot Table based on Column A while ensuring order in Column B
Given the following data frame containing three columns: Text Line_Number Value 521998135749 15 Pamphlet 2716253485 15 Local SRM 15 Info 12 B WAY 16 Info DANUBE 17 ...
[ "Use pivot and reindex by unique so:\n(df.pivot('Line_Number', 'Value', 'Text')\n .reindex(index=df['Line_Number'].unique(), columns=df['Value'].unique()))\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074486802_dataframe_pandas_python.txt
Q: Python playwright - existing browser and variable in function Below is the code of my web scraper, where I am trying to scrape the car names. I have also have list with locations. I would like to use the variable loc of the locationlist in my function. And also use the opened browser window, but the function does ...
Python playwright - existing browser and variable in function
Below is the code of my web scraper, where I am trying to scrape the car names. I have also have list with locations. I would like to use the variable loc of the locationlist in my function. And also use the opened browser window, but the function does not recognize the syntax 'page.' that is on line 16. F.e. like Sele...
[ "Here's how to initialize playwright browser globally without context managers.\nIn your particular code, this will work like below:\nfrom playwright.sync_api import Playwright, sync_playwright\n\nlocationList = [\n 'London Luton Airport',\n 'London Hilton',\n 'London City',\n 'London Wembley',\n 'Lo...
[ 0 ]
[]
[]
[ "playwright", "python" ]
stackoverflow_0074480301_playwright_python.txt
Q: Accessing MySQL docker container from Flask APP I have been trying all day, unsuccessfully, to connect to a MySQL running container from my SQLALCHEMY flask app. Don't know what I'm doing wrong, perhaps I'm missing something that you might call my attention to resolve my issue. Just for context. I have the followi...
Accessing MySQL docker container from Flask APP
I have been trying all day, unsuccessfully, to connect to a MySQL running container from my SQLALCHEMY flask app. Don't know what I'm doing wrong, perhaps I'm missing something that you might call my attention to resolve my issue. Just for context. I have the following files: docker-compose.yml file with MySQL and Admi...
[ "I have resolved your question in this github repo :\nhttps://github.com/jcroyoaun/stackoverflow-flask-question\nI would appreciate if you could clone my repo and try\ndocker-compose up --build\n\nfirst.\nAfter that, if it works for you please read on the explanation of what was wrong. (I modified a few things afte...
[ 0 ]
[]
[]
[ "docker_compose", "flask", "flask_sqlalchemy", "mysql_python", "python" ]
stackoverflow_0074482882_docker_compose_flask_flask_sqlalchemy_mysql_python_python.txt
Q: TensorFlow.js model converters.: error: unrecognized arguments: I am trying to follow this tutorial How to deploy your custom TensorFlow model to react native to convert my model to be deployed to my reactjs webapp. (Thesis) C:\Users\JHON MICHEAL>tensorflowjs_converter --input_format=keras C:\Users\JHON MICHEAL\De...
TensorFlow.js model converters.: error: unrecognized arguments:
I am trying to follow this tutorial How to deploy your custom TensorFlow model to react native to convert my model to be deployed to my reactjs webapp. (Thesis) C:\Users\JHON MICHEAL>tensorflowjs_converter --input_format=keras C:\Users\JHON MICHEAL\Desktop\Tan\Model\image-model\rabbit.h5 C:\Users\JHON MICHEAL\Desktop\T...
[ "It seems that this argument is not correct\n\n--input_format=keras\n\nand need to be changed to\n\n--input_format keras\n\nyou can see details here\nhttps://www.tensorflow.org/js/tutorials/conversion/import_keras\n" ]
[ 0 ]
[]
[]
[ "python", "reactjs", "tensorflow" ]
stackoverflow_0074486398_python_reactjs_tensorflow.txt
Q: How to Extract all Urls from href under a but it seems to give me an error all the time category_tag = soup.find_all('div' , {'class': '_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8'}) Output of category_tag: <div class="_p13n-zg-nav-tree-all_style_zg-...
How to Extract all Urls from href under a but it seems to give me an error all the time
category_tag = soup.find_all('div' , {'class': '_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8'}) Output of category_tag: <div class="_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8" role="treeitem"...
[ "Try to select your elements more specific and use id and tag structure over dynamic classes:\nsoup.select('#zg-left-col a')\n\nor to be more strict, to use only path that starts with specific pattern:\nsoup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')\n\nSo list could be created via lis comprehension:...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074486499_beautifulsoup_python_web_scraping.txt
Q: Is there any way to make an anti-aliased circle in OpenCV I'm trying to draw a circle in a picture using open CV with Python. Here is the picture I wish I can make : Here is the code I write : import cv2 import numpy as np import imutils text1 = "10x" text2 = "20gr" # Load image in OpenCV image = cv2....
Is there any way to make an anti-aliased circle in OpenCV
I'm trying to draw a circle in a picture using open CV with Python. Here is the picture I wish I can make : Here is the code I write : import cv2 import numpy as np import imutils text1 = "10x" text2 = "20gr" # Load image in OpenCV image = cv2.imread('Sasa.jfif') resized = imutils.resize(image, width=500) ...
[ "You can use anti aliasing to make the circle look better as described here:\ncv2.circle(resized,(350,150),65,(102,51,17),thickness=-1,lineType=cv2.LINE_AA)\n\n" ]
[ 5 ]
[]
[]
[ "draw", "opencv", "python" ]
stackoverflow_0074486877_draw_opencv_python.txt
Q: Find multiple text patterns and then output the next value in a sting in pandas I have a datframe with the following values Call Data 1 [{'b_id': '31358658', 'incentive': 0}, {'b_id': 'D8384E90', 'incentive': 0}, {'b_id': '681B405A','incentive': 100}] 2 [{'b_id': 'D8384E90','incentive': 0 }, {'b_id': '31358...
Find multiple text patterns and then output the next value in a sting in pandas
I have a datframe with the following values Call Data 1 [{'b_id': '31358658', 'incentive': 0}, {'b_id': 'D8384E90', 'incentive': 0}, {'b_id': '681B405A','incentive': 100}] 2 [{'b_id': 'D8384E90','incentive': 0 }, {'b_id': '31358658', 'incentive': 0}, {'b_id': '681B405A', 'incentive': 120}] 3 [{'b_id': '971C0B...
[ "you can use a loop in lambda function.:\nimport ast\ndf['Data']=df['Data'].apply(ast.literal_eval)\n\ndf['B_id']=df['Data'].apply(lambda x: [i['b_id'] for i in x])\ndf['incentive']=df['Data'].apply(lambda x: [i['incentive'] for i in x])\nprint(df.head(1)\n'''\n Call Data B_id ...
[ 1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074486950_json_pandas_python.txt
Q: How to find the common elements and total count of elements that are in DataFrame in Pandas I have below single DataFrame with columns as order_id , Order_date. Order_id Order_date 1 2022-11-16 2 2022-11-16 3 2022-11-16 4 2022-11-16 5 2022-11-17 6 2022-11-17 2 2022-11-17 1 2022-11-17 2 2022-11-18 7 2022...
How to find the common elements and total count of elements that are in DataFrame in Pandas
I have below single DataFrame with columns as order_id , Order_date. Order_id Order_date 1 2022-11-16 2 2022-11-16 3 2022-11-16 4 2022-11-16 5 2022-11-17 6 2022-11-17 2 2022-11-17 1 2022-11-17 2 2022-11-18 7 2022-11-18 Here order_id 2 and 1 are in both 2022-11-16 and 2022-11-17. Similary i...
[ "You can sort the dates, compute the successive differences per group to filter the deltas equal to 1 day, and count them:\ndf['Order_date'] = pd.to_datetime(df['Order_date'])\n\n(df.sort_values(by=['Order_id', 'Order_date'])\n .groupby('Order_id')['Order_date']\n .apply(lambda s: s.diff().eq('1d').sum())\n ....
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074486723_dataframe_pandas_python.txt
Q: Best way to groupby and join in pyspark Hi I have two dataframe like this: df_1: id item activity 1 2 a 34 14 b 1 2 b . . . Activity has two uniqe values a and b. df_2: id item activity 1 2 c 34 14 c 1 2 c Here activity has all same...
Best way to groupby and join in pyspark
Hi I have two dataframe like this: df_1: id item activity 1 2 a 34 14 b 1 2 b . . . Activity has two uniqe values a and b. df_2: id item activity 1 2 c 34 14 c 1 2 c Here activity has all same values c Now I want final df where I have to...
[ "You can change the spark config to allow for more memory. Can you clarify if it is storage space you're lacking or memory when running the program?\nOne method to reduce the memory of the spark session is to save each table to the disk before joining them. This helps runtime and memory usage (or atleast it did fo...
[ 0, 0 ]
[]
[]
[ "apache_spark", "join", "pyspark", "python", "scala" ]
stackoverflow_0074483461_apache_spark_join_pyspark_python_scala.txt
Q: Error in installing aria2c in python while installing Windows VM I'm trying to install Windows VM in accordance with the instructions https://sugary-selenium-eb9.notion.site/Power-BI-installation-guide-for-Mac-ed07be30d6b94cf2ad9325dddd38d9d3 I have a Mac with an Intel chip. I Enter the following commands: chmod ...
Error in installing aria2c in python while installing Windows VM
I'm trying to install Windows VM in accordance with the instructions https://sugary-selenium-eb9.notion.site/Power-BI-installation-guide-for-Mac-ed07be30d6b94cf2ad9325dddd38d9d3 I have a Mac with an Intel chip. I Enter the following commands: chmod +x uup_download_macos.sh ./uup_download_macos.sh And I get this error...
[ "You may need to install Homebrew (via Terminal):\n\nEnter /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"\nthen press enter/return\nRun echo 'eval \"$(/opt/homebrew/bin/brew shellenv)\"' >> ~/.zprofile\nRun brew install aria2 cabextract wimlib cdrtools sidneys/home...
[ 0 ]
[]
[]
[ "homebrew", "python", "virtual_machine" ]
stackoverflow_0074373316_homebrew_python_virtual_machine.txt
Q: How to show image in grayscale for some reason this isn't working. i may be making a silly mistake somewhere. please help # importing modules import urllib.request import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from PIL import Image #dowload mona lisa image urllib.request.urlretriev...
How to show image in grayscale
for some reason this isn't working. i may be making a silly mistake somewhere. please help # importing modules import urllib.request import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from PIL import Image #dowload mona lisa image urllib.request.urlretrieve( 'https://upload.wikimedia.org/...
[ "have you tried this answer ?\nHow can I convert an RGB image into grayscale in Python?\nfrom PIL import Image\nimg = Image.open('image.png').convert('L')\nimg.save('greyscale.png')\n\n", "you can convert the image to grayscale using PIL.Image.convert:\nimg = Image.open(\"/content/Mona_Lisa.png\").convert(\"L\")\...
[ 3, 1 ]
[]
[]
[ "image", "matplotlib", "python" ]
stackoverflow_0074487021_image_matplotlib_python.txt
Q: Pandas dataframe row counts to plt incrementally after every 4 consecutive rows I am trying to assign as ID to a pandas dataframe based on row count. For this I am trying to apply the below logic to pandas dataframe: num = df.shape[0] for i in range(num): print(math.ceil(i/4)) So the idea is that for every 4 c...
Pandas dataframe row counts to plt incrementally after every 4 consecutive rows
I am trying to assign as ID to a pandas dataframe based on row count. For this I am trying to apply the below logic to pandas dataframe: num = df.shape[0] for i in range(num): print(math.ceil(i/4)) So the idea is that for every 4 consecutive rows, an ID would be assigned. So the resultant dataframe would look like ...
[ "You can pass a function to apply, so create a named function and pass it\ndef everyFour(rowIdx):\n return math.ceil(rowIdx / 4)\n\ndf['GroupId'] = df['Index'].apply(everyFour)\n\nor just use a lambda\ndf['GroupId'] = df['Index'].apply(lambda rowIdx: math.ceil(rowIdx / 4))\n\nNote that this will leave the first ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074486976_python.txt
Q: Python OS - check if file exists, if so rename, check again, then save I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filen...
Python OS - check if file exists, if so rename, check again, then save
I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the ...
[ "Haven't tested this yet but you can use os.path.isfile() to check if a file already exists (for directories, use os.path.exists).\nimport os\n\ndef save():\n file = request.files['xx']\n extension = os.path.splitext(file.filename)[1]\n\n xx = generate_filename(extension)\n\n file.save(os.path.join(app....
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0043107577_python_python_3.x.txt
Q: discord.errors.NotFound: 404 Not Found (error code: 0): 404: Not Found i have this code: class Adduser(discord.ui.Modal, title="add"): answer = ui.TextInput(label = "ID de l'utilisateur à ajouter au ticket", style = discord.TextStyle.short, placeholder = "ID", required= True) def __ini...
discord.errors.NotFound: 404 Not Found (error code: 0): 404: Not Found
i have this code: class Adduser(discord.ui.Modal, title="add"): answer = ui.TextInput(label = "ID de l'utilisateur à ajouter au ticket", style = discord.TextStyle.short, placeholder = "ID", required= True) def __init__(self, channel): self.channel = channel super()._...
[ "Got it now.\nYou are using the Modal in the wrong way. You only get interaction being passed. Also, the answer variable contains a modal instance. You could just pass int(user.value) to fetch_member() but that wouldn‘t be proper python syntax\ninstead use\nasync def on_submit(self, interaction: discord.Interaction...
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074486433_discord.py_python.txt
Q: Positional Only Parameter Syntax '/' in Google Colaboratory Firstly, I'm using Python 3.11.0 in Colab. When I use / to make parameters positional-only, SyntaxError is raised. However, when I use * for keyword-only parameters, any error hasn't been raised. Is there anyone who knows why these things happen? # Syntax...
Positional Only Parameter Syntax '/' in Google Colaboratory
Firstly, I'm using Python 3.11.0 in Colab. When I use / to make parameters positional-only, SyntaxError is raised. However, when I use * for keyword-only parameters, any error hasn't been raised. Is there anyone who knows why these things happen? # SyntaxError is raised def foo(x, y, /): return x + y File "<ipyt...
[ "Python introduces the new function syntax in Python3.8.2 Version, Where we can introduce the / forward slash to compare the positional only parameter which comes before the / slash and parameters that comes after * is keyword only arguments. Rest of the arguments that are come between / and * can be either positio...
[ 0, 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074486841_google_colaboratory_python.txt
Q: Assign Pyspark window function the same uuid for each window I have a Pyspark dataframe as such: data = [ {"master_record_id": "001-0073-683496", 'dob': datetime.date(2000, 1, 1), "patient_ssn": "123456789", "dodid": "1234567891", "dqi_id":"123", "site_id":700}, ...
Assign Pyspark window function the same uuid for each window
I have a Pyspark dataframe as such: data = [ {"master_record_id": "001-0073-683496", 'dob': datetime.date(2000, 1, 1), "patient_ssn": "123456789", "dodid": "1234567891", "dqi_id":"123", "site_id":700}, {"master_record_id": "001-0013-101321", 'dob': datetime....
[ "I don't see the reason to use Window function.\nHow about concatenating all three \"key\" columns and then running md5?\n.withColumn('uuid',md5(concat('dodid','patient_ssn', 'dob' )))\n" ]
[ 0 ]
[]
[]
[ "group", "pyspark", "python", "uuid", "window" ]
stackoverflow_0074483910_group_pyspark_python_uuid_window.txt
Q: what difference between these two join methods in threading in python? I want to use threading package to calculate the square of num and my code like, import threading def my_squr(num): #if this function take long time to run print(num*num) return num*num if __name__ == "__main__": l1 = [1,3,5,7,1...
what difference between these two join methods in threading in python?
I want to use threading package to calculate the square of num and my code like, import threading def my_squr(num): #if this function take long time to run print(num*num) return num*num if __name__ == "__main__": l1 = [1,3,5,7,11,13,15,17] for i, item in enumerate(l1): if i % 3 == 0: ...
[ "If you immediately join after started an thread, it means that wait until it executes. However, this isn't different than calling function normally inside main thread. Assume that functions works takes a bit of time and you need to process them at the same time.\nThen you can start them and uncomment joins.\nThis ...
[ 3, 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074486815_multithreading_python.txt
Q: Shuffle list values into sublists of 19 values each I have a large list of around 200 values The list looks like this list_ids = [10148, 10149, 10150, 10151, 10152, 10153, 10154, 10155, 10156, 10157, 10158, 10159, 10160, 10161, 10163, 10164, 10165, 10167, 10168, 10169, 10170, 10171, 10172, ...
Shuffle list values into sublists of 19 values each
I have a large list of around 200 values The list looks like this list_ids = [10148, 10149, 10150, 10151, 10152, 10153, 10154, 10155, 10156, 10157, 10158, 10159, 10160, 10161, 10163, 10164, 10165, 10167, 10168, 10169, 10170, 10171, 10172, 10173, 10174, 10175, 10177, 10178, 10179, 10180, 1...
[ "you can shuffle the list with random.shuffle:\nimport random\n\n# shuffles list in place\nrandom.shuffle(list_ids)\n\n#split into lists containg 19 elements\nsplits = list([list_ids[i:i+19] for i in range(0,len(list_ids),19)])\n\n", "import random\n\ns = 19\nrandom.shuffle(list_ids)\nsub_lists = [list_ids[s*i:s*...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074487051_python.txt
Q: NameError: name 'reduce' is not defined in Python I'm using Python 3.2. Tried this: xor = lambda x,y: (x+y)%2 l = reduce(xor, [1,2,3,4]) And got the following error: l = reduce(xor, [1,2,3,4]) NameError: name 'reduce' is not defined Tried printing reduce into interactive console - got this error: NameError: name...
NameError: name 'reduce' is not defined in Python
I'm using Python 3.2. Tried this: xor = lambda x,y: (x+y)%2 l = reduce(xor, [1,2,3,4]) And got the following error: l = reduce(xor, [1,2,3,4]) NameError: name 'reduce' is not defined Tried printing reduce into interactive console - got this error: NameError: name 'reduce' is not defined Is reduce really removed in ...
[ "It was moved to functools.\n", "You can add\nfrom functools import reduce\n\nbefore you use the reduce.\n", "Or if you use the six library\nfrom six.moves import reduce\n\n", "In this case I believe that the following is equivalent:\nl = sum([1,2,3,4]) % 2\n\nThe only problem with this is that it creates big...
[ 336, 261, 10, 2, 2, 1, 1 ]
[]
[]
[ "python", "python_3.2", "reduce" ]
stackoverflow_0008689184_python_python_3.2_reduce.txt
Q: RuntimeWarning: coroutine 'Command.__call__' was never awaited self._run_job(job) Trying to send an embed at a set time only on weekdays, I can use asyncio sleep to run everyday (including weekends) but I want to skip Saturday and Sunday. Ive now imported schedule and get the error RuntimeWarning: coroutine 'Comma...
RuntimeWarning: coroutine 'Command.__call__' was never awaited self._run_job(job)
Trying to send an embed at a set time only on weekdays, I can use asyncio sleep to run everyday (including weekends) but I want to skip Saturday and Sunday. Ive now imported schedule and get the error RuntimeWarning: coroutine 'Command.__call__' was never awaited self._run_job(job) import discord from discord.ext im...
[ "I dont know the schedule library but you should have a look into the tasks extension of discord.py, it can handle tasks at specific times for you.\nBut it‘s very simple, the library you‘re using cannot handle async functions, what a command in fact is...\nJust use said extension. It‘s build in in discord.py and wo...
[ 0 ]
[]
[]
[ "discord.py", "python", "python_3.x" ]
stackoverflow_0074484913_discord.py_python_python_3.x.txt
Q: How can I print square of the numbers in full tringle (not left and right tringle) pattern in Python? Hi I got a problem with a nested loop where the output must be like this: Required pattern 1 4 9 16 25 36 49 64 81 100 Need exactly the same result A: def square_pyramid(n): number = 1 ...
How can I print square of the numbers in full tringle (not left and right tringle) pattern in Python?
Hi I got a problem with a nested loop where the output must be like this: Required pattern 1 4 9 16 25 36 49 64 81 100 Need exactly the same result
[ "def square_pyramid(n):\n number = 1 \n k=n*2\n for i in range(0,n):\n for j in range(0,k):\n print(end= \" \") #this sets spaces before each number\n k = k-2 #reduce space in front of every number, decreases row wise \n for j in range(0,i+1):\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074486471_python.txt
Q: TypeError: '>=' not supported between instances of 'builtin_function_or_method' and 'datetime.time' I'm trying to compare two datetime.time values but I get this error: File "c:\Users\xxxxxx\Desktop\pyfiche\code.py", line 33, in timeofweek if (a.time >= d0.time() and a.time() <= d6.time()) or (a.time() >= d21.tim...
TypeError: '>=' not supported between instances of 'builtin_function_or_method' and 'datetime.time'
I'm trying to compare two datetime.time values but I get this error: File "c:\Users\xxxxxx\Desktop\pyfiche\code.py", line 33, in timeofweek if (a.time >= d0.time() and a.time() <= d6.time()) or (a.time() >= d21.time() and a.time() <= d23.time()): TypeError: '>=' not supported between instances of 'builtin_function_or_...
[ "you aren't calling the .time() method for a in the second to last row. (You're missing brackets)\n" ]
[ 0 ]
[]
[]
[ "datetime", "python", "time", "typeerror" ]
stackoverflow_0074487261_datetime_python_time_typeerror.txt
Q: Filter and group list of duplicate names How do I change the shape of this data so that the subject column becomes a top row header containing all unique values. Name and Surnames are listed in the 1st and 2nd column as unique values. Then in each cell I need a true or false of whether the person is in that subjec...
Filter and group list of duplicate names
How do I change the shape of this data so that the subject column becomes a top row header containing all unique values. Name and Surnames are listed in the 1st and 2nd column as unique values. Then in each cell I need a true or false of whether the person is in that subject class. I need to transpose or reshape the da...
[ "Use:\n(df.value_counts().unstack(0)\n .notnull()\n .reindex(columns=df['SUBJECT'].unique())\n .reset_index()\n .rename_axis(columns=None))\n\nOutput:\n NAME SURNAME Art DT Photography Games\n0 person1 Surname1 True True True False\n1 person2 surname2 True False True ...
[ 2, 1 ]
[]
[]
[ "excel", "pandas", "python" ]
stackoverflow_0074487176_excel_pandas_python.txt
Q: Fetching data from postgres database on jupyter notebook I'm having this script to fetch data from Postgres DB. POSTGRES_PORT = 'xxxx' POSTGRES_USERNAME = 'xxx' ## CHANGE THIS TO YOUR PANOPLY/POSTGRES USERNAME POSTGRES_PASSWORD = 'xxx' ## CHANGE THIS TO YOUR PANOPLY/POSTGRES PASSWORD POSTGRES_DBNAME = 'xxxx' ## CH...
Fetching data from postgres database on jupyter notebook
I'm having this script to fetch data from Postgres DB. POSTGRES_PORT = 'xxxx' POSTGRES_USERNAME = 'xxx' ## CHANGE THIS TO YOUR PANOPLY/POSTGRES USERNAME POSTGRES_PASSWORD = 'xxx' ## CHANGE THIS TO YOUR PANOPLY/POSTGRES PASSWORD POSTGRES_DBNAME = 'xxxx' ## CHANGE THIS TO YOUR DATABASE NAME POSTGRES_DBNAME = 'xxx' postg...
[ "By default the database driver for Postgresql uses a client side cursor, but you can use a server side cursor and stream the data to the client in batches. The following code will iterate through the query result in batches of 1,000 rows as set by the chunksize parameter. You can adjust the value of chunksize to m...
[ 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0074486768_postgresql_python.txt
Q: I want to add two y axis values in a bokeh line plot whats wrong with this line of code..please help import pandas as pd from bokeh.models import ColumnDataSource from bokeh.plotting import figure, show, output_file output_file ('newfile.html') data = pd.read_excel(r'C:\Users\ASyed\OneDrive - NKT\PythonProj...
I want to add two y axis values in a bokeh line plot
whats wrong with this line of code..please help import pandas as pd from bokeh.models import ColumnDataSource from bokeh.plotting import figure, show, output_file output_file ('newfile.html') data = pd.read_excel(r'C:\Users\ASyed\OneDrive - NKT\PythonProject\bokehPractise\newfile\19AJ100429-GC3-FR-003-A1-KP240.0...
[ "When you are using source as an input to your figure, you are only allowed to add strings as a pointer to the data.\nIn your case use\np.line(x= 'KP [km]', y ='DOL [m]', source = SOURCE )\n\ninstead of\np.line(x= 'KP [km]', y =[['DOL [m]'], ['DOC [m]']], source = SOURCE )\n\nIf you want to add multiple lines to on...
[ 0 ]
[]
[]
[ "bokeh", "pandas", "python" ]
stackoverflow_0074486794_bokeh_pandas_python.txt
Q: What does 'index 0 is out of bounds for axis 0 with size 0' mean? I am new to both python and numpy. I ran a code that I wrote and I am getting this message: 'index 0 is out of bounds for axis 0 with size 0' Without the context, I just want to figure out what this means.. It might be silly to ask this but what do ...
What does 'index 0 is out of bounds for axis 0 with size 0' mean?
I am new to both python and numpy. I ran a code that I wrote and I am getting this message: 'index 0 is out of bounds for axis 0 with size 0' Without the context, I just want to figure out what this means.. It might be silly to ask this but what do they mean by axis 0 and size 0? index 0 means the first value in the ar...
[ "In numpy, index and dimension numbering starts with 0. So axis 0 means the 1st dimension. Also in numpy a dimension can have length (size) 0. The simplest case is:\nIn [435]: x = np.zeros((0,), int)\nIn [436]: x\nOut[436]: array([], dtype=int32)\nIn [437]: x[0]\n...\nIndexError: index 0 is out of bounds for axi...
[ 46, 10, 9, 0 ]
[]
[]
[ "error_handling", "index_error", "indexing", "numpy", "python" ]
stackoverflow_0041492288_error_handling_index_error_indexing_numpy_python.txt
Q: Measure of how well two dataframe columns move with each other I have two columns in a df and rows of dates. I'd like to see how well each column matches the other and moves in sync with the other column - ie. do they move in tandem and does one influence the movements in the other. ...
Measure of how well two dataframe columns move with each other
I have two columns in a df and rows of dates. I'd like to see how well each column matches the other and moves in sync with the other column - ie. do they move in tandem and does one influence the movements in the other. Col1 Col2 Date 199...
[ "If you want to calculate Spearman correlation coefficient you can use Scipy package\ndf = pd.DataFrame({'Date': ['1991-01-01 00:00:00+00:00', '1991-04-01 00:00:00+00:00', '1991-07-01 00:00:00+00:00'], \n 'Col1': [6.945847 , 8.377481, 7.869787], \n 'Col2': [3.4222, 6.7783, 4.6666]}...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074487023_dataframe_pandas_python.txt
Q: How to create Dict from a Python list I have a list of random objects generated from a Model (querySet). I intend to create a separate list of objects using some but not all of the values of the objects from the original list. For instance, people = [ {'name': 'John', 'age': 20, 'location': 'Lagos'}, {'nam...
How to create Dict from a Python list
I have a list of random objects generated from a Model (querySet). I intend to create a separate list of objects using some but not all of the values of the objects from the original list. For instance, people = [ {'name': 'John', 'age': 20, 'location': 'Lagos'}, {'name': 'Kate', 'age': 40, 'location': 'Athens'...
[ "Your code corrected\nmy_own_list = []\n\nfor person in people:\n # every time you create a new dictionary\n my_obj = {}\n my_obj['your_name'] = person['name']\n my_obj['your_location'] = person['location']\n my_own_list.append(my_obj)\n\nOne-liner that uses list and dict comprehension :-)\n[{k:v for...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074487324_python.txt
Q: Python XML parsing removing empty CDATA nodes I'm using minidom from xml.dom to parse an xml document. I make some changes to it and then re-export it back to a new xml file. This file is generated by a program as an export and I use the changed document as an import. Upon importing, the program tells me that t...
Python XML parsing removing empty CDATA nodes
I'm using minidom from xml.dom to parse an xml document. I make some changes to it and then re-export it back to a new xml file. This file is generated by a program as an export and I use the changed document as an import. Upon importing, the program tells me that there are missing CDATA nodes and that it cannot imp...
[ "Unfortunately the XML specification is not 100% explicit about what counts as significant information in a document and what counts as noise. But there's a fairly wide consensus that CDATA tags serve no purpose other than to delimit text that hasn't been escaped: so % and &#37; and &#x25 and <!CDATA[%]]> are diffe...
[ 1 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0074482942_minidom_python_xml.txt
Q: How to check my CPU usage, heap usage, thread count, process count using python? I have a multi processing program. I need to check it's CPU usage and other variables like heap memory usage and number of processes used.. number of thread used. how to do this? I just want to know how my code is effecting my system....
How to check my CPU usage, heap usage, thread count, process count using python?
I have a multi processing program. I need to check it's CPU usage and other variables like heap memory usage and number of processes used.. number of thread used. how to do this? I just want to know how my code is effecting my system.
[ "Using the psutil library saves a lot of work here. \nYou can install it via the various methods described on this page\n\nGetting CPU usage, heap usage, thread count, and process count:\nimport psutil\nimport threading\n\n\nprint(\"CPU usage\", psutil.cpu_percent())\nprint(\"HEAP usage\", psutil.virtual_memory())\...
[ 1 ]
[]
[]
[ "cpu", "cpu_usage", "heap_memory", "python", "python_3.x" ]
stackoverflow_0074485730_cpu_cpu_usage_heap_memory_python_python_3.x.txt
Q: Pythonnet importing class: "ModuleNotFoundError: No module named..." I am importing a C# dll into python using pythonnet. import sys import clr assemblydir = r"C:\Users\Nathan_Dehnel\source\repos\TFSHygiene\bin\Debug\net5.0-windows" sys.path.append(assemblydir) clr.AddReference("TFSHygiene") from TFSHygiene import...
Pythonnet importing class: "ModuleNotFoundError: No module named..."
I am importing a C# dll into python using pythonnet. import sys import clr assemblydir = r"C:\Users\Nathan_Dehnel\source\repos\TFSHygiene\bin\Debug\net5.0-windows" sys.path.append(assemblydir) clr.AddReference("TFSHygiene") from TFSHygiene import QueryExecutor The DLL is present inside assemblydir. Inside TFSHygiene: ...
[ "I never got it to work with .NET 5.0. For me it worked with .NET Framework 4.8. See my answer for more details.\n", "For .net core, you need to add load(\"coreclr\") before import clr:\nload(\"coreclr\")\nimport clr\n\n" ]
[ 0, 0 ]
[]
[]
[ ".net_5", "c#", "python", "python.net", "python_import" ]
stackoverflow_0072353293_.net_5_c#_python_python.net_python_import.txt
Q: Mapping of a row of a dataframe in pandas I have following dataframe named df. id letter 1 x,y 2 z 3 a The mapping condition is {'x' : 1, 'z' : 2, 'ELSE' : 0} my desired output dataframe should look like, id letter map 1 x,y 1 2 z 2 2 a 0 Which means, even any of the letters in column letter is x, then t...
Mapping of a row of a dataframe in pandas
I have following dataframe named df. id letter 1 x,y 2 z 3 a The mapping condition is {'x' : 1, 'z' : 2, 'ELSE' : 0} my desired output dataframe should look like, id letter map 1 x,y 1 2 z 2 2 a 0 Which means, even any of the letters in column letter is x, then the column map should be 1...
[ "You can use\npure pandas\ncond = {'x' : 1, 'z' : 2, 'ELSE' : 0}\n\ndf['map'] = (df['letter']\n .str.split(',').explode()\n .map(lambda x: cond.get(x, cond['ELSE']))\n .groupby(level=0).max()\n)\n\nIn case of multiple values I would get the max.\nAlternative for the first valid match:\ndf['map'] = (df['letter']\n ....
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074487208_pandas_python.txt
Q: I got some errors when I pip install bfieldtools PS C:\Python\source> pip install bfieldtools Collecting bfieldtools Using cached bfieldtools-0.9.13.3-py3-none-any.whl (1.2 MB) Collecting trimesh Using cached trimesh-3.16.4-py3-none-any.whl (663 kB) Collecting mayavi Using cached mayavi-4.8.1.tar.gz (20.6 MB...
I got some errors when I pip install bfieldtools
PS C:\Python\source> pip install bfieldtools Collecting bfieldtools Using cached bfieldtools-0.9.13.3-py3-none-any.whl (1.2 MB) Collecting trimesh Using cached trimesh-3.16.4-py3-none-any.whl (663 kB) Collecting mayavi Using cached mayavi-4.8.1.tar.gz (20.6 MB) Installing build dependencies ... error ERROR: C...
[ "Install below vtx\nby entering following command\npip install vtk==9.2.2\n\nhttps://pypi.org/project/vtk/\n" ]
[ 0 ]
[]
[]
[ "installation", "pip", "python", "windows" ]
stackoverflow_0074485347_installation_pip_python_windows.txt
Q: How to call async function in sync code and break async/await chain (i.e. how to wrap an async function in a sync function) All my code is written without asyncio in mind; however, I use one function that is async (written by another developer; for my purposes it's a black box). Let's call this func_1. I need to c...
How to call async function in sync code and break async/await chain (i.e. how to wrap an async function in a sync function)
All my code is written without asyncio in mind; however, I use one function that is async (written by another developer; for my purposes it's a black box). Let's call this func_1. I need to call this function from within another function, call it func_2 (which itself may be called in an arbitrarily long chain of functi...
[ "Essentially, you want to start an event loop (the \"engine\" of async code), submit your function to the event loop, and then wait until this function is done being executed by the event loop.\nOne approach is asyncio.run(func_1()), but you can run into issues if something else in your code already started an even...
[ 1, 0 ]
[]
[]
[ "async_await", "python", "python_asyncio" ]
stackoverflow_0068744830_async_await_python_python_asyncio.txt
Q: Printing from Numba CUDA kernel (In google Colab) I'm trying to learn CUDA for python using Numba in a Google Colab jupyter notebook. To learn how to apply 3D thread allocation for nested loops I wrote the following kernel: from numba import cuda as cd # Kernel to loop over 3D grid @cd.jit def grid_coordinate_GPU...
Printing from Numba CUDA kernel (In google Colab)
I'm trying to learn CUDA for python using Numba in a Google Colab jupyter notebook. To learn how to apply 3D thread allocation for nested loops I wrote the following kernel: from numba import cuda as cd # Kernel to loop over 3D grid @cd.jit def grid_coordinate_GPU(): i = cd.blockDim.x * cd.blockIdx.x + cd.threadI...
[ "The simple solution was to skip the formatted string and just use print(i,j,k) within the kernel instead.\n" ]
[ 2 ]
[]
[]
[ "cuda", "google_colaboratory", "numba", "printing", "python" ]
stackoverflow_0074475992_cuda_google_colaboratory_numba_printing_python.txt
Q: Pytorch Batchwise block diagonal I have two tensors containing batches of matrices of the same batch size (first dimension) but different matrix structure (all other dimensions). For example A of shape (n,d,d) and B (n,e,e). Now I would like to build block diagonals of A and B for all n. So that the output shape (...
Pytorch Batchwise block diagonal
I have two tensors containing batches of matrices of the same batch size (first dimension) but different matrix structure (all other dimensions). For example A of shape (n,d,d) and B (n,e,e). Now I would like to build block diagonals of A and B for all n. So that the output shape (n,(d+e),(d+e)). Is there an implementa...
[ "Unfortunately there's no vectorized implementation, you'd have to loop through the batch:\nA = torch.rand((2, 2, 2))\nB = torch.rand((2, 3, 3))\nC = torch.zeros((2, 5, 5))\nfor i in range(2):\n C[i] = torch.block_diag(A[i], B[i])\n\n" ]
[ 0 ]
[]
[]
[ "diagonal", "python", "pytorch", "torch" ]
stackoverflow_0074487220_diagonal_python_pytorch_torch.txt
Q: How to make a filename dynamic when extracting a table from BigQuery to a GCS Bucket? I am new to Stack Overflow, and this is my first post. I am also new to GCP, and I am writing a Python script (Airflow DAG) to extract a table from BigQuery to a GCS Bucket using the following: project = "bigquery-public-data" da...
How to make a filename dynamic when extracting a table from BigQuery to a GCS Bucket?
I am new to Stack Overflow, and this is my first post. I am also new to GCP, and I am writing a Python script (Airflow DAG) to extract a table from BigQuery to a GCS Bucket using the following: project = "bigquery-public-data" dataset_id = "samples" table_id = "my_dataset" destination_uri = "gs://{}/{}".format(bucket_...
[ "You can use the following operator with Airflow : BigQueryToGCSOperator :\nfrom airflow.providers.google.cloud.transfers.bigquery_to_gcs import BigQueryToGCSOperator\n\ndate_str = ...\n\nBigQueryToGCSOperator(\n task_id=\"task_id\",\n source_project_dataset_table=\"{my_project}:{my_dataset}.{my_table...
[ 0 ]
[]
[]
[ "airflow", "google_bigquery", "google_cloud_platform", "google_cloud_storage", "python" ]
stackoverflow_0074487080_airflow_google_bigquery_google_cloud_platform_google_cloud_storage_python.txt
Q: python decoding bytes from a GPS Module GY-NEO6MV2 connected to raspberry pi I have a GPS Module GY-NEO6MV2 connected to a raspberry pi 3. When I use the gpsmon command I get the data perfectly the output of gpsmon but I'm trying to use python to read the data from the serial. This is my code import serial ser = s...
python decoding bytes from a GPS Module GY-NEO6MV2 connected to raspberry pi
I have a GPS Module GY-NEO6MV2 connected to a raspberry pi 3. When I use the gpsmon command I get the data perfectly the output of gpsmon but I'm trying to use python to read the data from the serial. This is my code import serial ser = serial.Serial('/dev/ttyACM0') ser.flushInput() while True: try: ser_by...
[ "The data is packed info byte-array to unpack data use the Python struct library.\n>>> import struct\n>>> data =b'\\x10\\x01\\x00\\xa5\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x1e\\r\\x04\\x1c\\n'\n>>> struct.unpack(\"4f\", data)\n(-1.1102590235254148e-16, 0.0, 7.199780051661553e-21, 7.511888650386347e-33)\n\n" ]
[ 0 ]
[]
[]
[ "decode", "gps", "python", "raspberry_pi" ]
stackoverflow_0073717885_decode_gps_python_raspberry_pi.txt
Q: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users I'm developing an application with sqlalchemy and I'm constantly getting a no such table error when I try to add data to a table. However, such a table exists. Here is my code in models.py: DATABASE_NAME = 'test_task_db.sqlite' engine...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
I'm developing an application with sqlalchemy and I'm constantly getting a no such table error when I try to add data to a table. However, such a table exists. Here is my code in models.py: DATABASE_NAME = 'test_task_db.sqlite' engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() metadata =...
[ "I think the issue is with your connection String for sqlite. On sqlite3, for :memory: database, you may pass an empty connection string :\nsqlite://\n\nYou don't need to specify :memory: at the end.\nIf you want to specify a table, then you do something like :\nsqlite://{path}/dbname.db:\n\nThe number of slashes d...
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074487345_python_sqlalchemy.txt
Q: streamlit latex Can anyone help me with the layout of a streamlit website? I create a website with streamit, however, I use st.latex and the layout of my website looks like this. enter image description here I want the lines to be aligned to the left. Sample Code import streamlit as st st.set_page_config(layout="...
streamlit latex
Can anyone help me with the layout of a streamlit website? I create a website with streamit, however, I use st.latex and the layout of my website looks like this. enter image description here I want the lines to be aligned to the left. Sample Code import streamlit as st st.set_page_config(layout="wide") st.latex(r'''...
[ "Here is a hack on css on class katex-html. Add the text-align: left;\nAdd it after st.set_page_config(layout=\"wide\") from sample code above.\nst.markdown('''\n<style>\n.katex-html {\n text-align: left;\n}\n</style>''',\nunsafe_allow_html=True\n)\n\nOutput\n\n" ]
[ 1 ]
[]
[]
[ "latex", "python", "streamlit", "web" ]
stackoverflow_0074456419_latex_python_streamlit_web.txt
Q: does not appear to have any patterns in it. or circular import recently i started to studying django but there is a problem into my code and i cant find what exactly could be a decent fix to this problem so i thought i would be good to ask. ... from django.urls import path from . import views ulrpatterns = [ ...
does not appear to have any patterns in it. or circular import
recently i started to studying django but there is a problem into my code and i cant find what exactly could be a decent fix to this problem so i thought i would be good to ask. ... from django.urls import path from . import views ulrpatterns = [ path('' , views.index) ] ... well this is my code for urls.py into ...
[ "ulrpatterns = [\n path('' , views.index)\n\nDjango wants to see the urlpatterns in the urls.py file. You cannot rename it. \n", "I had the same error when I was doing this crash course Django project. I found at least 50% errors were made by TYPO ;)\nfrom django.urls import path\nfrom . import views\n\n**ulrp...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0061146625_django_python.txt
Q: How can I use tqdm to add a progress bar in this function? I have received from one colleague a Python script but (due to the large amount of data and the time processing) I would like to include a progress bar to check at each time its progress. from Bio import SeqIO from tqdm import tqdm import csv import pand...
How can I use tqdm to add a progress bar in this function?
I have received from one colleague a Python script but (due to the large amount of data and the time processing) I would like to include a progress bar to check at each time its progress. from Bio import SeqIO from tqdm import tqdm import csv import pandas as pd import re import time # Find code in "metadata_silv...
[ "You already imported tqdm. Wrap your loop in a tqdm call and it should work:\nfor index in tqdm(df.index):\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074487670_python.txt
Q: pandas average across dynamic number of columns I have a dataframe like as shown below customer_id revenue_m7 revenue_m8 revenue_m9 revenue_m10 1 1234 1231 1256 1239 2 5678 3425 3255 2345 I would like to do the below ...
pandas average across dynamic number of columns
I have a dataframe like as shown below customer_id revenue_m7 revenue_m8 revenue_m9 revenue_m10 1 1234 1231 1256 1239 2 5678 3425 3255 2345 I would like to do the below a) get average of revenue for each customer based on ...
[ "Use filter and slicing:\n# keep only the \"revenue_\" columns\ndf2 = df.filter(like='revenue_')\n# or\n# df2 = df.filter(regex=r'revenue_m\\d+')\n\n# get last 2/4 columns and aggregate as mean\ndf['revenue_mean_2m'] = df2.iloc[:, -2:].mean(axis=1)\ndf['revenue_mean_4m'] = df2.iloc[:, -4:].mean(axis=1)\n\nOutput:\n...
[ 3, 1 ]
[]
[]
[ "dataframe", "mean", "pandas", "python", "series" ]
stackoverflow_0074487627_dataframe_mean_pandas_python_series.txt
Q: Sub directory not available as package on parent package despite having __init__.py file in every folder If importing a package, it does not load its child packages, despite all folders having __init__.py. The example: mkdir -p parent/child touch parent/__init__.py touch parent/child/__init__.py Looks like: $ tre...
Sub directory not available as package on parent package despite having __init__.py file in every folder
If importing a package, it does not load its child packages, despite all folders having __init__.py. The example: mkdir -p parent/child touch parent/__init__.py touch parent/child/__init__.py Looks like: $ tree parent parent ├── child │   ├── file.py │   └── __init__.py └── __init__.py $ python3 ...
[]
[]
[ "Create init.py file like this it worked for me.\n$ tree\n├── __init__.py\n├── main.py\n└── parent\n ├── __init__.py\n └── child\n ├── __init__.py\n └── file.py\n\n" ]
[ -1 ]
[ "import", "python", "python_2.7", "python_3.x", "python_import" ]
stackoverflow_0074487179_import_python_python_2.7_python_3.x_python_import.txt
Q: How can I read a c3d file on Python? I'm trying to read a c3d file on Python with the btk library but I didn't succeed. I downloaded the library here https://code.google.com/archive/p/b-tk/downloads for Windows 10 (64 bit) and then wrote this code: A: try https://pypi.org/project/c3d/ or https://github.com/pyome...
How can I read a c3d file on Python?
I'm trying to read a c3d file on Python with the btk library but I didn't succeed. I downloaded the library here https://code.google.com/archive/p/b-tk/downloads for Windows 10 (64 bit) and then wrote this code:
[ "try https://pypi.org/project/c3d/\nor https://github.com/pyomeca/pyomeca\nits easier with them than with btk toolkit. You will need to see docs to get it done. I am using those to read only, then switch to numpy or pandas.\n" ]
[ 0 ]
[]
[]
[ "installation", "jsc3d", "pandas", "python", "windows" ]
stackoverflow_0072137839_installation_jsc3d_pandas_python_windows.txt
Q: How to zip 2D arrays a=np.array([[1,2,3],[4,5,6],[7,8,9]]) b=np.array([[1,2,3],[4,5,6],[7,8,9]]) I've 2 identical 2D arrays, I'm trying to zip them element-wise. It should look like: [[(1,1) (2,2), (3,3)] [(4,4) (5,5) (6,6)] [(7,7) (8,8) (9,9)]] I've tried the method below but it didn't work out. First flatten ...
How to zip 2D arrays
a=np.array([[1,2,3],[4,5,6],[7,8,9]]) b=np.array([[1,2,3],[4,5,6],[7,8,9]]) I've 2 identical 2D arrays, I'm trying to zip them element-wise. It should look like: [[(1,1) (2,2), (3,3)] [(4,4) (5,5) (6,6)] [(7,7) (8,8) (9,9)]] I've tried the method below but it didn't work out. First flatten the arrays, zip them, con...
[ "Don't zip, use numpy native functions! You want a dstack:\nout = np.dstack([a, b])\n\noutput:\narray([[[1, 1],\n [2, 2],\n [3, 3]],\n\n [[4, 4],\n [5, 5],\n [6, 6]],\n\n [[7, 7],\n [8, 8],\n [9, 9]]])\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "numpy", "numpy_ndarray", "python", "python_zip" ]
stackoverflow_0074487809_arrays_numpy_numpy_ndarray_python_python_zip.txt
Q: How to catch scrapy response from spider to pipeline? I need all the scrapy response with settings, pipelines, urls and everything in pipeline where i create model objects? Is there any way of catching it? pipeline.py class ScraperPipeline(object): def process_item(self, item, spider): logger = get_ta...
How to catch scrapy response from spider to pipeline?
I need all the scrapy response with settings, pipelines, urls and everything in pipeline where i create model objects? Is there any way of catching it? pipeline.py class ScraperPipeline(object): def process_item(self, item, spider): logger = get_task_logger("logs") logger.info("Pipeline activated....
[ "You can pass the full response along with the item in your callback methods if you need access to the response or request in your pipeline.\nFor example:\nclass SpiderClass(scrapy.Spider):\n ...\n ...\n\n def parse(self, response):\n for i in response.xpath(...):\n field1 = ...\n ...
[ 0 ]
[]
[]
[ "django", "pipeline", "python", "scrapy" ]
stackoverflow_0074483604_django_pipeline_python_scrapy.txt
Q: Time Limit exceeded on LeetCode I'm trying to solve the Leetcode's Two Sum problem (https://leetcode.com/problems/two-sum/) and my code runs well on small lists, but the website outputs me 'time limit exceeded' when trying this list and target (https://leetcode.com/submissions/detail/845707290/testcase/) (19999), ...
Time Limit exceeded on LeetCode
I'm trying to solve the Leetcode's Two Sum problem (https://leetcode.com/problems/two-sum/) and my code runs well on small lists, but the website outputs me 'time limit exceeded' when trying this list and target (https://leetcode.com/submissions/detail/845707290/testcase/) (19999), although my coding environment output...
[ "Use a dictionary to create a performant lookup.\nnums = [1,5,2,7,21]\ntarget = 23\n\nlookup = { k:v for (v,k) in enumerate(nums) }\n\nfor a in nums:\n b = target - a\n if lookup.get(b, None):\n print([lookup[a], lookup[b]])\n break\n\nOutput:\n[2, 4]\n\nMoving lookup.get() to the assignment of ...
[ 3, 0, 0 ]
[ "I thought about the O(n²) problematic and additonally I wanted to have it elegant :D.\nPythons tim-sort (sorted(), [].sort()) is O(n*log(n)) which is indeed better :).\nSo what I did:\n\nSort the input array (O(n * log(n))\niterate with two indizes through the array: one on the right and one on the left O(2*n) = O...
[ -1 ]
[ "python" ]
stackoverflow_0074487302_python.txt
Q: Changing Time Series Dataframe to Array I need the following 'ftse_change' dataframe to be in the format of the 'ts'. I have loaded the ftse_change data as CSV into python, but the 'ts' data is already built into a package that I am loading to run a few models from. (Screenshots below). I'm not sure what the diffe...
Changing Time Series Dataframe to Array
I need the following 'ftse_change' dataframe to be in the format of the 'ts'. I have loaded the ftse_change data as CSV into python, but the 'ts' data is already built into a package that I am loading to run a few models from. (Screenshots below). I'm not sure what the difference between the two is to begin with (namel...
[ "Assuming what you want is to extract only the 'Change column' to the format shown in the second screenshot. This is how I would do it.\narr = [[[i]] for i in ftse_change.Change.to_list()]\n\neg:\ncol1 = [1,2,3,4,5]\ncol2 = [1,2,3,4,5]\n\nftse_change = pd.DataFrame({\"Date\":col1, \"Change\": col2})\nftse_change.he...
[ 0 ]
[]
[]
[ "arrays", "python", "time_series" ]
stackoverflow_0074487723_arrays_python_time_series.txt
Q: Timestamp to iso I have a dataframe with timestamp of different formats one with 05-28-2022 14:05:30 and one with 06-04-2022 03:04:13.002 both I want to convert into iso format how can I do that? input output 05-28-2022 14:05:30 -> 2022-05-28T14:05:30.000+0000 06-04-2022 03:04:13.002 -...
Timestamp to iso
I have a dataframe with timestamp of different formats one with 05-28-2022 14:05:30 and one with 06-04-2022 03:04:13.002 both I want to convert into iso format how can I do that? input output 05-28-2022 14:05:30 -> 2022-05-28T14:05:30.000+0000 06-04-2022 03:04:13.002 -> 2022-06-04T03:04:13....
[ "You can use strptime() + strftime(). Here is an example:\nfrom datetime import datetime\nimport pytz\n\n# parse str to instance\nfirst = datetime.strptime('05-28-2022 14:05:30', '%m-%d-%Y %H:%M:%S')\nfirst = first.replace(tzinfo=pytz.UTC)\nprint(first.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))\nprint(f'{first.isoformat()...
[ 1 ]
[]
[]
[ "formatting", "iso", "pandas", "python" ]
stackoverflow_0074485470_formatting_iso_pandas_python.txt
Q: Activating existing conda enviornments in snakemake How do I get snakemake to activate a conda environment that already exists in my environment list? I know you can use the --use-conda with a .yaml environment file but that seems to generate a new environment which is just annoying when the environment already ex...
Activating existing conda enviornments in snakemake
How do I get snakemake to activate a conda environment that already exists in my environment list? I know you can use the --use-conda with a .yaml environment file but that seems to generate a new environment which is just annoying when the environment already exists. Any help with this would be much appreciated. I hav...
[ "This isn't possible and I'd argue it's mostly a good thing. Snakemake having sole ownership of the env helps improve reproducibility by requiring one to update the YAML instead of directly manipulating the env with conda (install|update|remove). Note that such a practice of updating a YAML and recreating is a Cond...
[ 2, 2, 2, 0 ]
[]
[]
[ "conda", "python", "snakemake" ]
stackoverflow_0059107413_conda_python_snakemake.txt
Q: scala map get keys from Map as Sequence sorting by both keys and values In Python I can do: in_dd = {"aaa": 1, "bbb": 7, "zzz": 3, "hhh": 9, "ggg": 10, "ccc": 3} out_ll = ['ggg', 'hhh', 'bbb', 'aaa', 'ccc', 'zzz'] so, I want to get keys sorted by value in descending order while having keys in ascending order taki...
scala map get keys from Map as Sequence sorting by both keys and values
In Python I can do: in_dd = {"aaa": 1, "bbb": 7, "zzz": 3, "hhh": 9, "ggg": 10, "ccc": 3} out_ll = ['ggg', 'hhh', 'bbb', 'aaa', 'ccc', 'zzz'] so, I want to get keys sorted by value in descending order while having keys in ascending order taking into consideration sorted values How can I do it in Scala? In Scala I know...
[ "In scala you could use:\nm.toSeq.sortBy(a => (a._2, a._1) )(Ordering.Tuple2(Ordering.Int.reverse, Ordering.String.reverse))\n\nfor List((ggg,10), (hhh,9), (bbb,7), (zzz,3), (ccc,3), (aaa,3))\nand\nm.toSeq.sortBy(a => (-a._2, a._1) )\n\nfor List((ggg,10), (hhh,9), (bbb,7), (aaa,3), (ccc,3), (zzz,3))\n" ]
[ 2 ]
[]
[]
[ "dictionary", "python", "scala", "sorting" ]
stackoverflow_0074487703_dictionary_python_scala_sorting.txt
Q: How do I use python pandas to read an already opened excel sheet Assuming I have an excel sheet already open, make some changes in the file and use pd.read_excel to create a dataframe based on that sheet, I understand that the dataframe will only reflect the data in the last saved version of the excel file. I woul...
How do I use python pandas to read an already opened excel sheet
Assuming I have an excel sheet already open, make some changes in the file and use pd.read_excel to create a dataframe based on that sheet, I understand that the dataframe will only reflect the data in the last saved version of the excel file. I would have to save the sheet first in order for pandas dataframe to take i...
[ "Have you tried using mitosheet package? It doesn't answer your question directly, but it allows you working on pandas dataframes as you would do in excel sheets. In this way, you may edit the data on the fly as in excel and still get a pandas dataframe as a result (meanwhile generating the code to perform the same...
[ 1, 0, 0, 0 ]
[]
[]
[ "excel", "pandas", "python" ]
stackoverflow_0052862768_excel_pandas_python.txt
Q: make a loop for videocapture with 5 minutees delay hi i use a code that take capture image from my webcam and do some image processing on image. i need to repeat the total code consecutive n times. paraphrase take image and do image processing consecutively every five minutes. thanks. import time import cv2 vide...
make a loop for videocapture with 5 minutees delay
hi i use a code that take capture image from my webcam and do some image processing on image. i need to repeat the total code consecutive n times. paraphrase take image and do image processing consecutively every five minutes. thanks. import time import cv2 videoCaptureObject = cv2.VideoCapture(0) result = True whil...
[ "There are so many issues with your code I don't know where to start. Let's go for simple. I think you want a structure like this:\nimport numpy as np\n\ndef captureImage():\n print('Capturing image')\n # Code to capture image goes here, simulate a random one for now\n im = np.random.randint(0, 256, size=(...
[ 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0074434959_image_python.txt
Q: dataframe get 2 rows with different values I want to query two rows with different values in the same column. name age Martin 28 Josh 37 Peter 24 Claire 57 df = pd.read_csv('names.csv') df.query('name.str.contains("Martin") & name.str.contains("Claire")') Now i expect to see the two rows where Claire an Mar...
dataframe get 2 rows with different values
I want to query two rows with different values in the same column. name age Martin 28 Josh 37 Peter 24 Claire 57 df = pd.read_csv('names.csv') df.query('name.str.contains("Martin") & name.str.contains("Claire")') Now i expect to see the two rows where Claire an Martin are in. But if i delete Claire t...
[ "try this:\n\nimport pandas as pd\ndf = pd.DataFrame({'name':['Martin', 'Josh', 'Peter', 'Claire'],\n 'age':[28, 37, 24, 57]})\n\nnew_df = df[df.name.isin(['Claire', 'Martin'])]\n\n\nThis gives\n name age\n0 Martin 28\n3 Claire 57\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074487904_dataframe_python.txt
Q: CondaValueError: The target prefix is the base prefix. Aborting. in anaconda prompt I've got following error when I try to make a virtual environment in anaconda prompt which is executed with administrator (base) C:\WINDOWS\system32>d: (base) D:\>cd anaconda (base) D:\anaconda>cd Scripts (base) D:\anaconda\Scri...
CondaValueError: The target prefix is the base prefix. Aborting. in anaconda prompt
I've got following error when I try to make a virtual environment in anaconda prompt which is executed with administrator (base) C:\WINDOWS\system32>d: (base) D:\>cd anaconda (base) D:\anaconda>cd Scripts (base) D:\anaconda\Scripts>conda create -m ppt python=3.8 CondaValueError: The target prefix is the base prefix...
[ "Create an environment in anaconda command prompt with the below command:\nconda create -n myenv3.7 python=3.7\nconda create myenv3.7\n\n\nSimilarly, you could try creating & activating an environment with python 3.8 with the below commands:\nconda create -n myenv3.8 python=3.8\nconda create myenv3.8\n\n", "conda...
[ 2, 0 ]
[]
[]
[ "admin", "anaconda", "prompt", "python" ]
stackoverflow_0067849025_admin_anaconda_prompt_python.txt
Q: Twitter bot with selenium I want to make Twitter bot with selenium but the Chrome window closes as soon as it opens. How can I fix this? My Code: from userinfo import username, password from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.common.keys impor...
Twitter bot with selenium
I want to make Twitter bot with selenium but the Chrome window closes as soon as it opens. How can I fix this? My Code: from userinfo import username, password from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class twitter: def ...
[ "Add the below chrome options in __init__() function:\nself.browserProfile.add_experimental_option(\"detach\", True)\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074483109_python_selenium_selenium_webdriver.txt
Q: Euclidean Distance for Arrays of 3D points in Python I have two .csv files of 3D points (numeric coordinate data) and associated attribute data (strings + numeric). I need to calculate the Euclidean distance between each point and every other point, and maintain the attribute data for each point associated with th...
Euclidean Distance for Arrays of 3D points in Python
I have two .csv files of 3D points (numeric coordinate data) and associated attribute data (strings + numeric). I need to calculate the Euclidean distance between each point and every other point, and maintain the attribute data for each point associated with the difference. I have a method that works for this, but it ...
[ "Two methods. Setup:\nimport numpy as np\nimport pandas as pd\nimport string\nfrom scipy.spatial.distance import cdist\n\nupper = list(string.ascii_uppercase)\nlower = list(string.ascii_lowercase)\n\ndf1 = pd.DataFrame(np.random.rand(26,3), \n columns = lower[-3:], \n index = lo...
[ 1 ]
[]
[]
[ "euclidean_distance", "numpy", "python", "spatial_data" ]
stackoverflow_0074486648_euclidean_distance_numpy_python_spatial_data.txt
Q: Sympy not properly displaying conjugate of square root of real I keep getting expressions like this image, despite declaring these symbols as reals. The code to reproduce is: import sympy as sp delta = sp.Symbol('delta', real=True) f = sp.sqrt(1/delta) prod = sp.conjugate(f)*f prod.subs(delta,delta) I expected to...
Sympy not properly displaying conjugate of square root of real
I keep getting expressions like this image, despite declaring these symbols as reals. The code to reproduce is: import sympy as sp delta = sp.Symbol('delta', real=True) f = sp.sqrt(1/delta) prod = sp.conjugate(f)*f prod.subs(delta,delta) I expected to get 1/delta Also trying simplify() does not work either.
[ "According to the official SymPy Docs for conjugate, it looks like the function is supposed to return the complex conjugate for its input. In other words, it takes the complex part of the number and flips the sign.\nIn your example, you are taking the square root of a variable. If delta = -1, then the resulting con...
[ 2 ]
[]
[]
[ "ipython", "jupyter_notebook", "python", "simplify", "sympy" ]
stackoverflow_0074487874_ipython_jupyter_notebook_python_simplify_sympy.txt
Q: smtplib.SMTPSenderRefused Authentication Error in Flask App I have created a flask app and whenever I use the forgot password module I get this error I have used this code in my init.py file login_manager = LoginManager(app) login_manager.login_view = 'login' login_manager.login_message_category ='info' app.config...
smtplib.SMTPSenderRefused Authentication Error in Flask App
I have created a flask app and whenever I use the forgot password module I get this error I have used this code in my init.py file login_manager = LoginManager(app) login_manager.login_view = 'login' login_manager.login_message_category ='info' app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT']= 587 app...
[ "Change:\napp.config['MAIL_SERVER']='smtp.gmail.com'\napp.config['MAIL_PORT']= 587\napp.config['MAIL_USE_TLS']=True\napp.config['MAIL_USERNAME']=os.environ.get('EMAIL_USER')\napp.config['MAIL_PASSWORD']=os.environ.get('EMAIL_PASS')\n\nTo:\napp.config.update(\nMAIL_SERVER='smtp.gmail.com',\nMAIL_PORT='587',\nMAIL_US...
[ 0, 0 ]
[]
[]
[ "flask", "python", "smtplib" ]
stackoverflow_0056911441_flask_python_smtplib.txt
Q: How to insert newline while logging lists and arrays? I am trying to output lists to a log file, using Python's logging module. The code I used is: import logging import os logging.basicConfig(filename = 'Log.log', level = logging.DEBUG, filemode = 'w', format = '%(asctime)s \t %(levelname)s \t %(message)s', datef...
How to insert newline while logging lists and arrays?
I am trying to output lists to a log file, using Python's logging module. The code I used is: import logging import os logging.basicConfig(filename = 'Log.log', level = logging.DEBUG, filemode = 'w', format = '%(asctime)s \t %(levelname)s \t %(message)s', datefmt="[%Y-%m-%d %H:%M:%S]") file_list = [] for root, director...
[ "Use standard Pretty Print module:\nfrom pprint import pformat\nlogging.info('Files in list:\\n%s', pformat(file_list))\n\nOutput example:\n[2015-03-14 14:23:47] INFO Files in list:\n['./tmpvYWsRB.png',\n './Log.log',\n './tmpCG2Dn2',\n './ tmp7I36mh.png',\n\nTo print filenames only, use standard os.path.base...
[ 2, 1, 0 ]
[]
[]
[ "list", "logging", "python" ]
stackoverflow_0029047319_list_logging_python.txt
Q: Specific web page doesn't load (empty page) HTML and CSS with Selenium? I started working with Selenium, it works for any website I tried except one (myvisit.com) that doesn't load the page. It opens Chrome but the page is empty. I tried to set number of delays but it still doesn't load. When I go to the website o...
Specific web page doesn't load (empty page) HTML and CSS with Selenium?
I started working with Selenium, it works for any website I tried except one (myvisit.com) that doesn't load the page. It opens Chrome but the page is empty. I tried to set number of delays but it still doesn't load. When I go to the website on a regular Chrome (without Selenium) it loads everything. Here is my simple ...
[ "from selenium.webdriver.chrome.options import Options\noptions = Options()\noptions.add_argument('--disable-blink-features=AutomationControlled')\ndriver = webdriver.Chrome(os.getcwd()+\"\\\\webdriver\\\\chromedriver.exe\",options=options)\n\nSimply add the arguement to remove it from determining it's an automatio...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074487869_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How to combine diagonal data? I am new to python, apologies if I do not explain well or provide partial solutions yet... I have a dataframe as below: a key, some dates (distributed in rows), and many other columns (same key, same value) Key Date 1 Date 2 Date 3 Column X Column Y Key 1 2022-01-01 X11111111 Y1111...
How to combine diagonal data?
I am new to python, apologies if I do not explain well or provide partial solutions yet... I have a dataframe as below: a key, some dates (distributed in rows), and many other columns (same key, same value) Key Date 1 Date 2 Date 3 Column X Column Y Key 1 2022-01-01 X11111111 Y11111111 Key 1 2022-01-02 X1...
[ "Assuming the empty cells are NaN, use groupby.first:\nout = df.groupby('Key', as_index=False).first()\n\nNB. If the empty cells are empty strings, use df.replace('', float('nan')).groupby('Key', as_index=False).first().\nOutput:\n Key Date 1 Date 2 Date 3 Column X Column Y\n0 Key 1 2022-01...
[ 2, 2 ]
[]
[]
[ "aggregate", "dataframe", "pandas", "pivot", "python" ]
stackoverflow_0074487910_aggregate_dataframe_pandas_pivot_python.txt
Q: How can I get the line.column index for the right-click event on Tkinter Text widget? Say - I am working on a tk.Text widget with the following content: this is a test text. which has two lines. Say I right-click on the beginning of the first "h" in the first word "which" in the second line - and I want to access...
How can I get the line.column index for the right-click event on Tkinter Text widget?
Say - I am working on a tk.Text widget with the following content: this is a test text. which has two lines. Say I right-click on the beginning of the first "h" in the first word "which" in the second line - and I want to access its location in the tk.Text's line.column format just as follows: rc_index = tk.Text.get_r...
[ "Assume text is the instance of the Text widget, then you can bind \"<Button-3>\" (right click event of mouse in Windows) to a callback and get the index inside the callback:\ndef on_right_click(event):\n idx = event.widget.index(\"current\")\n print(idx)\n\ntext.bind(\"<Button-3>\", on_right_click)\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074487818_python_tkinter.txt
Q: Extracting values from a df Problem statement: There are multiple instances of charging and discharging for each vehicle, get the minimum charge, maximum charge, min discharge and max discharge for each vehicle for a particular day. df1 Date Time vehicle_no soc SOC Diff 0 2022-10-01 02:27:56...
Extracting values from a df
Problem statement: There are multiple instances of charging and discharging for each vehicle, get the minimum charge, maximum charge, min discharge and max discharge for each vehicle for a particular day. df1 Date Time vehicle_no soc SOC Diff 0 2022-10-01 02:27:56 DL21GD0100 80.0 0 1 202...
[ "Read the whole answer for 3 different options\nmapping strictly charge/discharge\nYou can use groupby.diff to get the difference per group, then numpy.sign and map:\ndf['status'] = np.sign(df.groupby('vehicle_no')['soc'].diff()\n ).map({1: 'Charging', -1: 'Discharging'})\n\nOr with numpy.sele...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074431697_pandas_python.txt