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: autoscroll of text and scrollbar in python text box I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom a...
autoscroll of text and scrollbar in python text box
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always s...
[ "You can cause the text widget to scroll to any location with the see which takes an index.\nFor example, to make the last line of the widget visible you can use the index \"end\":\noutputwindow.see(\"end\")\n\nHere's a complete working example:\nimport time\ntry:\n # python 2.x\n import Tkinter as tk\nexcep...
[ 39, 14, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0030669015_python_tkinter.txt
Q: How to move plt.axhline I have a plot that my code is generating, example below: I am trying to find a way in which I can freely move the red line across the axis so it slides up and down, but so far I haven't found any guidance on how to do that, any advise would be appreciated, the code that generates the figur...
How to move plt.axhline
I have a plot that my code is generating, example below: I am trying to find a way in which I can freely move the red line across the axis so it slides up and down, but so far I haven't found any guidance on how to do that, any advise would be appreciated, the code that generates the figure is below: plt.figure() plt....
[ "Internally, the horizontal line is represented by x-values 0 and 1 and both corresponding y-values set to the given y-value. A \"y axis transform\" is used to tell that x should be interpreted as \"axis coordinates\", and y as \"data coordinates\". The matplotlib tutorial contains more information about coordinate...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074341009_matplotlib_python.txt
Q: Run py script with python.exe from specific conda env I use Anaconda3 and a specific environment rather than the base environment for my projects. The thing is that I cannot set my .py files to open with python.exe interpreter from that environment in anaconda3\envs\env1. When I right-click a py file, go to proper...
Run py script with python.exe from specific conda env
I use Anaconda3 and a specific environment rather than the base environment for my projects. The thing is that I cannot set my .py files to open with python.exe interpreter from that environment in anaconda3\envs\env1. When I right-click a py file, go to properties and set it to open with python.exe for that env and ru...
[]
[]
[ "You can set the python environment at the top of your python script.\nLike this:\n#!/usr/bin/env /user/anaconda3/envs/test/bin/python\n\ncode \n\nhere change /user/anaconda3/envs/test/bin/python to your python conda env path\n" ]
[ -1 ]
[ "anaconda3", "conda", "interpreter", "python", "windows" ]
stackoverflow_0074346382_anaconda3_conda_interpreter_python_windows.txt
Q: How to put Scrollbar inside a Listbox in Tkinter? how can i move the scrollbar inside a listbox? See the photo attached i used a red arrow for explain, here is my code: from tkinter import * window = Tk() window.geometry('500x500') window.config(bg='#3c3f41') window.state('zoomed') frame_listbox = Frame(window,bg=...
How to put Scrollbar inside a Listbox in Tkinter?
how can i move the scrollbar inside a listbox? See the photo attached i used a red arrow for explain, here is my code: from tkinter import * window = Tk() window.geometry('500x500') window.config(bg='#3c3f41') window.state('zoomed') frame_listbox = Frame(window,bg='#3c3f41') frame_listbox.pack(side=LEFT) listbox = List...
[ "It is recommended to put the scrollbar just to the right of the listbox instead of inside it. To achieve it:\n\nmake the scrollbar child of frame_listbox instead of window\nmove option padx=400 from scrollbar.pack(...) to frame_listbox.pack(...)\npack listbox to the LEFT side\n\nfrom tkinter import *\nwindow = Tk(...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074345552_python_tkinter.txt
Q: can I make a custom linestyle in matplotlib for plot made up of multiple parallel lines I am making a plot where I want to delineate two geological sections. To delineate I want to use three parallel dashed lines. I do not know how to make a multiline line in matplotlib. I made three sets of arrays that I offse...
can I make a custom linestyle in matplotlib for plot made up of multiple parallel lines
I am making a plot where I want to delineate two geological sections. To delineate I want to use three parallel dashed lines. I do not know how to make a multiline line in matplotlib. I made three sets of arrays that I offset. It looks okay but it is tedious to program and in some plots lines up really poorly. I d...
[ "You can use the Stroke path effects to re-draw the same line with a certain offset:\nimport matplotlib.pyplot as plt\nimport matplotlib.patheffects as path_effects\n\nPx = [23.6685,23.681,23.6935,23.706,23.7185,23.731,23.7435,23.756,23.7685,23.781,23.7935,23.806,23.8185,23.831,23.8435,23.856]\nPd = [17.5,22.5,27.5...
[ 1 ]
[]
[]
[ "linestyle", "matplotlib", "plot", "python" ]
stackoverflow_0074341371_linestyle_matplotlib_plot_python.txt
Q: how to delete for an empty row in a column in python csv I will like to delete all empty row in a column prices_dataframe[prices_dataframe['postcode'].isnull()] This only seems to be showing me the empty rows not deleting it. A: Is Null only returns the empty rows it does not drop them. Your empty rows should co...
how to delete for an empty row in a column in python csv
I will like to delete all empty row in a column prices_dataframe[prices_dataframe['postcode'].isnull()] This only seems to be showing me the empty rows not deleting it.
[ "Is Null only returns the empty rows it does not drop them. Your empty rows should contain NaN so you can use `prices_dataframe.dropna(inplace=True)\nTo drop them.\nIf your rows don't contain NaN you can first replace the empty rows with NaN\nprices_dataframe.replace('', np.nan, inplace=True) and then drop them\n",...
[ 0, 0 ]
[]
[]
[ "data_cleaning", "python", "rowdeleting" ]
stackoverflow_0074346672_data_cleaning_python_rowdeleting.txt
Q: how to fetch data from api and insert it inside new api code I am trying to fetch data from an existing api endpoint and using part of that data to create a new endpoint using python and fastapi, in this case I am trying to get the res_id from "https://www.zomato.com/mumbai/cuantos-kebabs-rolls-veera-desai-area" a...
how to fetch data from api and insert it inside new api code
I am trying to fetch data from an existing api endpoint and using part of that data to create a new endpoint using python and fastapi, in this case I am trying to get the res_id from "https://www.zomato.com/mumbai/cuantos-kebabs-rolls-veera-desai-area" and inserting it into my new object. I am relatively new to this an...
[ "Disclaimer: Hi, this is my first answer. I wanted to make a comment but I don't have enough rep\nThe link you gave is not an API, it's an html document. If you want to retrieve information from that url, you'll need a scrapper like BeautifulSoup (html parser) or Selenium (browser automation)\nAnyway, answering the...
[ 0 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0074346591_fastapi_python.txt
Q: Case Insensitive Dictionary Iteration I have a dictionary which has peoples' first names as keys. Each name has a capitalised first letter (James, Ben, John, etc). I use list comprehension to check if any keys are in a string: [val for key, val in name_dict.items() if key in new_message] The issue is that sometim...
Case Insensitive Dictionary Iteration
I have a dictionary which has peoples' first names as keys. Each name has a capitalised first letter (James, Ben, John, etc). I use list comprehension to check if any keys are in a string: [val for key, val in name_dict.items() if key in new_message] The issue is that sometimes the names appear in new_message without ...
[ "Use title() on new_message, it will capitalize all the words in the string\nnew_message = 'James, ben, JOHN'\nprint(new_message.title()) # James, Ben, John\n\n", "You can just lower the text while iterating,\nnew_message = [x.lower() for x in new_message]\n[val for key, val in name_dict.items() if key.lower() in...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074346684_python.txt
Q: how to check flow of bot in rasa (static bot)? I'm working with rasa chat bot and after writing stories(static flow). How do i insure that, flow is working properly or not? currently i'm testing each path manually!!! I want to check with all the possibility and want to make this task automated! A: You can define...
how to check flow of bot in rasa (static bot)?
I'm working with rasa chat bot and after writing stories(static flow). How do i insure that, flow is working properly or not? currently i'm testing each path manually!!! I want to check with all the possibility and want to make this task automated!
[ "You can define a story using a specific yml file starting with test and running rasa test it test the chatbot on the defined story. Here the documentation: https://rasa.com/docs/rasa/testing-your-assistant/\n" ]
[ 0 ]
[]
[]
[ "artificial_intelligence", "chatbot", "nlp", "python", "rasa" ]
stackoverflow_0074345984_artificial_intelligence_chatbot_nlp_python_rasa.txt
Q: Retrieving variable value in Python from a class object I would like to access the variable values defined with a class but everything I try results in an error of one kind or another. I will include the extract of Python code which defines the class which reads and shows the day, time and date from a DS3231 real ...
Retrieving variable value in Python from a class object
I would like to access the variable values defined with a class but everything I try results in an error of one kind or another. I will include the extract of Python code which defines the class which reads and shows the day, time and date from a DS3231 real time clock: class ds3231(object): weekday = ["Sunday","M...
[ "Before reading a variable from a class, in that case a property, you have to declare and initialize it.\nyou could definitely do this within your read_time function by adding the self keyword:\nclass ds3231:\n\n...\n \n def read_time(self):\n t = self.bus.readfrom_mem(int(self.address), int(self.start_...
[ 1 ]
[]
[]
[ "class", "object", "python", "rational_team_concert", "variables" ]
stackoverflow_0074346648_class_object_python_rational_team_concert_variables.txt
Q: How to write an error code for my tkinter program I've got this program which takes some input from the user and saves it in a CSV file. Now I want to make an error code so that every time when the message of a user exceeds 140 characters, it tells them that the max number of characters is 140. How could I program...
How to write an error code for my tkinter program
I've got this program which takes some input from the user and saves it in a CSV file. Now I want to make an error code so that every time when the message of a user exceeds 140 characters, it tells them that the max number of characters is 140. How could I program this? import tkinter import csv import random from tki...
[ "Try it:\ndef get_data():\n global button\n Message_data = Message.get()\n if len(Message_data) > 140:\n messagebox.showerror(\"Error\", 'Error: Het bericht mag maximaal 140 tekens bevatten')\n return\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074346728_python_tkinter.txt
Q: Executing Terminal commands using Python in Mac I want to change the IP address of the machine continuously, SO after a lot of search i got this useful link https://github.com/jotyGill/openpyn-nordvpn . I have done the steps as per this URL and i tried the steps in terminal window(Mac) and it is successfully chang...
Executing Terminal commands using Python in Mac
I want to change the IP address of the machine continuously, SO after a lot of search i got this useful link https://github.com/jotyGill/openpyn-nordvpn . I have done the steps as per this URL and i tried the steps in terminal window(Mac) and it is successfully changing the IP. But the issue is that need to manually ru...
[ "I don't usually use mac but this might work:\nimport os\nimport time\n\nos.system(Command)\ntime.sleep(0.25)\nos.system(password)\n\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "python_3.x" ]
stackoverflow_0059983625_macos_python_python_3.x.txt
Q: How to install a specific version of python with pip, venv, and distutils on ubuntu I've recently had to debug a cython library for a specific version of python on ubuntu and I needed python, venv, distutils, cython, pip, a compiler, and a text editor. I had to go fishing around the web for instructions on how to...
How to install a specific version of python with pip, venv, and distutils on ubuntu
I've recently had to debug a cython library for a specific version of python on ubuntu and I needed python, venv, distutils, cython, pip, a compiler, and a text editor. I had to go fishing around the web for instructions on how to do this, so I'm asking this question to answer with what I did. I googled it and found i...
[ "I figured this out on ubuntu 20 in docker (I was running as root). If you are not running as root - this answer won't help you.\n# update the package manager\napt-get update\n\n# install git, C/C++ compiler and a text editor (I prefer vim)\napt install -y git software-properties-common curl build-essential vim\n\...
[ 1, 1 ]
[]
[]
[ "cython", "pip", "python", "python_venv", "ubuntu" ]
stackoverflow_0074346897_cython_pip_python_python_venv_ubuntu.txt
Q: Plotly ticks are weirdly alligned Let's take the following pd.DataFrame as an example df = pd.DataFrame({ 'month': ['2022-01', '2022-02', '2022-03'], 'col1': [1_000, 1_500, 2_000], 'col2': [100, 150, 200], }).melt(id_vars=['month'], var_name='col_name') which creates month col_name value ----...
Plotly ticks are weirdly alligned
Let's take the following pd.DataFrame as an example df = pd.DataFrame({ 'month': ['2022-01', '2022-02', '2022-03'], 'col1': [1_000, 1_500, 2_000], 'col2': [100, 150, 200], }).melt(id_vars=['month'], var_name='col_name') which creates month col_name value ----------------------------- 0 2022-01 c...
[ "You can solve it by customizing the step as 1 month per tick with dtick=\"M1\", as follows:\nimport pandas as pd\nimport plotly.express as px\n\ndf = pd.DataFrame({\n 'month': ['2022-01', '2022-02', '2022-03'],\n 'col1': [1000, 1500, 2000],\n 'col2': [100, 150, 200],\n}).melt(id_vars=['month'], var_name='...
[ 0 ]
[]
[]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074346320_plotly_plotly_python_python.txt
Q: How to make python argcomplete run with PowerShell I am trying to see if I can use argument autocompletion in Windows Powershell for my python script. Powershell allegedly supports argument completion. Here's a minimal example which does not work: #!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK import argparse impo...
How to make python argcomplete run with PowerShell
I am trying to see if I can use argument autocompletion in Windows Powershell for my python script. Powershell allegedly supports argument completion. Here's a minimal example which does not work: #!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK import argparse import argcomplete from argcomplete.completers import Envir...
[ "It is possible, you just need a wrapper script and mind the correct encoding\n parser = argument_parser()\n output_stream = None\n if \"_ARGCOMPLETE_POWERSHELL\" in os.environ:\n output_stream = codecs.getwriter(\"utf-8\")(sys.stdout.buffer)\n argcomplete.autocomplete(parser, output_stream=outpu...
[ 0 ]
[]
[]
[ "powershell", "python" ]
stackoverflow_0064970692_powershell_python.txt
Q: Non periodic square function train in python How can I plot a square-like (non periodic) signal like the one in the image using python? with0 "n" the number of pulses, "p" the time between them, pulse duration, amplitude and "offset" as variables. Already tried scipy.signal.square but im looking for a non periodi...
Non periodic square function train in python
How can I plot a square-like (non periodic) signal like the one in the image using python? with0 "n" the number of pulses, "p" the time between them, pulse duration, amplitude and "offset" as variables. Already tried scipy.signal.square but im looking for a non periodic solution.
[ "The thing to do is to just write some custom code, instead of built-in modules like to tried. For instance:\nfrom matplotlib import pyplot as plt\n\ndef plot_square_pulses(n, p, dur, amp, offset):\n plt.figure()\n for i in range(n):\n x1 = i * (p + dur) + offset\n x2 = x1 + dur\n plt.hli...
[ 0 ]
[]
[]
[ "pulse", "python", "signals" ]
stackoverflow_0074346099_pulse_python_signals.txt
Q: Python Welsh-Powell graph coloring I have implemented algorithm for Welsh-Powell graph coloring. Task is that you have txt document with lines of 2 numbers, in which the first one represent vertex and the second one represent its neighbor. Looks like this: 1 2 1 4 1 5 1 8 1 9 1 11 2 3 2 4 2 5 2 6 2 7 2 8 2 10 2 11...
Python Welsh-Powell graph coloring
I have implemented algorithm for Welsh-Powell graph coloring. Task is that you have txt document with lines of 2 numbers, in which the first one represent vertex and the second one represent its neighbor. Looks like this: 1 2 1 4 1 5 1 8 1 9 1 11 2 3 2 4 2 5 2 6 2 7 2 8 2 10 2 11 2 12 3 4 3 5 3 6 3 7 3 8 3 9 3 11 4 6 4...
[ "For me it is working. And it also gives your desired output\n1 1\n2 2\n3 1\n4 2\n\nI think it is about how you run the script. Because when I run\npython .\\main.py I also get\nTraceback (most recent call last):\n File \"C:\\Users\\fhdwnig\\Desktop\\main.py\", line 5, in <module>\n graph = file_to_graph(sys.ar...
[ 0 ]
[]
[]
[ "graph", "graph_coloring", "greedy", "python", "sat" ]
stackoverflow_0074346800_graph_graph_coloring_greedy_python_sat.txt
Q: pyconfig.h - Cannot open include file: 'io.h': No such file or directory Background: I am new to python/Cpp and I am trying to install a python package python-crfsuite which needs to VS to compile. I have installed Anaconda3, pyhon3.6 all in VS2017 community installer (because I think it is better because I will ...
pyconfig.h - Cannot open include file: 'io.h': No such file or directory
Background: I am new to python/Cpp and I am trying to install a python package python-crfsuite which needs to VS to compile. I have installed Anaconda3, pyhon3.6 all in VS2017 community installer (because I think it is better because I will use compiler of VS: cl.exe) I have already run vcvarsall.bat All commands I ru...
[ "I got the same error but I was installing a package. I solved installing more tools from Visual Studio (I'm using VS 2017 Community and Python 3.6.4). I installed those tools (see installer screenshot here):\n\nDesktop development with C++: I included all defaulted items and the next ones:\n\nWindows XP support fo...
[ 4, 0 ]
[]
[]
[ "anaconda", "c++", "python", "visual_studio_2017" ]
stackoverflow_0045007577_anaconda_c++_python_visual_studio_2017.txt
Q: Is it possible to find an element using multiple words using By.CLASS_NAME in selenium python? I am working on a browser bot and have encountered a problem. Every documentation has an example where an element is found(by class_name) using only one string that represents a class. My problem is that I want to use mo...
Is it possible to find an element using multiple words using By.CLASS_NAME in selenium python?
I am working on a browser bot and have encountered a problem. Every documentation has an example where an element is found(by class_name) using only one string that represents a class. My problem is that I want to use more than one string(more than one word) to find a class(to be more specific). Here is what every exam...
[ "No.\nTo locate element based on multiple class name values you should use CSS Selector or XPath.\nCSS_Selector:\nbrowser.find_element(By.CSS_SELECTOR, \".text-orange-400.transition.hover:opacity-70\")\n\nXPath\nbrowser.find_element(By.XPATH, \"//*[@class='text-orange-400 transition hover:opacity-70']\")\n\n" ]
[ 1 ]
[]
[]
[ "css_selectors", "python", "selenium_webdriver", "web_scraping", "xpath" ]
stackoverflow_0074347018_css_selectors_python_selenium_webdriver_web_scraping_xpath.txt
Q: How to transform str to bytes (not change every byte) in python? for example,how to change s to b here? s="\x00\x01\x02\x00\xad\xaa" b=b"\x00\x01\x02\x00\xad\xaa" I know str.encode() will return a encoded bytes, but it did not meet my expectations(because sometimes len(str)!=len(bytes)). I read some method change...
How to transform str to bytes (not change every byte) in python?
for example,how to change s to b here? s="\x00\x01\x02\x00\xad\xaa" b=b"\x00\x01\x02\x00\xad\xaa" I know str.encode() will return a encoded bytes, but it did not meet my expectations(because sometimes len(str)!=len(bytes)). I read some method change str to bytes such as encode/decode, base64, but all it can't meet my ...
[ "You can use python's built in encode method with raw_unicode_escape encoding to preserve literal escape sequences.\ns = '\\x00\\x01\\x02\\x00\\xad\\xaa'\nb = s.encode(encoding='raw_unicode_escape')\nprint(b)\n>>> b'\\x00\\x01\\x02\\x00\\xad\\xaa'\n\n" ]
[ 1 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0074347023_binary_python.txt
Q: Conda stuck when creating env from yml file Conda will not create an environment from the yml file OS: ubuntu 22.04 jammy jellyfish conda version: last available (py39, linux x86_64) name: env-name channels: - conda-forge - bioconda dependencies: - python>=3.5, <3.7 - cmake>=3.9, <3.11 - r-essentials - r-rgl...
Conda stuck when creating env from yml file
Conda will not create an environment from the yml file OS: ubuntu 22.04 jammy jellyfish conda version: last available (py39, linux x86_64) name: env-name channels: - conda-forge - bioconda dependencies: - python>=3.5, <3.7 - cmake>=3.9, <3.11 - r-essentials - r-rgl - pandas - numpy - scipy - scikit-learn - j...
[ "You can try by following these steps:\nconda config --remove channels conda-forge\nconda config --add channels conda-forge\n\nif it doesn't work then try this:\nconda update conda\n\nif nothing works try to see: https://github.com/conda/conda/issues/9367#issuecomment-558863143\n" ]
[ 0 ]
[]
[]
[ "bash", "conda", "python", "r", "yaml" ]
stackoverflow_0074335509_bash_conda_python_r_yaml.txt
Q: Python handling KeyError in nested JSON def get_users(): url = "https://blablabla/api/users" headers = {"Authorization": accessToken, "Content-Type": "application/json", "Accept": "application/json"} r = requests.get(url, headers=headers) r_dict = r.json() return r_dict get_user_function = get...
Python handling KeyError in nested JSON
def get_users(): url = "https://blablabla/api/users" headers = {"Authorization": accessToken, "Content-Type": "application/json", "Accept": "application/json"} r = requests.get(url, headers=headers) r_dict = r.json() return r_dict get_user_function = get_users() I get a JSON list with given reques...
[ "Instead of using brackets you can use dict.get function which does not throw KeyErrror but instead assigns None or a default value you pass as second argument.\ncreated = item.get(\"created\", \"2020-01-01 00:00:00.000 +0000 UTC\")\n\n", "I was dealing with the same problem of nested dictionaries with optional f...
[ 1, 0 ]
[]
[]
[ "json", "keyerror", "python" ]
stackoverflow_0074344838_json_keyerror_python.txt
Q: How to replace NaT in pandas dataframe with a date using information from other columns noob here. I have a dataframe that looks like this: start end start_year NaT NaT 2020 NaT NaT 2021 and I want to fill in the NaT's with the first and last day of the year listed in the start_year column. So it would look li...
How to replace NaT in pandas dataframe with a date using information from other columns
noob here. I have a dataframe that looks like this: start end start_year NaT NaT 2020 NaT NaT 2021 and I want to fill in the NaT's with the first and last day of the year listed in the start_year column. So it would look like this: start end start_year 2020-01-01 2020-12-31 2020 2021-01-01 2021-...
[ "Use:\n#if necessary\n#df['start'] = pd.to_datetime(df['start'])\n#df['end'] = pd.to_datetime(df['end'])\n\n#replace missing values by Year - first day and last day\ndf['start'] = df['start'].fillna(pd.to_datetime(df['start_year'],format='%Y'))\ndf['end'] = (df['end'].fillna(pd.to_datetime(df['start_year'].add(1), ...
[ 0, 0, 0 ]
[]
[]
[ "nan", "pandas", "python" ]
stackoverflow_0074346808_nan_pandas_python.txt
Q: Pygame installed but not available on enviroment Just started playing with pygame and when creating a new projetc in Pycharm, i'm not able to import pygame. From what i've read i have pygame intalled correctly (running Powershell in the pygame project folder PS C:\Users\54294\PycharmProjects\pygame> pip install py...
Pygame installed but not available on enviroment
Just started playing with pygame and when creating a new projetc in Pycharm, i'm not able to import pygame. From what i've read i have pygame intalled correctly (running Powershell in the pygame project folder PS C:\Users\54294\PycharmProjects\pygame> pip install pygame==2.1.2 Requirement already satisfied: pygame==2.1...
[ "It seems that your Python interpreter settings might be set incorrectly.\nPlease check your paths under File > Settings > Project > Python interpreter. Based on your log, it should be set to: c:\\users\\54294\\appdata\\local\\programs\\python\\Scripts\\python.exe\nHere, you can also check the installed packages of...
[ 0 ]
[]
[]
[ "pycharm", "pygame", "python" ]
stackoverflow_0074346947_pycharm_pygame_python.txt
Q: groupby with nth() and agg I have a dataframe and would like to groupby ìndex1 and get new columns for the first, 2nd, 3rd, fourth and last values of column A (if they exist). So I would like to use agg so I can aggregate all at once. But somehow that does not work with nth. What am I doing wrong? df = pd.DataFram...
groupby with nth() and agg
I have a dataframe and would like to groupby ìndex1 and get new columns for the first, 2nd, 3rd, fourth and last values of column A (if they exist). So I would like to use agg so I can aggregate all at once. But somehow that does not work with nth. What am I doing wrong? df = pd.DataFrame({'index1':[1,2,2,2,3,3], 'A':[...
[ "You can combine pivot and groupby.last:\ng = df.groupby('index1')\n\n(df.assign(col=g.cumcount().add(1))\n .pivot(index='index1', columns='col', values='A')\n .assign(last=g.last())\n .reset_index()\n)\n\noutput:\ncol index1 1 2 3 last\n0 1 1.0 NaN NaN 1\n1 2 1.0 2.0 3.0 ...
[ 1 ]
[]
[]
[ "aggregate", "aggregate_functions", "pandas", "python" ]
stackoverflow_0074346878_aggregate_aggregate_functions_pandas_python.txt
Q: Locally I get a connection error, in Lambda all I get is a Timeout I'm having trouble doing some very basic error handling in Lambda to identify connection issues with some databases (ElasticSearch and Neo4J). I'm using a fake IP to force a connection error. When I run the code locally I get the expected connectio...
Locally I get a connection error, in Lambda all I get is a Timeout
I'm having trouble doing some very basic error handling in Lambda to identify connection issues with some databases (ElasticSearch and Neo4J). I'm using a fake IP to force a connection error. When I run the code locally I get the expected connection error, but in Lambda, I get nothing, only a timeout. I already increas...
[ "Ok, after some debugging, trials and errors I managed to find a \"solution\". I added some code using socket to test the connection before attempting to use py2neo (which, as it seems, has no timeout treatment whatsoever in its methods).\nHere's my testing code, which works both locally and on Lambda:\ntry:\n s...
[ 0 ]
[]
[]
[ "aws_lambda", "neo4j", "py2neo", "python", "python_3.x" ]
stackoverflow_0074320221_aws_lambda_neo4j_py2neo_python_python_3.x.txt
Q: In python how to print a character before a matching pattern that occur multiple times? I have a stringified data from which I'm trying to print a character that occurs before a matching pattern. This matching pattern will occur multiple times so the result can also be a list of characters E.g Stringified data is ...
In python how to print a character before a matching pattern that occur multiple times?
I have a stringified data from which I'm trying to print a character that occurs before a matching pattern. This matching pattern will occur multiple times so the result can also be a list of characters E.g Stringified data is [[1, "[{\"name\": \"john\", \"id\": \"1\"}]", [2, "[{\"name\": \"john\", \"id\": \"1\"}]"] Th...
[ "Purely on the basis of what's asked in the question (and not wondering WHY?) one could do this:\nastring = '[[1, \"[{\\\"name\\\": \\\"john\\\", \\\"id\\\": \\\"1\\\"}]\", [2, \"[{\\\"name\\\": \\\"john\\\", \\\"id\\\": \\\"1\\\"}]\"]'\n\npattern = ', \"['\n\noffset = 0\npchars = []\n\nwhile (index := astring[offs...
[ 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074347149_python_string.txt
Q: How to chain a list of items with an operator Scenario I want to filter a dataframe in pandas. It should return a dataframe with all rows that have a numeric value in a list of columns - the length of the list is arbitrary. Example a b c 1 1 1 1 2 1 g 8 3 h 1 1 4 2 2 ...
How to chain a list of items with an operator
Scenario I want to filter a dataframe in pandas. It should return a dataframe with all rows that have a numeric value in a list of columns - the length of the list is arbitrary. Example a b c 1 1 1 1 2 1 g 8 3 h 1 1 4 2 2 2 If I call my function with columns [b, c], I ex...
[ "I would use a different approach, check the status as 2D and aggregate with all:\ncols = ['b', 'c']\n\ns = (df[cols].apply(pd.to_numeric, errors='coerce')\n .notna().all(axis=1)\n )\n\nout = s[s].index.to_list()\n\nOr, if you are sure to have strings as input:\ncols = ['b', 'c']\n\ns = (df[cols]\n .appl...
[ 4 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074346985_pandas_python.txt
Q: Python - paho.mqtt.client - WebSocket handshake error, connection not upgraded I'm trying to connect to an existing MQTT service (over websockets) that is not managed by me, using paho.mqtt.client. This is my code: import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected w...
Python - paho.mqtt.client - WebSocket handshake error, connection not upgraded
I'm trying to connect to an existing MQTT service (over websockets) that is not managed by me, using paho.mqtt.client. This is my code: import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("$SYS/#") def on_message(client, us...
[ "I found the solution, pretty stupid actually. By default paho.mqtt.client uses /mqtt as path. In my case I needed the root as path, so what I needed to do is just set it:\nclient.ws_set_options(path=\"/\")\n\nThe actual response from the service was 404, but the way the library code is written is recognizing it as...
[ 0 ]
[]
[]
[ "mqtt", "paho", "python", "python_paho", "websocket" ]
stackoverflow_0074344689_mqtt_paho_python_python_paho_websocket.txt
Q: How to create a GUI in Python without advanced libraries? I want to create a GUI, without Tkinter or any other library (preferably in Windows and CPython). Basically, if you go into the files of Python and its libraries, you can find the functions of the libraries. An example is the randint function of the random ...
How to create a GUI in Python without advanced libraries?
I want to create a GUI, without Tkinter or any other library (preferably in Windows and CPython). Basically, if you go into the files of Python and its libraries, you can find the functions of the libraries. An example is the randint function of the random library: def randint(self, a, b): """Return random integer ...
[ "okay ... that's too elaborate, all the functions to create and manipulate applications on windows are written in C and are stored in win32 api dlls on windows for example this is how you do it in C as stated in win32 docs\nthis program needs to be translated to python through ctypes, which will be calling C code f...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074346199_python.txt
Q: How to plot multiple scatterplots with trendlines as subplots using Plotly I'm trying to stack 12 interactive plots showing OLS result and the scattered X and Ys. However, I found it incredibly more difficult than I thought. I successfully drew a single OLS plot (fitted line + scatters) in multiple ways, but putti...
How to plot multiple scatterplots with trendlines as subplots using Plotly
I'm trying to stack 12 interactive plots showing OLS result and the scattered X and Ys. However, I found it incredibly more difficult than I thought. I successfully drew a single OLS plot (fitted line + scatters) in multiple ways, but putting them together is another story. So my dataset looks like this: ID tmax01 ...
[ "If you transform the data a little, you can include facet_row() in the px.scatter() call to make a facet / trellis plot like in the figure below with this setup:\nfig = px.scatter(dfs, y = 'regressand', x = 'regressor',\n facet_row = 'regressand_name',\n trendline = 'ols',...
[ 1 ]
[]
[]
[ "linear_regression", "pandas", "plotly", "plotly_python", "python" ]
stackoverflow_0074325447_linear_regression_pandas_plotly_plotly_python_python.txt
Q: Count Nan-Values per Column in an ndarray Problem: I have a ndarray (2000,7) and I want to count the numbers of Nan's per column and save it in an ndarray Tried: number_nan_in_arr = np.count_nonzero(np.isnan(arr)) But this count the total number of nan's over all columns Solution: ? A: Simply sum the True value...
Count Nan-Values per Column in an ndarray
Problem: I have a ndarray (2000,7) and I want to count the numbers of Nan's per column and save it in an ndarray Tried: number_nan_in_arr = np.count_nonzero(np.isnan(arr)) But this count the total number of nan's over all columns Solution: ?
[ "Simply sum the True values:\nnumber_nan_in_arr = np.isnan(arr).sum(0)\n\n", "You can add axis=0 to count null per column:\nnumber_nan_in_arr = np.count_nonzero(np.isnan(arr), axis=0)\n\nExample:\nimport numpy as np \n\na = np.array([[0, np.nan, 7, 0],\n [3, 0, 2, np.nan]])\nnp.count_nonzero(np.isnan...
[ 2, 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074347282_arrays_numpy_python.txt
Q: Common elements in two dataframe Having two data frame as below: data frame:1 new_data = { "Fruits": ['AB', 'AB','BC', 'CD','DE','EG'], "price": [50, 30, 45,55,47,43] } new_df = pd.DataFrame(new_data) print(new_df) dataframe:2 import pandas as pd data = { "Food": ['AB','AB','BC', 'CE','DE','EF','EM','FB'...
Common elements in two dataframe
Having two data frame as below: data frame:1 new_data = { "Fruits": ['AB', 'AB','BC', 'CD','DE','EG'], "price": [50, 30, 45,55,47,43] } new_df = pd.DataFrame(new_data) print(new_df) dataframe:2 import pandas as pd data = { "Food": ['AB','AB','BC', 'CE','DE','EF','EM','FB'], "Calories": [150, 405, 450,55,47,...
[ "You can use .loc[] with .isin() to check if a value in the Fruits from new_df exist in the Food column of df:\nnew_df.loc[new_df['Fruits'].isin(df['Food'])]\n\n Fruits price\n0 AB 50\n1 AB 30\n2 BC 45\n4 DE 47\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074347334_dataframe_python.txt
Q: Log all messages to non-root logger in python The docs for logging.Logger.setLevel state the following: When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that t...
Log all messages to non-root logger in python
The docs for logging.Logger.setLevel state the following: When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING. The t...
[ "\nHow do I make a non-root logger log all messages of any severity without delegating to a parent at any point?\n\nHere is an answer to your question:\nlogger = logging.getLogger('name') # non-root logger\nlogger.propagate = False # never delegate to a parent\nlogger.setLevel(logging.DEBUG) # debug is the lowest e...
[ 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0074312995_logging_python.txt
Q: MLFlow projects; bash: python: command not found I'm running MLflow Project for a model using following command from my ubuntu 20.04 terminal mlflow run . --no-conda -P alpha=0.5 My system doesn't have conda or python (It does however have python3). So, I added alias for python using terminal alias python='python...
MLFlow projects; bash: python: command not found
I'm running MLflow Project for a model using following command from my ubuntu 20.04 terminal mlflow run . --no-conda -P alpha=0.5 My system doesn't have conda or python (It does however have python3). So, I added alias for python using terminal alias python='python3' After which I could open python in terminal using ...
[ "Change python to python3 in the MLproject file to the resolve error.\ncommand: \"python3 tracking.py {alpha} {l1_ratio}\"\n\n", "Running the command below in the terminal helped me:\n$ sudo apt install python-is-python3\n\nAfter installation, run the ML project and it should work.\n" ]
[ 1, 0 ]
[]
[]
[ "bash", "mlflow", "python", "terminal", "ubuntu" ]
stackoverflow_0070051420_bash_mlflow_python_terminal_ubuntu.txt
Q: How repeat a row after a match in Python I have the following data: A B 0 27.9 1.0 1 20.6 1.0 2 10.3 1.0 3 0.0 1.0 4 349.7 1.0 5 339.4 2.0 6 329.1 1.0 7 318.9 1.0 And I would like every time there is a number higher than 1 in B, then the column wil...
How repeat a row after a match in Python
I have the following data: A B 0 27.9 1.0 1 20.6 1.0 2 10.3 1.0 3 0.0 1.0 4 349.7 1.0 5 339.4 2.0 6 329.1 1.0 7 318.9 1.0 And I would like every time there is a number higher than 1 in B, then the column will be duplicated by that number. The output of ...
[ "You can try something like this:\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'A': [27.9, 20.6, 10.3, 0.0, 349.7, 339.4, 329.1, 318.9],\n 'B': [1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0]\n})\n\nfor i in range(len(df)):\n if df['B'][i] > 1.0:\n # this inserts a new row between the current and previous...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074343450_python.txt
Q: why i cant load json file to pandas data frame My code: import json import requests responseGBP=requests.get("https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-exchange-rates&sort=date&facet=currency&rows=30&facet=date&q=date:[2020-12-01+TO+2020-12-31]&refine.currency=GBP") response_jGBP=respons...
why i cant load json file to pandas data frame
My code: import json import requests responseGBP=requests.get("https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-exchange-rates&sort=date&facet=currency&rows=30&facet=date&q=date:[2020-12-01+TO+2020-12-31]&refine.currency=GBP") response_jGBP=responseGBP.content.decode("utf-8") df = pd.read_json(respo...
[ "Because you didn't analyze dictionary structure properly.\nYou have to understand that for all columns in pandas rows will be of same count, and you can also load specific part of response if you want.\nimport pandas as pd\nres = requests.get(\"https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-e...
[ 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074347217_json_pandas_python.txt
Q: What is the best way to display data of a text file using the fetch function of Java Script in Flask by by clicking a button? I am trying to click a button which opens a text file raw_vlans. I am using Flask and Bootstrap and at the same time I am using the fetch function from Java Script to do the loading of the...
What is the best way to display data of a text file using the fetch function of Java Script in Flask by by clicking a button?
I am trying to click a button which opens a text file raw_vlans. I am using Flask and Bootstrap and at the same time I am using the fetch function from Java Script to do the loading of the text file data. But nothing displays when I click on the button. When I click on the view function, I notice the following: "GET /...
[ "I discovered that when using flask, I needed to have a static folder, otherwise flask will not recognize the path. Therefore, the js folder should be insider the static folder, and the path:\n<script src=\"js/app.js\"></script>\n\nchanged to:\n <script src=\"/static/js/app.js\"></script>\n\n" ]
[ 0 ]
[]
[]
[ "database", "flask", "javascript", "python" ]
stackoverflow_0073339965_database_flask_javascript_python.txt
Q: The default dtype for empty Series will be 'object' instead of 'float64' in a future version I am running a python script with the following code: def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: tik = time.perf_counter() #only 1 time for populates, dont work backte...
The default dtype for empty Series will be 'object' instead of 'float64' in a future version
I am running a python script with the following code: def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: tik = time.perf_counter() #only 1 time for populates, dont work backtesting btc_info_pair = "BTC/USDT" if metadata['pair'] in btc_info_pair: ...
[ "Reading one column creates pandas.series and if it is empty then this warning comes up.\nYou can give column type as below.\ndataframe['btctrend'] = self.custom_trendBTC_info['trend'].astype(float)\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074338740_python.txt
Q: Python Performance difference between iterators and iterable Is there any performance difference between iterables and iterators in python? do I need to convert every iterable to a iterator to get better performance? I was studying the topic iterators and iterable in python. I came across a doubt in my mind, Is it...
Python Performance difference between iterators and iterable
Is there any performance difference between iterables and iterators in python? do I need to convert every iterable to a iterator to get better performance? I was studying the topic iterators and iterable in python. I came across a doubt in my mind, Is iterators faster than iterable and do I need to convert iterable to ...
[ "When you iterate over an iterable it automatically calls either the __iter__() method for an iterator or uses the __getitem__() with sequential indexes starting with 0.\nDefinitions:\n\nIterable is any class in Python that defines an __iter__()or a __getitem__() method. This includes all sequence types such as lis...
[ 0 ]
[]
[]
[ "iterable", "iterator", "performance", "python" ]
stackoverflow_0074347351_iterable_iterator_performance_python.txt
Q: How to count occurance of characters in string including variations, like upside-down characters Sometimes we get text like reversed when people scan documents in reverse, which will look like this: stri = "1234 ᔭƐᘔІ " I would like to count occurance of the each number in this cases like. 1 - occured 2 times incl...
How to count occurance of characters in string including variations, like upside-down characters
Sometimes we get text like reversed when people scan documents in reverse, which will look like this: stri = "1234 ᔭƐᘔІ " I would like to count occurance of the each number in this cases like. 1 - occured 2 times including reversed one. 2 - occured 2 times including reversed one 3 - occured 2 times including reversed ...
[ "Firstly, the characters that you are using aren't really flipped but they are some other UNICODE characters. Python, doesn't recognize 1 because it is 1, but it rather recognized it by UNICODES. Therefore, there is no theoretical way to achieve this. However, here's a practical method:\n# Create a dict with the ma...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074347276_python_python_3.x.txt
Q: How To Display One Value in Pandas? how do i display only andir values, with each value beside it. cari = df.groupby(['Kecamatan','Kelurahan'])['No'].count().reset_index( name='Jumlah').sort_values(['Kecamatan','Jumlah'], ascending=[True,False]) cari.style.hide_index() I have tried this but it doesn't work A:...
How To Display One Value in Pandas?
how do i display only andir values, with each value beside it. cari = df.groupby(['Kecamatan','Kelurahan'])['No'].count().reset_index( name='Jumlah').sort_values(['Kecamatan','Jumlah'], ascending=[True,False]) cari.style.hide_index() I have tried this but it doesn't work
[ "Try this:\nimport pandas as pd\n\next_val = df.loc[df['Kecamatan'] == 'Andir']\nprint(ext_val)\n\n" ]
[ 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074347378_group_by_pandas_python.txt
Q: How to use pytest fixture with argument? I have a pytest fixture: TEST_DIR_JSON = 'test_data/test_telemetry' @pytest.fixture def create_telemetry_fixture(): """Create and delete .json files""" items = [ {"ts_str": "2021-07-15_10_00_01", "ts": "2021-07-15 10:00:00", "sensor_id": "sensor1", "value":...
How to use pytest fixture with argument?
I have a pytest fixture: TEST_DIR_JSON = 'test_data/test_telemetry' @pytest.fixture def create_telemetry_fixture(): """Create and delete .json files""" items = [ {"ts_str": "2021-07-15_10_00_01", "ts": "2021-07-15 10:00:00", "sensor_id": "sensor1", "value": -61.2105297502}, {"ts_str": "2021-07-...
[ "The parametrize with indirect=True requires that the argument name of the feature was exactly the \"request\" and no other word.\nI created a simplified version of your code where I use this approach. You can try it:\nimport pytest\n\nitems1 = [\n {\"ts_str\": \"item1_ts_str1\"},\n {\"ts_str\": \"it...
[ 1 ]
[]
[]
[ "fixtures", "pytest", "python" ]
stackoverflow_0074346446_fixtures_pytest_python.txt
Q: How do I make inputted letters as big letters using asterisk? For example i inputted "ABC" The output should be: *** ** *** * * * * * *** ** * * * * * * * * ** *** I only tried the letter A but it results an error. Can someone help me do it in plain python without any modules text = input("Enter my text: ").sp...
How do I make inputted letters as big letters using asterisk?
For example i inputted "ABC" The output should be: *** ** *** * * * * * *** ** * * * * * * * * ** *** I only tried the letter A but it results an error. Can someone help me do it in plain python without any modules text = input("Enter my text: ").split() A = [3, [1,0,1], 3, [1,0,1], [1,0,1]] for i in range(text+1...
[ "That representation seems inconsistent, if you wanted to use a matrix to represent which elements are asterisks I'd suggest\nA = [[1,1,1], [1,0,1], [1,1,1], [1,0,1], [1,0,1]]\n\nThen you can loop over each row and print out either an asterisk or whitespace as appropriate\nfor row in A:\n print(''.join('*' if s ...
[ 1, 0 ]
[]
[]
[ "letter", "python" ]
stackoverflow_0074347196_letter_python.txt
Q: Calling asyncio.run_coroutine_threadsafe across different event loops I have a class inside a microservice that looks like this: import asyncio import threading class A: def __init__(self): self.state = [] self._flush_thread = self._start_flush() self.tasks = set() def _start_flush(self):...
Calling asyncio.run_coroutine_threadsafe across different event loops
I have a class inside a microservice that looks like this: import asyncio import threading class A: def __init__(self): self.state = [] self._flush_thread = self._start_flush() self.tasks = set() def _start_flush(self): threading.Thread(target=self._submit_flush).start() def _submit...
[ "The answer here is that asyncio.run_coroutine_threadsafe does not protect us from any thread safety issues across different event loops. We need to implement locks to protect any shared states while they are being modified. Credits to @Paul Cornelius for the reply.\n" ]
[ 0 ]
[]
[]
[ "event_loop", "multithreading", "python", "python_asyncio", "thread_safety" ]
stackoverflow_0074294180_event_loop_multithreading_python_python_asyncio_thread_safety.txt
Q: Append string variable to LaTeX based raw string Trying to append an integer as per this post and this post. Requirement: from IPython.display import display, Markdown N = 128 text = r'$QFT=\frac{1}{\sqrt{'+str(N)+'}} \begin{bmatrix}' text = text + r'1 & 2 \\ 3 & 4 \\' text = text + r' \end{bmatrix}$' display(Mar...
Append string variable to LaTeX based raw string
Trying to append an integer as per this post and this post. Requirement: from IPython.display import display, Markdown N = 128 text = r'$QFT=\frac{1}{\sqrt{'+str(N)+'}} \begin{bmatrix}' text = text + r'1 & 2 \\ 3 & 4 \\' text = text + r' \end{bmatrix}$' display(Markdown(text)) Tried: IndexError: Replacement index 1 ...
[ "Double each curly bracket if it's a part of the string:\n> N = 128\n> text = r\"$QFT = \\frac{{1}}{{\\sqrt{{{0}}}}} \\begin{{bmatrix}}\".format(N)\n> print(text)\n$SQFT = \\frac{1}{\\sqrt{128} \\begin{bmatrix}\n\nIn case you want to use a parameter N in the string, then use the explicit parameter format(N=N) to ge...
[ 1 ]
[]
[]
[ "latex", "python" ]
stackoverflow_0074347320_latex_python.txt
Q: Can't install anything in the environment I have created I have set up a new environment on conda. Once it was created, I disabled threading so that the performance of the software I would be using will be maximised using: conda env config vars set OMP_NUM_THREADS=1 conda env config vars set NUMEXPR_MAX_THREADS=1 ...
Can't install anything in the environment I have created
I have set up a new environment on conda. Once it was created, I disabled threading so that the performance of the software I would be using will be maximised using: conda env config vars set OMP_NUM_THREADS=1 conda env config vars set NUMEXPR_MAX_THREADS=1 I then tried to install the software and got the error CondaS...
[ "I have now resolved this!\nIf anyone else has the same issue, going back into the base environment and then using \"conda install -n name_of_environment python\" worked.\n" ]
[ 0 ]
[]
[]
[ "conda", "environment", "python" ]
stackoverflow_0074345434_conda_environment_python.txt
Q: python divide the data into intervals I need to transform the data into an interval variation series import numpy as np import math import sys import os import pandas as pd data = pd.read_csv("euro-dollar-exchange-rate-historical-chart.csv",index_col=['date'] ) data df=data['2017-01-02':] df value; date ...
python divide the data into intervals
I need to transform the data into an interval variation series import numpy as np import math import sys import os import pandas as pd data = pd.read_csv("euro-dollar-exchange-rate-historical-chart.csv",index_col=['date'] ) data df=data['2017-01-02':] df value; date 1999-01-04 1.1825; 1999-01-05 1.1774; 19...
[ "Do you want intervals on exchange-rate or the dates? I think you're trying to pd.cut a Series-object, try to use pd.cut(df.values, bins=l) if you want the exchange-rate, or pd.cut(df.index, bins = l) if you want date-intervals.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "probability", "python" ]
stackoverflow_0074347303_dataframe_probability_python.txt
Q: Django - create_superuser() got an unexpected keyword argument 'user_type' I am trying to create a custom user model for my django app. Here is the code for CustomUser and CustomUserManager. from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def _create_user(self, an...
Django - create_superuser() got an unexpected keyword argument 'user_type'
I am trying to create a custom user model for my django app. Here is the code for CustomUser and CustomUserManager. from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def _create_user(self, anonymous, first_name, last_name, email, username, password, home_address, user_ty...
[ "I don't see where you ever assign the custom manager to your custom model. This is indicated by the fact that it seems to be looking at the default manager in the stack trace. Try assigning your custom manager to the model as described in the docs.\n", "Hi just run into the same issue, and taking a look at your ...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0047369930_django_django_models_python.txt
Q: Upload File operation using FastAPI does not work on Deta Cloud Platform When I run this code via uvicorn main:app everything works, but when I run it using Deta, I get Internal Server Error and only GET endpoint works (the POST one is not even called as it was supposed to). Can you please help me? Thanks in advan...
Upload File operation using FastAPI does not work on Deta Cloud Platform
When I run this code via uvicorn main:app everything works, but when I run it using Deta, I get Internal Server Error and only GET endpoint works (the POST one is not even called as it was supposed to). Can you please help me? Thanks in advance. import os from pathlib import Path from fastapi import FastAPI, Form, Upl...
[ "Deta is very restrictive. As shown in the Technical Specifications, Deta Micros (micro servers) provide a read-only file system, only /tmp can be written to, which has a 512 MB storage limit.\nDeta provides two additional services, i.e., Deta Base (a fully-managed, NoSQL database, which you can use to store, query...
[ 1 ]
[ "The error occured due to absence of poppler-utils and has nothing to do with FastApi.\nMy program requires linux package poppler-utils to process pdf files. Since Deta cloud does not have one and does not allow users to execute any ... apt install ... commands, aforementioned error occured.\n" ]
[ -1 ]
[ "fastapi", "python" ]
stackoverflow_0074344217_fastapi_python.txt
Q: How to return arrays from a function in python I have a function to read some data files and make some pandas data. I have 4 paths I want to read and make dataframes. def read_files(paths:np.array,scalings:np.array): names = ['E','I'] for p,s in zip(paths,scalings): df = pd.read_csv(p,engine = 'pyt...
How to return arrays from a function in python
I have a function to read some data files and make some pandas data. I have 4 paths I want to read and make dataframes. def read_files(paths:np.array,scalings:np.array): names = ['E','I'] for p,s in zip(paths,scalings): df = pd.read_csv(p,engine = 'python', sep ='\s+', names=names) energy_ = df[...
[ "\nHow to return arrays from a function in python\n\nHere's an example on how to return 2 array from a function:\ndef function():\n array = [1,2,3]\n array2 = [4,5,6]\n return array, array2\n\na, a2 = function()\nprint(a)\nprint(a2)\n\n\nHow can I get call each specific dataframe\n\nWhat?\nI can only guess...
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074347554_dataframe_numpy_pandas_python.txt
Q: python - numpy image, crop one side, fill with black the ther I have a image with resolution 816x624, and would need to make a 640x640 image out of it. To do so, i'd have to crop the long side (centered), and fill up the short side with black (centered). the resulting image should be the center of the starting ima...
python - numpy image, crop one side, fill with black the ther
I have a image with resolution 816x624, and would need to make a 640x640 image out of it. To do so, i'd have to crop the long side (centered), and fill up the short side with black (centered). the resulting image should be the center of the starting image, with a small black strip on top and bottom. How can this be don...
[ "Given an imput image img, an expected height h and an expected width w:\ndef resize_img(img, h, w):\n\n #cut the image\n cutted_img = img[\n max(0, int(img.shape[0]/2-h/2)):min(img.shape[0], int(img.shape[0]/2+h/2)),\n max(0, int(img.shape[1]/2-w/2)):min(img.shape[1], int(img.shape[1]/2+w/2)),\n ]\n\...
[ 3 ]
[]
[]
[ "crop", "image", "numpy", "python" ]
stackoverflow_0074344904_crop_image_numpy_python.txt
Q: Overwrite superclass instance in Python I can create a FasterRCNN object using model = fasterrcnn_resnet50_fpn(...) which I want to inherit from, as class MyDetector(FasterRCNN): ... but overwrite the superclass instance from the fasterrcnn_resnet50_fpn() factory. I have tried using __new__, as: class MyDetec...
Overwrite superclass instance in Python
I can create a FasterRCNN object using model = fasterrcnn_resnet50_fpn(...) which I want to inherit from, as class MyDetector(FasterRCNN): ... but overwrite the superclass instance from the fasterrcnn_resnet50_fpn() factory. I have tried using __new__, as: class MyDetector(FasterRCNN): def __new__(cls): ...
[ "I guess you'd be better to make your own factory function.\nimport libraries\nfrom typing import Optional, Any\nimport torch\nfrom torch import nn\nimport torchvision\nfrom torchvision.models.resnet import resnet50, ResNet50_Weights\nfrom torchvision.models.detection import FasterRCNN_ResNet50_FPN_Weights, FasterR...
[ 0 ]
[]
[]
[ "class", "factory", "inheritance", "python" ]
stackoverflow_0074346531_class_factory_inheritance_python.txt
Q: Nested loop with conditional list comprehension I have 2 lists l1 = [['a',1],['b',2],['c',3]] l2 = [['b',2,10],['c',3,8]] I want the below code to be replicated using list comprehension in python: for i in range(len(l1)): cnt = 0 for j in range(len(l2)): if (l1[i][0]==l2[j][0]) & (l1[i][1]==l2[j][1...
Nested loop with conditional list comprehension
I have 2 lists l1 = [['a',1],['b',2],['c',3]] l2 = [['b',2,10],['c',3,8]] I want the below code to be replicated using list comprehension in python: for i in range(len(l1)): cnt = 0 for j in range(len(l2)): if (l1[i][0]==l2[j][0]) & (l1[i][1]==l2[j][1]): cnt = 1 if cnt==1: isintb...
[ "Since the inner for actually check if there is any match you can use any in the list comprehensions and cast the bool to int\nisintb = [int(any((l1[i][0] == l2[j][0]) & (l1[i][1] == l2[j][1]) for j in range(len(l2)))) for i in range(len(l1))]\n# [0, 1, 1]\n\n", "There you go. You can try using any() of python to...
[ 0, 0, 0, 0 ]
[]
[]
[ "list_comprehension", "nested_loops", "python" ]
stackoverflow_0074347406_list_comprehension_nested_loops_python.txt
Q: Microservice notification better with Firebase or celery? I have a microservice project. I am using DRF. Now I need to add notification system to this project. Since we have multiple service notification can come from any service. We also have web version and mobile version in frontend. Which will be better option...
Microservice notification better with Firebase or celery?
I have a microservice project. I am using DRF. Now I need to add notification system to this project. Since we have multiple service notification can come from any service. We also have web version and mobile version in frontend. Which will be better option for notification service? Notification with firebase or Notifi...
[ "if you have mobile version, use Firebase Cloud Messagin and firestore with listening realtime updates. I will speed up your development with possibility to add new firebase features later.\n", "Firebase Cloud Messaging and Celery are solving very different problems, so it's really not an either/or choice.\nFireb...
[ 0, 0 ]
[]
[]
[ "architecture", "django_rest_framework", "microservices", "notifications", "python" ]
stackoverflow_0074161274_architecture_django_rest_framework_microservices_notifications_python.txt
Q: apply a snakemake rule on a list of values in parallel I'm currently exploring using snakemake as a workflow tool. In my specific use case I don't start from a list of files but rather from a list of values that should result in the creation of a list of files. In my example, I create the files with a small python...
apply a snakemake rule on a list of values in parallel
I'm currently exploring using snakemake as a workflow tool. In my specific use case I don't start from a list of files but rather from a list of values that should result in the creation of a list of files. In my example, I create the files with a small python snippet which works fine but when I want to use those files...
[ "The last rule should be changed to remove expand (since this rule is creating only a single file):\nrule bar:\n input:\n file=expand('{file}.foo', file=data)\n output:\n outfile='{file}.bar'\n shell:\n \"\"\"echo {output.outfile}; echo bar > {output.outfile} \"\"\"\n\n", "Probably y...
[ 2, 2 ]
[]
[]
[ "python", "snakemake" ]
stackoverflow_0074347235_python_snakemake.txt
Q: Scraping tweets in the Arabic language I am trying to scrape tweets with a hashtag and I want tweets only in the Arabic Language. But I still get tweets in all languages. Can anyone help please import snscrape.modules.twitter as sntwitter query = ["#Covid19", 'lang: ar'] tweets = [] limit = 5000 for tweet in snt...
Scraping tweets in the Arabic language
I am trying to scrape tweets with a hashtag and I want tweets only in the Arabic Language. But I still get tweets in all languages. Can anyone help please import snscrape.modules.twitter as sntwitter query = ["#Covid19", 'lang: ar'] tweets = [] limit = 5000 for tweet in sntwitter.TwitterSearchScraper(query).get_items...
[ "Well one of the ways to think about this problem is to check if the tweet.content actually contains something else from another language or check if the text is arabic(better solution.) To check if the text is arabic you can use the langdetect module and here is a simple implementation of how you can actually use ...
[ 0, 0 ]
[]
[]
[ "arabic", "python", "scrape", "twitter" ]
stackoverflow_0074170116_arabic_python_scrape_twitter.txt
Q: Counting indices from numpy where So I have two rather large lists (3636586 values in both) and I am trying to use np.where() to find the number of values that satisfy two conditions using those two lists. The lists are cat1 = [ 0.01027171 0.01691939 0.01614619 ..., 10.18688393 10.21286678 10.20675182] ca...
Counting indices from numpy where
So I have two rather large lists (3636586 values in both) and I am trying to use np.where() to find the number of values that satisfy two conditions using those two lists. The lists are cat1 = [ 0.01027171 0.01691939 0.01614619 ..., 10.18688393 10.21286678 10.20675182] cat2 = [ 4.81194684e-09 5.13640614e-08...
[ "I guess you cannot get it by using np.where, if you want the length of the indices satisfying your condition, a better approach would be to use boolean conditioning and then use 'np.count_nonzero' over it.\nFor instance what you could do is:\nnp.count_nonzero((cat1 > 6.) & (cat2*1000 > .83)) to get the length of t...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0038725180_numpy_python.txt
Q: Pylance disable all warnings I am currently running both Pylint and Pylance at the same time. I use Pylint for linting and use Pylance for all the other things it does (like code highlighting). This means I am getting some warnings twice, once from Pylint, once from Pylance. I wish to disable all Pylance warnings....
Pylance disable all warnings
I am currently running both Pylint and Pylance at the same time. I use Pylint for linting and use Pylance for all the other things it does (like code highlighting). This means I am getting some warnings twice, once from Pylint, once from Pylance. I wish to disable all Pylance warnings. I have tried setting Analysis: Ty...
[ "Please see: https://github.com/microsoft/pyright/blob/main/docs/configuration.md\nI you want to disable everything (I assume all output from pylance are warnings),\nyou can add a <project-root>/pyrightconfig.json in your repo:\n{\n \"ignore\": [\n \"**\"\n ]\n}\n\nPlease read the link above for all th...
[ 0 ]
[]
[]
[ "pylance", "python" ]
stackoverflow_0074310693_pylance_python.txt
Q: replace values in dictionary python i have 2 dictionary named ch_jaman and cdf950 ch jaman {'Ancolmekar': array([0. , 0. , 0. , ..., 0. , 0. , 0.5]), 'Cidurian': array([0., 0., 0., ..., 0., 0., 0.]), 'Dayeuhkolot': array([0., 0., 0., ..., 0., 0., 0.]), 'Hantap': array([0., 0., 0., ..., 0., 0., 0.]), 'Kertasari': a...
replace values in dictionary python
i have 2 dictionary named ch_jaman and cdf950 ch jaman {'Ancolmekar': array([0. , 0. , 0. , ..., 0. , 0. , 0.5]), 'Cidurian': array([0., 0., 0., ..., 0., 0., 0.]), 'Dayeuhkolot': array([0., 0., 0., ..., 0., 0., 0.]), 'Hantap': array([0., 0., 0., ..., 0., 0., 0.]), 'Kertasari': array([0., 0., 0., ..., 0., 0., 0.]), 'Met...
[ "It appears that ch_jaman is a dictionary from strings to list of numbers, while cdf950 maps strings into numbers.\nTherefore, the expression ch_jaman[stas]>=cdf950[stas] is trying to compare a list of numbers with a number.\nWhat is your goal here? Do you want to compare each element of the array ch_jaman[stas] wi...
[ 2 ]
[]
[]
[ "arrays", "dictionary", "python" ]
stackoverflow_0074347559_arrays_dictionary_python.txt
Q: Attempt to convert a value () with an unsupported type () to a Tensor def preprocess(image_path): slide = OpenSlide(image_path) region = (1000,1000) size = (5000, 5000) image = slide.read_region(region, 0, size) image = tf.image.resize(image, (512, 512)) image = np.array(image) ...
Attempt to convert a value () with an unsupported type () to a Tensor
def preprocess(image_path): slide = OpenSlide(image_path) region = (1000,1000) size = (5000, 5000) image = slide.read_region(region, 0, size) image = tf.image.resize(image, (512, 512)) image = np.array(image) return image train_x=[] for i in tqdm(train_df['file_path']): x1=prep...
[ "The slide.read_region(region, 0, size) converts the image file into an \"in-memory\" representation of an image. The resizing Ops such as tf.image.resize() accept input images as tensors or np.array but you are passing a PIL image which causes the error. Kindly change the preprocess function like below\ndef prepro...
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074220612_python_tensorflow.txt
Q: Selenium error (DevToolsActivePort file doesn't exist) I am writing a test for the site, earlier the script ran without problems, but after some time an error occurred - "DevToolsActivePort file doesn't exist", which I tried to fix by adding - "options.add_argument("--remote-debugging-port=9222")", after adding I ...
Selenium error (DevToolsActivePort file doesn't exist)
I am writing a test for the site, earlier the script ran without problems, but after some time an error occurred - "DevToolsActivePort file doesn't exist", which I tried to fix by adding - "options.add_argument("--remote-debugging-port=9222")", after adding I get the error "chrome not reachable".. Tried different optio...
[ "Solution:\nTake command:\n\ngoogle-chrome --headless\n\nThe response will include a description of the problem, in my case it was:\n\n[1107/164427.276365:ERROR:filesystem_posix.cc(63)] mkdir /tmp/Crashpad/new: Permission denied (13)\n\nI used the following command to solve:\n\nsudo chmod -R 777 /tmp/Crashpad/new/\...
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074346244_python_python_3.x_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Python how to merge dictionaries getting from function and loop I have several requests to Prometheus for different metrics, which I would like to merge into one dictionary. Aim of the result should be like this: {'domain': 'domain.com', 'uptime': '100', 'threats_number': '12345'} # Uptime def uptime_percent(): ...
Python how to merge dictionaries getting from function and loop
I have several requests to Prometheus for different metrics, which I would like to merge into one dictionary. Aim of the result should be like this: {'domain': 'domain.com', 'uptime': '100', 'threats_number': '12345'} # Uptime def uptime_percent(): uptime_data = prom.custom_query( query="avg_over_time(host_...
[ "It mighn't elegant but partially works for me\n# Uptime\ndef uptime_percent():\n uptime_data = prom.custom_query(\n query=\"avg_over_time(host_tracker_uptime_percent{job='donodeexporter'}[10d])\"\n )\n for domain_z in uptime_data:\n domain_zone = domain_z['metric']['zone']\n uptime = ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074344640_python.txt
Q: Frameset indeed in frame problem PYTHON SELENIUM I want to go inside frame name "body", but it isnt work. I can go to first frame and everything works, but problem is when I try to go inside indeed frameset. Selenium cant see it This is my code: frame = driver.find_element(By.XPATH, "/html/frameset/frame[2]") driv...
Frameset indeed in frame problem PYTHON SELENIUM
I want to go inside frame name "body", but it isnt work. I can go to first frame and everything works, but problem is when I try to go inside indeed frameset. Selenium cant see it This is my code: frame = driver.find_element(By.XPATH, "/html/frameset/frame[2]") driver.switch_to.frame(frame) frame= driver.find_element(B...
[ "You need to locate elements correctly. Also, according to HTML you shared the 'body' frame is not inside frame2_fr. In case all you want is to go inside body frame you can do that with the following code:\nframe = driver.find_element(By.XPATH, \"//frame[@name='Body']\")\ndriver.switch_to.frame(frame)\n\nWhen you f...
[ 0, 0 ]
[]
[]
[ "frame", "iframe", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074346979_frame_iframe_python_selenium_selenium_webdriver.txt
Q: How to access user instance in custom login system? I want to make a very custom login system and I'm failing to receive the user instance when the token is sent within the headers. I have number of APIs which need to work with and without users logged in and need to access the user.id (primary key). In my custom ...
How to access user instance in custom login system?
I want to make a very custom login system and I'm failing to receive the user instance when the token is sent within the headers. I have number of APIs which need to work with and without users logged in and need to access the user.id (primary key). In my custom Login, I want to get the user instance and do a custom ch...
[ "I think that user.is_active may be False.\nIt appears that the specific error message you are seeing is raised directly from the TokenAuthentiation or BasicAuthentication class.\nif not token.user.is_active:\n raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))\n\nSession auth, to my surprise,...
[ 1 ]
[]
[]
[ "django", "django_rest_framework", "django_settings", "django_views", "python" ]
stackoverflow_0074250197_django_django_rest_framework_django_settings_django_views_python.txt
Q: Pip for Python 3.8 How do I install Pip for Python 3.8 ? I made 3.8 my default Python version. sudo apt install python3.8-pip gives unable to locate package python3.8-pip and running python3.8 -m pip install [package] gives no module named pip I can't run sudo apt install python3-pip because it installs pip ...
Pip for Python 3.8
How do I install Pip for Python 3.8 ? I made 3.8 my default Python version. sudo apt install python3.8-pip gives unable to locate package python3.8-pip and running python3.8 -m pip install [package] gives no module named pip I can't run sudo apt install python3-pip because it installs pip for Python 3.6
[ "Install pip the official way:\ncurl https://bootstrap.pypa.io/get-pip.py -o get-pip.py\npython3.8 get-pip.py\n\n\nmade 3.8 my default Python version\n\nIt depends on how you did that, but it might break something in your OS. For example some packages on Ubuntu 18.04 might depend on python being python2.7 or pytho...
[ 62, 41, 23, 1, 1 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0061717006_pip_python_python_3.x.txt
Q: Power spectrum from image gives peak at the same position for different images I copied a code for analysing the power spectrum of an image and adapted it to my needs. My problem consists on the fact that on different images I get always a peak at same frequencies, even from images where the peak should be at diff...
Power spectrum from image gives peak at the same position for different images
I copied a code for analysing the power spectrum of an image and adapted it to my needs. My problem consists on the fact that on different images I get always a peak at same frequencies, even from images where the peak should be at different values. That's the piece of code: import matplotlib.pyplot as plt import numpy...
[ "the second image has been rescaled up to (328, 328), if you scale it down to the same size as the first image (256,256) you will get the correct answer, when working with images and spatial frequencies know that scaling up in space (number of pixels) is scaling down in the spatial frequency domain.\nimport matplot...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074347604_python.txt
Q: LightGBM running simulation after each fit step My model performs a multi-class (3) classification task. I would like to change the way model "fits". Instead of calculation of a metric such as acc or logloss - I would like to run a simulation on whole data set to see how the model performs after each fit, in real-...
LightGBM running simulation after each fit step
My model performs a multi-class (3) classification task. I would like to change the way model "fits". Instead of calculation of a metric such as acc or logloss - I would like to run a simulation on whole data set to see how the model performs after each fit, in real-time. Please note that simulation != loss/error. Simu...
[ "The custom eval function should work. As per the docs, preds is:\n\nThe predicted values. Predicted values are returned before any transformation, e.g. they are raw margin instead of probability of positive class for binary task.\n\nSo if this is a classification problem, you might need to apply the softmax transf...
[ 0 ]
[]
[]
[ "lightgbm", "python", "xgboost" ]
stackoverflow_0074345241_lightgbm_python_xgboost.txt
Q: Why does this adj_matrix keep writing to the same row instead of iterating over the rows? I am trying to create an adjacency matrix from an adjacency dictionary. Basically I want to create an empty matrix filled with zeros. Then iterate over every item in the adjacency dictionary and assign the correct weight in t...
Why does this adj_matrix keep writing to the same row instead of iterating over the rows?
I am trying to create an adjacency matrix from an adjacency dictionary. Basically I want to create an empty matrix filled with zeros. Then iterate over every item in the adjacency dictionary and assign the correct weight in the matrix. But for some reason the code keeps assigning the values to the same row. I used matr...
[ "I think this line is a problem\nadj_matrix = [[0] * len(digraph.adj_dict)] * len(digraph.adj_dict)\n\nYou are copying the same list len(digraph.adj_dict) times and then every row in the matrix points to the list at the same location in memory, but each row in the matrix should not be the same. Changing it to list ...
[ 1 ]
[]
[]
[ "adjacency_matrix", "graph_theory", "python" ]
stackoverflow_0074344110_adjacency_matrix_graph_theory_python.txt
Q: Is there a way to throw all Selenium exceptions in Python as a single parent exception type? I am working on a suite of Selenium scrapers and monitoring the results of scraper runs all in one place. It would be helpful to be able to take a quick look at the logs and see if a scraper error is one that I expected an...
Is there a way to throw all Selenium exceptions in Python as a single parent exception type?
I am working on a suite of Selenium scrapers and monitoring the results of scraper runs all in one place. It would be helpful to be able to take a quick look at the logs and see if a scraper error is one that I expected and raised vs. an unexpected error thrown by Selenium. Selenium can throw a variety of different err...
[ "They already all inherit from selenium.common.exceptions.WebDriverException() so you can capture them using that class. From there you can than create some log for them. For example like this:\ntry:\n # code that can throw selenium exceptn\nexcept selenium.common.exceptions.WebDriverException as e:\n logging...
[ 1 ]
[]
[]
[ "exception", "kibana", "logging", "python", "selenium" ]
stackoverflow_0074263163_exception_kibana_logging_python_selenium.txt
Q: Loop and fill values randomly (string) in pandas I've a dataset which has columns named "dish_liked" it has values like based on the corresponding columns which is named "rest_type" and it has input like "Cafe" "Quick Bites" "Delivery" etc Output of "dish_liked" columns when corresponding column "rest_type" values...
Loop and fill values randomly (string) in pandas
I've a dataset which has columns named "dish_liked" it has values like based on the corresponding columns which is named "rest_type" and it has input like "Cafe" "Quick Bites" "Delivery" etc Output of "dish_liked" columns when corresponding column "rest_type" values = "Quick Bites" Waffles ...
[ "What you still did not understand from my point is:\n1 - your top 5 are tuples, not a flat list\n2 - If you want to use a tuple the approach has to be different, which I don't be believe to be the case. Below you have two versions to get your job done, the first one is pretty manual and the second one will make it...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074347469_dataframe_pandas_python.txt
Q: Why does my tkinter window and plot appear differently on different monitors, as well as before/after pyinstaller? I'm developing a program with a tkinter GUI that has an embedded matplotlib bar chart. The program itself is sturdy, but the GUI gives me some weird issues. On the PC in my office (windows 10, 1920x10...
Why does my tkinter window and plot appear differently on different monitors, as well as before/after pyinstaller?
I'm developing a program with a tkinter GUI that has an embedded matplotlib bar chart. The program itself is sturdy, but the GUI gives me some weird issues. On the PC in my office (windows 10, 1920x1080 monitor), running the program in sublime text shows a perfectly normal GUI. I then built the program into a single ex...
[ "I was able to solve my issue outside of code. The problem was that python.exe and the .exe file that I build with pyinstaller were both using high DPI scaling behavior. Because of this, running the program on the PC with higher DPI resulted in all the widgets being shrunk by under-the-hood functionality.\nTo stop ...
[ 0 ]
[]
[]
[ "matplotlib", "pyinstaller", "python", "tkinter" ]
stackoverflow_0074319532_matplotlib_pyinstaller_python_tkinter.txt
Q: Rolling average in time series for specific time intervals I have data, I want to add a column that shows the moving average of the val column for each day. df timestamp val val_mean 2022-10-10 00:00 10 10 2022-10-10 00:01 20 15 .. 2022-10-10 23:59 50 23 2022-10-11 00:00...
Rolling average in time series for specific time intervals
I have data, I want to add a column that shows the moving average of the val column for each day. df timestamp val val_mean 2022-10-10 00:00 10 10 2022-10-10 00:01 20 15 .. 2022-10-10 23:59 50 23 2022-10-11 00:00 80 80 How can I achieve this
[ "Looks like you want a grouped, expanding mean:\ngroup = pd.to_datetime(df['timestamp']).dt.normalize()\n\ndf['val_mean'] = df.groupby(group)['val'].expanding().mean().droplevel(0)\n\noutput:\n timestamp val val_mean\n0 2022-10-10 00:00 10 10.000000\n1 2022-10-10 00:01 20 15.000000\n2 2022-10-1...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074347137_dataframe_pandas_python.txt
Q: How to join two words together in a list with a space in the middle? I have a list like this : ['which', 'means', 'which', 'one','which', 'will] How can I possibly join two words together and form this: ['which means', 'which one', 'which will'] A: Here's an option using join and zip: >>> words = ['which', 'mea...
How to join two words together in a list with a space in the middle?
I have a list like this : ['which', 'means', 'which', 'one','which', 'will] How can I possibly join two words together and form this: ['which means', 'which one', 'which will']
[ "Here's an option using join and zip:\n>>> words = ['which', 'means', 'which', 'one', 'which', 'will']\n>>> [' '.join(z) for z in zip(words[::2], words[1::2])]\n['which means', 'which one', 'which will']\n\nBreaking it down a little to show what the slice operation [::2] does and what zip does:\n>>> words[::2], wor...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074348044_python_python_3.x.txt
Q: Button to switch languages in Streamlit? In my Streamlit app, I store the name of the current language in session state. All the translated text is in a dictionary and I am looking at the session state language value to display the current one. The problem is, I have some multiselect and select box items that do n...
Button to switch languages in Streamlit?
In my Streamlit app, I store the name of the current language in session state. All the translated text is in a dictionary and I am looking at the session state language value to display the current one. The problem is, I have some multiselect and select box items that do not seem to get translated, even when I update ...
[ "I could not reproduce your code specifically, because there are some elements that are missing. However, my example below attempts to achieve what I think you are trying to do. \nIn my example:\n\nI store the stations in a dictionary\nI made up the callback function for demonstration purposes only\nI included two ...
[ 1 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074336582_python_streamlit.txt
Q: Compare strings if something is the same 2 times Something like: string_one = "hello world one" string_two = "hello john one" if string_one = string_two: do something So if it detects 2 words in 2 (or more) strings that are the same do something. But I can't figure out how to do it. A: Use split() to turn t...
Compare strings if something is the same 2 times
Something like: string_one = "hello world one" string_two = "hello john one" if string_one = string_two: do something So if it detects 2 words in 2 (or more) strings that are the same do something. But I can't figure out how to do it.
[ "Use split() to turn the strings into lists of words, then turn them into sets so you can take the intersection and see if its len is greater than 2.\n>>> string_one = \"hello world one\"\n>>> string_two = \"hello john one\"\n>>> set(string_one.split()) & set(string_two.split())\n{'hello', 'one'}\n>>> if len(set(st...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0074347954_python_python_3.x_string.txt
Q: Normalise JSON with Python Prompt me, please, how to normalize this JSON file using Python? This question is related to the previous The current JSON contains: { "total_stats": [ { "domain": "domain.com", "uptime": "100" }, { "domain": "domain.com", ...
Normalise JSON with Python
Prompt me, please, how to normalize this JSON file using Python? This question is related to the previous The current JSON contains: { "total_stats": [ { "domain": "domain.com", "uptime": "100" }, { "domain": "domain.com", "threats": "345.01111...
[ "If you want to merge the dictionaries according the \"domain\" key you can use (note: if dictionaries have common keys, the last dictionary value will be used):\ndct = {\n \"total_stats\": [\n {\"domain\": \"domain.com\", \"uptime\": \"100\"},\n {\"domain\": \"domain.com\", \"threats\": \"345.0111...
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074347818_json_python.txt
Q: How to merge dataframes where a value is not matching in other column I have huge data and I want merge it on a specific column where values from df1 is not available in df2 and vice versa. Example: df1: Domain Sales google.com 100 facebook.com 200 youtube.com 300 df2: Domain Sales google.com ...
How to merge dataframes where a value is not matching in other column
I have huge data and I want merge it on a specific column where values from df1 is not available in df2 and vice versa. Example: df1: Domain Sales google.com 100 facebook.com 200 youtube.com 300 df2: Domain Sales google.com 100 yahoo.com 200 youtube.com 300 Required output: Domain Sa...
[ "pd.concat([df1, df2]).drop_duplicates('Domain', keep=False)\n\n", "As you have a huge dataset you can use set operations to pre-filter the data before concat:\nS = set(df1['Domain']).symmetric_difference(df2['Domain'])\nout = pd.concat([d.loc[lambda d: d['Domain'].isin(S)] for d in [df1, df2]])\n\noutput:\n ...
[ 2, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074348037_pandas_python.txt
Q: Pyodbc - Login Failed for user - Confirmed user information is correct and working I am connecting to an SQL server. This application was working last week. The server lost power over the weekend and shutdown. I came in this morning and turned everything on, and now I cannot connect to the SQL server. When I open...
Pyodbc - Login Failed for user - Confirmed user information is correct and working
I am connecting to an SQL server. This application was working last week. The server lost power over the weekend and shutdown. I came in this morning and turned everything on, and now I cannot connect to the SQL server. When I open SQL Server management configuration and use the username and login specified in my conn...
[ "Looking through the SQL Server Configuration Manager, the TCP Port was reset to something in the 4x,xxx range. I set it to 1433 like it was before and everything works now.\n" ]
[ 0 ]
[]
[]
[ "pyodbc", "python", "sql_server" ]
stackoverflow_0074347809_pyodbc_python_sql_server.txt
Q: Output sys.stdout and sys.stderr to a file I have a module that redirects console outputs to the Tkinter window, which I found here on StackOverflow. It works perfectly, however, I realized I also need to save the console output to a file. But everything I tried either doesn't work, breaks the module, or nothing h...
Output sys.stdout and sys.stderr to a file
I have a module that redirects console outputs to the Tkinter window, which I found here on StackOverflow. It works perfectly, however, I realized I also need to save the console output to a file. But everything I tried either doesn't work, breaks the module, or nothing happens. EDIT: I need to modify the following mod...
[ "try:\n sys.stdout = open('file.txt', 'w')\n # some working code\nfinally:\n # close file.txt\n sys.stdout.close() \n sys.stdout = sys.__stdout__\n\nUpdate. You can write your custom logging class to suit your needs\nimport sys\n\nclass Logger:\n\ndef __init__(self, filename):\n self.console = sys.std...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074341632_python_python_3.x_tkinter.txt
Q: calling a dict object / printing dict keys with value I have a list of dict objects called results in the following format: {('AAPL', 'AAPL'): 1.0, ('AAPL', 'ABBV'): 0.2895481094217945, ('AAPL', 'AMZN'): 0.7985187751534586, ('AAPL', 'BAC'): 0.5923872592768968, ('AAPL', 'BRK-B'): 0.6076448647592143, ('AAPL', '...
calling a dict object / printing dict keys with value
I have a list of dict objects called results in the following format: {('AAPL', 'AAPL'): 1.0, ('AAPL', 'ABBV'): 0.2895481094217945, ('AAPL', 'AMZN'): 0.7985187751534586, ('AAPL', 'BAC'): 0.5923872592768968, ('AAPL', 'BRK-B'): 0.6076448647592143, ('AAPL', 'COST'): 0.6723253260025647, ('AAPL', 'CVX'): 0.28082643644...
[ "You're already iterating over the keys, so just print the key as you're going.\nfor key in results:\n if results[key] > 0.8:\n print(key, results[key])\n\nAlternatively, and more Pythonically, use results.items() so you don't need to access the dict twice:\nfor key, result in results.items():\n if res...
[ 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074348136_dictionary_python.txt
Q: Type hinting with many possibilities in python What is the best way of type hinting with many possible inputs? For instance, for a function: def example(input1): return input1 If input1 is one of, for instance, 10 possible classes, is it still best using Union, or is there a better method? A: The type of th...
Type hinting with many possibilities in python
What is the best way of type hinting with many possible inputs? For instance, for a function: def example(input1): return input1 If input1 is one of, for instance, 10 possible classes, is it still best using Union, or is there a better method?
[ "The type of the identity function is usually:\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\n\ndef identity(x:T) -> T:\n return x\n \n\n" ]
[ 0 ]
[]
[]
[ "python", "python_typing" ]
stackoverflow_0074348109_python_python_typing.txt
Q: How to add space in alphabets and digits using regex python I want to separate string from the digits using regex. I don't want to replace anything just add space. I don't want to add space in digit and special character or string and special character. for example "A-21PHASE-1,ASHOK VIHARA-21, PHASE-1, - ASHOK V...
How to add space in alphabets and digits using regex python
I want to separate string from the digits using regex. I don't want to replace anything just add space. I don't want to add space in digit and special character or string and special character. for example "A-21PHASE-1,ASHOK VIHARA-21, PHASE-1, - ASHOK VIHAR110052" output for above example should look like, "A-21 PH...
[ "User re.sub:\nthestring = re.sub(r'(\\d)([A-Z])', r'\\1 \\2', thestring)\nthestring = re.sub(r'([A-Z])(\\d)', r'\\1 \\2', thestring)\n\nFirst one puts spaces between digits and capital letters, second one between capital letters and digits.\n", "One pass by positive lookahead assertion (?<=...).\nimport re\n\nis...
[ 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074347952_python_string.txt
Q: Python treeview, double click to copy file but change displayed filename according to matching ID in separate file The script below makes a treeview of files in a folder and when I double click a file, it is copied to the clipboard which works perfectly for my use case. The filenames (photos) in the folder are st...
Python treeview, double click to copy file but change displayed filename according to matching ID in separate file
The script below makes a treeview of files in a folder and when I double click a file, it is copied to the clipboard which works perfectly for my use case. The filenames (photos) in the folder are stored anonymously while I have a another txt file that contains the names to each ID: How can I, in the treeview in the ...
[ "You can store the ID text in the Treeview item's text attribute, and the filename as a column value , then just hide the additional column\nself.tree = ttk.Treeview(self, show='tree', columns='hide_me')\nself.tree.item(item, text=id_text, values=path_to_file)\nself.tree.column(0, width=0, minwidth=0)\n\nThen you c...
[ 0 ]
[]
[]
[ "python", "tkinter", "treeview" ]
stackoverflow_0074347832_python_tkinter_treeview.txt
Q: Generic Type conversion in Python How can I perform a generic type conversion in python similar to the following mechanism that I use in C# .NET: string typetoConvertTo = "System.String"; string value = (string)Convert.ChangeType( "1", Type.GetType( typetoConvertTo )); typetoConvertTo = "System.Int32"; int value1...
Generic Type conversion in Python
How can I perform a generic type conversion in python similar to the following mechanism that I use in C# .NET: string typetoConvertTo = "System.String"; string value = (string)Convert.ChangeType( "1", Type.GetType( typetoConvertTo )); typetoConvertTo = "System.Int32"; int value1 = (int)Convert.ChangeType( "1", Type.G...
[ "Classes are first-class objects in Python.\n>>> t = str\n>>> t(123)\n'123'\n>>> d = {'str': str}\n>>> d['str'](123)\n'123'\n\n", "If you're wanting to delay type conversions for some reason, just store the value and the type conversion as a pair.\n>>> entry = (int, '123')\n>>> entry[0](entry[1])\n123\n\nIf you h...
[ 6, 1, 0, 0 ]
[]
[]
[ ".net", "python" ]
stackoverflow_0009290146_.net_python.txt
Q: Change default faker locale in factory_boy How can I set the default locale in Python's factory_boy for all of my Factories? In docs says that one should set it with factory.Faker.override_default_locale but that does nothing to my fakers... import factory from app.models import Example from custom_fakers import C...
Change default faker locale in factory_boy
How can I set the default locale in Python's factory_boy for all of my Factories? In docs says that one should set it with factory.Faker.override_default_locale but that does nothing to my fakers... import factory from app.models import Example from custom_fakers import CustomFakers # I use custom fakers, this indeed ...
[ "The Faker.override_default_locale() is a context manager, although it's not very clear from the docs.\nAs such, to change the default locale for a part of a test:\nwith factory.Faker.override_default_locale('es_ES'):\n ExampleFactory()\n\nFor the whole test:\n@factory.Faker.override_default_locale('es_ES')\ndef...
[ 10, 8, 3, 1, 0 ]
[]
[]
[ "django", "factory_boy", "python" ]
stackoverflow_0045773954_django_factory_boy_python.txt
Q: Calling pip package files from within pip package? (`No module named 'src.snnalgorithms'`) Whilst in some_other_package, I am importing files from the snnalgorithms pip package. I received the error: No module named 'src.snnalgorithms'. This is a valid error because that src.snnalgorithms file does not exist in th...
Calling pip package files from within pip package? (`No module named 'src.snnalgorithms'`)
Whilst in some_other_package, I am importing files from the snnalgorithms pip package. I received the error: No module named 'src.snnalgorithms'. This is a valid error because that src.snnalgorithms file does not exist in the some_other_package project from which I was calling the pip package. As a solution, I can make...
[ "You can use editable mode for development mode\npip install -e . # Install package locally \n\nFrom pip documentation:\n\nEditable installs allow you to install your project without copying any files. Instead, the files in the development directory are added to Python’s import path. This approach is well suited f...
[ 2 ]
[]
[]
[ "import", "pip", "python" ]
stackoverflow_0074348173_import_pip_python.txt
Q: Snakemake with one input but multiple parameters permutations I have been trying to wrap my head around this problem which probably has a very easy solution. I am running a bioinformatics workflow where I have one file as input and I want to run a program on it. However I want that program to be run with multiple ...
Snakemake with one input but multiple parameters permutations
I have been trying to wrap my head around this problem which probably has a very easy solution. I am running a bioinformatics workflow where I have one file as input and I want to run a program on it. However I want that program to be run with multiple parameters. Let me explain. I have file.fastq and I want to run cut...
[ "When specifying params, right now you are providing full lists rather than specific values. Contrast the following parameter values:\nE = [0.1, 0.5]\nTRIM = [5, 0]\n\n\nrule all\n input: expand(\"../outputs/trim{TRIM}_error{E}/trimmed_file.fastq\", E=E, TRIM=TRIM)\n\nrule cutadapt:\n input:\n \"file.f...
[ 1, 0 ]
[]
[]
[ "parameters", "python", "snakemake", "wildcard", "workflow" ]
stackoverflow_0074344912_parameters_python_snakemake_wildcard_workflow.txt
Q: batched version of roll in tensorflow I am writing a batched version of tf.roll, where each sample x[i] in a batch x is shifted by an individual amount shifts[i] along the last axis. For example, let shifts = tf.constant([3,2,1,0,-1]) x = tf.repeat(tf.range(5)[None], repeats=shifts.shape[0], axis=0) print(x) # [[0...
batched version of roll in tensorflow
I am writing a batched version of tf.roll, where each sample x[i] in a batch x is shifted by an individual amount shifts[i] along the last axis. For example, let shifts = tf.constant([3,2,1,0,-1]) x = tf.repeat(tf.range(5)[None], repeats=shifts.shape[0], axis=0) print(x) # [[0 1 2 3 4] # [0 1 2 3 4] # [0 1 2 3 4] # ...
[ "You need axis = 0. I am unsure as to why. Maybe vectorized_map shapes the data differently at dispatch than map_fn, which throws the code off? I don't know. See below. Note that I renamed x to input_x.\nimport tensorflow as tf\n\nshifts = tf.constant([3,2,1,0,-1])\ninput_x = tf.repeat(tf.range(5)[None], repeats=sh...
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074347039_python_tensorflow.txt
Q: Python folium synchronizing 2 markerclusters I have a situation, where I decided to distinguish my markers slightly by adding the MarkerCluster to the existing Marker. The clustering works, although isn't synchronized. It means, that if I switch one layer off, just the first markercluster disappears, whereas the s...
Python folium synchronizing 2 markerclusters
I have a situation, where I decided to distinguish my markers slightly by adding the MarkerCluster to the existing Marker. The clustering works, although isn't synchronized. It means, that if I switch one layer off, just the first markercluster disappears, whereas the second criterion defined as CircleMarker still appe...
[ "If I got you right, I think there are two possibilities:\nUse the same cluster\nAdd your markers from or_stat_marker to the openreach_cluster and not to another cluster to de-/activate them at the same time with the same button\n# was\nopenreach_cluster.add_child(or_marker)\nopenreach_status.add_child(or_stat_mark...
[ 1 ]
[]
[]
[ "folium", "python" ]
stackoverflow_0074306852_folium_python.txt
Q: Django - How to add multiple permissions on group? I have a list of permissions list = ['view', 'add', 'edit'] The permissions inside the list are already saved on my table. I first clear the group's previous permission so I can insert a new one group = Group.objects.get(name='Group1') group.permissions.clear() ...
Django - How to add multiple permissions on group?
I have a list of permissions list = ['view', 'add', 'edit'] The permissions inside the list are already saved on my table. I first clear the group's previous permission so I can insert a new one group = Group.objects.get(name='Group1') group.permissions.clear() Is there a way to add the list of permission to Group1 p...
[ "Say you have an app named blog and a model named BlogPost and want to add permissions view, change, add for that model to the group named Blogger, you should be able to do:\nfrom django.contrib.auth.models import Group, Permission\n\ncodenames = ['view_blogpost', 'change_blogpost', 'add_blogpost']\n\ngroup = Group...
[ 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0071225949_django_django_authentication_python.txt
Q: Oanda API errors I am currently coding a candle plot system for the Oanda API on notebook and im having some errors. I will be attaching my 2 import files to this so you can follow better. import utils: def get_his_data_filename(pair, granularity): return f"his_data/{pair}_{granularity}.pkl" def get_instrum...
Oanda API errors
I am currently coding a candle plot system for the Oanda API on notebook and im having some errors. I will be attaching my 2 import files to this so you can follow better. import utils: def get_his_data_filename(pair, granularity): return f"his_data/{pair}_{granularity}.pkl" def get_instruments_data_filename(): ...
[ "Okay so I figured it out for my errors,\nnow my only issue is when executing the codes, I only see 1 MA but can't see the candles or the other MA\nbelow is an image.\n" ]
[ 0 ]
[]
[]
[ "api", "jupyter_notebook", "oanda", "python" ]
stackoverflow_0074348256_api_jupyter_notebook_oanda_python.txt
Q: numeric progressive filename with pandas I have a dataframe like this: |name |code| |---------|----| |fa.st.pdf|10 | |creed.txt|10 | |logs.log |11 | |log.s.txt|11 | |foo.bar |11 | what I need is to create a progressive filename for each code, like this: |name |code| |-----|----| |1.pdf|10 | |2.txt|1...
numeric progressive filename with pandas
I have a dataframe like this: |name |code| |---------|----| |fa.st.pdf|10 | |creed.txt|10 | |logs.log |11 | |log.s.txt|11 | |foo.bar |11 | what I need is to create a progressive filename for each code, like this: |name |code| |-----|----| |1.pdf|10 | |2.txt|10 | |1.log|11 | |2.txt|11 | |3.bar|11 | ...
[ "Use groupby.cumcount to enumerate the rows per group and str.extract to get the file extension. Concatenate both as string:\ndf['name'] = (df.groupby('code').cumcount().add(1).astype(str)\n + df['name'].str.extract('(\\.[^.]+$)', expand=False)\n )\n\nOutput:\n name code\n0 1.pdf 1...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074348396_dataframe_pandas_python.txt
Q: How to combine kivy file and loops in python files? I'm learning how to use kivy. And to get things a little more difficult, I'm using kivyMD to use themes. I'm trying to simply create a layout in a kivy file and fill it with a python loop in the python file. My python file, for example : from kivy.lang import Bu...
How to combine kivy file and loops in python files?
I'm learning how to use kivy. And to get things a little more difficult, I'm using kivyMD to use themes. I'm trying to simply create a layout in a kivy file and fill it with a python loop in the python file. My python file, for example : from kivy.lang import Builder from kivymd.app import MDApp from kivymd.uix.label ...
[ "After a lot of researchs, I found a solution. I hope it will help someone.\n'''\nfrom kivy.app import App \nfrom kivy.uix.label import Label\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.properties import ObjectProperty\nfrom kivy.lang import Builder\n\nKV=\"\"\"\n<MainScreen>:\n grid: _g...
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python", "python_3.x" ]
stackoverflow_0074306003_kivy_kivymd_python_python_3.x.txt
Q: Python 3sum solution using itertools module exceeds time limit Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. My solution passed 308/311 t...
Python 3sum solution using itertools module exceeds time limit
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. My solution passed 308/311 test cases, but exceeded the time limit when it got to 308. I used t...
[ "Consider the following code.\ndef threeSum(nums: List[int]) -> List[List[int]]:\n x = itertools.combinations(nums, 3)\n y = [sorted(i) for i in x if (sum(i) == 0)]\n z = []\n for i in y:\n if i not in z:\n z.append(i)\n return z\n\nNotice that in the last few lines you keep appendi...
[ 0 ]
[]
[]
[ "arrays", "combinations", "list_comprehension", "python", "python_itertools" ]
stackoverflow_0074347345_arrays_combinations_list_comprehension_python_python_itertools.txt
Q: changing the size of open3d point cloud I am trying to visualize the point clouds using the following code but I can't find the way to adjacent the point size. Although there is a parameter point_size= with o3d.visualization.draw([pcd], point_size=5) but i want to use draw_geometries for this work. Any help will b...
changing the size of open3d point cloud
I am trying to visualize the point clouds using the following code but I can't find the way to adjacent the point size. Although there is a parameter point_size= with o3d.visualization.draw([pcd], point_size=5) but i want to use draw_geometries for this work. Any help will be much appreciated pcd = o3d.io.read_point_cl...
[ "You can use + to increase the point size and - to decrease the point size in the draw_geometry visualization window.\nBy the way, you can use H to get help information.\n" ]
[ 0 ]
[]
[]
[ "open3d", "python" ]
stackoverflow_0073236168_open3d_python.txt
Q: Find the row indexes of several values in a numpy array I have an array X: X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) And I wish to find the index of the row of several values in this array: searched_values = np.array([[4, 2], ...
Find the row indexes of several values in a numpy array
I have an array X: X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) And I wish to find the index of the row of several values in this array: searched_values = np.array([[4, 2], [3, 3], [5, 6]]) F...
[ "Approach #1\nOne approach would be to use NumPy broadcasting, like so -\nnp.where((X==searched_values[:,None]).all(-1))[1]\n\nApproach #2\nA memory efficient approach would be to convert each row as linear index equivalents and then using np.in1d, like so -\ndims = X.max(0)+1\nout = np.where(np.in1d(np.ravel_multi...
[ 45, 8, 8, 2, 1, 0, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0038674027_arrays_numpy_python.txt
Q: Check if a socket is already opened - python I have an azure timer function which runs every minute to trigger a socket which gets data from a website. I don't want to establish a connection everytime the timer runs the function. So, is there a way in Python which I can check if a socket is open for a particular w...
Check if a socket is already opened - python
I have an azure timer function which runs every minute to trigger a socket which gets data from a website. I don't want to establish a connection everytime the timer runs the function. So, is there a way in Python which I can check if a socket is open for a particular website on particular port? Or, is there a way to r...
[ "You can always use global variables to reuse objects in future invocations. The following example was copied from Google Cloud Platform documentation, but you can apply the same concept to your Azure Function:\n# Global (instance-wide) scope\n# This computation runs at instance cold-start\ninstance_var = heavy_com...
[ 0 ]
[]
[]
[ "azure_functions", "python", "python_3.x" ]
stackoverflow_0074348390_azure_functions_python_python_3.x.txt
Q: How to change treemap color scale on "Dash example - modal treemap" I try to change color scale on example (modal treemap). https://dash-example-index.herokuapp.com/modal-treemap I added color definition to treemap call but it does not change the color. Where I need to put my modification to make it active. fig = ...
How to change treemap color scale on "Dash example - modal treemap"
I try to change color scale on example (modal treemap). https://dash-example-index.herokuapp.com/modal-treemap I added color definition to treemap call but it does not change the color. Where I need to put my modification to make it active. fig = px.treemap( dff, path=[px.Constant("all"), "Segment", "Region...
[ "You should use color_continuous_scale along with color to be able to see the impact of the colors. You can use the following:\nfig = px.treemap(\n dff, path=[px.Constant(\"all\"), \"Segment\", \"Region\"], \n values=\"profit_derived\", \n color=\"profit_derived\",\n colo...
[ 1 ]
[]
[]
[ "plotly_dash", "python", "treemap" ]
stackoverflow_0074347228_plotly_dash_python_treemap.txt
Q: The target is binary, but I get "ValueError: Supported target types are: ('binary', 'multiclass'). Got 'unknown' instead." I'm facing an issue in a simple ML model using sklearn KFold I categorize my target value using the following code: # Import the DB df = pd.read_csv("DB_ML_TJA20182019.csv") #Transform continu...
The target is binary, but I get "ValueError: Supported target types are: ('binary', 'multiclass'). Got 'unknown' instead."
I'm facing an issue in a simple ML model using sklearn KFold I categorize my target value using the following code: # Import the DB df = pd.read_csv("DB_ML_TJA20182019.csv") #Transform continuous target into binary category = pd.cut(df.length,bins=[0,4,100],labels=[0,1]) df.insert(18,"length_over", category) Now, if I...
[ "Very late to the party, but I met this error while performing a multi-label classification and using MultilabelStratifiedKFold().\nEssentially, ensure that each label you have is a numpy array with correct data type (int, for example).\nIn my case, after performing some operations on a pd.DataFrame, the y label wa...
[ 0 ]
[]
[]
[ "machine_learning", "pandas", "python", "python_3.x", "scikit_learn" ]
stackoverflow_0062801653_machine_learning_pandas_python_python_3.x_scikit_learn.txt