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: Updating a "Table" in a different Class in Tkinter I have a python GUI that is Build up like that: First of all i have a File with the Class "App", which creats the basic form of the GUI: import tkinter as tk from tkinter import ttk from Frame1 import Do_SomethingPart1 from Frame2 import Do_SomethingPart2 from Hea...
Updating a "Table" in a different Class in Tkinter
I have a python GUI that is Build up like that: First of all i have a File with the Class "App", which creats the basic form of the GUI: import tkinter as tk from tkinter import ttk from Frame1 import Do_SomethingPart1 from Frame2 import Do_SomethingPart2 from Header import Measurments class App(tk.Tk): def __init...
[ "Have you tried to pass the Application when you create the Do_SomethingPart2 object?\nSomething like this\nDo_SomethingPart2(Data, self.application)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074137843_python_python_3.x_tkinter.txt
Q: Split Dataframe when hyphen appears I have a Dataframe with approx. 70000 rows and 6 columns. The inputs are numbers expect of some hyphens. I want to split the dataframe (by rows) every time a hyphen appears. The row with the hyphen can be deleted. Example of Dataframe: Timestamp ; power(kW) ; .... 2020-01-01 17:...
Split Dataframe when hyphen appears
I have a Dataframe with approx. 70000 rows and 6 columns. The inputs are numbers expect of some hyphens. I want to split the dataframe (by rows) every time a hyphen appears. The row with the hyphen can be deleted. Example of Dataframe: Timestamp ; power(kW) ; .... 2020-01-01 17:50:10 ; 4.32 ; ... 2020-01-01 17:55:15 ...
[ "You can use:\n# identify rows with \"-\"\nm = df['power(kW)'].eq('-')\n# or based on non-numbers:\n# m = pd.to_numeric(df['power(kW)'], errors='coerce').isna()\n\n# split per group while removing the invalid rows\nsubdfs = [d for _,d in df[~m].groupby(m.cumsum())]\n\noutput list:\n[ Timestamp power(kW)...
[ 0 ]
[]
[]
[ "dataframe", "python", "split" ]
stackoverflow_0074140292_dataframe_python_split.txt
Q: Accuracy impact when not using stride and padding for maxpooling layers in a CNN I'm testing parameters out for my CNN that aims at classifying images according to three classes. Images are 224x224, the CNN architecture is very basic and consists of 3 convolutional layers (32, 32 and 64 filters) with ReLU activati...
Accuracy impact when not using stride and padding for maxpooling layers in a CNN
I'm testing parameters out for my CNN that aims at classifying images according to three classes. Images are 224x224, the CNN architecture is very basic and consists of 3 convolutional layers (32, 32 and 64 filters) with ReLU activation after which there is a maxpooling layer. After the 3 convolution layers, there's a ...
[ "There are two issues arises with convolution:\nEvery time after convolution operation, original image size getting shrinks:\n#!/usr/bin/python\n# import necessary modules\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\n\nmodel = Sequential()\nmodel.add(Conv2D(1, (3,3), strides=(2, 2), input_...
[ 1 ]
[]
[]
[ "conv_neural_network", "max_pooling", "padding", "python", "tensorflow" ]
stackoverflow_0074139503_conv_neural_network_max_pooling_padding_python_tensorflow.txt
Q: ImportError: libGL.so.1: cannot open shared object file: No such file or directory I am trying to run cv2, but when I try to import it, I get the following error: ImportError: libGL.so.1: cannot open shared object file: No such file or directory The suggested solution online is installing apt install libgl1-mesa-g...
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
I am trying to run cv2, but when I try to import it, I get the following error: ImportError: libGL.so.1: cannot open shared object file: No such file or directory The suggested solution online is installing apt install libgl1-mesa-glx but this is already installed and the latest version. NB: I am actually running this ...
[ "Add the following lines to your Dockerfile:\nRUN apt-get update\nRUN apt-get install ffmpeg libsm6 libxext6 -y\n\nThese commands install the cv2 dependencies that are normally present on the local machine, but might be missing in your Docker container causing the issue.\n", "Even though the above solutions work...
[ 512, 110, 70, 60, 26, 22, 12, 12, 4, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ "python", "ubuntu_14.04" ]
stackoverflow_0055313610_python_ubuntu_14.04.txt
Q: How do I change the speed of an audio file in Python, like in Audacity, without quality loss? I'm building a simple Python application that involves altering the speed of an audio track. (I acknowledge that changing the framerate of an audio also make pitch appear different, and I do not care about pitch of the au...
How do I change the speed of an audio file in Python, like in Audacity, without quality loss?
I'm building a simple Python application that involves altering the speed of an audio track. (I acknowledge that changing the framerate of an audio also make pitch appear different, and I do not care about pitch of the audio being altered). I have tried using solution from abhi krishnan using pydub, which looks like th...
[ "Assuming what you want to do is to play audio back at say x1.5 the speed of the original. This is synonymous to saying to resample the audio samples down by 2/3rds and pretend that the sampling rate hasn't changed. Assuming this is what you are after, I suspect most DSP packages would support it (search audio resa...
[ 0 ]
[]
[]
[ "audio", "ffmpeg", "ffmpeg_python", "pydub", "python" ]
stackoverflow_0074136596_audio_ffmpeg_ffmpeg_python_pydub_python.txt
Q: no module named 'Seaborn' after installed it -- (Mac OS) Jupyter lab Python version 3.10.8. I used the Mac terminal to install seaborn. Still get error ModuleNotFoundError: No module named 'seaborn' in the Jupyter lab. Restart both Jupyter lab and the computer several times and not working. pip 22.3 from /Library/...
no module named 'Seaborn' after installed it -- (Mac OS) Jupyter lab
Python version 3.10.8. I used the Mac terminal to install seaborn. Still get error ModuleNotFoundError: No module named 'seaborn' in the Jupyter lab. Restart both Jupyter lab and the computer several times and not working. pip 22.3 from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip...
[ "Your jupyter notebook is not running from the same environment. I would suggest you install the package from notebook.\nIn notebook cell run this:\n%pip install seaborn\n\nThis will install seaborn in the whatever environment you are using.\n" ]
[ 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0074139436_macos_python.txt
Q: Recreate Towhee Image Embeddings with Timm For now I have been using https://github.com/towhee-io/towhee for creating image embeddings. But in order to fully understand how Towhee works I wanted to recreate image embeddings with timm (https://rwightman.github.io/pytorch-image-models/). However I can't seem to get ...
Recreate Towhee Image Embeddings with Timm
For now I have been using https://github.com/towhee-io/towhee for creating image embeddings. But in order to fully understand how Towhee works I wanted to recreate image embeddings with timm (https://rwightman.github.io/pytorch-image-models/). However I can't seem to get the same result and Towhee is built in a way unf...
[]
[]
[ "I got the answer I was looking for here:\nhttps://github.com/towhee-io/towhee/discussions/2215\nThanks to @junjiejiangjjj\nAlso copying the working code below.\nimport timm\nimport torch\nfrom PIL import Image as PILImage\n\nfrom timm.data.transforms_factory import create_transform\nfrom timm.data import resolve_d...
[ -1 ]
[ "computer_vision", "image_processing", "python", "pytorch" ]
stackoverflow_0074137894_computer_vision_image_processing_python_pytorch.txt
Q: Edit: Can I detect *any key* being pressed without input or installing any module? I am writing a code where the text comes out like this: import time def animation(phrase): for i in phrase: print(i,end="",flush=True) #Animates text to be printed out one by one time.sleep(0.035) print(phrase) Whil...
Edit: Can I detect *any key* being pressed without input or installing any module?
I am writing a code where the text comes out like this: import time def animation(phrase): for i in phrase: print(i,end="",flush=True) #Animates text to be printed out one by one time.sleep(0.035) print(phrase) While the text is coming out one by one, the user can press enter in between the letters. Af...
[ "To detect keyboard input you will need to use the Curses library.\nWhich is a built-in library in python.\nimport curses\nimport os\n\n\ndef main(win):\n win.nodelay(True)\n key = \"\"\n win.clear()\n win.addstr(\"Detected key:\") # curses version of print\n\n while True:\n try:\n ...
[ 3, 3 ]
[]
[]
[ "enter", "grok", "python", "text" ]
stackoverflow_0074140537_enter_grok_python_text.txt
Q: Append wildcard results to a list in python Please forgive me I am teaching myself and am pretty new to this. I have searched and found nothing that addressed my issue, lots of things dealing with os and file directories but I couldn't figure out how to implement them here. I also am not super familiar with regex...
Append wildcard results to a list in python
Please forgive me I am teaching myself and am pretty new to this. I have searched and found nothing that addressed my issue, lots of things dealing with os and file directories but I couldn't figure out how to implement them here. I also am not super familiar with regex, and have tried implementing that as well but ke...
[ "You can use the fnmatch built in library.\nFor example, if you want to find all the words in your text that ends with 'thispattern', you can do it like this:\nimport fnmatch \n\ntxt = [\"longerthepattern is the word i want\", \"thisisthepattern and it works\"]\n\npattern = '*thepattern'\n\nto_add_to_stoplist = []...
[ 1 ]
[]
[]
[ "python", "wildcard" ]
stackoverflow_0074140160_python_wildcard.txt
Q: Rolling average on previous dates per group I have the following dataset: Name Loc Site Date Total Alex Italy A 12.31.2020 30 Alex Italy B 12.31.2020 40 Alex Italy B 12.30.2020 100 Alex Italy A 12.30.2020 80 Alex France A 12.28.2020 10 Alex France B 12.28.2...
Rolling average on previous dates per group
I have the following dataset: Name Loc Site Date Total Alex Italy A 12.31.2020 30 Alex Italy B 12.31.2020 40 Alex Italy B 12.30.2020 100 Alex Italy A 12.30.2020 80 Alex France A 12.28.2020 10 Alex France B 12.28.2020 20 Alex France B 12.27.2020 10 I wan...
[ "First aggregate mean per 3 columns, add one day to MultiIndex for match previous day and last use DataFrame.join:\ndf['Date'] = pd.to_datetime(df['Date'])\n\n\ns = df.groupby(['Name','Loc','Date'])['Total'].mean().rename('Prv_Avg')\nprint (s)\nName Loc Date \nAlex France 2020-12-27 10\n ...
[ 2, 0 ]
[]
[]
[ "group_by", "pandas", "python", "time_series" ]
stackoverflow_0074138848_group_by_pandas_python_time_series.txt
Q: return SQL table as JSON in python I'm playing around with a little web app in web.py, and am setting up a url to return a JSON object. What's the best way to convert a SQL table to JSON using python? A: Here is a really nice example of a pythonic way to do that: import json import psycopg2 def db(database_nam...
return SQL table as JSON in python
I'm playing around with a little web app in web.py, and am setting up a url to return a JSON object. What's the best way to convert a SQL table to JSON using python?
[ "Here is a really nice example of a pythonic way to do that:\nimport json\nimport psycopg2\n\ndef db(database_name='pepe'):\n return psycopg2.connect(database=database_name)\n\ndef query_db(query, args=(), one=False):\n cur = db().cursor()\n cur.execute(query, args)\n r = [dict((cur.description[i][0], v...
[ 108, 38, 20, 13, 7, 5, 5, 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "json", "python", "sql" ]
stackoverflow_0003286525_json_python_sql.txt
Q: Parsing XML document that includes another XML document embedded in a CDATA section I'm trying out web scraping for the first time using lxml.etree. The website I want to scrape has an XML feed, which I can read fine, except for a part of its XML which is embedded within a CDATA section: from lxml import etree pa...
Parsing XML document that includes another XML document embedded in a CDATA section
I'm trying out web scraping for the first time using lxml.etree. The website I want to scrape has an XML feed, which I can read fine, except for a part of its XML which is embedded within a CDATA section: from lxml import etree parser = etree.XMLParser(recover=True) data=b'''<?xml version="1.0" encoding="UTF-8"?> <fe...
[ "This has nothing to do with indentation. The problem is that the xml within the CDATA is not well formed. It uses namespaces (<ns2:name>Gassco AS</ns2:name>, for example), but without a namespace declaration. So when you try to parse block.text you should get\nXMLSyntaxError: Namespace prefix ns2 on name is not de...
[ 2, 1 ]
[]
[]
[ "cdata", "lxml", "python", "xml" ]
stackoverflow_0074071948_cdata_lxml_python_xml.txt
Q: importing an excel file to python I have a basic question about importing xlsx files to Python. I have checked many responses about the same topic, however I still cannot import my files to Python whatever I try. Here's my code and the error I receive: import pandas as pd import xlrd file_location = 'C:\Users\ca...
importing an excel file to python
I have a basic question about importing xlsx files to Python. I have checked many responses about the same topic, however I still cannot import my files to Python whatever I try. Here's my code and the error I receive: import pandas as pd import xlrd file_location = 'C:\Users\cagdak\Desktop\python_self_learning\Cours...
[ "With pandas it is possible to get directly a column of an Excel file. Here is the code.\nimport pandas\ndf = pandas.read_excel('sample.xls')\n\n#print the column names\nprint df.columns\n\n#get the values for a given column\nvalues = df['column_name'].values\n\n#get a data frame with selected columns\nFORMAT = ['C...
[ 20, 3, 1, 0 ]
[]
[]
[ "import_from_excel", "python" ]
stackoverflow_0043964513_import_from_excel_python.txt
Q: How to check which words of text appear in database and their frequency I have a long text and a database table that acts as a dictionary, with the columns term, entity_type and main_name. I would like to compare the words from my text to the term column and recover the terms that appear in the text, their frequen...
How to check which words of text appear in database and their frequency
I have a long text and a database table that acts as a dictionary, with the columns term, entity_type and main_name. I would like to compare the words from my text to the term column and recover the terms that appear in the text, their frequency, their entity_type and their main_name. I could do this looping through ev...
[ "First as Mike Organek suggests split your text to table with a query like this\nselect distinct upper(w) as word \n from regexp_split_to_table(:your_text, '[^\\w]+') w;\n\nThen inner join it with the table and make your statistics\nwith words_in_text as\n(\n select distinct upper(w) as word\n from regexp_split_...
[ 2 ]
[]
[]
[ "postgresql", "python", "sql" ]
stackoverflow_0074140604_postgresql_python_sql.txt
Q: In Cpython implementation, are strings an array of characters or array of references/pointers like python lists? I went through the post https://rushter.com/blog/python-strings-and-memory/ Based on that article, Depending on the type of characters in a string, each character in that string would be represented us...
In Cpython implementation, are strings an array of characters or array of references/pointers like python lists?
I went through the post https://rushter.com/blog/python-strings-and-memory/ Based on that article, Depending on the type of characters in a string, each character in that string would be represented using either 1/2/4 bytes Since the address length of each such character is fixed (either 1/2/4), we can find the addres...
[ "The key piece of information can be read in this answer to a similiar question - \"Indexing into a string creates a new string\" - which means, both s1[4] and s2[1] create new string, \"o\". Because strings are interned, Python optimalizes the reference to point to the same object in memory, which is not necessari...
[ 0 ]
[]
[]
[ "cpython", "python", "string" ]
stackoverflow_0074140678_cpython_python_string.txt
Q: How to delete only one row in tkinter python? when i run app and delete one row is worked but whene i close the app to update, all rows are deleted what should i do import sqlite3 from tkinter import * from tkinter import ttk class root(Tk): def __init__(self): super().__init__() self.bookInfo...
How to delete only one row in tkinter python?
when i run app and delete one row is worked but whene i close the app to update, all rows are deleted what should i do import sqlite3 from tkinter import * from tkinter import ttk class root(Tk): def __init__(self): super().__init__() self.bookInfodb = sqlite3.connect("test.db") self.c = s...
[ "I don't know if this is the problem but self.c.execute(\"DELETE FROM books\") will delete the entire books table.\nYou probably need to add a WHERE clause in your DELETE statement\nself.c.execute(\"DELETE FROM books WHERE ...\")\n\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074140772_python_tkinter.txt
Q: Split list into two lists, odd and even, using a lambda This is what I have: ev_filt = filter(lambda x: x % 2 == 0, list1) od_filt = filter(lambda x: x % 2 != 0, list1) ev_list = list(ev_filt) od_list = list(od_filt) length = int(input("Enter the number of words yer gon pass")) # initialize the list using for l...
Split list into two lists, odd and even, using a lambda
This is what I have: ev_filt = filter(lambda x: x % 2 == 0, list1) od_filt = filter(lambda x: x % 2 != 0, list1) ev_list = list(ev_filt) od_list = list(od_filt) length = int(input("Enter the number of words yer gon pass")) # initialize the list using for loop for i in range(0, length): item = int(input("Pass a nu...
[ "As I mentioned in my comment, code runs from top to bottom in order. You sort your list1 into odd and even before it's initialized and before there are values in the list. Switch the order and you should be golden:\nlength = int(input(\"Enter the number of words yer gon pass\"))\n\n# initialize the list using for ...
[ 2, 1 ]
[]
[]
[ "lambda", "python", "split" ]
stackoverflow_0074140733_lambda_python_split.txt
Q: Is there a way to check if a list contains unique values that only occur once in a list contiguously I am trying to find a way to check if a list contains contiguous elements which are not duplicated. For example, A = [1, 1, 4, 2, 2, 2] this list contains contiguous elements which are not duplicated. A = [1, 1, ...
Is there a way to check if a list contains unique values that only occur once in a list contiguously
I am trying to find a way to check if a list contains contiguous elements which are not duplicated. For example, A = [1, 1, 4, 2, 2, 2] this list contains contiguous elements which are not duplicated. A = [1, 1, 4, 4, 3, 4, 7, 7, 7] this list does not contains contiguous elements which are not duplicated. Here the va...
[ "Here are some examples which may help:\n# Sorting based Python implementation\n# to check whether the array\n# contains a set of contiguous integers\n \ndef areElementsContiguous(arr, n):\n # Sort the array\n arr.sort()\n \n # After sorting, check if\n # current element is either\n # same as pre...
[ 1, 1 ]
[]
[]
[ "list", "python", "python_itertools" ]
stackoverflow_0074139939_list_python_python_itertools.txt
Q: Save Jupyter Notebook with Plotly Express widgets displaying I have a Jupyter notebook (python) where I used plotly express to plot in the notebook for analysis purposes. I want to share this notebook with non-coders, and have the interactive visuals be available still - but it does not seem to work. I tried follo...
Save Jupyter Notebook with Plotly Express widgets displaying
I have a Jupyter notebook (python) where I used plotly express to plot in the notebook for analysis purposes. I want to share this notebook with non-coders, and have the interactive visuals be available still - but it does not seem to work. I tried following recommendations made here but even after saving widgets state...
[ "After running plotly.offline.init_notebook_mode() in a cell,\nyou can export the notebook with full interactivity via the file menu:\nFile --> Export Notebook as... --> Export Notebook to HTML.\n", "I was having similar issues but with JupyterLab. Followed the instructions here: https://plot.ly/python/renderers/...
[ 30, 1, 0, 0 ]
[]
[]
[ "data_visualization", "jupyter_notebook", "plotly", "plotly_express", "python" ]
stackoverflow_0057658935_data_visualization_jupyter_notebook_plotly_plotly_express_python.txt
Q: Print all the "a" of a string on python I'm trying to print all the "a" or other characters from an input string. I'm trying it with the .find() function but just print one position of the characters. How do I print all the positions where is an specific character like "a" A: You can use find with while loop a =...
Print all the "a" of a string on python
I'm trying to print all the "a" or other characters from an input string. I'm trying it with the .find() function but just print one position of the characters. How do I print all the positions where is an specific character like "a"
[ "You can use find with while loop\na = \"aabababaa\"\nk = 0\nwhile True:\n k = a.find(\"a\", k) # This is saying to start from where you left\n if k == -1:\n break\n k += 1\n print(k)\n\n", "This is also possible with much less amount of code if you don't care where you want to start.\na = \"aa...
[ 1, 1, 0 ]
[]
[]
[ "find", "python", "string" ]
stackoverflow_0074138201_find_python_string.txt
Q: how to store all values of loop in list of dictionary python dic = {} list =[] def bathSum(): for ZPRODHDR in root.iter('ZPRODHDR'): for ZPRODITM in ZPRODHDR.iter('ZPRODITM'): component = ZPRODITM.findtext('COMPONENT') quantity = ZPRODITM.findtext('QUANTITY') compo...
how to store all values of loop in list of dictionary python
dic = {} list =[] def bathSum(): for ZPRODHDR in root.iter('ZPRODHDR'): for ZPRODITM in ZPRODHDR.iter('ZPRODITM'): component = ZPRODITM.findtext('COMPONENT') quantity = ZPRODITM.findtext('QUANTITY') component = int(component) quantity = float(quantity) ...
[ "The problem is that you are not resetting your dictionary dic at each ZPRODHDR loop. The values are then always updated in the original dictionnary, and always overriding the old values.\nThis variable is an intermediate variable that should be cleaned at each loop from its values.\nYou need to move the dic variab...
[ 1 ]
[]
[]
[ "dictionary", "list", "loops", "python", "python_3.x" ]
stackoverflow_0074140677_dictionary_list_loops_python_python_3.x.txt
Q: convert a list to real number for scatter plot I have two lists of latitude and longitude which latitude (xx) is like: print(xx) [['46.0'], ['-69.7'], ['-50.7'], ['-22.3'], ['-36.7'], ['65.1'], ['-26.3'], ['-47.5'], ['19.4'], ['-82.3'], ['50.8'], ['-63.5'], ['34.2'], ['65.1']] I want to have a simple scatter plo...
convert a list to real number for scatter plot
I have two lists of latitude and longitude which latitude (xx) is like: print(xx) [['46.0'], ['-69.7'], ['-50.7'], ['-22.3'], ['-36.7'], ['65.1'], ['-26.3'], ['-47.5'], ['19.4'], ['-82.3'], ['50.8'], ['-63.5'], ['34.2'], ['65.1']] I want to have a simple scatter plot of these latitudes and longitudes but I receive th...
[ "Very straightforward way of doing this\nimport numpy as np\nx = np.array([['46.0'], ['-69.7'], ['-50.7'], ['-22.3'], ['-36.7'], ['65.1'], ['-26.3'], ['-47.5'], ['19.4'], ['-82.3'], ['50.8'], ['-63.5'], ['34.2'], ['65.1']]).flatten()\ny = x.astype(np.float)\n\nprint(y)\n\n" ]
[ 0 ]
[]
[]
[ "list", "matplotlib_basemap", "python" ]
stackoverflow_0074140864_list_matplotlib_basemap_python.txt
Q: Multiplying dataframes based on index value across all columns I have 2 dataframes with 'age' as the index on both. I want to use the multiplication rates in one df and apply these to the population in the other. The multiplication rates by age are in a single column dataframe: rate_for_yr = pd.DataFrame(np.array(...
Multiplying dataframes based on index value across all columns
I have 2 dataframes with 'age' as the index on both. I want to use the multiplication rates in one df and apply these to the population in the other. The multiplication rates by age are in a single column dataframe: rate_for_yr = pd.DataFrame(np.array([[15,90],[16,80],[17,70]]), columns=["Age","2020"...
[ "Since you already have the common index you can simply do a multiplication along row axis\npop_by_town.mul(rate_for_yr['2020'], axis=0)\n\n\n townA townB townC townD townE townF\nAge \n15 90 180 270 360 450 540\n16 560 640 720 800 ...
[ 1 ]
[]
[]
[ "indexing", "pandas", "python" ]
stackoverflow_0074140620_indexing_pandas_python.txt
Q: Starting Kivy service on bootup (Android) I'm trying to start my kivy app's service on bootup. I'm sure that my service is ok because it works when I start my app. But on bootup I have a problem. I've read this article and tried to make it: package net.saband.myapp; import android.content.BroadcastReceiver; impor...
Starting Kivy service on bootup (Android)
I'm trying to start my kivy app's service on bootup. I'm sure that my service is ok because it works when I start my app. But on bootup I have a problem. I've read this article and tried to make it: package net.saband.myapp; import android.content.BroadcastReceiver; import android.content.Intent; import android.conten...
[ "OMG! I've found the solution by solving my another issue with kivy service. It's enough just add some extras. Here is work code:\npackage net.saband.myapp;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Intent;\nimport android.content.Context;\nimport net.saband.myapp.ServiceMyservice;\n\npub...
[ 2, 1, 0 ]
[]
[]
[ "android", "java", "kivy", "python" ]
stackoverflow_0046867907_android_java_kivy_python.txt
Q: Face comparison (Not recognition or detection) using OpenCV and Keras? First of all here is my github link for the question. And here is my question: I would like to do a face comparison function using Python. And I can successfully(?) recognize faces using OpenCV. Now, how do I do the comparison thing? What I u...
Face comparison (Not recognition or detection) using OpenCV and Keras?
First of all here is my github link for the question. And here is my question: I would like to do a face comparison function using Python. And I can successfully(?) recognize faces using OpenCV. Now, how do I do the comparison thing? What I understand is this: In general Machine learning approach, I need to gather lo...
[ "You can use the idea of face-embeddings, which for example is proposed in the highly-cited paper FaceNet and implemented in OpenFace (which also comes pre-trained).\nThe general idea: take some preprocessed face (frontal, cropped, ...) and embedd it to some lower dimension with the characteristic, that similar fac...
[ 18, 5, 2, 1 ]
[]
[]
[ "convolution", "face_recognition", "neural_network", "opencv", "python" ]
stackoverflow_0046168182_convolution_face_recognition_neural_network_opencv_python.txt
Q: Send a adaptive card with data in python using 1.2 version Based on the below, I have a card template and data separately as json. https://adaptivecards.io/samples/FlightItinerary.html But i am not sure how to send data through python for the below card. I cant find a documentation examples for template and data f...
Send a adaptive card with data in python using 1.2 version
Based on the below, I have a card template and data separately as json. https://adaptivecards.io/samples/FlightItinerary.html But i am not sure how to send data through python for the below card. I cant find a documentation examples for template and data for python. How do I send data to this card through python # ...
[ "I couldn't find any way to pass in data to the JSON template using the Python SDK. However, I was able to solve this problem doing the following:\n\nIn your .json file add tags (${key_name}) wherever you want to add a value passed in from python:\n\n{\n \"text\": \"${name}\"\n}\n\n\nCreate a function that recei...
[ 4, 0, 0 ]
[]
[]
[ "adaptive_cards", "azure_bot_service", "python" ]
stackoverflow_0062268633_adaptive_cards_azure_bot_service_python.txt
Q: Sonarqube client fails to parse pytest coverage results I'm trying to set up a gitlab ci pipeline for a python project and I'm having some issues with sonarqube client which is not able to pars the coverage.xml file The error I'm getting is the following: INFO: Python test coverage INFO: Parsing report '/builds/c...
Sonarqube client fails to parse pytest coverage results
I'm trying to set up a gitlab ci pipeline for a python project and I'm having some issues with sonarqube client which is not able to pars the coverage.xml file The error I'm getting is the following: INFO: Python test coverage INFO: Parsing report '/builds/core-tech/tools/nlu/mix-nlu-middleware/server/tests/cov.xml' W...
[ "You need to assist sonarqube to found proper file, an easy way could be include the following step in your GH actions after running the tests and generate the report, and before calling souncarcloud scan\n--> step that run tests\n\n - name: fix code coverage paths\n run: |\n sed -i 's/\\/home\...
[ 3, 2, 0 ]
[]
[]
[ "gitlab_ci", "gitlab_ci_runner", "pytest", "python", "sonarqube" ]
stackoverflow_0057220171_gitlab_ci_gitlab_ci_runner_pytest_python_sonarqube.txt
Q: Errors working with Spacy document vectors in Pyspark dataframes I am having an incredibly bad time working with document vectors produced by the Spacy pre-trained large model in a Pyspark environment on AWS. The problems specifically start when I put the document vectors into a dataframe. For example, this code w...
Errors working with Spacy document vectors in Pyspark dataframes
I am having an incredibly bad time working with document vectors produced by the Spacy pre-trained large model in a Pyspark environment on AWS. The problems specifically start when I put the document vectors into a dataframe. For example, this code works just fine for me: # Load infrastructure libraries import pandas a...
[ "\nWhy does every attempt to view the embedding vectors in a dataframe fail?\n\nThis seems to be an issue with EMR versions above 6.2.0 creating a venv path on the executors that doesn't exist. Discussed a little more in this question\n\nwhy does the column containing the document vectors have a string datatype?\n\...
[ 0 ]
[]
[]
[ "nlp", "pyspark", "python", "spacy" ]
stackoverflow_0073776152_nlp_pyspark_python_spacy.txt
Q: Resampling without changing pitch and ratio I'm doing speech recognition and denoising. In order to feed the data to my model I need to resample and make it 2 channels. although I don't know the optimized resampling rate for each sound. when I use a fixed number for resampling rate(resr) like 20000 or 16000 someti...
Resampling without changing pitch and ratio
I'm doing speech recognition and denoising. In order to feed the data to my model I need to resample and make it 2 channels. although I don't know the optimized resampling rate for each sound. when I use a fixed number for resampling rate(resr) like 20000 or 16000 sometimes it works and sometimes it makes the pitch wro...
[ "\nI don't know the optimized resampling rate for each sound\n\nSample rate is not a parameter you tune for each audio, rather, the same sample rate that was used to train the speech recognition model should be used.\n\nsometimes it works and sometimes it makes the pitch wrong or makes it slow.\n\nResampling when p...
[ 1 ]
[]
[]
[ "python", "resampling", "speech_recognition", "torch", "torchaudio" ]
stackoverflow_0074136160_python_resampling_speech_recognition_torch_torchaudio.txt
Q: How to write a Dataframe and images to separate worksheets of an excel file I have found a similar and well answered question, Python: Writing Images and dataframes to the same excel file, but the answer writes the image into the same sheet as the Dataframe. I have 5 images I want to write to separate worksheet to...
How to write a Dataframe and images to separate worksheets of an excel file
I have found a similar and well answered question, Python: Writing Images and dataframes to the same excel file, but the answer writes the image into the same sheet as the Dataframe. I have 5 images I want to write to separate worksheet to that of the Dataframe. As this answer is well written I shall use it here if tha...
[ "Instead of using writer, add a new sheet using workbook.add_worksheet():\nwith pd.ExcelWriter('pandas_image2.xlsx', engine='xlsxwriter') as writer:\n df.to_excel(writer, sheet_name='Sheet1')\n\n workbook = writer.book\n worksheet = workbook.add_worksheet('Sheet2')\n worksheet.insert_image('D3', 'TRAJ_...
[ 2 ]
[]
[]
[ "excel", "python", "writer", "xlsxwriter" ]
stackoverflow_0074140805_excel_python_writer_xlsxwriter.txt
Q: What does "wrap" in np.pad actually do? When I am padding a numpy 2d array with mode='wrap', the return from it make me confuse: import numpy as np a = np.arange(9, dtype=float).reshape(3, 3) print(np.pad(a, [(2, 4), (1, 1)], mode='wrap')) it return: [[5. 3. 4. 5. 3.] [8. 6. 7. 8. 6.] [2. 0. 1. 2. 0.] [5. 3. 4...
What does "wrap" in np.pad actually do?
When I am padding a numpy 2d array with mode='wrap', the return from it make me confuse: import numpy as np a = np.arange(9, dtype=float).reshape(3, 3) print(np.pad(a, [(2, 4), (1, 1)], mode='wrap')) it return: [[5. 3. 4. 5. 3.] [8. 6. 7. 8. 6.] [2. 0. 1. 2. 0.] [5. 3. 4. 5. 3.] [8. 6. 7. 8. 6.] [2. 0. 1. 2. 0.] ...
[ "Here's the definition of wrap mode :\n\n'wrap'\nPads with the wrap of the vector along the axis.\nThe first values are used to pad the end and the\nend values are used to pad the beginning.\n\nAnd here's the code in pad method :\n@array_function_dispatch(_pad_dispatcher, module='numpy')\ndef pad(array, pad_width, ...
[ 0 ]
[]
[]
[ "numpy", "padding", "python" ]
stackoverflow_0074140891_numpy_padding_python.txt
Q: Some HTML presentations created using nbconvert from notebooks are not showing Plotly plots I'm using Plotly inside a notebook. I have this in one of my cells. from IPython.display import Javascript from plotly.offline import get_plotlyjs Javascript(get_plotlyjs()) I load data and run Plotly in another cell. The ...
Some HTML presentations created using nbconvert from notebooks are not showing Plotly plots
I'm using Plotly inside a notebook. I have this in one of my cells. from IPython.display import Javascript from plotly.offline import get_plotlyjs Javascript(get_plotlyjs()) I load data and run Plotly in another cell. The plots show in the notebook. I save the notebook and run this from the command line. jupyter nbcon...
[ "The error comes from running the notebook inside VS Code.\nRunning the notebook in jupyter lab and then saving it solves the problem. You can now run jupyter nbconvert and create an HTML presentation with plots.\n" ]
[ 0 ]
[]
[]
[ "jupyter_lab", "jupyter_notebook", "plotly", "python", "visual_studio_code" ]
stackoverflow_0074141140_jupyter_lab_jupyter_notebook_plotly_python_visual_studio_code.txt
Q: For some reason, pycharm is not able to compute my following code for finding factors of a number n = int(input("Enter a number : ")) a = [1, n] fac = 2 while fac <= n/2: if n % fac == 0: a.append(fac) fac += 1 print(a) A simple code to print the factors of a number. A: cha...
For some reason, pycharm is not able to compute my following code for finding factors of a number
n = int(input("Enter a number : ")) a = [1, n] fac = 2 while fac <= n/2: if n % fac == 0: a.append(fac) fac += 1 print(a) A simple code to print the factors of a number.
[ "change your code like this\nif n % fac == 0:\n a.append(fac)\nfac += 1\n\n" ]
[ 1 ]
[]
[]
[ "list", "numbers", "python" ]
stackoverflow_0074141118_list_numbers_python.txt
Q: Using metaclass to keep track of instances in python I need to keep tracks of instances of some classes (and do other stuff with those classes). I would like to not have to declare any extra code in the classes in question, thus everything should ideally be handled in the metaclass. What I can't figure out is how ...
Using metaclass to keep track of instances in python
I need to keep tracks of instances of some classes (and do other stuff with those classes). I would like to not have to declare any extra code in the classes in question, thus everything should ideally be handled in the metaclass. What I can't figure out is how to add a weak reference to each new instance of those clas...
[ "The method on the metaclass that is called when each new instance of its \"afiliated\" classes is __call__. If you put the code to record the instances in there, that is all the work you need:\n\nfrom weakref import WeakSet\n\n# A convenient class-level descriptor to retrieve the instances:\n\nclass Instances:\n ...
[ 5, 2, 0 ]
[]
[]
[ "metaclass", "python", "python_3.x" ]
stackoverflow_0056918764_metaclass_python_python_3.x.txt
Q: Django Rest Framework: Not sending email from react form Error 400 I'm trying to send a form using the API endpoint beneath. The problem is that I get a 400 error when I use my react based application. If I'm using the api endpoint page it works. I checked the payload and the only difference seems to be that i'm n...
Django Rest Framework: Not sending email from react form Error 400
I'm trying to send a form using the API endpoint beneath. The problem is that I get a 400 error when I use my react based application. If I'm using the api endpoint page it works. I checked the payload and the only difference seems to be that i'm not sending a csrf token in my react app. So far it was never neccesary w...
[ "This fixed it for me. Using the generic views was my issue:\nviews.py\n@api_view(['POST',])\ndef proposal(request):\n if request.method == \"POST\":\n serializer = ProposalEmailSerializer(data=request.data)\n if serializer.is_valid():\n ClientName = request.POST['ClientName']\n ...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074113237_django_django_rest_framework_python.txt
Q: dataframe conversation from list to rows I have pandas to extract the data from excel files and adding them to a dataframe using the following code flow_df_temp = {'date': date_fmt_csv, 'point_id': point_id_list_flow,'water_flow': water_list_flow} flow_df = flow_df.append(flow_df_temp, ignore_index=True)` Output ...
dataframe conversation from list to rows
I have pandas to extract the data from excel files and adding them to a dataframe using the following code flow_df_temp = {'date': date_fmt_csv, 'point_id': point_id_list_flow,'water_flow': water_list_flow} flow_df = flow_df.append(flow_df_temp, ignore_index=True)` Output that I get. date point_id ...
[ "assuming that the point_id and aggreggated_flow are lists, and element counts are same for all rows. Here is how you make those lists turn into their own rows\ndf.explode(['point_id','aggregated_flow'])\n\n\n date point_id aggregated_flow\n 0 10/02/2022 7 2.353\n 0 10/02/2022...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074141112_dataframe_pandas_python.txt
Q: fizz buzz game in python Write a simple function called fizzBuzz that takes in a positive integer, and returns ‘fizz’, ‘buzz’, ‘fizzbuzz’ or the argument it receives, based on the following: Returns ‘fizz’ if the argument is divisible by 3 Returns buzz if the argument is divisible by 5 Returns ‘fizzBuzz’ if the ar...
fizz buzz game in python
Write a simple function called fizzBuzz that takes in a positive integer, and returns ‘fizz’, ‘buzz’, ‘fizzbuzz’ or the argument it receives, based on the following: Returns ‘fizz’ if the argument is divisible by 3 Returns buzz if the argument is divisible by 5 Returns ‘fizzBuzz’ if the argument is divisible by 3 and 5...
[ "easiest way I think:\ndef fizz_buzz(input):\n if (input % 3 == 0) and (input % 5 == 0):\n return 'FizzBuzz'\n if input % 3 == 0:\n return 'Fizz'\n if input % 5 == 0:\n return 'Buzz'\n return input\n\nprint(fizz_buzz(3))\nPS: change print(fizz_buzz(3)) with any number to test it\n",...
[ 1, 0, 0, 0, 0, 0 ]
[ "def fizzbuzz(n):\n\n if n % 3 == 0 and n % 5 == 0:\n print('FizzBuzz')\n elif n % 3 == 0:\n print('Fizz')\n elif n % 5 == 0:\n print('Buzz')\n else:\n return str(n)\n\nn=int(input(\"Enter number:\"))\n\nfizzbuzz(n)\n\nthis works...\n" ]
[ -1 ]
[ "fizzbuzz", "python" ]
stackoverflow_0048528144_fizzbuzz_python.txt
Q: Use a list of values to select rows from a Pandas dataframe Let’s say I have the following Pandas dataframe: df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) df A B 0 5 1 1 6 2 2 3 3 3 4 5 I can subset based on a specific value: x = df[df['A'] == 3] x A B 2 3 3 But how...
Use a list of values to select rows from a Pandas dataframe
Let’s say I have the following Pandas dataframe: df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) df A B 0 5 1 1 6 2 2 3 3 3 4 5 I can subset based on a specific value: x = df[df['A'] == 3] x A B 2 3 3 But how can I subset based on a list of values? - something like this: l...
[ "You can use the isin method:\nIn [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})\n\nIn [2]: df\nOut[2]:\n A B\n0 5 1\n1 6 2\n2 3 3\n3 4 5\n\nIn [3]: df[df['A'].isin([3, 6])]\nOut[3]:\n A B\n1 6 2\n2 3 3\n\nAnd to get the opposite use ~:\nIn [4]: df[~df['A'].isin([3, 6])]\nOut[4]:\n A ...
[ 2012, 66, 7, 7, 5, 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0012096252_dataframe_pandas_python.txt
Q: Tkinter buttons resize, when longer text is displayed on them I am making a program that can launch files and programs like a Stream Deck. After selecting the file I want to assign to a button, the button resizes due to the filename being wider that the placeholder text "Add". I couldn't find any solutions to this...
Tkinter buttons resize, when longer text is displayed on them
I am making a program that can launch files and programs like a Stream Deck. After selecting the file I want to assign to a button, the button resizes due to the filename being wider that the placeholder text "Add". I couldn't find any solutions to this problem anywhere. I am desperate on finding the solution as this i...
[ "A widget appears in its natural size, if not defined otherwise. The natural size is usally the smallest amount of pixels needed to display the widget in width and height. You can change that appearance by defining a width for your Button, even better have a constant if you use the same value for a couple of Button...
[ 1 ]
[]
[]
[ "button", "python", "python_3.x", "tkinter", "tkinter_button" ]
stackoverflow_0074139574_button_python_python_3.x_tkinter_tkinter_button.txt
Q: Tkinter GUI Updating Toplevel Window from tkinter import* from tkinter import ttk from tkinter import messagebox from tkinter import filedialog import time import matplotlib.pyplot as plt import re import tkinter.font as font root=Tk() root.geometry("700x900+500+250") my_notebook = ttk.Notebook(root) my_notebook...
Tkinter GUI Updating Toplevel Window
from tkinter import* from tkinter import ttk from tkinter import messagebox from tkinter import filedialog import time import matplotlib.pyplot as plt import re import tkinter.font as font root=Tk() root.geometry("700x900+500+250") my_notebook = ttk.Notebook(root) my_notebook.pack() my_frame1=Frame(my_notebook,width...
[ "I'm not sure why you need to open multiple windows if only one choice is allowed at a time and that value from value_inside.get() is always used as the window titile. I imagine you could simply instantiate a single Toplevel window whenever a choice is made\ntop = None\n\n\ndef open_popup(top): # pass in 'top'\n ...
[ 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0074140470_python_tkinter_user_interface.txt
Q: Script doesn't recognize values in XML This is not answering my own question, but I'll edit the solution later. This is a follow-up question from topic HERE. If I use the solution from this post, I get an error AttributeError: 'NoneType' object has no attribute 'text' The values are in the XML file, so i really d...
Script doesn't recognize values in XML
This is not answering my own question, but I'll edit the solution later. This is a follow-up question from topic HERE. If I use the solution from this post, I get an error AttributeError: 'NoneType' object has no attribute 'text' The values are in the XML file, so i really don't know what to do... The code: import pan...
[ "The error does not reproduce with provided sample so it could be a problem with a particular file. Adding a try-except would help to catch the problematic filename\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport xml.etree.ElementTree as ET\n\nfiles = [\"S1.xml\"]\n\n\n#files = glob.glob('./*.xml')\n\na...
[ 1, 0 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0074140141_python_xml_xml_parsing.txt
Q: torchaudio load for PCM file - EfficientConformer I'm struggling with parsing audio length in PCM file. EfficientConformer use LibriSpeechDataset and the audio file format is flac, but in my case i'm using pcm files. EfficientConformer extracts audio length by torchaudio like this audio_length = torchaudio.load(DA...
torchaudio load for PCM file - EfficientConformer
I'm struggling with parsing audio length in PCM file. EfficientConformer use LibriSpeechDataset and the audio file format is flac, but in my case i'm using pcm files. EfficientConformer extracts audio length by torchaudio like this audio_length = torchaudio.load(DATASET_PATH)[0].size(1) But for my case, it doesn't wor...
[ "If you are using TorchAudio v0.12 or later, then using torchaudio.io.StreamReader allows to load PCM directly.\nRef: https://pytorch.org/audio/main/tutorials/streamreader_basic_tutorial.html#headerless-media\ns = StreamReader(src=PATH, format=\"s16le\", option={\"sample_rate\": \"16000\"})\ns.add_basic_audio_strea...
[ 0 ]
[]
[]
[ "deep_learning", "python", "pytorch", "speech_recognition", "torchaudio" ]
stackoverflow_0073810750_deep_learning_python_pytorch_speech_recognition_torchaudio.txt
Q: Given a List get all the combinations of tuples without duplicated results I have a list=[1,2,3,4] And I only want to receive tuple results for like all the positions in a matrix, so it would be (1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4) I've seen several codes...
Given a List get all the combinations of tuples without duplicated results
I have a list=[1,2,3,4] And I only want to receive tuple results for like all the positions in a matrix, so it would be (1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4) I've seen several codes that return all the combinations but i don't know how to restrict it only to th...
[ "If you just want to do this for making pairs of all symbols in the list\ntuple_pairs = [(r,c) for r in lst for c in lst]\n\nIf you have instead some maximum row/colum numbers max_row and max_col you could avoid making the lst=[1,2,3,4] and instead;\ntuple_pairs = [(r,c) for r in range(1,max_row+1) for c in range(1...
[ 1, 1, 1, 0 ]
[]
[]
[ "combinations", "list", "python", "tuples" ]
stackoverflow_0074140972_combinations_list_python_tuples.txt
Q: Pandas Date %y defaults to 20xx instead of 19xx I have a date like: 28.01.58 I am trying to convert using: df['date'] = pd.to_datetime(df['date'], format='%d.%m.%y') Pandas returns: 2058-01-28 My expected return: 1958-01-28 A: Unfortunately because of Y2K shenanigans, pandas works implicitly with 2 digit years,...
Pandas Date %y defaults to 20xx instead of 19xx
I have a date like: 28.01.58 I am trying to convert using: df['date'] = pd.to_datetime(df['date'], format='%d.%m.%y') Pandas returns: 2058-01-28 My expected return: 1958-01-28
[ "Unfortunately because of Y2K shenanigans, pandas works implicitly with 2 digit years, as a fix for this you can try\ndf['date'] = pd.to_datetime(df['date'].str[:-2]+'20'+df['date'].str[-2:], format='%d.%m.%y')\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074141136_datetime_pandas_python.txt
Q: Django return new property in json response I have a view in Django that fetches some objects, adds new attribute to them and returns them as JSON response. The code looks like this: def stats(request): items = MyItem.objects.all().order_by('-id') for item in items: item.new_attribute = 10 ...
Django return new property in json response
I have a view in Django that fetches some objects, adds new attribute to them and returns them as JSON response. The code looks like this: def stats(request): items = MyItem.objects.all().order_by('-id') for item in items: item.new_attribute = 10 items_json = serializers.serialize('json', ...
[ "Default serializer looks into fields defined in model. Thus, there are two options to resolve it:\n\nAdd the attribute to your model MyItem\nUse a custom serializer to serialize your model with this dynamic attribute\n\nExample of such serializer:\nserializers.py\nclass MyItemSerializer(serializers.ModelSerializer...
[ 2, 0 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0074141238_django_json_python.txt
Q: Plot curve with varying opacity with matplotlib I have a plot with several curves that looks like this: These curves start from the top right corner and finish around the point (0.86, 0.5). I want to focus attention on the end point. If I zoom on this region, it is still not very easy to distinguish the different...
Plot curve with varying opacity with matplotlib
I have a plot with several curves that looks like this: These curves start from the top right corner and finish around the point (0.86, 0.5). I want to focus attention on the end point. If I zoom on this region, it is still not very easy to distinguish the different lines because they overlap several times. My idea is...
[ "You could always break down your x and y arrays into smaller arrays that you plot separately. This would give you the opportunity to modify alpha for each segment.\nSee example below:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN_samp=1000\nx=np.arange(N_samp)\ny=np.sin(2*np.pi*x/N_samp)\nstep=10\n[plt...
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074139801_matplotlib_python.txt
Q: CMake must be installed to build dlib even after installing Cmake and setting environmental variable CMake must be installed to build dlib even after installing Cmake and setting environmental variable. Can anyone please help me I am stuck in this issue since 4 days :( A: Kindly see this thread. It will be more ...
CMake must be installed to build dlib even after installing Cmake and setting environmental variable
CMake must be installed to build dlib even after installing Cmake and setting environmental variable. Can anyone please help me I am stuck in this issue since 4 days :(
[ "Kindly see this thread. It will be more helpful if you post the screenshot of the issue.\nCmake issue Solving\n", "You can do these commands :\npip install cmake (or pip3 install cmake)\n\nOn Debian-based system\nsudo apt install cmake\n\nOn Mac\nbrew install cmake\n\n" ]
[ 0, 0 ]
[]
[]
[ "cmake", "dlib", "python" ]
stackoverflow_0072045340_cmake_dlib_python.txt
Q: Is it possible to mix two mono audio tensors of different length (number of frames) in torchaudio? I have two byte arrays - one from mic and one from soundcard of same duration (15 seconds). They have different formats (sample rate of mic = 44100, n_frames = 1363712; sample rate of stereo = 48000, n_frames=1484160...
Is it possible to mix two mono audio tensors of different length (number of frames) in torchaudio?
I have two byte arrays - one from mic and one from soundcard of same duration (15 seconds). They have different formats (sample rate of mic = 44100, n_frames = 1363712; sample rate of stereo = 48000, n_frames=1484160). I had assumed resampling would help (16k desired) but they are still of differing lengths and can't s...
[ "Mixing audio is simply taking sum or average of source waveforms, so TorchAudio does not provide a specialized method, but users are expected to do the operation with pure PyTorch Tensor operation.\nNow the problem you need to think is how to handle the different lengths, i.e. how to make them the same length.\nYo...
[ 1 ]
[]
[]
[ "python", "sox", "torchaudio" ]
stackoverflow_0073718299_python_sox_torchaudio.txt
Q: List Comprehension starting at a specific number I was trying to create this [80000, 104000, 135000...] list in Python. Its the value, starting at 80,000 multiplied by 1.3 each time I want What i've tried: a = [num*1.5 for num in ??? if num>=80000] #???--> i've tried range(10) I should be able to do this but I ca...
List Comprehension starting at a specific number
I was trying to create this [80000, 104000, 135000...] list in Python. Its the value, starting at 80,000 multiplied by 1.3 each time I want What i've tried: a = [num*1.5 for num in ??? if num>=80000] #???--> i've tried range(10) I should be able to do this but I can't find any solutions rn.. I must use list-comprehens...
[ "There is a very basic mathematical operation that represents multiplying by the same value many time: power.\na = [80000 * (1.3**n) for n in range(100)]\n\n", "You could write your own generator then use that in conjunction with a list comprehension.\ndef numgen(start, factor, limit):\n for _ in range(limit):...
[ 2, 1 ]
[ "import numpy as np\nprint(80000 * 1.3**np.arange(3))\n# [ 80000. 104000. 135200.]\n\n" ]
[ -3 ]
[ "list_comprehension", "python" ]
stackoverflow_0074140917_list_comprehension_python.txt
Q: Copy lines into new file named after the multiple input files I want to use this script to get all lines that start with #Solution out of multiple files in the directory and put them together in a new file that is named after the sample id that is in the title of the input files. The directory has multiple files o...
Copy lines into new file named after the multiple input files
I want to use this script to get all lines that start with #Solution out of multiple files in the directory and put them together in a new file that is named after the sample id that is in the title of the input files. The directory has multiple files of different samples (so different sample id's) so I want to make it...
[ "You want to use a with context manager whenever you use open() so that the file is properly closed at the end.\nfor f in os.listdir(dr):\n new_lines = [] # clear out this list for each new file we look at\n if f.endswith(tag):\n print(f)\n new_file_name = f.split('_')[0]+'.txt' # get the name o...
[ 0 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0074139604_filenames_python.txt
Q: NumPy replace values in matrix with np array I have numpy array like: x = np.array([ ... [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]] ... ]) with shape (4800, 4, 4). So i need to replace every 0 with [1, 1, 2] and every 1 with [5, 5, 9] Result should be like this: [[[1, 1, 2...
NumPy replace values in matrix with np array
I have numpy array like: x = np.array([ ... [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]] ... ]) with shape (4800, 4, 4). So i need to replace every 0 with [1, 1, 2] and every 1 with [5, 5, 9] Result should be like this: [[[1, 1, 2], [1, 1, 2], [1, 1, 2], [1, 1, 2]], [[1, 1, 2], [...
[ "Take advantage of the fact that you have 0 and 1, define a mapper array and index it:\n # 0 1\nmapper = np.array([[1, 1, 2], [5, 5, 9]])\n\nout = mapper[a]\n\noutput:\narray([[[[1, 1, 2],\n [1, 1, 2],\n [1, 1, 2],\n [1, 1, 2]],\n\n [[1, 1, 2],\n [...
[ 3, 1 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0074141242_matrix_numpy_python.txt
Q: Scraping free proxy listing website I am trying to scrape one of the free proxy listings website but, I just couldn't be able to scrape the proxies. Below is my code: import requests import re url = 'https://free-proxy-list.net/' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKi...
Scraping free proxy listing website
I am trying to scrape one of the free proxy listings website but, I just couldn't be able to scrape the proxies. Below is my code: import requests import re url = 'https://free-proxy-list.net/' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Cafari/537.3...
[ "It is generally best to use a parser such as BeautifulSoup to extra data from html rather than regular expressions because it is very difficult to reproduce BeautifulSoup's acturacy; however, you can try this with pure regex:\nimport re\nurl = 'https://free-proxy-list.net/'\nheaders = {'User-Agent': 'Mozilla/5.0 (...
[ 14, 11, 4, 4, 0, 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0048426624_python_web_scraping.txt
Q: Get specific data from API response using parameter I'm unsure how to word the title of this question and no doubt there is an easy solution but I am a beginner. I need to pass a parameter (symbol) to this function and have it return the 'minTradeQuantity'. def get_exchange_minqtyize(symbol): return session_au...
Get specific data from API response using parameter
I'm unsure how to word the title of this question and no doubt there is an easy solution but I am a beginner. I need to pass a parameter (symbol) to this function and have it return the 'minTradeQuantity'. def get_exchange_minqtyize(symbol): return session_auth.query_symbol()['result'] I can retrieve the whole res...
[ "Go through the result & filter by symbol:\ndef get_exchange_minqtyize(symbol):\n data = session_auth.query_symbol()['result']\n for sym_data in data:\n if sym_data['name'] == symbol: # assuming the name here is the symbol you're looking for\n return sym_data['minTradeQuantity']\n\n\n" ]
[ 1 ]
[]
[]
[ "bybit", "json", "python" ]
stackoverflow_0074141453_bybit_json_python.txt
Q: Trying to get BeautifulSoup to print URL list from Yahoo Finance of firstname Goal is to get Python / BeautifulSoup to scrape Yahoo Finance and the first/last name of public company owner: from bs4 import BeautifulSoup import requests url = 'https://finance.yahoo.com/quote/GTVI/profile?p=GTVI' page = requ...
Trying to get BeautifulSoup to print URL list from Yahoo Finance of firstname
Goal is to get Python / BeautifulSoup to scrape Yahoo Finance and the first/last name of public company owner: from bs4 import BeautifulSoup import requests url = 'https://finance.yahoo.com/quote/GTVI/profile?p=GTVI' page = requests.get(url, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS...
[ "Check your indents to get your code running and also your requests. Cause expected result from your question is not that clear, this is just a hint how to fix or get a result.\nExample\nfrom bs4 import BeautifulSoup\nimport requests\n\nurl = ['https://finance.yahoo.com/quote/GTVI/profile?p=GTVI',\n'https://finance...
[ 0 ]
[]
[]
[ "finance", "python", "scrape", "web_scraping", "yahoo" ]
stackoverflow_0074140849_finance_python_scrape_web_scraping_yahoo.txt
Q: How to set the funcion timeout for Genetic Algorithm to more than 10 sec? I have a loss function that opens an external .exe file for calculation, and running this executable file usually takes around 2 or 3 minutes. It works very well, but When I want to pass this function to the Genetic Algorithm for optimizatio...
How to set the funcion timeout for Genetic Algorithm to more than 10 sec?
I have a loss function that opens an external .exe file for calculation, and running this executable file usually takes around 2 or 3 minutes. It works very well, but When I want to pass this function to the Genetic Algorithm for optimization, I face this error: AssertionError: After 10.0 seconds delay func_timeout: th...
[ "From the geneticalgorithm library Github page:\n\nFunction timeout\ngeneticalgorithm is designed such that if the given function does not\nprovide any output before timeout (the default value is 10 seconds),\nthe algorithm would be terminated and raise the appropriate error. In\nsuch a case make sure the given fun...
[ 0 ]
[]
[]
[ "genetic_algorithm", "machine_learning", "optimization", "python", "timeout" ]
stackoverflow_0074141241_genetic_algorithm_machine_learning_optimization_python_timeout.txt
Q: Plotnine (ggplot) : Set the direction legend elements are populated when specifying n rows I am doing this in plotnine, but hoping ggplotters can assist as well. Consider the following plot: df = pd.DataFrame({ 'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6), 'variable' : ['A','B...
Plotnine (ggplot) : Set the direction legend elements are populated when specifying n rows
I am doing this in plotnine, but hoping ggplotters can assist as well. Consider the following plot: df = pd.DataFrame({ 'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6), 'variable' : ['A','B','C','D','E','F']*11, 'value' : np.random.choice(range(50),66) }) p = (ggplot(df, aes(x='...
[ "As in ggplot2 this could be achieved via the byrow argument of guide_legend. Simply set it to True:\nimport pandas as pd\nimport numpy as np\nfrom plotnine import *\n\ndf = pd.DataFrame({\n 'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6),\n 'variable' : ['A','B','C','D','E','F']*11...
[ 1 ]
[]
[]
[ "ggplot2", "plotnine", "python" ]
stackoverflow_0074141448_ggplot2_plotnine_python.txt
Q: how can I apply label encoding by using a dataframe without using labelencoder etc. in Python? I have two data frames: first: l1=[123,345,546,245] l2=["a","a","b","b"] l3=["j","k","l","pp"] l4=["m","n","m","n"] df1=pd.DataFrame(list(zip(l1,l2,l3,l4)),columns=['id','X','Y','Z']) df1.head() enter image description...
how can I apply label encoding by using a dataframe without using labelencoder etc. in Python?
I have two data frames: first: l1=[123,345,546,245] l2=["a","a","b","b"] l3=["j","k","l","pp"] l4=["m","n","m","n"] df1=pd.DataFrame(list(zip(l1,l2,l3,l4)),columns=['id','X','Y','Z']) df1.head() enter image description here second: l1=["X","X","Y","Y","Y","Y","Z","Z"] l2=["a","b","j","k","l","pp","m","n"] l3=["1","2"...
[ "here is one way to do it, using melt, and pivot\n# melt the dataframe to make it columner\n# merge with the reference dataframe\n# finally pivot to get back to the original format\n(df.melt(id_vars=['id'], var_name='key' ).merge(df2,\n left_on=['key','value'],\n ...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "label", "python" ]
stackoverflow_0074140921_dataframe_dictionary_label_python.txt
Q: Sort dataframe by asc and desc I have a data frame that has two columns, let's call A and B I want to sort A desc and B asc. In order words, I want a list of elements which has a minor value in columns A and a greater value in column B Is it possible? A: pass 0 (false), 1 (true) to the ascending attribute in sor...
Sort dataframe by asc and desc
I have a data frame that has two columns, let's call A and B I want to sort A desc and B asc. In order words, I want a list of elements which has a minor value in columns A and a greater value in column B Is it possible?
[ "pass 0 (false), 1 (true) to the ascending attribute in sort_values\ndf.sort_values(['cola','colb'], ascending=[0,1]\n\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074141613_pandas_python.txt
Q: Different binwidth for each plot in FacetGrid Seaborn I would like to give each histplot in FacetGrid from seaborn a different binwidth. To give each plot a binwidth of 3 is possible like this: import seaborn as sns sns.set_theme(style="darkgrid") tips = sns.load_dataset("tips") g = sns.FacetGrid(tips, col="day"...
Different binwidth for each plot in FacetGrid Seaborn
I would like to give each histplot in FacetGrid from seaborn a different binwidth. To give each plot a binwidth of 3 is possible like this: import seaborn as sns sns.set_theme(style="darkgrid") tips = sns.load_dataset("tips") g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65) g.map(sns.histplot, "total_bill",...
[ "You could loop simultaneously through g.axes_dict and the widths, and call the function separately for each subplot. You'll need to manually create the correct subset of the dataframe.\nimport seaborn as sns\n\nsns.set_theme(style=\"darkgrid\")\ntips = sns.load_dataset(\"tips\")\n\ng = sns.FacetGrid(tips, col=\"da...
[ 4 ]
[]
[]
[ "facet", "matplotlib", "python", "seaborn" ]
stackoverflow_0074141227_facet_matplotlib_python_seaborn.txt
Q: How to get the unique string values in a column with numbers and characters in python I want to print the unique values taken in this column and not the numerical ones. I only want to output the values taken before the special characters (when there is one) and I don't want the second part of the string. For examp...
How to get the unique string values in a column with numbers and characters in python
I want to print the unique values taken in this column and not the numerical ones. I only want to output the values taken before the special characters (when there is one) and I don't want the second part of the string. For example for the row "lala :59 lzenvke" I don't want to take into account "lzenvke" but only "lal...
[ "here is one way about it\nAssumption: rows that don't have : are also included in the result set\nimport numpy as np\n\n# split the values on colon (:), limited to 1 split, and form list (with expand)\n# take the first element\n# find unique using np.unique\n# finally create a DF\n\n\npd.DataFrame(np.unique(df['co...
[ 1 ]
[]
[]
[ "character", "dataframe", "python", "string", "unique" ]
stackoverflow_0074141601_character_dataframe_python_string_unique.txt
Q: compare two files line by line and write unmatched line to another file I have two text file. I have to compare two files line by line and write unmatched lines to another file. suppose my file is like this: file_1.txt 000b423573 bdbaskbjejbajbkjfsjba 00036713dc sjgdjgdgdjadgygdeg263 00123fd351 heqgrg63u1quidg87gd...
compare two files line by line and write unmatched line to another file
I have two text file. I have to compare two files line by line and write unmatched lines to another file. suppose my file is like this: file_1.txt 000b423573 bdbaskbjejbajbkjfsjba 00036713dc sjgdjgdgdjadgygdeg263 00123fd351 heqgrg63u1quidg87gduq 0105517f52 vgfeeyguuiduiueyruuur and another file, file_2.txt 000b423573 ...
[ "There might be duplicated lines in the files and using a set function, we will lose them. We can loop through the first file content and add the unique line to a result list to get the unmatched lines from first file. We can do the same for the second file to get the unmatched lines from second file.\nfile_1_conte...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074140681_python.txt
Q: How to recalculate data from table in flask/python? I want to show df in my app, im using flask to do it. But how can i make the table editable and calculated sum value by using button? I couldn't found good and easy way to edit that html table, and somehow send it to backend to recalculate. Most tips i found abuo...
How to recalculate data from table in flask/python?
I want to show df in my app, im using flask to do it. But how can i make the table editable and calculated sum value by using button? I couldn't found good and easy way to edit that html table, and somehow send it to backend to recalculate. Most tips i found abuot editables tables involve data from sql and model. I'm n...
[ "You can convert your data to a matrix to present it on table with inputs. And when you press the button you grab the data from the table and make an AJAX request to send the data in JSON format to another route and recalculate the sum.\nAfter updating the data you just need to reload the page to see the changes.\n...
[ 1 ]
[]
[]
[ "flask", "pandas", "python" ]
stackoverflow_0074100065_flask_pandas_python.txt
Q: How can I get hold of a function reflectively within in the same module I need to be able to be able to call a function reflectively that's defined within the same module e.g a = getattr('foo_1') b = a(5) def foo_1(x) : return x*x This fails because getattr requires 2 params, but I don't know what to put for the...
How can I get hold of a function reflectively within in the same module
I need to be able to be able to call a function reflectively that's defined within the same module e.g a = getattr('foo_1') b = a(5) def foo_1(x) : return x*x This fails because getattr requires 2 params, but I don't know what to put for the first param, as there is no enclosing type or other module to import by name...
[ "Use globals to access the names in your module namespace:\ndef foo_1():\n print('hi')\n\n\nglobals()['foo_1']()\n\nResult:\nhi\n\n" ]
[ 1 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0074141721_python_reflection.txt
Q: Connect views.py to a Javascript file I'm working on a Django project showing PDF files from a dummy database. I have the function below in views.py to show the PDF files. def pdf_view(request): try: with open ('static/someData/PDF', 'rb') as pdf: response = HttpResponse(pdf.read(), content...
Connect views.py to a Javascript file
I'm working on a Django project showing PDF files from a dummy database. I have the function below in views.py to show the PDF files. def pdf_view(request): try: with open ('static/someData/PDF', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type="application/pdf") respon...
[ "Finally, I added an \"Iframe tag\" in the JavaScript file. Then there was no need to use the \"def pdf_view(request)\" function.\n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0074126982_django_javascript_python.txt
Q: function to change font color and weight based on condition I set up a summary dataframe to only show the high/low of 3 measures across the country and then color coded the negative values. I'm stuck on also bolding the negative values in the same step. When I try: color = '#AF0061' & 'font-weight: bold' It says...
function to change font color and weight based on condition
I set up a summary dataframe to only show the high/low of 3 measures across the country and then color coded the negative values. I'm stuck on also bolding the negative values in the same step. When I try: color = '#AF0061' & 'font-weight: bold' It says unsupported operand type(s) for &: 'str' and 'str', but I don't ...
[ "& is the binary addition operator. You might have meant + as @DonPre suggests, but that won't quite work either, as the properties should need to be separated by ;.\nI'm pretty sure the following works but don't have a df handy to test it against\ndef format_font(x):\n if x < 0:\n style = \"color: #AF00...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074141266_python.txt
Q: Dimensionality Reduction Autoencoder Pytorch I'm trying to use the Autoencoder which code you can see below as a tool for Dimensionality Reduction, I was wondering how can I "extract" the hidden layer and use it for my purpose My original Dataset went under Standard Scaling Here I define a Dictionary to centralize...
Dimensionality Reduction Autoencoder Pytorch
I'm trying to use the Autoencoder which code you can see below as a tool for Dimensionality Reduction, I was wondering how can I "extract" the hidden layer and use it for my purpose My original Dataset went under Standard Scaling Here I define a Dictionary to centralize the values CONFIG = { 'BATCH_SIZE' : 1024...
[ "You can simply return not just the decoded output, but also the encoded embedding layer, like this:\nclass AE(torch.nn.Module):\n def __init__(self):\n super().__init__()\n \n self.encoder = torch.nn.Sequential(\n torch.nn.Linear(31,16),\n torch.nn.ReLU(),\n ...
[ 1 ]
[]
[]
[ "autoencoder", "neural_network", "pandas", "python", "pytorch" ]
stackoverflow_0074141355_autoencoder_neural_network_pandas_python_pytorch.txt
Q: Tkinter How to cut widgets and labels that go beyond frame width? In my Code the user can add text and widgets to a Frame. Sometimes the row ends with a combobox, sometimes with a label. Sometimes these widgets go beyond the Frame. Is there any way to place widgets like Combobox in second row and to cut labels at ...
Tkinter How to cut widgets and labels that go beyond frame width?
In my Code the user can add text and widgets to a Frame. Sometimes the row ends with a combobox, sometimes with a label. Sometimes these widgets go beyond the Frame. Is there any way to place widgets like Combobox in second row and to cut labels at the end of the frame and place the rest of it also in the second row. T...
[ "A simple solution for putting widgets in a row and having them wrap when they do not fit is to use a text widget to manage the other widgets. A text widget has wrapping features built in.\nHere's an example that creates a couple of rows of widgets that need to wrap. Once the UI opens, you can resize it to see the ...
[ 0 ]
[]
[]
[ "combobox", "frame", "python", "tkinter", "widget" ]
stackoverflow_0074116291_combobox_frame_python_tkinter_widget.txt
Q: Python Matplotlib -> give each x axis a nummeric Label I want to give each x Point a Label. From 0 to Inf. The Label should be visible at the point, that is the highest. Function: def plot_pics(self, figure,title, x, a1, a2, a3, labelx, labely): ax = figure.add_subplot(111) ax.plot(x,a1,'-o') ...
Python Matplotlib -> give each x axis a nummeric Label
I want to give each x Point a Label. From 0 to Inf. The Label should be visible at the point, that is the highest. Function: def plot_pics(self, figure,title, x, a1, a2, a3, labelx, labely): ax = figure.add_subplot(111) ax.plot(x,a1,'-o') ax.plot(x,a2,'-o') ax.plot(x,a3,'-o') ax.legend([...
[ "Here is a minimal working example of what I think you want to achieve.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Random plotting data\nx_arr = np.arange(10)\nrand_arr = np.random.random((10, 3))\n\n# Plot everything\nplt.plot(x_arr, rand_arr, '-o')\n\n# Find maximas for every x-value\nrand_max_arr ...
[ 2 ]
[]
[]
[ "label", "matplotlib", "python" ]
stackoverflow_0074140671_label_matplotlib_python.txt
Q: question about python's csv.DictReader() when printing the first row I have a csv file named "employee_birthday.txt": name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March The followinng script manage to print the content properly: import csv with open('employee_birthday.txt', mode=...
question about python's csv.DictReader() when printing the first row
I have a csv file named "employee_birthday.txt": name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March The followinng script manage to print the content properly: import csv with open('employee_birthday.txt', mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) line_count...
[ "If you just add a simple print('loop') within your loop you'll see what's going on:\nimport csv\n\nwith open('test.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n print('loop') # prints once per loop\n if line_count == 0:\n ...
[ 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074141865_csv_python.txt
Q: TypeError: fromisoformat: argument must be str I have accidentally made '1' the default value for the models.DateField(). Now Django throws an error everytime I try to migrate, even if I delete the CharacterField / change the default value using (default=datetime.now()). Is there a way to fix this? Applying mainAp...
TypeError: fromisoformat: argument must be str
I have accidentally made '1' the default value for the models.DateField(). Now Django throws an error everytime I try to migrate, even if I delete the CharacterField / change the default value using (default=datetime.now()). Is there a way to fix this? Applying mainApp.0006_test_date...Traceback (most recent call last)...
[ "You can remove the 0006_*****.py migration in the dirs apps/app/migrations if it is the last one, and recreate the migration after change the default value in your field by using command makemigrations\nIf it is not the last one, you have to remove all next after 0006_***, change the default value of your DateFiel...
[ 2, 0 ]
[]
[]
[ "database", "django", "model", "python" ]
stackoverflow_0074141749_database_django_model_python.txt
Q: Dynamically pull query in FLASK I have a small application built in flask and also I am new to it and hence learning it Appreciate if you could help me solve below ask. Right now, the all contents in the dataframe(2 rows) are displayed. Is there a way to display only what is selected in the dropdown(say 'Karan' so...
Dynamically pull query in FLASK
I have a small application built in flask and also I am new to it and hence learning it Appreciate if you could help me solve below ask. Right now, the all contents in the dataframe(2 rows) are displayed. Is there a way to display only what is selected in the dropdown(say 'Karan' so only row with Karan should be displa...
[ "The following example shows you how you can use the form data transmitted via a GET request to filter your DataFrame.\nThe user can select several entries from a list of names and submit the form. All selected entries are now queried on the server side using the name of the form field. Then the rows of the DataFra...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074106490_flask_python.txt
Q: Calculations based on values from 2 tables I am trying to find the farthest point by coordinates. I have 2 data tables: data={'X':[1,1,1,3,4],'Y':[1,2,4,3,5]} data=pd.DataFrame(data) points={'ID':['1','2','3','4'],'X':[1,2,4,5],'Y':[3,3,4,1]} points=pd.DataFrame(points) I would like to determine which point from...
Calculations based on values from 2 tables
I am trying to find the farthest point by coordinates. I have 2 data tables: data={'X':[1,1,1,3,4],'Y':[1,2,4,3,5]} data=pd.DataFrame(data) points={'ID':['1','2','3','4'],'X':[1,2,4,5],'Y':[3,3,4,1]} points=pd.DataFrame(points) I would like to determine which point from the "points" table is the farthest one from the...
[ "I think you want to do something like this:\ndata={'X':[1,1,1,3,4],'Y':[1,2,4,3,5]}\ndata=pd.DataFrame(data)\n\npoints={'ID':['1','2','3','4'],'X':[1,2,4,5],'Y':[3,3,4,1]}\npoints=pd.DataFrame(points)\n\ndef distance(x1, x2, y1, y2):\n return np.sqrt(\n ((x2-x1)**2) + ((y2-y1)**2)\n )\n \nresults =...
[ 0, 0 ]
[]
[]
[ "dataframe", "if_statement", "lambda", "loops", "python" ]
stackoverflow_0074141542_dataframe_if_statement_lambda_loops_python.txt
Q: How to sort a list based of values inside it's elements? Knowing that the values inside the list num, num2 will change, the idea is to sort the output list, or the lists that form the output, based on the sorted num2. This is the code: letter = ['A','B','C','D','E'] num = [7,6,1,1,1] num2 = [24000,20900,5250,4500,...
How to sort a list based of values inside it's elements?
Knowing that the values inside the list num, num2 will change, the idea is to sort the output list, or the lists that form the output, based on the sorted num2. This is the code: letter = ['A','B','C','D','E'] num = [7,6,1,1,1] num2 = [24000,20900,5250,4500,5000] output = [] for i in range(len(letter)): output.app...
[ "zip then sort:\noutput = sorted(zip(letter, num, num2), key=lambda x: x[2], reverse=True)\nprint(*output)\n\nOutput:\n[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('E', 1, 5000), ('D', 1, 4500)]\n\n", "Using list comprehension you could avoid the temporary assignment altogether as well.\n[(x, y, z) for x, ...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074141643_list_python.txt
Q: Trim dataframe by total of column Let's say that I have a data frame with a column named subtotal, and I want to extract a sub-data frame with a maximum sum of all subtotal l = [100, 200, 300, 400, 500] df = pd.DataFrame(l) Here, I want to get a df with maximum value of 1000, in this case, should return [100, 20...
Trim dataframe by total of column
Let's say that I have a data frame with a column named subtotal, and I want to extract a sub-data frame with a maximum sum of all subtotal l = [100, 200, 300, 400, 500] df = pd.DataFrame(l) Here, I want to get a df with maximum value of 1000, in this case, should return [100, 200, 300, 400] How can I do this using pa...
[ "here is one way to do it\n#take cumsum and choose only rows that are at or below the threshold\n\ndf.loc[df[0].cumsum()<=1000]\n\n0\n0 100\n1 200\n2 300\n3 400\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074141962_pandas_python.txt
Q: How do i know what classes can this model predict? Lets say i got a pretrained model model.pt how do i know what classes can this model predict? i think it is saved inside the model but how do I extract it? Im trying to understand what https://github.com/AndreyGuzhov/AudioCLIP does it has a pretrained AudioCLIP-F...
How do i know what classes can this model predict?
Lets say i got a pretrained model model.pt how do i know what classes can this model predict? i think it is saved inside the model but how do I extract it? Im trying to understand what https://github.com/AndreyGuzhov/AudioCLIP does it has a pretrained AudioCLIP-Full-Training.pt how do I know the labels or classes insi...
[ "take a look at its demo notebook: https://github.com/AndreyGuzhov/AudioCLIP/blob/master/demo/AudioCLIP.ipynb.\nAs a CLIP model, the labels used in classification is an model inputs.\n", "As @lauthu already said, the first place to look would be the Notebook:\nhttps://github.com/AndreyGuzhov/AudioCLIP/blob/master...
[ 0, 0 ]
[]
[]
[ "classification", "machine_learning", "python", "pytorch" ]
stackoverflow_0074134706_classification_machine_learning_python_pytorch.txt
Q: how to remove the contents of a column without deleting the column in pandas I am trying to delete the contents of a column but would like to keep the column. For instance I have a table like. Numbers1 Numbers2 Numbers3 Numbers4 Numbers5 five four three two two six seven eight nine ten nine seven four two two ...
how to remove the contents of a column without deleting the column in pandas
I am trying to delete the contents of a column but would like to keep the column. For instance I have a table like. Numbers1 Numbers2 Numbers3 Numbers4 Numbers5 five four three two two six seven eight nine ten nine seven four two two seven six five three one I would like to remove all the contents of ...
[ "try:\ndf['Numbers2']='' #empty string\n\ndf['Numbers2']=np.nan #nan\n\n", "Simply assign an \"empty\" value (NaN, empty string, None, whatever you want):\ndf['Numbers2'] = float('NaN')\n\noutput:\n Numbers1 Numbers2 Numbers3 Numbers4 Numbers5\n0 five NaN three two two\n1 six ...
[ 1, 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074141926_pandas_python.txt
Q: How to count how many times a substring appears in string Say I have a string of s1 and s2. I wanted to be able to make a program which tells how many times s1 appears in s2. This is my attempt: char1 = int(input("number of character of s1: ")) s1 = str(input("insert string 1: ")) char2 = int(input("number of char...
How to count how many times a substring appears in string
Say I have a string of s1 and s2. I wanted to be able to make a program which tells how many times s1 appears in s2. This is my attempt: char1 = int(input("number of character of s1: ")) s1 = str(input("insert string 1: ")) char2 = int(input("number of character of s2: ")) s2 = str(input("insert string 2: ")) n = 0 boo...
[ "You could use a comprehension / generator expression to match and count -\ntimes = sum(1 if word == s1 else 0 for word in s2.split())\nprint(f's1 appears {times} times in s2') \n\nOutput\ns1 appears 3 times in s2\n\n", "You could repeatedly compare the wanted string to slices of the target string. For instance, ...
[ 1, 1, 0 ]
[]
[]
[ "arrays", "python", "string" ]
stackoverflow_0074141486_arrays_python_string.txt
Q: How to select certain values from JSON to build Pandas dataframe? I use the requests module to hit an endpoint and get back a JSON response: response = requests.get(endpoint, auth=(user_name, api_key)).json() The response looks like this: {'SalesInfoStatus': {'next_offset': 15, 'sales': [{'saSalesID': '761S-166...
How to select certain values from JSON to build Pandas dataframe?
I use the requests module to hit an endpoint and get back a JSON response: response = requests.get(endpoint, auth=(user_name, api_key)).json() The response looks like this: {'SalesInfoStatus': {'next_offset': 15, 'sales': [{'saSalesID': '761S-1666031549-adhoc-0:0', 'identifier': '761', 'origin': 'New York', ...
[ "You can use pd.json_normalize on the list value of sales key\ndf = pd.json_normalize(response['SalesInfoStatus']['sales'])[['filed_time.date', 'origin', 'destination', 'identifier']]\n\nprint(df)\n\n filed_time.date origin destination identifier\n0 10/19/2022 New York London 761\n1 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074141942_pandas_python.txt
Q: ubuntu: rollback all installation to an early date Before this day, I was having this one version of python on my machine (python3.10). Now after installing anaconda, which didn't work unfortunately, and I uninstalled it, I am left with several python-related files that I don't really have before. As I start typin...
ubuntu: rollback all installation to an early date
Before this day, I was having this one version of python on my machine (python3.10). Now after installing anaconda, which didn't work unfortunately, and I uninstalled it, I am left with several python-related files that I don't really have before. As I start typing python, I see them. $ pyth python python3...
[ "This works for me.\nList of packages installed today:\n$ grep \"2022-10-20.*.install \" /var/log/dpkg.log | awk '{ print $4 }' | cut -d: -f1\npython3-backcall\npython3-decorator\npython3-parso\npython3-jedi\npython3-traitlets\npython3-matplotlib-inline\npython3-pickleshare\npython3-wcwidth\n...\n\nThen uninstalled...
[ 0 ]
[]
[]
[ "python", "ubuntu", "ubuntu_22.04" ]
stackoverflow_0074141863_python_ubuntu_ubuntu_22.04.txt
Q: Using regex expresion to create a new Dataframe Column I have the following Python DataFrame: | ColumnA | File | | -------- | -------------- | | First | aasdkh.xls | | Second | sadkhZ.xls | | Third | asdasdPH.xls | | Fourth | adsjklahsd.xls | and so on. I'm trying to get the followi...
Using regex expresion to create a new Dataframe Column
I have the following Python DataFrame: | ColumnA | File | | -------- | -------------- | | First | aasdkh.xls | | Second | sadkhZ.xls | | Third | asdasdPH.xls | | Fourth | adsjklahsd.xls | and so on. I'm trying to get the following DataFrame: | ColumnA | File | Category| | --...
[ "Let's try\ndf['Category'] = df['File'].str.extract('(Z|PH)\\.xls$').fillna('N')\n\nprint(df)\n\n ColumnA File Category\n0 First aasdkh.xls N\n1 Second sadkhZ.xls Z\n2 Third asdasdPH.xls PH\n3 Fourth adsjklahsd.xls N\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python", "regex" ]
stackoverflow_0074142065_pandas_python_regex.txt
Q: NotImplementedError: pd.Grouper is currently not supported by Dask I want to use pd.Grouper inside a Dask Dataframe but I get NotImplementedError: pd.Grouper is currently not supported by Dask A sample dataframe: import dask.dataframe as dd data_dict = { "FaturaTarih": { 0: Timestamp("2021-10-04 00:...
NotImplementedError: pd.Grouper is currently not supported by Dask
I want to use pd.Grouper inside a Dask Dataframe but I get NotImplementedError: pd.Grouper is currently not supported by Dask A sample dataframe: import dask.dataframe as dd data_dict = { "FaturaTarih": { 0: Timestamp("2021-10-04 00:00:00"), 1: Timestamp("2021-12-18 00:00:00"), 2: Timesta...
[ "pd.Grouper is not supported in dask, as documented in this PR.\nYou can, however, group by using df.FaturaTarih.dt.year and df.FaturaTarih.dt.month, as shown in my code below:\nimport dask.dataframe as dd\nimport pandas as pd\n\ndata_dict = {\n \"FaturaTarih\": {\n 0: pd.Timestamp(\"2021-10-04 00:00:00\"...
[ 2 ]
[]
[]
[ "dask", "dataframe", "pandas", "python" ]
stackoverflow_0074110189_dask_dataframe_pandas_python.txt
Q: "not a supported wheel on this platform" error installing pyodbc on Windows 10 This has been asked before and there are some git threads also online, but none of these solutions are working for me and I can't figure out why. I'm running windows 10 and have a python Flask project running inside a venv. I need to co...
"not a supported wheel on this platform" error installing pyodbc on Windows 10
This has been asked before and there are some git threads also online, but none of these solutions are working for me and I can't figure out why. I'm running windows 10 and have a python Flask project running inside a venv. I need to connect to a SQL Server database to retrieve data and so I am trying to install PYODBC...
[ "Your venv is apparently not running the version of Python that you think it is. For example, if my venv is running 64-bit Python 3.9 and I try to install the wheel for 64-bit Python 3.10 I get the error\n(venv) PS C:\\Users\\Gord\\git\\so74122423> pip install .\\pyodbc-4.0.32-cp310-cp310-win_amd64.whl\nERROR: pyod...
[ 0 ]
[]
[]
[ "pyodbc", "python" ]
stackoverflow_0074122423_pyodbc_python.txt
Q: Get in python what web server is used by a website How can I know if a website is using apache, nginx or other and get this information in python? Thanks in advance A: This information if available is given in the header of the response to a HTTP Request. With Python you can perform HTTP requests using the modul...
Get in python what web server is used by a website
How can I know if a website is using apache, nginx or other and get this information in python? Thanks in advance
[ "This information if available is given in the header of the response to a HTTP Request. With Python you can perform HTTP requests using the module requests.\nMake a simple GET request to the interested site and then print the headers parameter of the returned object.\nimport requests\nr = requests.get(YOUR_SITE)\n...
[ 0 ]
[]
[]
[ "http", "python", "server", "web" ]
stackoverflow_0074142150_http_python_server_web.txt
Q: Drag button inside a field to a set boundary It's been a number of years since I asked for help. I'm creating a number of drag and drop buttons inside a frame. When the button is released It triggers that works fine. I have set up a boundary inside the button_drag().The problem I'm having is if the button is dragg...
Drag button inside a field to a set boundary
It's been a number of years since I asked for help. I'm creating a number of drag and drop buttons inside a frame. When the button is released It triggers that works fine. I have set up a boundary inside the button_drag().The problem I'm having is if the button is dragged right up to the boundary the button fails to tr...
[ "The normal behavior of buttons is to not call their command if you release the mouse button when the cursor is not over the button. This allows the user to prevent the button from being clicked if they change their mind after pressing the button.\nIf you want the button to be triggered no matter where the cursor i...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074141998_python_tkinter.txt
Q: Using proxies with playwright in python I'm using playwright to extract data from a website and I want to use proxies which I get from this website : https://www.proxy-list.download/HTTPS. It doesn't work, and I'm wondering if this is because the proxies are free ? If this is the reason, can someone know where can...
Using proxies with playwright in python
I'm using playwright to extract data from a website and I want to use proxies which I get from this website : https://www.proxy-list.download/HTTPS. It doesn't work, and I'm wondering if this is because the proxies are free ? If this is the reason, can someone know where can i find proxies that will work ? This is my c...
[ "Yes, according to your link, all proxies are \"dead\"\nBefore using proxies try checking them here is one possible solution:\nimport json\nimport requests\nfrom pythonping import ping\nfrom concurrent.futures import ThreadPoolExecutor\n\n\ncheck_proxies_url = \"https://httpbin.org/ip\"\ngood_proxy = set()\n\n# pro...
[ 0 ]
[]
[]
[ "playwright", "playwright_python", "proxy", "python", "web_scraping" ]
stackoverflow_0074136702_playwright_playwright_python_proxy_python_web_scraping.txt
Q: Logging in Custom Handler for TorchServe I have written a custom handler for an DL model using torch-serve and am trying to understand how to add manual log messages to the handler. I know that I can simply print any messages and it will show them within the MODEL_LOG logger at level INFO. What if I want to add a ...
Logging in Custom Handler for TorchServe
I have written a custom handler for an DL model using torch-serve and am trying to understand how to add manual log messages to the handler. I know that I can simply print any messages and it will show them within the MODEL_LOG logger at level INFO. What if I want to add a custom message at DEBUG level or ERROR level? ...
[ "I am trying to do something similar. I found example logger usage in base_handler.py, where the logger is initialized on line 23 as:\nlogger = logging.getLogger(__name__) and used in several places in the rest of the source file, typically as: logger.debug() or logger.warning(), etc. I am assuming that these messa...
[ 1 ]
[]
[]
[ "python", "pytorch", "torchserve" ]
stackoverflow_0073136920_python_pytorch_torchserve.txt
Q: Prevent change of workers of gunicorn between requests flask I'm using flask to develop my application with multiple routes. Running my application on my local machine with a single "thread", it works very well. When I deploy it the problem occurs. The following snippet represents the situation: object_a = None @...
Prevent change of workers of gunicorn between requests flask
I'm using flask to develop my application with multiple routes. Running my application on my local machine with a single "thread", it works very well. When I deploy it the problem occurs. The following snippet represents the situation: object_a = None @app.route(/route_a) def route_a(): global object_a object_a ...
[ "When you run multiple workers, there will be separate processes\nAnd separate processes can't share data directly.\nYou need to use some kind of IPC to share your object, or store it in external storage, e.g. Redis\n", "Like @aramcpp said, you'll need to use IPC (inter-process comm) because I believe gunicron sp...
[ 0, 0 ]
[]
[]
[ "flask", "gunicorn", "python" ]
stackoverflow_0074141871_flask_gunicorn_python.txt
Q: Pandas apply value from a JSON into a dataframe I have the following JSON file: {"xx":1,"bb":2,"cc":3} I want to add a column to a data frame by using the value from the JSON My data frame df = pd.DataFrame([{"region": "xx"}, {"region": "xx"}, {"region": "cc"}]) So, using the column region, I want to add a colum...
Pandas apply value from a JSON into a dataframe
I have the following JSON file: {"xx":1,"bb":2,"cc":3} I want to add a column to a data frame by using the value from the JSON My data frame df = pd.DataFrame([{"region": "xx"}, {"region": "xx"}, {"region": "cc"}]) So, using the column region, I want to add a column with the value of the column region on the data fra...
[ "I think what you want is this:\ndf['value'] = df['region'].apply(my_dict.get)\n>>> df\n region value\n0 xx 1\n1 xx 1\n2 cc 3\n\nseries.apply creates a new series with the results of the function you pass it, so for the first row it will run my_dict.get('xx') and so on.\n", "IIUC, you...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074142243_pandas_python.txt
Q: Pandas on Apple Silicon M1 chip within the Ubuntu container I have a trouble understanding the issue here: We have Docker image ubuntu:20.04 MacBook Pro on M1 chip Old pandas version wheel (legacy system) Within our Docker image, we use Poetry to manage dependencies: [tool.poetry.dependencies] python = ">=3.8,<3...
Pandas on Apple Silicon M1 chip within the Ubuntu container
I have a trouble understanding the issue here: We have Docker image ubuntu:20.04 MacBook Pro on M1 chip Old pandas version wheel (legacy system) Within our Docker image, we use Poetry to manage dependencies: [tool.poetry.dependencies] python = ">=3.8,<3.9" pandas = [ { platform = "linux", url = "***/pandas-0.24....
[ "M1 is an arm64-based chip, but you try to install pandas for x86_64.\nI'm not a pythonist, but looks like you need to add a dependency for linux arm64:\npandas = [\n { platform = \"linux\", markers=\"platform_machine=='arm64'\" … # <- here\n { platform = \"linux\", markers=\"platform_machine=='x86_64'\", url...
[ 1 ]
[]
[]
[ "apple_m1", "docker", "pandas", "python" ]
stackoverflow_0074138804_apple_m1_docker_pandas_python.txt
Q: How do you create a Django HttpRequest object with the META fields populated? Is there a way to create an HttpRequest object in Django that has all of the cgi META variables present? I'm attempting to process a view, but can't figure out how to (easily) make the request object. I just want to make sure I'm not mak...
How do you create a Django HttpRequest object with the META fields populated?
Is there a way to create an HttpRequest object in Django that has all of the cgi META variables present? I'm attempting to process a view, but can't figure out how to (easily) make the request object. I just want to make sure I'm not making life harder than need be manually copying all the fields from an existing reque...
[ "First, I just want to clarify a couple things in your question:\n\nI'm attempting to process a view\n\nBy \"process a view\", I think you mean that you want to pass an HttpRequest object into your view's functions. This is usually done through a URL dispatcher.\n\nI just want to make sure I'm not making life harde...
[ 23, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0028182704_django_python.txt
Q: Unable to install hunspell library (python 3.9) on mac m1 I am using python 3.9 and macOS Big Sur with an m1 chip. I have been trying to use spell checking library (hunspell) in python for spelling correction. While following their official documentation from https://github.com/hunspell/hunspell I am getting the f...
Unable to install hunspell library (python 3.9) on mac m1
I am using python 3.9 and macOS Big Sur with an m1 chip. I have been trying to use spell checking library (hunspell) in python for spelling correction. While following their official documentation from https://github.com/hunspell/hunspell I am getting the following error after pip install hunspell : Complete output (12...
[ "I had the same error when trying to install cython_hunspell.\nI had to first clone it, then install locally for it to work properly :\ngit clone https://github.com/MSeal/cython_hunspell.git\ncd cython_hunspell\npip install .\n\nYou can test it works properly :\ncd ..\npython -c \"from hunspell import Hunspell; h =...
[ 0 ]
[ "Firstly, you make sure to install gcc by using brew install gcc command. After that you can use brew install hunspell command for installation.\n" ]
[ -1 ]
[ "homebrew", "macos", "pip", "python" ]
stackoverflow_0072127156_homebrew_macos_pip_python.txt
Q: How can I optimize this Python code for Codewars? The task is: You are given a node that is the beginning of a linked list. This list contains a dangling piece and a loop. Your objective is to determine the length of the loop. The Codewars compiler throws the error "Execution Timed Out (12000 ms)", although the ...
How can I optimize this Python code for Codewars?
The task is: You are given a node that is the beginning of a linked list. This list contains a dangling piece and a loop. Your objective is to determine the length of the loop. The Codewars compiler throws the error "Execution Timed Out (12000 ms)", although the code works as intended. Please help me optimize my code...
[ "This algorithm is better then prevous, because in the end, when we looking for element's index, it's faster to get it by using dictionary, because dictionary is a hash map, that search any item for time O(1). So all the problem in my previous solution, was the using arr.index(currentElement) , and this method is r...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074141620_python.txt
Q: Python PULP optimization - LpVariable across THREE factors? Is it possible to create an LpVariable in Python PULP across three variables? So far, I've had success using the combination of two variables - here's an example using the combination of Basketball Player and Basketball Position. The optimizer will choose...
Python PULP optimization - LpVariable across THREE factors?
Is it possible to create an LpVariable in Python PULP across three variables? So far, I've had success using the combination of two variables - here's an example using the combination of Basketball Player and Basketball Position. The optimizer will choose combinations of players+positions that each one will play at to ...
[ "Sure. The indices can be arbitrarily dimensional. You'll probably want to gin up a few convenience sets to make this easier to write your constraints, etc. Here is an example for your 3-tuple index\nimport pulp\n\n\n# SETS\n\nplayers = {'Jordan', 'Abdul Jabar', 'Johnson'}\npositions = {'FWD', 'CTR', 'GRD'}\ngam...
[ 1 ]
[]
[]
[ "optimization", "pulp", "python" ]
stackoverflow_0074141929_optimization_pulp_python.txt
Q: SciPy skewnormal fitting I am trying to fit data into a skew normal distribution using the SciPy Skewnorm package. However, I am failing to understand the usage properly as I cannot find proper documentation or examples on this matter. On the help section I found Documentation and trying to use skewnorm.fit() alon...
SciPy skewnormal fitting
I am trying to fit data into a skew normal distribution using the SciPy Skewnorm package. However, I am failing to understand the usage properly as I cannot find proper documentation or examples on this matter. On the help section I found Documentation and trying to use skewnorm.fit() along with skewnorm.pdf() to fit d...
[ "Here is an example to get you started.\n>>> from scipy import stats\n\n# choose some parameters\n>>> a, loc, scale = 1.3, -0.1, 2.2\n# draw a sample\n>>> sample = stats.skewnorm(a, loc, scale).rvs(1000)\n\n# estimate parameters from sample\n>>> ae, loce, scalee = stats.skewnorm.fit(sample)\n>>> ae\n1.2495366661560...
[ 9, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0050140371_python_scipy.txt
Q: Handling table with two classes to fit a simple classifier I have this dataframe with euclidean distances: import pandas as pd df = pd.DataFrame({ 'O1': [0.0, 1.7, 1.4, 0.4, 2.2, 3.7, 5.2, 0.2, 4.3, 6.8, 6.0], 'O2': [1.7, 0.0, 1.0, 2.0, 1.3, 2.6, 4.5, 1.8, 3.2, 5.9, 5.2], 'O3': [1.4, 1.0, 0.0, 1.7, 0...
Handling table with two classes to fit a simple classifier
I have this dataframe with euclidean distances: import pandas as pd df = pd.DataFrame({ 'O1': [0.0, 1.7, 1.4, 0.4, 2.2, 3.7, 5.2, 0.2, 4.3, 6.8, 6.0], 'O2': [1.7, 0.0, 1.0, 2.0, 1.3, 2.6, 4.5, 1.8, 3.2, 5.9, 5.2], 'O3': [1.4, 1.0, 0.0, 1.7, 0.9, 2.4, 4.1, 1.5, 3.0, 5.5, 4.8], 'O4': [0.4, 2.0, 1.7, 0.0...
[ "You mainly want to include the point name as an additional column in the dataframe. Here I am using point indices as x and y:\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n 1: [0.0, 1.7, 1.4, 0.4, 2.2, 3.7, 5.2, 0.2, 4.3, 6.8, 6.0],\n 2: [1.7, 0.0, 1.0, 2.0, 1.3,...
[ 0 ]
[]
[]
[ "machine_learning", "pandas", "python", "regression" ]
stackoverflow_0074142062_machine_learning_pandas_python_regression.txt
Q: Loop through list of dictionaries if certain values to create a new list I am working on a project off codecademy focusing on creating custom iterable classes and having trouble figuring out this section. I have a list of dictionaries of students, example below: student_roster = [ { "name": "Karina M", "...
Loop through list of dictionaries if certain values to create a new list
I am working on a project off codecademy focusing on creating custom iterable classes and having trouble figuring out this section. I have a list of dictionaries of students, example below: student_roster = [ { "name": "Karina M", "age": 8, "height": 48, "favorite_subject": "Math", "favorite_anima...
[ "student_roster[i][key] == \"Math\" or \"Science\"\n\nThis will alwayse evaluate True because the interpreter does not compare your entry to both \"Math\" and \"Science\", but only to \"Math\" and will then evaluate the expression\nif \"Science\"\n\nas a standalone thing.\nYou have to do\nstudent_roster[i][key] == ...
[ 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0074141712_dictionary_loops_python.txt
Q: how to modify python logging module name in formatter I've got my python logger configured like this in one of my projects. Logging from certain modules in subfolders makes the %(name)s very long and therefore hard to read the logs. Can I modify the string to only show the actual module name, not the full hierarch...
how to modify python logging module name in formatter
I've got my python logger configured like this in one of my projects. Logging from certain modules in subfolders makes the %(name)s very long and therefore hard to read the logs. Can I modify the string to only show the actual module name, not the full hierarchy? code import logging import time def run(): logforma...
[ "I found the line in the Python logging code where the message is created from the record. You can simply override this function with your own implementation.\nThere you can for example split the name of the module and overwrite the name in the dct with the first module level name.\nIf before A.B.C was printed as n...
[ 0 ]
[]
[]
[ "logging", "python", "python_3.x" ]
stackoverflow_0066297595_logging_python_python_3.x.txt
Q: How do i calculate the time period in days for which the customer was active using pandas? How do i calculate the time period in days for which the customer was active using pandas? A: from datetime import datetime def days_between(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.strptime(d...
How do i calculate the time period in days for which the customer was active using pandas?
How do i calculate the time period in days for which the customer was active using pandas?
[ "from datetime import datetime\n\ndef days_between(d1, d2):\n d1 = datetime.strptime(d1, \"%Y-%m-%d\")\n d2 = datetime.strptime(d2, \"%Y-%m-%d\")\n return abs((d2 - d1).days)\n\n\n" ]
[ 0 ]
[]
[]
[ "data_science", "pandas", "python" ]
stackoverflow_0074142259_data_science_pandas_python.txt
Q: python colorbar can set only one value to be a specific value? My image has a donut shape and I only want to have different colors on that donut shape. Other than that want to make it black. How to set only the background to be black? fig, axe = plt.subplots() im2 = axe.imshow(data1, vmin=-30, vmax=5, cmap...
python colorbar can set only one value to be a specific value?
My image has a donut shape and I only want to have different colors on that donut shape. Other than that want to make it black. How to set only the background to be black? fig, axe = plt.subplots() im2 = axe.imshow(data1, vmin=-30, vmax=5, cmap='viridis') cbar_ax = fig.add_axes([1, 0.15, 0.04, 0.7]) fig...
[ "Try getting the color map and setting the value for 0 yourself:\ncmap = mpl.cm.get_cmap(\"viridis\").copy()\ncmap.set_under(color='black') \nim2 = axe.imshow(data1, vmin=0.0000001, vmax=5, cmap=cmap)\n\n" ]
[ 0 ]
[]
[]
[ "background", "colorbar", "colormap", "python" ]
stackoverflow_0074142457_background_colorbar_colormap_python.txt
Q: How to check multiple columns for matching regex rules to output in another column in PySpark My dataframe: I have to check if the value in each column matches a certain rule. For example: If column 'a' has a number, column 'b' has xx or yy, column 'c' has 1 or 2, and column 'd' has 0 -> then the output should b...
How to check multiple columns for matching regex rules to output in another column in PySpark
My dataframe: I have to check if the value in each column matches a certain rule. For example: If column 'a' has a number, column 'b' has xx or yy, column 'c' has 1 or 2, and column 'd' has 0 -> then the output should be 'output1' It is not necessary that all columns should have rules. If a rule does not exist then i...
[ "The thing is, you pass every rule separately to the column. After you pass the first, the second overwrites the first, etc. So, if the first yielded \"output1\", the second would overwrite it with \"no matches found\". The third would overwrite both first results and return just \"output3\" + \"no matches found\"....
[ 3, 3 ]
[]
[]
[ "apache_spark", "multiple_columns", "multiple_conditions", "pyspark", "python" ]
stackoverflow_0074141523_apache_spark_multiple_columns_multiple_conditions_pyspark_python.txt