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:
jupyterlab - change styling - font, font size
I recently updated to the most recent version of JupyterLab (0.28.12). I'm on Windows.
I've tried adjusting the variables.css file located in \Lib\site-packages\jupyterlab\themes\@jupyterlab\theme-light-extension of my Miniconda/Anaconda folder. I mainly want to chang... | jupyterlab - change styling - font, font size | I recently updated to the most recent version of JupyterLab (0.28.12). I'm on Windows.
I've tried adjusting the variables.css file located in \Lib\site-packages\jupyterlab\themes\@jupyterlab\theme-light-extension of my Miniconda/Anaconda folder. I mainly want to change the font family and size, which I've tried using ... | [
"I am running version 0.35.4 right now on Ubuntu and it is possible to edit the fonts in the Settings->Advanced Settings Editor, selected from the top bar menu.\nThere are a number of options that can be set by changing the json strings in the Raw View. See the picture below:\n\n",
"I'm on ubuntu, so probably ha... | [
23,
8,
6,
5,
0,
0
] | [] | [] | [
"css",
"jupyter_lab",
"python"
] | stackoverflow_0047048278_css_jupyter_lab_python.txt |
Q:
How do i avoid getting a list inside of a list
I am making a blackjack simulator with python and are having problems with when the player want another card. To begin with the player gets a random sample of two numbers from a list and then get the option to take another card or not to. When the answer is yes anothe... | How do i avoid getting a list inside of a list | I am making a blackjack simulator with python and are having problems with when the player want another card. To begin with the player gets a random sample of two numbers from a list and then get the option to take another card or not to. When the answer is yes another card is added to the random sample but it gets add... | [
"random.sample(kortlek,1)\nrandom.sample returns a list, so you end up appending a list to handspelare (which creates the sublists).\nYou could change append to extend, but random.sample(..., 1) is just random.choice, so it makes more sense to use handspelare.append(random.choice(kortlek)).\n",
"you should create... | [
3,
1
] | [
"Use list concatenation rather than append.\nhandspelare += random.sample(kortlek,1)\n\nappend will not unbundle its argument\na = [1]\na.append([2]) # [1, [2]]\n\na = [1]\na += [2] # [1, 2]\n\n"
] | [
-1
] | [
"blackjack",
"card",
"list",
"python"
] | stackoverflow_0074266511_blackjack_card_list_python.txt |
Q:
Dymos: How can I export the derivatives or jacobian?
I am trying to export the gradient information from the evtol_dymos_vectorized.py found here.
Here is a similar answer that I found.
I tried to record the derivatives the way you would in OpenMDAO. However, when I do so, I get the following error.
KeyError: 'tra... | Dymos: How can I export the derivatives or jacobian? | I am trying to export the gradient information from the evtol_dymos_vectorized.py found here.
Here is a similar answer that I found.
I tried to record the derivatives the way you would in OpenMDAO. However, when I do so, I get the following error.
KeyError: 'traj.phases.phase0->final_boundary_constraint->x'
import open... | [
"This is definitely a bug. I have put up an issue for it so that you can track its progress.\n"
] | [
0
] | [] | [] | [
"nonlinear_optimization",
"openmdao",
"python"
] | stackoverflow_0074255146_nonlinear_optimization_openmdao_python.txt |
Q:
Selectively convert dict of lists with dicts into a dataframe
I would like to convert a dict of lists of a dict into a dataframe selectively. I would only like to take the publisher and the title from the results if the publisher name is Benzinga:
{'results': [{'id': 'knNyIzsECbl3YYPAKIQsEoaO4_roXDftV-auy9lSB-w',... | Selectively convert dict of lists with dicts into a dataframe | I would like to convert a dict of lists of a dict into a dataframe selectively. I would only like to take the publisher and the title from the results if the publisher name is Benzinga:
{'results': [{'id': 'knNyIzsECbl3YYPAKIQsEoaO4_roXDftV-auy9lSB-w',
'publisher': {'name': 'Benzinga',
'homepage_url': 'https://... | [
"Normalize the dict using comprehension then create a new dataframe\npd.DataFrame({'publisher': d['publisher']['name'], 'title': d['title']} for d in dct['results'])\n\nOr you can also try json_normalize:\npd.json_normalize(dct['results'])[['title', 'publisher.name']]\n\nResult\n publisher ... | [
1,
0
] | [] | [] | [
"dataframe",
"dictionary",
"list",
"pandas",
"python"
] | stackoverflow_0074266172_dataframe_dictionary_list_pandas_python.txt |
Q:
Python Decorator function
I am tweaking a Telegram bot.
I have several async functions that lead to specific actions. Since I am using handlers and commands to call the bot, in every function I need to split the user message or atleast the first word. I am looking for decorator function that can do this for me ins... | Python Decorator function | I am tweaking a Telegram bot.
I have several async functions that lead to specific actions. Since I am using handlers and commands to call the bot, in every function I need to split the user message or atleast the first word. I am looking for decorator function that can do this for me instead of me putting another line... | [
"just like you make any other decorator\ndef my_decorator(fn):\n def __inner(update:Update, context:ContextTypes.DEFAULT_TYPE):\n text_input = str(update.message.text.split(' ', 1)[1])\n wiki_text = wikipedia.page(f'{text_input}')\n return fn(wiki_text, context)\n return __inner\n\n@my_de... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074266636_python.txt |
Q:
How do I pass multiple arguments through Keras Tuner Function
I am having difficulty figuring out how to pass multiple arguments through keras tuner function. I looked all over all available documentation and questions related to this and I could not find anything for this particular problem.
I just want to be abl... | How do I pass multiple arguments through Keras Tuner Function | I am having difficulty figuring out how to pass multiple arguments through keras tuner function. I looked all over all available documentation and questions related to this and I could not find anything for this particular problem.
I just want to be able to pass additional arguments through this function:
def build_mod... | [
"You can create your own HyperModel subclass to do achieve this, check this link.\nExample implementation, which will do what you are trying to do :-\nimport kerastuner as kt\n\nclass MyHyperModel(kt.HyperModel):\n\n def __init__(self, some_val_1, some_val_2):\n self.some_val_1 = some_val_1\n self.... | [
4,
0
] | [] | [] | [
"arguments",
"keras",
"parameter_passing",
"python",
"tensorflow"
] | stackoverflow_0063767275_arguments_keras_parameter_passing_python_tensorflow.txt |
Q:
Regex error in python but not PCRE2 (regex101.com)
I'm trying to create a regex to validate the following formats:
[1 Or More Upper-Case Letters not including X] e.g BY, BZ, B
[1 Or More Upper-Case Letters not including X][X][Any Number of Digits between 1-9] e.g. BYX11, BZX12, BX5
I developed this regular expre... | Regex error in python but not PCRE2 (regex101.com) | I'm trying to create a regex to validate the following formats:
[1 Or More Upper-Case Letters not including X] e.g BY, BZ, B
[1 Or More Upper-Case Letters not including X][X][Any Number of Digits between 1-9] e.g. BYX11, BZX12, BX5
I developed this regular expression using regex101.com with the PCRE2 flavor
^[A-WY-Z]... | [
"You can just use\n^[A-WY-Z]+(?:X[1-9]+)?$\n\nSee the regex demo.\nDetails:\n\n^ - start of string\n[A-WY-Z]+ - one or more uppercase ASCII letters other than X\n(?:X[1-9]+)? - an optional sequence of X and one or more non-zero digits\n$ - end of string.\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x",
"regex"
] | stackoverflow_0074266639_python_python_3.x_regex.txt |
Q:
Destroy an on-screen tkinter label and then create another
I'm creating a BMI calc that works fine, however, once it has displayed the result label if someone enters a different value and a new label is made the previous one still remains.
I'm trying to code it so that the first label disappears once the calc func... | Destroy an on-screen tkinter label and then create another | I'm creating a BMI calc that works fine, however, once it has displayed the result label if someone enters a different value and a new label is made the previous one still remains.
I'm trying to code it so that the first label disappears once the calc function is rerun but I can't get it to work. No matter where I put ... | [
"Instead of dynamically creating a new lblResult for each BMI case, you should create a single label and update its value when necessary\n# SOME CODE HAS BEEN OMITTED FOR BREVITY\nimport tkinter as tk\n\nwindow = tk.Tk() # creates the GUI window\nwindow.title(\"BMI\") # labels the window title\nwindow.geometry(\"... | [
1
] | [] | [] | [
"function",
"label",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074266680_function_label_python_tkinter_user_interface.txt |
Q:
Pandas join record by matching on at least one column
I have the following dataframe:
id phone email
10352897
10352897 10225967
10352897 user@gmail.com
10352897 10225967 user@gmail.com
10225967
10225967 user@gmail.com
... | Pandas join record by matching on at least one column | I have the following dataframe:
id phone email
10352897
10352897 10225967
10352897 user@gmail.com
10352897 10225967 user@gmail.com
10225967
10225967 user@gmail.com
user@gmail.com
23578910
23578910 382567... | [
"Use pandas.core.groupby.DataFrameGroupBy.aggregate as follows\ndf_new = df.groupby('id').agg(lambda x: x.value_counts().index[0]).reset_index()\n\n[Out]:\n\n id phone email\n0 10352897 10225967 user@gmail.com\n1 23578910 38256789 user2@gmail.com\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074266629_pandas_python.txt |
Q:
Issue with importing TextExplainer from eli5.lime package relating to deprecated 'itemfreq' function
I am working on a BERT model for text classification and wish to use TextExplainer for model interpretation. However, when loading the library eli5.lime I receive the following error:
ImportError: cannot import nam... | Issue with importing TextExplainer from eli5.lime package relating to deprecated 'itemfreq' function | I am working on a BERT model for text classification and wish to use TextExplainer for model interpretation. However, when loading the library eli5.lime I receive the following error:
ImportError: cannot import name 'itemfreq' from 'scipy.stats'
It appears that scipy.stats.itemfreq is deprecated and was removed from t... | [
"import scipy\nimport numpy as np\ndef monkeypath_itemfreq(sampler_indices):\n return zip(*np.unique(sampler_indices, return_counts=True))\n\nscipy.stats.itemfreq=monkeypath_itemfreq\n\n"
] | [
0
] | [] | [] | [
"eli5",
"lime",
"python",
"scipy",
"scipy.stats"
] | stackoverflow_0073556675_eli5_lime_python_scipy_scipy.stats.txt |
Q:
Get info from table of specific position td with beautifulsoup
Hello I have a tbody html with various tr and tds inside them, and i want to extract always the 3,7,11 td position inside every tr, how can i do that?
I want to extract from X row inside table, value of position td 1 7 and 11 of every row.
Thanks in ad... | Get info from table of specific position td with beautifulsoup | Hello I have a tbody html with various tr and tds inside them, and i want to extract always the 3,7,11 td position inside every tr, how can i do that?
I want to extract from X row inside table, value of position td 1 7 and 11 of every row.
Thanks in advance
| [
"I think something like this in selenium works,\n\nhow_many_tr = driver.find_elements(By.CSS_SELECTOR,'table tbody tr')\n\nfor i in range(len(how_many_tr)):\n driver.find_element(By.XPATH,f'table/tbody/tr[{i}]/td[1]').text\n driver.find_element(By.XPATH,f'table/tbody/tr[{i}]/td[7]').text\n driver.find_elem... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074266089_beautifulsoup_python_selenium_web_scraping.txt |
Q:
Numpy: np.where() with new dimensions
Python/numpy beginner so this should be easy to solve. Given a numpy 2d array of floats map, e.g.
map = [[0.19982308 0.19982308 0.19986019 ... 0.25456086 0.25463998 0.25463998]
[0.19982308 0.19982308 0.19986019 ... 0.25456086 0.25463998 0.25463998]
[0.19998285 0.19... | Numpy: np.where() with new dimensions | Python/numpy beginner so this should be easy to solve. Given a numpy 2d array of floats map, e.g.
map = [[0.19982308 0.19982308 0.19986019 ... 0.25456086 0.25463998 0.25463998]
[0.19982308 0.19982308 0.19986019 ... 0.25456086 0.25463998 0.25463998]
[0.19998285 0.19998285 0.20000038 ... 0.25459546 0.25466287... | [
"transform map to a np array first:\nimport numpy as np\n#import matplotlib.pyplot as plt\n\n#create map\nmap = np.random.rand(200,200)\n\n#to show\n#plt.matshow(map)\n\n\noutput_var = np.zeros([*map.shape,3])\n\noutput_var[map>0.4]=np.array([255,255,255])\n\n\n",
"There is a broadcast issue because numpy.where s... | [
2,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074266658_arrays_numpy_python.txt |
Q:
Django AttributeError: 'list' object has no attribute 'sort_values'
I'm getting AttributeError: 'list' object has no attribute 'sort_values' in below code,
task.py:
from __future__ import absolute_import,unicode_literals
from celery import shared_task
from time import sleep
import eda
import os
@shared_task
def a... | Django AttributeError: 'list' object has no attribute 'sort_values' | I'm getting AttributeError: 'list' object has no attribute 'sort_values' in below code,
task.py:
from __future__ import absolute_import,unicode_literals
from celery import shared_task
from time import sleep
import eda
import os
@shared_task
def aync_task(amz_columns_dict, download_path, file_name, data):
sleep(10)... | [
"Your data variable that is being passed to the async_task method is being set using data = json.loads(json_records) so it's a normal Python list. You must convert this to a Pandas dataframe before using it with eda_object.create_report.\n",
"this solved my issue:\ntask.py :\n@shared_task\ndef aync_task(amz_colum... | [
0,
0
] | [] | [] | [
"dataframe",
"django",
"django_celery",
"pandas",
"python"
] | stackoverflow_0074254260_dataframe_django_django_celery_pandas_python.txt |
Q:
Determine possibilities where all elements in a list are present and in the same order as in another list
The problem
e.g.
list1 = ["a", "c", "b", "a", "b", "c", "a", "c", "b"]
list2 = ["a", "c", "a", "b"]
Possibilities:
1.
list1 = ["a", "c", "b", "a", "b", "c", "a", "c", "b"]
list2 = ["a", "c", "a", "b"]
those ar... | Determine possibilities where all elements in a list are present and in the same order as in another list | The problem
e.g.
list1 = ["a", "c", "b", "a", "b", "c", "a", "c", "b"]
list2 = ["a", "c", "a", "b"]
Possibilities:
1.
list1 = ["a", "c", "b", "a", "b", "c", "a", "c", "b"]
list2 = ["a", "c", "a", "b"]
those are indexes: [1, 2, 4, 5
2.
list1 = ["a", "c", "b", "a", "b", "c", "a", "c", "b"]
list2 = ["a", "c", "a", "b"]
th... | [
"The following python code does the job I think. It is not necessarily optimal and uses only basic python capabilities.\ntarget = [ \"a\", \"c\", \"b\", \"a\", \"b\", \"c\", \"a\", \"c\", \"b\" ]\ntemplate = [ \"a\", \"c\", \"a\", \"b\" ]\n\ndef getEmbedded(target, relNdx, template):\n embeddeds = []\n if le... | [
0,
0
] | [] | [] | [
"algorithm",
"python",
"subsequence"
] | stackoverflow_0074253018_algorithm_python_subsequence.txt |
Q:
Can not switch to iFrame using selenium (python)
I encountered a challenge while trying to switch to a certain iFrame using selenium (in python if it matters)
I have this inner iFrame which resides in this weird HTML component
The iFrame is in this macroponent element:
and I cannot fetch it via selenium. I tried ... | Can not switch to iFrame using selenium (python) | I encountered a challenge while trying to switch to a certain iFrame using selenium (in python if it matters)
I have this inner iFrame which resides in this weird HTML component
The iFrame is in this macroponent element:
and I cannot fetch it via selenium. I tried using driver.switch_to_frame("gsft_main") and also tri... | [
"Refer this link for one of the example using CSS selector to access iframe in Shadow-dom:\nHow to access element inside shadow root in Robot framework\nThis link has full explanation to work with shadow-dom using python, java, javascript\nhttps://titusfortner.com/2021/11/22/shadow-dom-selenium.html\n"
] | [
0
] | [] | [] | [
"iframe",
"python",
"selenium"
] | stackoverflow_0074266420_iframe_python_selenium.txt |
Q:
How can I rename list items so that they are all unique?
I have a list like this:
lista=['a','b','b','c','d','e','c','e','b','b']
note that the list will be filled from another source, so I can't know the items nor number
what I need is this result:
['a','b','b_1','c','d','e','c_1','e_1','b_2','b_3']
I tried wit... | How can I rename list items so that they are all unique? | I have a list like this:
lista=['a','b','b','c','d','e','c','e','b','b']
note that the list will be filled from another source, so I can't know the items nor number
what I need is this result:
['a','b','b_1','c','d','e','c_1','e_1','b_2','b_3']
I tried with recursive checks but it doesn't garantee that all recurranci... | [
"You can make a counter variable to keep track of how many have been seen:\nlista = ['a','b','b','c','d','e','c','e','b','b']\n\noutput = []\ncounter = {}\n\nfor x in lista:\n if x in counter.keys():\n output.append(f\"{x}_{counter[x]}\")\n counter[x] += 1\n else:\n output.append(x)\n ... | [
7,
3,
0
] | [
"I would keep a hashmap (string to number) tracker of all the different entries and update the number as used like this:\nfunction arrayCounter():\nhashmap = {}\nnew_list = []\n\nfor x in list:\n if x in hashmap:\n new_list.append(x+\"_\"+hashmap[x])\n hashmap[x] = hashmap[x] +1\n else:\n ... | [
-1
] | [
"list",
"python"
] | stackoverflow_0074266797_list_python.txt |
Q:
Trying to scrape projections from PrizePicks
I am currently trying to streamline my projection model process by scraping the projections from PrizePicks. I keep running into an error that says Invalid Syntax. Any help would be greatly appreciated. Here is my code
import requests
import pandas as pd
pp_props_url... | Trying to scrape projections from PrizePicks | I am currently trying to streamline my projection model process by scraping the projections from PrizePicks. I keep running into an error that says Invalid Syntax. Any help would be greatly appreciated. Here is my code
import requests
import pandas as pd
pp_props_url = 'https://api.prizepicks.com/projections?league_... | [
"Your questions was troublesome for me. First of all, I got prompted errors on retrieving the .json file. These were solved after removing 'Accept-Encoding': 'gzip, deflate, br' from your headers. After this indeed a valid .json file is returned, but perhaps this was already the case for you.\nThen after retrievin... | [
0,
0
] | [] | [] | [
"api",
"json",
"python",
"request",
"web_scraping"
] | stackoverflow_0074250698_api_json_python_request_web_scraping.txt |
Q:
How to check and see if a value in rows below is less than the current row value
I am trying to create a conditional column (We will call it "Y/N"), to test and see if a value in all rows below have a value that is greater than the current row value. If so, the binary "Y/N" column would return "Y". It also needs t... | How to check and see if a value in rows below is less than the current row value | I am trying to create a conditional column (We will call it "Y/N"), to test and see if a value in all rows below have a value that is greater than the current row value. If so, the binary "Y/N" column would return "Y". It also needs to check and see if any of the rows below have the same ID. In this case it will be sor... | [
"def my_func(x):\n ind = (df.loc[x.index[0]:, 'ID'] == x['ID'].values[0]) & (df.loc[x.index[0]:, 'Value'] > x['Value'].values[0])\n dff = df[x.index[0]:]\n if len(dff[ind]) > 0:\n return 'Y'\n else:\n return 'N'\n\ndf.loc[:, 'Y/N'] = df.groupby(df.index).apply(my_func)\n\nprint(df)\n\nThe ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074257494_pandas_python.txt |
Q:
How to save List of Dictionaries in a .txt or .doc file in prettify format?
I have a list of dictionaries in python.
[{'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 34731019, 'yId': 28782454, 'zId': 'dafd'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 48046171, 'yId': 28984154, ... | How to save List of Dictionaries in a .txt or .doc file in prettify format? | I have a list of dictionaries in python.
[{'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 34731019, 'yId': 28782454, 'zId': 'dafd'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 48046171, 'yId': 28984154, 'zId': 'mmgj'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 3... | [
"Instead of using pprint.pprint use pprint.pformat, then save normally:\nimport pprint\n\nd = [{'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 34731019, 'yId': 28782454, 'zId': 'dafd'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 48046171, 'yId': 28984154, 'zId': 'mmgj'}}, {'type'... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074266857_pandas_python.txt |
Q:
How do I Convert a "String Dictionary" into an flatten dictionary
I'm trying to flatten a column in a Dataframe my_df['replies'].
I have tried pd.json_normalize without success (error 'str' object has no attribute 'values'). I also tried answers to similar questions but nothing has worked for me.
I would like to ... | How do I Convert a "String Dictionary" into an flatten dictionary | I'm trying to flatten a column in a Dataframe my_df['replies'].
I have tried pd.json_normalize without success (error 'str' object has no attribute 'values'). I also tried answers to similar questions but nothing has worked for me.
I would like to get a dataframe with a column for ID (which will be repeated because th... | [
"Your question is a bit blur, but I hope I understand what you expect. You want to create a replies dataframe, with columns all the keys in the serialised string\nI created a dummy dictionary (because your dict is malformed)\nmy_dict = {'ID': {166: 166, 167: 167},\n 'replies': {166: \"[{'comment_id': '5438065574108... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074266017_pandas_python.txt |
Q:
Python Unit Test : How do I test loading data from database?
I'm using psycopg2-binary to connect to a database. This is the class I've written to query data from the database given a query and return as a dataframe. I'm stuck on how I would unit test this function without having to hit the real database.
code :
i... | Python Unit Test : How do I test loading data from database? | I'm using psycopg2-binary to connect to a database. This is the class I've written to query data from the database given a query and return as a dataframe. I'm stuck on how I would unit test this function without having to hit the real database.
code :
import pandas as pd
class HitDB(object):
def __init__(self, db... | [
"Since all the function does is pass its query and self.conn to another function, mock pd.read_sql and check it receives the expected arguments.\nWhich suggests getting rid of this function and just call pd.read_sql directly.\n\nIf it did something more significant with the database, run a local PostgreSQL server (... | [
1
] | [] | [] | [
"pytest",
"python",
"python_3.x",
"unit_testing"
] | stackoverflow_0074266657_pytest_python_python_3.x_unit_testing.txt |
Q:
Python can't find packages in Virtual Environment
I'm trying to setup my environment for a project but python isn't able to find the modules I've installed with pip.
I did the following:
mkdir helloTwitter
cd helloTwitter
virtualenv myenv
Installing setuptools, pip, wheel...done.
source myenv/bin/activate
pip ins... | Python can't find packages in Virtual Environment | I'm trying to setup my environment for a project but python isn't able to find the modules I've installed with pip.
I did the following:
mkdir helloTwitter
cd helloTwitter
virtualenv myenv
Installing setuptools, pip, wheel...done.
source myenv/bin/activate
pip install tweepy
Collecting tweepy
Using cached tweepy-3.5... | [
"It looks like you're manually setting your $PATH to point to your virtual environment. The whole point of the myenv/bin/activate script is to take care of this for you. \nOnce you have activated your virtual environment, any package you install using pip will be placed in the relevant venv site-packages directory ... | [
4,
3,
0,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0039630944_python_virtualenv.txt |
Q:
Getting parent node through child node using XPATH
I'm trying to access parent node of an element in a tree using e.find('..)' but it is not working. For the fallowing code:
import xml.etree.ElementTree as etree
xml = "<a> <b> </b> </a>"
root = etree.fromstring(xml)
child = root.find('*')
print(child.find('..')... | Getting parent node through child node using XPATH | I'm trying to access parent node of an element in a tree using e.find('..)' but it is not working. For the fallowing code:
import xml.etree.ElementTree as etree
xml = "<a> <b> </b> </a>"
root = etree.fromstring(xml)
child = root.find('*')
print(child.find('..'))
the output is: None, why? and, how can i get parent ... | [
"Your snippet Returns None because the parent of the root is the root itself.\nTry lxml Package, lxml is a Pythonic binding for the C libraries libxml2 and libxslt.\nIt is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatib... | [
0
] | [
"It is possible to get the parent with ElementTree, but you cannot use find() on the child directly.\nThe documentation states:\n\n.. selects the parent element. Returns None if the path attempts to reach the ancestors of the start element (the element find was called on).\n\nDemo:\nimport xml.etree.ElementTree as ... | [
-1
] | [
"elementtree",
"python",
"xml_parsing",
"xpath"
] | stackoverflow_0074260844_elementtree_python_xml_parsing_xpath.txt |
Q:
Find the maximum cost path from the bottom-left corner to the top-right corner
Hi, everybody! I try to find best solution with assignment in title. But I don't understand how I can output way of calculation. I write python program, it can output random massive and max sum, but I need way too.
from collections impo... | Find the maximum cost path from the bottom-left corner to the top-right corner | Hi, everybody! I try to find best solution with assignment in title. But I don't understand how I can output way of calculation. I write python program, it can output random massive and max sum, but I need way too.
from collections import deque as queue
import random
import numpy as np
array=[]
def creatArray():
r ... | [
"A naive solution would just be to store the route taken to achieve the max in every cell in max_value as you build the max_value array. A very ugly solution would look something like below\nNOTE: the implementation below does not count for multiple valid 'way's, it will simply choose the first valid 'way' it find... | [
0,
0
] | [] | [] | [
"dynamic_programming",
"python"
] | stackoverflow_0074266046_dynamic_programming_python.txt |
Q:
Python Turtle becomes unresponsive and hangs after using a while loop
I'm trying to make a program that is essentially an etchasketck, with some minor tweaks for my school project(the required use of a main function, wasd as movement controls, and q to quit the program and p to pick up or drop down the turtle pen)... | Python Turtle becomes unresponsive and hangs after using a while loop | I'm trying to make a program that is essentially an etchasketck, with some minor tweaks for my school project(the required use of a main function, wasd as movement controls, and q to quit the program and p to pick up or drop down the turtle pen). I was testing this code in trinket.io and it was working fine. You can se... | [
"You've effectively put a while True: loop in an event-driven program where one should never be used. If I were writing this for the command line, with the constraints listed, I might go about it this way (dropping command line processing for example simplicity):\nfrom turtle import Screen, Turtle\n\nWIDTH, HEIGHT... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_turtle",
"turtle_graphics",
"while_loop"
] | stackoverflow_0074266225_python_python_3.x_python_turtle_turtle_graphics_while_loop.txt |
Q:
Edit function to work for arrays instead of lists
I have a function that does the following:
Takes uses the list as an input
Computes the sum of the list
Appends the output (the sum) to the input list
Runs itself again (this time with a list of N + 1 data).
I want to to do this exact thing for an input of a nump... | Edit function to work for arrays instead of lists | I have a function that does the following:
Takes uses the list as an input
Computes the sum of the list
Appends the output (the sum) to the input list
Runs itself again (this time with a list of N + 1 data).
I want to to do this exact thing for an input of a numpy array, but I don't get a complete solution.
This is w... | [
"It's probably best to form the result array at the start of the function. numpy.append is quite slow.\ndef AppendSumNP(data, steps, dtype = np.float64 ):\n result = np.zeros( len(data) + steps, dtype = dtype ) \n # The result array is big enough for the whole result\n result[ :len(data) ] = data\n for... | [
0
] | [] | [] | [
"arrays",
"for_loop",
"numpy",
"python"
] | stackoverflow_0074264797_arrays_for_loop_numpy_python.txt |
Q:
How to return the max value from another dataframe
I have two dataframes:
df1 is a reference table with a list of individual codes and their corresponding values.
df2 is a excerpt from a larger dataset, wherein one of the columns will contain multiple examples of the codes. It will also contain other values I want... | How to return the max value from another dataframe | I have two dataframes:
df1 is a reference table with a list of individual codes and their corresponding values.
df2 is a excerpt from a larger dataset, wherein one of the columns will contain multiple examples of the codes. It will also contain other values I want to ignore e.g. blanks and 'Not Applicable'.
I need to s... | [
"Code\ndf2['max'] = (\n df2['Code']\n .str.split(',')\n .explode()\n .map(df1.set_index('Code')['Value'])\n .groupby(level=0).max()\n)\n\nHow it works?\n\nSplit by delimiter ,\nExplode to convert lists to rows\nUse map to substitute values from df1\nGroupby on level=0 to find max value per row group\... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074266371_dataframe_pandas_python.txt |
Q:
How can I get overflow bin in my histogram using plotly/python
I am using this code to build a histogram:
import matplotlib.pyplot as plt
import plotly.express as px
df = px.data.tips()
fig = px.histogram(dataset, x="salesperday")
fig.update_traces(xbins=dict( # bins used for histogram
start=0.0,
... | How can I get overflow bin in my histogram using plotly/python | I am using this code to build a histogram:
import matplotlib.pyplot as plt
import plotly.express as px
df = px.data.tips()
fig = px.histogram(dataset, x="salesperday")
fig.update_traces(xbins=dict( # bins used for histogram
start=0.0,
end=1400.0,
size=40
))
fig.show()
How can I customize ... | [
"Try this:\nimport plotly.express as px\nimport numpy as np\nimport pandas as pd\n\n# Force values outside range to a_min and a_max\ndf[\"salesperday_clip\"] = np.clip(salesperday.values, a_min=-0, a_max=75)\n\nfig = px.histogram(df, \"salesperday_clip\")\n\nWe use numpy.clip() which forces any values outside the r... | [
0
] | [] | [] | [
"histogram",
"plotly",
"python",
"statistics"
] | stackoverflow_0074169101_histogram_plotly_python_statistics.txt |
Q:
Plotext and Curses - windows
Needed help with this code:
import plotext as plt
from contextlib import redirect_stdout
import io
import curses
import locale
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()
PlotFile = io.StringIO()
with redirect_stdout(PlotFile):
y = plt.sin() # sinusoi... | Plotext and Curses - windows | Needed help with this code:
import plotext as plt
from contextlib import redirect_stdout
import io
import curses
import locale
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()
PlotFile = io.StringIO()
with redirect_stdout(PlotFile):
y = plt.sin() # sinusoidal signal
plt.scatter(y, mar... | [
"the example does not run on my machine, but I can tell you that plotext outputs [ inside the ansi code of the colored plot.\nHere is, for example, the string \"plotext\" colored red:\n'\\x1b[38;5;1mplotext\\x1b[0m'\n\nIf undesired, try the clear_color() method to remove colors and so the undesired ansi codes. Good... | [
1
] | [] | [] | [
"python",
"python_curses",
"terminal",
"unicode",
"utf_8"
] | stackoverflow_0071450124_python_python_curses_terminal_unicode_utf_8.txt |
Q:
How to get Microsoft Graph API token to read mails
I'm trying to retrieve mails from my organization's mailbox, and I can do that via Graph Explorer. However, when I use the same information that I used in Graph Explorer, the generated token returns an error stating '/me request is only valid with delegated authen... | How to get Microsoft Graph API token to read mails | I'm trying to retrieve mails from my organization's mailbox, and I can do that via Graph Explorer. However, when I use the same information that I used in Graph Explorer, the generated token returns an error stating '/me request is only valid with delegated authentication flow.' in me/messages endpoint.
So, how can I g... | [
"It sounds like the endpoint you're using in Graph Explorer is something like this\nhttps://graph.microsoft.com/v1.0/me/messages\n/me is referring to the user signed into Graph Explorer. If you want to read another user's messages you would use\nhttps://graph.microsoft.com/v1.0/users/user@domain.com/messages\nWhen ... | [
1
] | [] | [] | [
"microsoft_graph_api",
"postman",
"python"
] | stackoverflow_0074264483_microsoft_graph_api_postman_python.txt |
Q:
Joining 2 dictionary in python with specific value
i tried to join this 2 dictionary
company_detail_list = {
'Company 1': {
'name': 'Company 1',
'domain': 'Retail'
},
'Company 2': {
'name': 'Company 2',
'domain': 'Construction'
}
}
employee_detail_list = {
'John... | Joining 2 dictionary in python with specific value | i tried to join this 2 dictionary
company_detail_list = {
'Company 1': {
'name': 'Company 1',
'domain': 'Retail'
},
'Company 2': {
'name': 'Company 2',
'domain': 'Construction'
}
}
employee_detail_list = {
'John Doe': {
'full_name': 'John Doe',
'compa... | [
"You can use dict.get() and dict.update() and create your list of dicts like the below:\nlst = []\nfor k, v in employee_detail_list.items():\n dct_tmp = v\n dct_tmp.update({'domain' : company_detail_list.get(v['company'], {}).get('domain')})\n lst.append(dct_tmp)\nprint(lst)\n\nOutput:\n[\n {'full_name'... | [
2
] | [] | [] | [
"arrays",
"dictionary",
"json",
"list",
"python"
] | stackoverflow_0074267088_arrays_dictionary_json_list_python.txt |
Q:
An element is visible and still not able to click on it like I click on others like it
I click on a specific button on a page, but for some reason there is one of the buttons that I can't click on, even though it's positioned exactly like the other elements like it that I can click on.
The code below as you will n... | An element is visible and still not able to click on it like I click on others like it | I click on a specific button on a page, but for some reason there is one of the buttons that I can't click on, even though it's positioned exactly like the other elements like it that I can click on.
The code below as you will notice, it opens a page, then clicks to access another page, do this step because only then c... | [
"What you missing here is to wrap the command in the loop opening those sections with try-except block.\nthe following code works. I tried running is several times.\nimport datetime\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.chrome.ser... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_firefoxdriver",
"selenium_webdriver",
"try_catch"
] | stackoverflow_0074264688_python_selenium_selenium_firefoxdriver_selenium_webdriver_try_catch.txt |
Q:
Vaex: getValues / rows from a filtered dataframe
I am trying to filter a dataframe and get the rows that meet the filter criteria. I have been able to get a the first object from the dataframe by using the select function first and then calling the evaluate function to get the value:
df.select( (df['mycol1'] =... | Vaex: getValues / rows from a filtered dataframe | I am trying to filter a dataframe and get the rows that meet the filter criteria. I have been able to get a the first object from the dataframe by using the select function first and then calling the evaluate function to get the value:
df.select( (df['mycol1'] == filter_val1) & (df['mycol2'] == filter_val2))
x_... | [
"Does this fit your usecase:\ndf_filtered = df[(df['mycol1'] == filter_val1) & (df['mycol2'] == filter_val2)]\n\nAlternatively, if you need to gradually build an expression you are going to use to filter the dataframe, you can also do:\nboolean_expression = df['mycol1'] == filter_val1) & (df['mycol2'] == filter_val... | [
0
] | [] | [] | [
"dataframe",
"python",
"vaex"
] | stackoverflow_0074256257_dataframe_python_vaex.txt |
Q:
How can I get the max of two lists
my goal is to get the max of two lists,
for instance :
list a -[1,2,3]
list b - [0,4,1]
the desire resuls: 1,4,3
def ddh(a,b):
v=[]
for i,j in range(len(a),len(b)):
if a[i]>b[j]:
v.append (a[i])
else:
v.append (b[j])
return v
... | How can I get the max of two lists | my goal is to get the max of two lists,
for instance :
list a -[1,2,3]
list b - [0,4,1]
the desire resuls: 1,4,3
def ddh(a,b):
v=[]
for i,j in range(len(a),len(b)):
if a[i]>b[j]:
v.append (a[i])
else:
v.append (b[j])
return v
a=[1,2,555,9999]
b=[22,... | [
"You can use a list comprehension to iterate over the 2 lists at the same time using zip and take the max of every iteration:\nlist_a = [1, 2, 3]\nlist_b = [0, 4, 1]\n\nmaxes = [max(a, b) for a, b in zip(list_a, list_b)]\n# [1, 4, 3]\n\nYou don't even need to unpack the tuple:\nmaxes = [max(values) for values in z... | [
6,
0,
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074266692_list_python_python_3.x.txt |
Q:
Pandas: get unique rows with unique value in column grouped by another column value
Let's say I hace a datframe like this:
df = pd.DataFrame({
'COUNTRY_CODE': ['CO','CO','CO','BR','BR','BR'],
'VERTICAL_GROUP_ID': [2,2,3,2,3,3],
'SUB_VERTICAL': ['SUPER','SUPER','HOME','LICOR','SPORTS','HOME'],
'PRODUCT_ID': [111... | Pandas: get unique rows with unique value in column grouped by another column value | Let's say I hace a datframe like this:
df = pd.DataFrame({
'COUNTRY_CODE': ['CO','CO','CO','BR','BR','BR'],
'VERTICAL_GROUP_ID': [2,2,3,2,3,3],
'SUB_VERTICAL': ['SUPER','SUPER','HOME','LICOR','SPORTS','HOME'],
'PRODUCT_ID': [1111,1111,1111,1111,1111,2222],
'SHOWN': [7,8,12,14,16,1],
})
I want to get in another da... | [
"You could try:\ndf.groupby(['COUNTRY_CODE', 'VERTICAL_GROUP_ID', 'PRODUCT_ID']).agg('first').reset_index()\n\n COUNTRY_CODE VERTICAL_GROUP_ID PRODUCT_ID SUB_VERTICAL SHOWN\n0 BR 2 1111 LICOR 14\n1 BR 3 1111 SPORTS 16\n2 ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074267021_pandas_python.txt |
Q:
Cartesian zoom with polar plot in python
I am trying to plot some data in polar coordinates (I am currently using the polar projection):
The code I am using is the following:
import matplotlib.pyplot as plt
import numpy as np
# Create radial and angular array
r = np.linspace(1.0,10,11)
t = np.linspace(0.0,0.5*np... | Cartesian zoom with polar plot in python | I am trying to plot some data in polar coordinates (I am currently using the polar projection):
The code I am using is the following:
import matplotlib.pyplot as plt
import numpy as np
# Create radial and angular array
r = np.linspace(1.0,10,11)
t = np.linspace(0.0,0.5*np.pi,101)
# Define the quantity that I want to... | [
"You can create an X, Y mesh yourself that is has a higher resolution on the inner part of the domain and use that with ax.pcolormesh()\n# Create radial and angular array\nr = np.linspace(1.0,10,11)\nt = np.linspace(0.0,0.5*np.pi,101)\n\n# Define the quantity that I want to plot\nz = np.zeros((len(t),len(r)))\nfor ... | [
1,
1
] | [] | [] | [
"matplotlib",
"plot",
"polar_coordinates",
"python",
"zooming"
] | stackoverflow_0069631851_matplotlib_plot_polar_coordinates_python_zooming.txt |
Q:
When there are duplicate values, how to return only one value from (loc)?
I tried to get only one value using (loc) but it takes all possible values. How to return only one value?
A:
@kkameleon has the right answer if you only want the first value. So you could modify that with .sort_values() to get the smallest... | When there are duplicate values, how to return only one value from (loc)? |
I tried to get only one value using (loc) but it takes all possible values. How to return only one value?
| [
"@kkameleon has the right answer if you only want the first value. So you could modify that with .sort_values() to get the smallest or largest either.\nWith your force/deformation data, you might want the average of the values, so use\nDeforAtMax.mean()\n\nThat'll give you a single value which is the average of the... | [
1
] | [] | [] | [
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074266532_jupyter_notebook_pandas_python.txt |
Q:
Python, django sessions, how update django session by key
i try to update my session data
my code:
try:
s = Session.objects.get(session_key=token)
except ObjectDoesNotExist:
return 400, {"error": "Token invalid."}
newObject = {'user_pk': 3, 'company_id': 55}
s['user_login_info'] = ... | Python, django sessions, how update django session by key | i try to update my session data
my code:
try:
s = Session.objects.get(session_key=token)
except ObjectDoesNotExist:
return 400, {"error": "Token invalid."}
newObject = {'user_pk': 3, 'company_id': 55}
s['user_login_info'] = newObject
s.save()
but i get error
TypeError: 'Session' ob... | [
"Taken from the source below.\n\nThe key point is that session_data is a pickled dictionary. The\nSession Middleware takes care of deserializing and serializing as a\nconvenience, but since you're not using it, you'll have to do the\nextra bits yourself.\n\nd = s.get_decoded()\nd['user_login_info'] = newObject\ns.s... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0071031254_django_python.txt |
Q:
User input required to update the date in my SQL file using Python
UPDATE! I am still looking for some way that to indicate to the user to make an update to these dates but I went with this method:
I declared a variable in my SQL file so it looks like:
declare @date date = DATE
Select * from table WHERE da... | User input required to update the date in my SQL file using Python | UPDATE! I am still looking for some way that to indicate to the user to make an update to these dates but I went with this method:
I declared a variable in my SQL file so it looks like:
declare @date date = DATE
Select * from table WHERE date = @date
and then in my python it looks like:
DATE = date(2022, ... | [
"You still have not posted any code requested, but I still give it a try.\nWhat you want is a parameterised query\ncursor.execute(\"select * from table as x where x.date = (?)\", (user_input))\n\nThis way you can define user_input and use it as part of the query.\nYou could also simply format a string:\nquery = f\"... | [
0
] | [] | [] | [
"date",
"python",
"replace",
"sql",
"string"
] | stackoverflow_0074257499_date_python_replace_sql_string.txt |
Q:
how to add a function to a button thats within a button on Tkinter
Im trying to add a command on newButton where when clicked, it shows a new blank page where i can then enter several input boxes and labels (almost like a survey)
I'm just not sure how to add a command to the 'START' button, to do all of this.
Thi... | how to add a function to a button thats within a button on Tkinter | Im trying to add a command on newButton where when clicked, it shows a new blank page where i can then enter several input boxes and labels (almost like a survey)
I'm just not sure how to add a command to the 'START' button, to do all of this.
This is the section of the code:
# create label text
myLabel_1 = Label(wind... | [
"Just re-configure the existing myButton once it's been clicked and calls myClick(), same with myLabel. There's no need to destroy these widgets only to recreate them later.\ndef start():\n pass\n\n\ndef myClick(lbl, btn): # add parameters to accept the label and button objects\n # update the label\n lbl.... | [
0
] | [] | [] | [
"button",
"command",
"function",
"python",
"tkinter"
] | stackoverflow_0074267234_button_command_function_python_tkinter.txt |
Q:
Ambivalent encoding of BeautifulSoup object constructed from website with duplicate meta header. How do I make sure the encoding is not mixed up?
I have fetched data from a website using BeautifulSoup module. I know from meta header that the source encoding for this document is 'iso-8859-1'. I also know that Beuti... | Ambivalent encoding of BeautifulSoup object constructed from website with duplicate meta header. How do I make sure the encoding is not mixed up? | I have fetched data from a website using BeautifulSoup module. I know from meta header that the source encoding for this document is 'iso-8859-1'. I also know that BeutifulSoup automatically transcode to 'UTF-8' upon creation of BeautifulSoup object.
import requests
from bs4 import BeautifulSoup
url = "https://www.ass... | [
"BeautifulSoup used the ISO-8859-1 encoding to decode the r.content (a bytes object) into Unicode (a str object). A str is not encoded at all. It is made of of Unicode code points.\nIt turns out the data wasn't encoded in ISO-8859-1. It was encoded in Windows-1252, a similar encoding with a few extra translation... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"encoding",
"html",
"python",
"utf_8"
] | stackoverflow_0074264812_beautifulsoup_encoding_html_python_utf_8.txt |
Q:
Points with different radius using HeatMapWithTime in Folium
I'm trying to plot a heatmap timelapse using Folium. However, I need each point to have a different radius.
I've tried the following:
from folium import plugins
map_hooray = folium.Map(location=[-23.5506507, -46.6333824],
zoom_start ... | Points with different radius using HeatMapWithTime in Folium | I'm trying to plot a heatmap timelapse using Folium. However, I need each point to have a different radius.
I've tried the following:
from folium import plugins
map_hooray = folium.Map(location=[-23.5506507, -46.6333824],
zoom_start = 10)
# Ensure you're handing it floats
df_acc['LAT'] = df_acc['... | [
"So here's a similar case for a standard heatmap:\nhttps://stackoverflow.com/a/53188739\nThe radius argument is expected to be an int, and is the same for all points in each HeatMap object. So the above answer's solution is to create a HeatMap object for each desired radius.\nSince you want this radius based on you... | [
0
] | [] | [] | [
"folium",
"heatmap",
"python"
] | stackoverflow_0072717946_folium_heatmap_python.txt |
Q:
get entered text and exit if the text in mass (tkinter)
good day! here's my code:
import tkinter as tk
namemass =["dev", "Dev1"]
self.entry_name = ttk.Entry(self)
self.entry_name.place(x=200, y=50)
btn_cancel = ttk.Button(self, text="cancel", command=self.destroy)
... | get entered text and exit if the text in mass (tkinter) | good day! here's my code:
import tkinter as tk
namemass =["dev", "Dev1"]
self.entry_name = ttk.Entry(self)
self.entry_name.place(x=200, y=50)
btn_cancel = ttk.Button(self, text="cancel", command=self.destroy)
btn_cancel.place(x=300, y=800)
btn_ok = ttk.Button(... | [
"To fetch the current entry text, use the get method:\ncurrent_text = Entry.get()\n\nin your example you can just:\nfrom tkinter import *\nimport sys\n\ndef destroy():\n name = entry_name.get()\n if name in namemass:\n sys.exit()\n\nroot = Tk()\nnamemass = [\"dev\", \"Dev1\"]\n\nentry_name = Entry(root... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0059288878_python_python_3.x_tkinter.txt |
Q:
Python Try Except stopping program as opposed to skipping over errror
I am running a sequence of scripts that are independent of each other. Meaning if one of them fails I want the rest to continue on and just be notified of the one that failed(I can implement the notification later). For now I am just trying to f... | Python Try Except stopping program as opposed to skipping over errror | I am running a sequence of scripts that are independent of each other. Meaning if one of them fails I want the rest to continue on and just be notified of the one that failed(I can implement the notification later). For now I am just trying to figure out why the program is not continuing on.
I am trying doing a test in... | [
"errorFunction(Script1(), 'Script1')\n\nThis is your problem. Since there are parentheses on the end of Script1(), you are actually calling that function here, before errorFunction() even executes.\nTake off the parentheses here, like so:\nerrorFunction(Script1, 'Script1')\n\nAnd then add parentheses here, like so... | [
2
] | [] | [] | [
"python",
"try_catch"
] | stackoverflow_0074267472_python_try_catch.txt |
Q:
ValueError: Shapes (None, 1) and (None, 3) are incompatible
I have a 3 dimensional dataset of audio files where X.shape is (329,20,85). I want to have a simpl bare-bones model running, so please don't nitpick and address only the issue at hand. Here is the code:
model = tf.keras.models.Sequential()
model.add(tf.ke... | ValueError: Shapes (None, 1) and (None, 3) are incompatible | I have a 3 dimensional dataset of audio files where X.shape is (329,20,85). I want to have a simpl bare-bones model running, so please don't nitpick and address only the issue at hand. Here is the code:
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.LSTM(32, return_sequences=True, stateful=False, input_... | [
"The first problem is with the LSTM input_shape. input_shape = (20,85,1).\nFrom the doc: https://keras.io/layers/recurrent/\nLSTM layer expects 3D tensor with shape (batch_size, timesteps, input_dim).\nmodel.add(tf.keras.layers.Dense(nb_classes, activation='softmax')) - this suggets you're doing a multi-class class... | [
39,
14,
6,
1,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0061550026_keras_python_tensorflow.txt |
Q:
Printing nested json - Python3
I have the following json output assigned to a variable called "mydict":
{
"data": {
"endpoints": {
"edges": [
{
"node": {
"name": "test1.net",
"ipAddress": "1.2.3.4"
}
},
{
"node": {
... | Printing nested json - Python3 | I have the following json output assigned to a variable called "mydict":
{
"data": {
"endpoints": {
"edges": [
{
"node": {
"name": "test1.net",
"ipAddress": "1.2.3.4"
}
},
{
"node": {
"name": "test2.net",
"... | [
"for edge in mydict['data']['endpoints']['edges']:\n print(edge['node']['name'])\n\n"
] | [
2
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0074267521_dictionary_json_python.txt |
Q:
How do I use HTTPS proxy with aiohttp?
How do I use HTTPS proxy with aiohttp in Python?
I have seen the docs where it is said I need to upgraded to HTTPS via the HTTP CONNECT method. But I have not found any complete Pythonic example how to do it? I have also viewed the questions Using https proxy with aiohttp and... | How do I use HTTPS proxy with aiohttp? | How do I use HTTPS proxy with aiohttp in Python?
I have seen the docs where it is said I need to upgraded to HTTPS via the HTTP CONNECT method. But I have not found any complete Pythonic example how to do it? I have also viewed the questions Using https proxy with aiohttp and Does aiohttp support HTTPS proxies. They re... | [
"You need to turn off the ssl_context to http server, see this thread for more information https://github.com/aio-libs/aiohttp/issues/206\nasync with aiohttp.ClientSession(timeout=timeout) as client:\n async with client.get(\n proxy=url,\n url=server_url,\n data=b\"Test content!\",\n ... | [
1
] | [] | [] | [
"aiohttp",
"proxy",
"python"
] | stackoverflow_0066545715_aiohttp_proxy_python.txt |
Q:
Combine multiple NetCDF files into timeseries multidimensional array python
I am using data from multiple netcdf files (in a folder on my computer). Each file holds data for the entire USA, for a time period of 5 years. Locations are referenced based on the index of an x and y coordinate. I am trying to create a t... | Combine multiple NetCDF files into timeseries multidimensional array python | I am using data from multiple netcdf files (in a folder on my computer). Each file holds data for the entire USA, for a time period of 5 years. Locations are referenced based on the index of an x and y coordinate. I am trying to create a time series for multiple locations(grid cells), compiling the 5 year periods into ... | [
"Nice start, I would recommend the following to help solve your issues. \nFirst, check out ncrcat to quickly concatenate your individual netCDF files into a single file. I highly recommend downloading NCO for netCDF manipulations, especially in this instance where it will ease your Python coding later on. \nLet's ... | [
12,
4,
2,
2,
1
] | [] | [] | [
"cdo_climate",
"nco",
"netcdf",
"python"
] | stackoverflow_0030946476_cdo_climate_nco_netcdf_python.txt |
Q:
Function for ids based on sowing date-harvest date duration
I want to keep only the rows from column for the period between the <sowing_date> and <harvest_date> based on ID because every id has different sowing date and harvest date
ID time NDVI sowing_date harvesting_date
106 2020-03-01 0.30796... | Function for ids based on sowing date-harvest date duration | I want to keep only the rows from column for the period between the <sowing_date> and <harvest_date> based on ID because every id has different sowing date and harvest date
ID time NDVI sowing_date harvesting_date
106 2020-03-01 0.307967 2020-04-21 2020-11-01
106 2020-03-02 0.299089 2020-04-21 ... | [
"This is basically just a filter then. One common way of filtering a dataframe is to create a list of True/False for each line and then filter on that. This looks something like:\nfilter = [(df.time <= df.harvesting_date) & (df.time >= df.sowing_date)]\nfiltered_df = df[filter]\n\nYou could also do that in one line... | [
0
] | [] | [] | [
"dataframe",
"function",
"pandas",
"python"
] | stackoverflow_0074267448_dataframe_function_pandas_python.txt |
Q:
TypeError: expected string or bytes-like object while starting Spyder 5.2.2
I created a new environment in conda with Spyder 5.2.2 and Python 3.10.2. Now, I'm experiencing an error telling me that the program expects a string or byte-like object while starting the Spyder. Interestingly, this does not happen when m... | TypeError: expected string or bytes-like object while starting Spyder 5.2.2 | I created a new environment in conda with Spyder 5.2.2 and Python 3.10.2. Now, I'm experiencing an error telling me that the program expects a string or byte-like object while starting the Spyder. Interestingly, this does not happen when my Python is 3.9.* . Any reason this can happen?
Here is the error encountered:
(p... | [
"(Spyder maintainer here) This is an error in the code that checks if PyQt5 is present and it will be fixed in our next version (5.3.0) to be released in March 2022 (see here).\n",
"I have glanced through the posts about the issues in Spyder and apparently, it involves upgrading or downgrading certain packages to... | [
3,
1,
0
] | [] | [] | [
"conda",
"python",
"python_3.x",
"spyder",
"typeerror"
] | stackoverflow_0071261324_conda_python_python_3.x_spyder_typeerror.txt |
Q:
Python program that displays height of a ball that is thrown. The program doesn't output anything
The height of an object, in metres, t seconds after it is launched straight up into the air is given by the equation h = -4.9t^2+bt+c where b represents the ball’s initial speed in metres per second and c represents t... | Python program that displays height of a ball that is thrown. The program doesn't output anything | The height of an object, in metres, t seconds after it is launched straight up into the air is given by the equation h = -4.9t^2+bt+c where b represents the ball’s initial speed in metres per second and c represents the ball’s initial height in metres. Using the elif statement, write a Python program that displays the ... | [
"while h>=0:\n h = round(-4.9*t**2+b*t+c, 2)\n\nThe way your code is indented, this is a loop all by itself, and it never ends because h is always >= 0.\n",
"Bad formatting. All those if and print statements, and the increment of t, have to be indented to be inside the while loop.\nt = 0\nh = 0\nb = float(inpu... | [
1,
1
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074267562_math_python.txt |
Q:
How can I create a new column in a dataframe on a condition
I have been trying to create a new column in my dataframe base on a condition and I keep getting a key error. I suspect it might have something to do with the indexing or headers but have hit a roadblock.
What I am trying to achieve is a new column which ... | How can I create a new column in a dataframe on a condition | I have been trying to create a new column in my dataframe base on a condition and I keep getting a key error. I suspect it might have something to do with the indexing or headers but have hit a roadblock.
What I am trying to achieve is a new column which says gas or coal based on if the technology field (which has thre... | [
"You want to use apply like this:\ndef func(value):\n if value == \"COAL\":\n return \"coal\"\n else:\n return \"gas\"\n \nrank_table_pivot[\"Gas/Coal\"] = rank_table_pivot['Technology'].apply(func) \n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074267637_pandas_python.txt |
Q:
How to filter a dataframe with a list of tuples
I have a list of tuples like this one (PRODUCT_ID, COUNTRY_CODE):
[(1111, 'CO'),
(2222, 'CO'),
(1111, 'BR')]
and a dataframe like this one:
df = pd.DataFrame({
'COUNTRY_CODE': ['CO','CO','CO','BR','BR','BR','CO'],
'VERTICAL_GROUP_ID': [2,2,3,2,3,3,3],
'SUB_VERTI... | How to filter a dataframe with a list of tuples | I have a list of tuples like this one (PRODUCT_ID, COUNTRY_CODE):
[(1111, 'CO'),
(2222, 'CO'),
(1111, 'BR')]
and a dataframe like this one:
df = pd.DataFrame({
'COUNTRY_CODE': ['CO','CO','CO','BR','BR','BR','CO'],
'VERTICAL_GROUP_ID': [2,2,3,2,3,3,3],
'SUB_VERTICAL': ['SUPER','SUPER','HOME','LICOR','SPORTS','HOME'... | [
"Lets use Multiindex.isin\ndf[df.set_index(['PRODUCT_ID', 'COUNTRY_CODE']).index.isin(tup)]\n\nAlternatively you can create a new dataframe from tuples then inner merge with the given dataframe\nfilters = pd.DataFrame(tup, columns=['PRODUCT_ID', 'COUNTRY_CODE'])\ndf.merge(filters)\n\n\n COUNTRY_CODE VERTICAL_GROU... | [
3,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074267656_pandas_python.txt |
Q:
making recursion faster using array
I was trying to get this recursion faster but when I use numbers 50 and 44.4 it takes too long my desired outcome for those numbers is -800555.6302016332
z = int(input())
x = float(input())
def rec(n):
global x
l = {}
if n == 0:
return -1
elif n == 1:
... | making recursion faster using array | I was trying to get this recursion faster but when I use numbers 50 and 44.4 it takes too long my desired outcome for those numbers is -800555.6302016332
z = int(input())
x = float(input())
def rec(n):
global x
l = {}
if n == 0:
return -1
elif n == 1:
return x
elif n == 2:
r... | [
"You are reinitializing your dictionary l = {} each time you recurse. Making l a global var should fix your problem:\nl = {}\n\ndef rec(n):\n global x\n global l\n if n == 0:\n return -1\n elif n == 1:\n return x\n elif n == 2:\n return -(x+1)/3\n else:\n if n in l:\n ... | [
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074267441_python_recursion.txt |
Q:
Why am I getting an empty index?
All this is asking me to do is write a code that shows if there are any missing values where it is not the customers first order. I have provided the DataFrame. Should I use column 'Order_number" instead? Is my code wrong?
I named the DataFrame df_orders.
I thought my code would fi... | Why am I getting an empty index? | All this is asking me to do is write a code that shows if there are any missing values where it is not the customers first order. I have provided the DataFrame. Should I use column 'Order_number" instead? Is my code wrong?
I named the DataFrame df_orders.
I thought my code would find the columns that have missing value... | [
"When you say .isna() you are returning a series of True or False. So that will never be > 1\nInstead, try this:\n m_v_fo= df_orders[df_orders['days_since_prior_order'].isna().sum() > 1]\n\nIf that doesn't solve the problem, then I'm not sure - try editing your question to add more detail and I can try again. :)\nU... | [
0
] | [] | [] | [
"error_handling",
"pandas",
"python"
] | stackoverflow_0074267165_error_handling_pandas_python.txt |
Q:
How do I get 1 href per one (multiple of them)?
I am trying to get images which are placed inside of <li>'s anchor tag as a href.
I am able to get only one link, but not everything.
I am trying to scrape the following page:
https://www.msxdistribution.com/love-triangle
As you can see there are multiple product im... | How do I get 1 href per one (multiple of them)? | I am trying to get images which are placed inside of <li>'s anchor tag as a href.
I am able to get only one link, but not everything.
I am trying to scrape the following page:
https://www.msxdistribution.com/love-triangle
As you can see there are multiple product images and I am trying to get them but unfortunately I a... | [
"Try:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.msxdistribution.com/love-triangle\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nfor img in soup.select(\".etalage_thumb_image\"):\n print(img[\"src\"])\n\nPrints:\nhttps://www.msxdistribution.com/media/catalog... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x",
"python_requests_html"
] | stackoverflow_0074266171_beautifulsoup_python_python_3.x_python_requests_html.txt |
Q:
Problem with web-scraped text using Python
I have issues getting text for the first printed item as nothing shows up except a blank line, but there are no issues with the second item text showing up in print. I would like to know if there is a workaround for this text print issue or if there is something about pyt... | Problem with web-scraped text using Python | I have issues getting text for the first printed item as nothing shows up except a blank line, but there are no issues with the second item text showing up in print. I would like to know if there is a workaround for this text print issue or if there is something about python coding that I have overlooked.
This code has... | [
"Are you trying to get the date? Because if so, the code:\nprint(soup.select('li p')[1].text)\n\nFor me, I got the date with this line of code:\n# We want to find the p element with this class\ndate = soup.find(\"p\", {\"class\": \"list-details__item__date\"})[\"data-dt\"] \nprint(date)\n\nEDIT:\nit also worked wi... | [
0
] | [] | [] | [
"python",
"visual_studio_2022",
"web_scraping"
] | stackoverflow_0074267721_python_visual_studio_2022_web_scraping.txt |
Q:
variable isn't global or defined
I tried running this code and it just crashes, giving me the error (NameError: name 'coordenadas' is not defined).
I need to be able to work with that in the future, therefor printing right away, eventho it solves the code, it doesn't solve my problem.
from tkinter import *
ronda... | variable isn't global or defined | I tried running this code and it just crashes, giving me the error (NameError: name 'coordenadas' is not defined).
I need to be able to work with that in the future, therefor printing right away, eventho it solves the code, it doesn't solve my problem.
from tkinter import *
ronda = 0
root = Tk()
root.title("Batalha... | [
"Here 'coordenadas' won't be defined until you press the button 'botao'. Before you have the chance to press the button, the print under 'botao.pack()' will try to access the variable coordenadas which is not defined yet; this will raise the NameError.\nIf you need to access coordenadas on the global scope, I will ... | [
0
] | [] | [] | [
"global_variables",
"python",
"tkinter",
"tkinter_button"
] | stackoverflow_0074267331_global_variables_python_tkinter_tkinter_button.txt |
Q:
I can't authorize gmail api application in google colaboratory
I'm running the quickstart code from https://developers.google.com/people/quickstart/python in a colab notebook.
# \[START people_quickstart\]
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
fr... | I can't authorize gmail api application in google colaboratory | I'm running the quickstart code from https://developers.google.com/people/quickstart/python in a colab notebook.
# \[START people_quickstart\]
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oau... | [
"There is something wrong with the way you are loading the run_local_server if you are getting a 404 error.\nThe code below is my standard QuickStart for People api. I just tested it and it works fine. I am not getting a 404 error.\n# To install the Google client library for Python, run the following command:\n... | [
1
] | [] | [] | [
"google_api",
"google_api_python_client",
"google_colaboratory",
"google_people_api",
"python"
] | stackoverflow_0074267784_google_api_google_api_python_client_google_colaboratory_google_people_api_python.txt |
Q:
Web scraping returned null in selenium but loaded in normal browser
image here.
Hi I am try to get the price of domain by selenium, the page is not loading, don't know why, I have attached the screenshot, my code was :
import time
import chromedriver_autoinstaller
from selenium import webdriver
chromedriver_autoi... | Web scraping returned null in selenium but loaded in normal browser | image here.
Hi I am try to get the price of domain by selenium, the page is not loading, don't know why, I have attached the screenshot, my code was :
import time
import chromedriver_autoinstaller
from selenium import webdriver
chromedriver_autoinstaller.install() # Check if the current version of chromedriver exis... | [
"It seems it is detecting you are running a bot.\nAs an workaround you can do couple of things.\n\nuse random user agent\ndisable-blink-features\nwhen load the page wait for couple of seconds and then refreshed the browser and wait for couple of second\n\ncode:\nfrom selenium import webdriver\nfrom selenium.webdriv... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"web_scraping"
] | stackoverflow_0074266650_python_selenium_selenium_chromedriver_web_scraping.txt |
Q:
Why does the fill of the clone turtle affects the original turtle fill?
Sry for being quite amateur at write this problem. This is my first time writing one.
I was doing some python turtle exercise for my assignment till I encounter this problem when filling up the Chinese character that I tried creating.
I tried... | Why does the fill of the clone turtle affects the original turtle fill? | Sry for being quite amateur at write this problem. This is my first time writing one.
I was doing some python turtle exercise for my assignment till I encounter this problem when filling up the Chinese character that I tried creating.
I tried to fill everything outline with black, but I keep on getting this weird whit... | [
"I see your primary issue as two-fold, first your begin_fill() and end_fill() calls don't match:\nturtletop.begin_fill() \nturtletop.end_fill()\n T.begin_fill() \n T.begin_fill() \nT.end_fill()\nTsquare.end_fill()\n\nThey should occur in matching pairs. (OK, they sorta do when you account for cloning, but:)\... | [
0
] | [] | [] | [
"python",
"python_turtle"
] | stackoverflow_0074262610_python_python_turtle.txt |
Q:
Python Dask max() function on a column not working
The max() for Dask on a column does not work. The below code returns with the result. Could anyone help to advise how to get the max() of a column in Dask dataframe?
import numpy as np
import pandas as pd
import dask.dataframe as dd
import dask.array as da
impo... | Python Dask max() function on a column not working | The max() for Dask on a column does not work. The below code returns with the result. Could anyone help to advise how to get the max() of a column in Dask dataframe?
import numpy as np
import pandas as pd
import dask.dataframe as dd
import dask.array as da
import dask.bag as db
pandas_df = pd.DataFrame({'Name': ['T... | [
"You have to use .compute() to make it an integer\nprint(ddf['Age'].max().compute())\n\n"
] | [
1
] | [] | [] | [
"dask",
"python"
] | stackoverflow_0074267874_dask_python.txt |
Q:
How to construct a Python object that has an underlying non-contiguous buffer (as obtained by `PyObject_GetBuffer`)?
The Python C API includes a function, PyBuffer_IsContiguous for verifying if the returned buffer is contiguous.
How to construct an object such as that function returns a false value?
Here are a few... | How to construct a Python object that has an underlying non-contiguous buffer (as obtained by `PyObject_GetBuffer`)? | The Python C API includes a function, PyBuffer_IsContiguous for verifying if the returned buffer is contiguous.
How to construct an object such as that function returns a false value?
Here are a few examples that do not work (all tried with Python 3.10):
a = b"123"
b = b"456"
c = bytearray(a[0:1] + b[0:1])
# This one r... | [
"\nc = bytearray(a[0:1] + b[0:1])\n# This one returns a contiguous buffer even if id(b[0]) == id(c[1])\n# Who does the copying? Why? Any rules?\n\n\nThere are actually many different copied copies. a[0:1] and b[0:1] return new (i.e. copied) bytes objects, not views on the existing bytes objects. ... + ... also retu... | [
0
] | [] | [] | [
"python",
"python_c_api"
] | stackoverflow_0074262681_python_python_c_api.txt |
Q:
OOP in Python / Tkinter: how to define a module with a support class in which all widgets events are defined
I'm quite new with OOP. Let's say I have defined a Tkinter application in a file called myApp.py. This is its content:
import tkinter as tk
from tkinter import ttk
from tkinter.constants import *
import my... | OOP in Python / Tkinter: how to define a module with a support class in which all widgets events are defined | I'm quite new with OOP. Let's say I have defined a Tkinter application in a file called myApp.py. This is its content:
import tkinter as tk
from tkinter import ttk
from tkinter.constants import *
import myApp_support
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('myApp')
self.resi... | [
"You need to pass the instance of App to AppSupport\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n ...\n self.supportClass = myApp_support.AppSupport(app=self)\n ...\n\nclass AppSupport():\n def __init__(self, app):\n self.app = app\n\n"
] | [
2
] | [] | [] | [
"oop",
"python",
"tkinter"
] | stackoverflow_0074267961_oop_python_tkinter.txt |
Q:
Concatenate 2 dataframes based on conditions
I have 2 dataframes, df_products_cp, like this one:
product_id
version
country
1111
2
CO
1111
2
BR
1111
2
MX
2222
2
CO
3333
2
CO
3333
2
MX
4444
2
CO
4444
2
BR
4444
2
MX
and df_products_ec like this one:
product_id
version
country
1111
3
CO
1111
3
MX
2222
... | Concatenate 2 dataframes based on conditions | I have 2 dataframes, df_products_cp, like this one:
product_id
version
country
1111
2
CO
1111
2
BR
1111
2
MX
2222
2
CO
3333
2
CO
3333
2
MX
4444
2
CO
4444
2
BR
4444
2
MX
and df_products_ec like this one:
product_id
version
country
1111
3
CO
1111
3
MX
2222
3
CO
4444
3
CO
4444
3... | [
"Let us do merge then wide_to_long\nout = pd.wide_to_long(df1.merge(df2,on=['product_id','country']),\n 'version',\n ['product_id','country'],\n j = 'drop',\n suffix = '\\w+').reset_index().drop(['drop'],axis = 1)\nOut[275]: \n pr... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074267988_pandas_python.txt |
Q:
Can't start project file Django using django-admin startproject mysite
so I am learning how to work with Django and for some reason I always get this error:
I installed Django with
py -m pip install Django==2.0.4
and then I updated it with command. It always create empty folder without any file inside of it.
I ha... | Can't start project file Django using django-admin startproject mysite | so I am learning how to work with Django and for some reason I always get this error:
I installed Django with
py -m pip install Django==2.0.4
and then I updated it with command. It always create empty folder without any file inside of it.
I have no idea why is this happening.
Any help would be blessing.
| [
"Okay so I installed it again with the right version from start and it seems to work fine now. No idea why updating on same version didnt work, but if anyone had same issue, install right version right from start, it should work. :)\n"
] | [
1
] | [] | [] | [
"django",
"frameworks",
"python"
] | stackoverflow_0074267794_django_frameworks_python.txt |
Q:
changing site after post request. no error message but screen page does not change
I have been working with Flask, HTML and javascript. I have to re-create a pizza site for school. almost everything is going fine, I know how to go to other pages through html and python. But at some point I will be using a button w... | changing site after post request. no error message but screen page does not change | I have been working with Flask, HTML and javascript. I have to re-create a pizza site for school. almost everything is going fine, I know how to go to other pages through html and python. But at some point I will be using a button which runs a javascript script which is fine. But when I try to change sites by redirecti... | [
"you need to enclose your href URL in quotes like this:\n<li><a href=\"{{ url_for('store') }}\">Menu</a></li> \n\n"
] | [
0
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0074261064_flask_html_python.txt |
Q:
How to run a command before CMD in dockerfile?
I have a dockerfile looking like this :
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
ADD . /app
CMD python script.py
(requirements.txt contains "black").
I would like to run black on script.py before running script.py... | How to run a command before CMD in dockerfile? | I have a dockerfile looking like this :
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
ADD . /app
CMD python script.py
(requirements.txt contains "black").
I would like to run black on script.py before running script.py, so that script.py get formatted correctly when the... | [
"Solution is here.\nIn my case, it is :\nDockerfile:\nFROM python:3.10-slim\nWORKDIR /app\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nADD . /app\nADD start.sh /\nRUN chmod +x /start.sh\n\nCMD [\"/start.sh\"]\n\nstart.sh:\n#!/bin/bash\n\nblack script.py\npython script.py\n\n"
] | [
-2
] | [] | [] | [
"docker",
"dockerfile",
"python"
] | stackoverflow_0074267920_docker_dockerfile_python.txt |
Q:
Ploting a values from a dictionary that holds a list of dictionary
I am trying to plot to see if what I am doing is correct, but not quite sure how this can be done.
I have this dict under:
k = {'Boston': [{'name': 'Jayson Tatum','rebounds': 8.0, 'assists': 4.4, 'points': 26.9}, {'name': 'Jaylen Brown','rebounds':... | Ploting a values from a dictionary that holds a list of dictionary | I am trying to plot to see if what I am doing is correct, but not quite sure how this can be done.
I have this dict under:
k = {'Boston': [{'name': 'Jayson Tatum','rebounds': 8.0, 'assists': 4.4, 'points': 26.9}, {'name': 'Jaylen Brown','rebounds': 6.1, 'assists': 3.5, 'points': 23.6}, {'name': 'Marcus Smart', 'rebound... | [
"You could first convert the data to a more structured dataframe and then plot as required.\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nmydict = {}\n\ni = 0\nfor team in k:\n for player in k[team]:\n mydict[i] = [team, player[\"name\"], player[\"rebounds\"], player[\"assists\"], player[\"poin... | [
1
] | [
"You can extract all the elements like rebounds for each team using a mix of dictionary keys and list comprehension:\nrebounds = [y['rebounds'] for team in mydict for y in mydict[team]]\n\nThis will give you rebounds for every player on every team.\nEdit: Full code I tested:\nmydict = {'Boston':[{'name':'a', 'rebou... | [
-1
] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074267685_matplotlib_pandas_python.txt |
Q:
micro:bit python - random library only generates one number
I am making a hangman game on my microbit and am having trouble with the random library. I need to choose a random number between 1 and 7, and every single time I run the program it always yields the number '5'.The strangest part is when I copy the exact ... | micro:bit python - random library only generates one number | I am making a hangman game on my microbit and am having trouble with the random library. I need to choose a random number between 1 and 7, and every single time I run the program it always yields the number '5'.The strangest part is when I copy the exact same code into a IDE like visual code studio and run in via the t... | [
"As @Oppy correctly diagnosed, this should work correctly in the micro:bit device, and the problem only affected the Python Editor simulator. In this case the issue was that the simulator random number generator was not seeded correctly.\nThe micro:bit Python Editor issue has been fixed and deployed today:\nhttps:/... | [
1,
0,
0
] | [] | [] | [
"bbc_microbit",
"python",
"random"
] | stackoverflow_0074077710_bbc_microbit_python_random.txt |
Q:
Can't import deepspeech on kivy for android
I am using kivy to create an android app. I need to install the deepspeech framework, however, in order for deepspeech to be installed it is necessary to create a recipe.
I created a recipe and built the apk, there were no errors in the build, it created the apk and also... | Can't import deepspeech on kivy for android | I am using kivy to create an android app. I need to install the deepspeech framework, however, in order for deepspeech to be installed it is necessary to create a recipe.
I created a recipe and built the apk, there were no errors in the build, it created the apk and also, as far as I could see in the folders, the deeps... | [
"Add pillow in your requirements and check if it works!\nrequirements = python3==3.7.14, hostpython3==3.7.14, kivy, kivymd, sqlite3, numpy==1.14.5, deepspeech, apsw, pillow\n"
] | [
0
] | [] | [] | [
"android",
"buildozer",
"kivy",
"mozilla_deepspeech",
"python"
] | stackoverflow_0074262646_android_buildozer_kivy_mozilla_deepspeech_python.txt |
Q:
Get NameError when printing out the result, but I've assigned a variable to it
seq = 'TGCCTTGGGCACCATGCAGTACCAAACGGAACGATAGTG'
for nucleotide in seq:
if nucleotide == 'A':
a_nt = seq.count('A')
elif nucleotide == 'G':
g_nt = seq.count('G')
elif nucleotide == 'C':
c_nt = seq.cou... | Get NameError when printing out the result, but I've assigned a variable to it | seq = 'TGCCTTGGGCACCATGCAGTACCAAACGGAACGATAGTG'
for nucleotide in seq:
if nucleotide == 'A':
a_nt = seq.count('A')
elif nucleotide == 'G':
g_nt = seq.count('G')
elif nucleotide == 'C':
c_nt = seq.count('C')
elif nucleotide == 'T':
t_nt = seq.count('T')
elif nucleotid... | [
"Just count everything without the for loop, then all variables are set, even if zero:\nseq = 'TGCCTTGGGCACCATGCAGTACCAAACGGAACGATAGTG'\n\na_nt = seq.count('A')\ng_nt = seq.count('G')\nc_nt = seq.count('C')\nt_nt = seq.count('T')\nn_nt = seq.count('N')\n\nprint(a_nt, g_nt, c_nt, t_nt, n_nt)\n\n# or more efficient\n... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074267980_python.txt |
Q:
TransportError (429) 'Data too large' when loading JSON docs to ElasticSearch
I have a process running in Python 3.7 that loads JSON files, gathers file rows into chunks in async queues, and incrementally posts chunks to ElasticSearch for indexing.
Chunking is meant to avoid overloading the ElasticSearch connectio... | TransportError (429) 'Data too large' when loading JSON docs to ElasticSearch | I have a process running in Python 3.7 that loads JSON files, gathers file rows into chunks in async queues, and incrementally posts chunks to ElasticSearch for indexing.
Chunking is meant to avoid overloading the ElasticSearch connection.
def load_files_to_queue(file_queue, incomplete_files, doc_queue, index):
log... | [
"basically this means your request to Elasticsearch was too large for it to handle, so you could try reducing the chunk size\nalternatively, look at using the _bulk api, there are helpers in the python clients which should take most of the pain away for this\n",
"We are encountering this again in our QA environme... | [
2,
0
] | [] | [] | [
"asynchronous",
"elasticsearch",
"python"
] | stackoverflow_0068794144_asynchronous_elasticsearch_python.txt |
Q:
OSMnx - Unbelievable speed_kph value in highway
Using Python osmnx package to work with OpenStreetMaps, I have created the following bounding box in Madrid, Spain:
north, south, east, west = 40.45, 40.40, -3.691, -3.74
# create network from that bounding box
H = ox.graph_from_bbox(north, south, east, west, networ... | OSMnx - Unbelievable speed_kph value in highway | Using Python osmnx package to work with OpenStreetMaps, I have created the following bounding box in Madrid, Spain:
north, south, east, west = 40.45, 40.40, -3.691, -3.74
# create network from that bounding box
H = ox.graph_from_bbox(north, south, east, west, network_type="drive_service")
fig, ax = ox.plot_graph(H, no... | [
"Yes, you can tell OSMnx what speeds to use if you pass the hwy_speeds argument, as described in the docs.\n\nBy default, this imputes free-flow travel speeds for all edges via the mean maxspeed value of the edges of each highway type. For highway types in the graph that have no maxspeed value on any edge, it assig... | [
1
] | [] | [] | [
"openstreetmap",
"osmnx",
"python"
] | stackoverflow_0074253481_openstreetmap_osmnx_python.txt |
Q:
Error: 'List' object is not callable in map() function
def powerof(num):
return num**2
number = [1,2,3,4,5,6,7,8]
s = list(map( powerof , number))
print(s)
Error : 'list' object is not callable
A:
You have defined list as a variable earlier in your code.
Do not do this. Call your variable lst or perhaps so... | Error: 'List' object is not callable in map() function | def powerof(num):
return num**2
number = [1,2,3,4,5,6,7,8]
s = list(map( powerof , number))
print(s)
Error : 'list' object is not callable
| [
"You have defined list as a variable earlier in your code.\nDo not do this. Call your variable lst or perhaps something more descriptive.\nMinimal example to replicate your error:\nlist = [1, 2, 3]\n\ndef powerof(num):\n return num**2\n\nnumber = [1,2,3,4,5,6,7,8]\ns = list(map( powerof , number))\nprint(s)\n\n-... | [
6,
3,
0,
0
] | [
"list = [1, 2, 3] # remove this list variable name and use any different one, then it will work.\n\ndef powerof(num):\n return num**2\n\nnumber = [1,2,3,4,5,6,7,8]\n\ns = set(map( powerof , number))\nprint(s)\n\ninstead of list use set\n"
] | [
-1
] | [
"list",
"map_function",
"python",
"typeerror"
] | stackoverflow_0049998740_list_map_function_python_typeerror.txt |
Q:
Grouping Count of values in Pandas dataframs
The sample data in my dataframe is as follows.
enter image description here
What I want to do is create a new dataframe from this one that contains 2 columns, I want to have all 12 community areas (as below) and the count of times "OFFENSE INVOLVING CHILDREN" from the p... | Grouping Count of values in Pandas dataframs | The sample data in my dataframe is as follows.
enter image description here
What I want to do is create a new dataframe from this one that contains 2 columns, I want to have all 12 community areas (as below) and the count of times "OFFENSE INVOLVING CHILDREN" from the primary type column shows up for each of these comm... | [
"IIUC, value_counts gives you the count of the\ndf.loc[df['Primary Type'].eq('OFFENSE INVOLVING CHILDREN')]['Community Area'].value_counts()\n\nPS: if you had shared the minimal reproducible example, it would have allowed me to share the results too\n"
] | [
0
] | [] | [] | [
"dataframe",
"grouping",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074267121_dataframe_grouping_jupyter_notebook_pandas_python.txt |
Q:
Insert vertical line below tabs in tkinter.text
I am creating a code editor as my project, and I think it is nice to have vertical lines under tabs so its easier for the coder. I want to draw a vertical line below tabs (I think the image below will be better to understand what I want, Just a screenshot from vs cod... | Insert vertical line below tabs in tkinter.text | I am creating a code editor as my project, and I think it is nice to have vertical lines under tabs so its easier for the coder. I want to draw a vertical line below tabs (I think the image below will be better to understand what I want, Just a screenshot from vs code):
Here you can see that there is a vertical line u... | [
"The text widget doesn't directly support this. You can fake it by using ascii line drawing characters, but it would probably be a lot of work. It should be doable, though.\nYou can do this if you base your IDE on a canvas rather than a Text widget, but the text-editing ability of the canvas text item would be very... | [
3
] | [] | [] | [
"python",
"python_3.x",
"tabs",
"tkinter",
"tkinter_text"
] | stackoverflow_0074267900_python_python_3.x_tabs_tkinter_tkinter_text.txt |
Q:
subprocess or multithreading or threading pool
I'm going to run the command line utility multiple times in parallel using Python.
I know that multithreading is better to use for I/O operations, multiprocessing - for CPU oriented operations.
But what should I use for parallel subprocess.run?
I also know that I can ... | subprocess or multithreading or threading pool | I'm going to run the command line utility multiple times in parallel using Python.
I know that multithreading is better to use for I/O operations, multiprocessing - for CPU oriented operations.
But what should I use for parallel subprocess.run?
I also know that I can create a pool from the subprocess module, but how is... | [
"In a situation like this, I tend to run subprocesses from a ThreadPoolExecutor, basically because it's easy.\nExample (from here):\nfrom datetime import datetime\nfrom functools import partial\nimport argparse\nimport concurrent.futures as cf\nimport logging\nimport os\nimport subprocess as sp\nimport sys\n\n__ver... | [
1
] | [] | [] | [
"multiprocessing",
"multithreading",
"python",
"subprocess"
] | stackoverflow_0074268212_multiprocessing_multithreading_python_subprocess.txt |
Q:
Copy DIV HTML from another URL
Hello I would like to copy Div HTML from another URL and paste/echo it on my website using Python or Jquery
Can someone help please
Im using Cpanel and Wordpress
A:
this should point you in the right direction:
var response = $.get('url');
var content = $(response).find('div_id').... | Copy DIV HTML from another URL | Hello I would like to copy Div HTML from another URL and paste/echo it on my website using Python or Jquery
Can someone help please
Im using Cpanel and Wordpress
| [
"this should point you in the right direction:\nvar response = $.get('url');\nvar content = $(response).find('div_id').html(); // get the html of the div\n\n"
] | [
1
] | [] | [] | [
"cpanel",
"jquery",
"php",
"python",
"wordpress"
] | stackoverflow_0074268298_cpanel_jquery_php_python_wordpress.txt |
Q:
Passing variables between an open window and a window that hasn't been opened yet
I am currently stuck on a problem of passing variables between two scripts in a python GUI code. I think I have figured out that the variable is not getting sent from the main widget to the secondary widget but I'm not sure how to ge... | Passing variables between an open window and a window that hasn't been opened yet | I am currently stuck on a problem of passing variables between two scripts in a python GUI code. I think I have figured out that the variable is not getting sent from the main widget to the secondary widget but I'm not sure how to get around it.
Using designer, I've mocked up two example scripts mainWidget.py
from PyQt... | [
"You can get around this problem by using the shelve method given in example by https://www.tutorialspoint.com/python-object-persistence-shelve#:~:text=The%20shelve%20module%20in%20Python's,stored%20in%20a%20disk%20file.\n"
] | [
0
] | [] | [] | [
"python",
"widget"
] | stackoverflow_0074240820_python_widget.txt |
Q:
PyPDF2 error "PyCryptodome is required for AES algorithm"
I've got hundreds on PDFs I need to set password. I tried to use pyPDF2 to do that but I got an error:
"DependencyError: PyCryptodome is required for AES algorithm".
I've tried to google any other module like pikepdf but I found only how to crack the passwo... | PyPDF2 error "PyCryptodome is required for AES algorithm" | I've got hundreds on PDFs I need to set password. I tried to use pyPDF2 to do that but I got an error:
"DependencyError: PyCryptodome is required for AES algorithm".
I've tried to google any other module like pikepdf but I found only how to crack the password using it and not to actually set password.
Any ideas how to ... | [
"A.) Great way to do it:\nhttps://roytuts.com/how-to-encrypt-pdf-as-password-protected-file-in-python/\nimport PyPDF2\n\n#pdf_in_file = open(\"simple.pdf\",'rb')\npdf_in_file = open(\"gre_research_validity_data.pdf\",'rb')\n\ninputpdf = PyPDF2.PdfFileReader(pdf_in_file)\npages_no = inputpdf.numPages\noutput = PyPDF... | [
0,
0
] | [] | [] | [
"pikepdf",
"pypdf2",
"python"
] | stackoverflow_0073701005_pikepdf_pypdf2_python.txt |
Q:
How to authorize OpenAPI page from an API
I'm building a FastAPI application with OAuth2 and JWT authentication. I've got two endpoints that create the JWT token. The first is hidden from the OpenAPI page but is used by the page Authorize button. The second does the same functionality but is available to the users... | How to authorize OpenAPI page from an API | I'm building a FastAPI application with OAuth2 and JWT authentication. I've got two endpoints that create the JWT token. The first is hidden from the OpenAPI page but is used by the page Authorize button. The second does the same functionality but is available to the users as an API endpoint.
If the user uses the page ... | [
"When using the Authorize button, the Authorization header with the token in it is automatically sent in every subsequent request you make to the FastAPI backend, and hence, the user gets authenticated.\nUsing your get_token endpoint, users will obtain the token as a response, and have to manually place it in the h... | [
1
] | [] | [] | [
"fastapi",
"jwt",
"oauth_2.0",
"openapi",
"python"
] | stackoverflow_0074267757_fastapi_jwt_oauth_2.0_openapi_python.txt |
Q:
I need to optimaze my code that containt two loops. The code is for calculating a sum of numbers
I was traying to write a code that calculate the sum of 2*j+i+1 where 0<=j<=i<=n but I wasn't very optimazed
there are my code :
def get_sum(n):
s=0
for j in range(n+1):
ss=0
ss=sum(2*j+i+1 for ... | I need to optimaze my code that containt two loops. The code is for calculating a sum of numbers | I was traying to write a code that calculate the sum of 2*j+i+1 where 0<=j<=i<=n but I wasn't very optimazed
there are my code :
def get_sum(n):
s=0
for j in range(n+1):
ss=0
ss=sum(2*j+i+1 for i in range(j,n+1))
s+=ss
return s
Write to calculate a a sum of 2*j+i+1 where 0<=j<=i<=n ... | [
"Before delving into optimizing the code, always take a step back and consider what the code does. In this case, try to solve the equations with pen and paper, instead of brute-forcing them with a computer.\nThe value you want, lets call it S is defined as\n\nCompute the inner sum first\n\nAnd, finally, substitute ... | [
4,
2
] | [] | [] | [
"mathematical_optimization",
"optimization",
"performance",
"python",
"sum"
] | stackoverflow_0074267736_mathematical_optimization_optimization_performance_python_sum.txt |
Q:
Pandas find first row matching condition (or last if not found) in a forward-rolling window
I have a data frame with two columns j and k. I'd like to do a 3-element forward rolling calculation like this:
Find the first element (in order) in k that's smaller than j if it exists
Otherwise - if all elements in k ar... | Pandas find first row matching condition (or last if not found) in a forward-rolling window | I have a data frame with two columns j and k. I'd like to do a 3-element forward rolling calculation like this:
Find the first element (in order) in k that's smaller than j if it exists
Otherwise - if all elements in k are greater than j - use the last (in order) from k
The result would go into column l.
Example:
n... | [
"Here is a way using shift to align all values of the rolling windows on k with the value of j. Then keep only the values where they are less than the column j. Use bfill along the columns to get the first non null value found in the row back to the first column, that you can select with iloc[:, 0] and fillna the r... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074268041_pandas_python.txt |
Q:
How to run tests on Edge using the browser library in robot framework
I have been using browser library for executing my web UI tests on chrome browser in the robot framework. But now I want to run them on Edge. Since Browser library is based on playwright. And in playwright documentation it is mentioned like
| ... | How to run tests on Edge using the browser library in robot framework | I have been using browser library for executing my web UI tests on chrome browser in the robot framework. But now I want to run them on Edge. Since Browser library is based on playwright. And in playwright documentation it is mentioned like
| =Browser= | =Browser with this engine= |
| ``chrom... | [
"you can use the channel msedge\nrobotframework example\nNew Browser chromium headless=false channel=msedge\nNew Context viewport={'width': 1920, 'height': 1080}\nNew Page https://marketsquare.github.io/robotframework-browser/Browser.html\n"
] | [
0
] | [] | [] | [
"playwright",
"python",
"robotframework"
] | stackoverflow_0072127579_playwright_python_robotframework.txt |
Q:
Why is my regex expression returning None?
I have a python 3 code that is utilizing regex expressions to extract certain parts of sequences.
import re
seqs = """>UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+)
MFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS
NVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASIEKS... | Why is my regex expression returning None? | I have a python 3 code that is utilizing regex expressions to extract certain parts of sequences.
import re
seqs = """>UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+)
MFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS
NVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASIEKSNIIRGWIFGTTLDSKTQSLIIV
NNATNVVIKVCEFQFCNDPFLDVYY... | [
"I believe this implementation does what you're after\nimport re\n\n\nseqs = \"\"\">UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+)\nMFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS\nNVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASIEKSNIIRGWIFGTTLDSKTQSLIIV\nNNATNVVIKVCEFQFCNDPFLDVYYHKNNKSWMESGVYSSANNCTFEYVSQPFL... | [
2
] | [] | [] | [
"list",
"python",
"python_3.x",
"regex"
] | stackoverflow_0074268344_list_python_python_3.x_regex.txt |
Q:
Error: Simple error keeps popping up, unable to progress
So I'm trying to answer a leetcode question but I believe I'm stuck on something simple but I can't figure it out.
The error that keeps popping up is "name 'twoSum' is not defined". Can anyone tell me what I'm missing here? It's clearly defined as far as I c... | Error: Simple error keeps popping up, unable to progress | So I'm trying to answer a leetcode question but I believe I'm stuck on something simple but I can't figure it out.
The error that keeps popping up is "name 'twoSum' is not defined". Can anyone tell me what I'm missing here? It's clearly defined as far as I can see?
class Solution:
def twoSum(num: int, target: int) ... | [
"You need to create an object of that class Solution first\nChange your main to below -\ndef main():\n num = [3,2,4]\n target = 6\n s = Solution()\n r = s.twoSum(num, target)\n print(r)\n\nAlso I makes me assume that it is one of your first attempts to leetcode. (Apologies if assumption is wrong). Th... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074268361_python.txt |
Q:
Disable hover information on trace, plotly
I'm currently using the plotly service to graph some water quality data. I've added some lines to represent the the various stages of water quality, with them shaded so they are green, yellow, and red.
I've been able to remove some unnecessary lines from the legend, but ... | Disable hover information on trace, plotly | I'm currently using the plotly service to graph some water quality data. I've added some lines to represent the the various stages of water quality, with them shaded so they are green, yellow, and red.
I've been able to remove some unnecessary lines from the legend, but they still show up when hovering over the data. ... | [
"On your trace add: hoverinfo='skip'\ntrace = dict(\n x=[1,2,3,4],\n y=[1,2,3,4],\n hoverinfo='skip'\n )\n\n",
"from plotly.offline import plot\nimport plotly.graph_objs as go\n\ndef spline(x_axis,loop):\n\n trace = go.Scatter(\n x = x_axis,\n y = l... | [
57,
10,
2,
1
] | [] | [] | [
"plot",
"plotly",
"python"
] | stackoverflow_0032319619_plot_plotly_python.txt |
Q:
I want to read input from file then scrapping results with selenium and python
I need to scrape website data by entering userId and fetching all data returned into a CSV file. So I created a CSV file that contain all Ids.
How can I add id as input and wait till the data loads? I need the following:
Enter input fr... | I want to read input from file then scrapping results with selenium and python | I need to scrape website data by entering userId and fetching all data returned into a CSV file. So I created a CSV file that contain all Ids.
How can I add id as input and wait till the data loads? I need the following:
Enter input from CSV into the forum
Load the data
Scrape results for 1000 users
Here's my code c... | [
"See code below on how to process a csv file with ids using cloudscraper and pandas:\nimport cloudscraper\nimport pandas as pd\nimport time\n\n# first get the request verification token\nscraper = cloudscraper.create_scraper()\nSeatingNo = '870000'\nres = scraper.get(\"https://g12-result.moe.gov.eg/\")\nsoup = Beau... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074262190_jupyter_notebook_python_selenium_web_scraping.txt |
Q:
How do to sort on item in a Python dictionary?
I have created a dictionary using dict() where the key is a word and the item is the amount of time that word occurs in a text file.
I am trying to sort on the amount of occurrences a word has from high to low.
An example of the input is:
{'stack': 2, 'over': 1, 'flow... | How do to sort on item in a Python dictionary? | I have created a dictionary using dict() where the key is a word and the item is the amount of time that word occurs in a text file.
I am trying to sort on the amount of occurrences a word has from high to low.
An example of the input is:
{'stack': 2, 'over': 1, 'flow': 3}
The desired output is any type of list that sh... | [
"You can iterate over the sorted keys and construct the new list:\nlst = [[k, dct[k]] for k in sorted(dct, key=dct.get, reverse=True)]\nprint(lst)\n\nPrints:\n[['flow', 3], ['stack', 2], ['over', 1]]\n\n\nOr: sort the dictionary items directly:\nlst = sorted(map(list, dct.items()), key=lambda x: x[1], reverse=True)... | [
1,
0
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0074268437_dictionary_python_sorting.txt |
Q:
How to sort Pandas crosstab columns by sum of values
I have a crosstab table with 4 rows and multiple columns, containing numeral values (representing the number of dataset elements on the crossing of two factors). I want to sort the order of columns in the crosstab by the sum of values in each column.
e.g. I have... | How to sort Pandas crosstab columns by sum of values | I have a crosstab table with 4 rows and multiple columns, containing numeral values (representing the number of dataset elements on the crossing of two factors). I want to sort the order of columns in the crosstab by the sum of values in each column.
e.g. I have:
ct = pd.crosstab(df_flt_reg['experience'], df_flt_reg['r... | [
"Calculate the sum and sort the values. Once you have the sorted series get the index and reorder your columns with it.\nsorted_df = ct[ct.sum().sort_values(ascending=False).index]\n\n d e b c a\n0 3 6 0 7 1\n1 5 4 4 1 2\n2 7 2 5 0 3\n3 9 1 3 1 1\n\n"
] | [
3
] | [] | [] | [
"pandas",
"pivot_table",
"python",
"sorting"
] | stackoverflow_0074268552_pandas_pivot_table_python_sorting.txt |
Q:
Getting _register_s3_control_events() Error
I am trying to read a csv from an S3 bucket using my jupyter notebook. I have previously read this csv before and had no issues but now am receiving an error.
Here is the code I am running:
import pandas as pd
list = pd.read_csv(r's3://analytics/wordlist.csv')
And the e... | Getting _register_s3_control_events() Error | I am trying to read a csv from an S3 bucket using my jupyter notebook. I have previously read this csv before and had no issues but now am receiving an error.
Here is the code I am running:
import pandas as pd
list = pd.read_csv(r's3://analytics/wordlist.csv')
And the error I am getting is:
An error was encountered:
_... | [
"You could use boto to import the csv from s3. Boto is a python library for AWS.\nBy the way, this should work:\nimport boto\nimport pandas as pd\ndata = pd.read_csv('s3://bucket....csv')\n\nIf you are on python 3.4+, you need:\nimport boto3\nimport io\nimport pandas as pd\ns3 = boto3.client('s3')\nobj = s3.get_obj... | [
1
] | [] | [] | [
"amazon_s3",
"pandas",
"python"
] | stackoverflow_0074268474_amazon_s3_pandas_python.txt |
Q:
Using multiple replace function in Beautifulsoup
I have been dealing with something, but it didn't work no matter what i tried. I need to use multiple replace function, howewer python allowed me to use it only one time.
It's my csv output. (https://i.stack.imgur.com/HtBSn.png)]
Firstly, there are values which seem... | Using multiple replace function in Beautifulsoup | I have been dealing with something, but it didn't work no matter what i tried. I need to use multiple replace function, howewer python allowed me to use it only one time.
It's my csv output. (https://i.stack.imgur.com/HtBSn.png)]
Firstly, there are values which seem as N/A. it has to be 0 or something, briefly, should ... | [
"Edit:\nI this code works for me. The repetitive work I excluded into a method and call it in the csv.writerow\nimport csv\nimport requests\nfrom bs4 import BeautifulSoup\nfrom csv import QUOTE_NONE\nfrom csv import writer\n\n\nresponse = requests.get('https://www.worldometers.info/coronavirus/#news').content\n\nso... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074268375_beautifulsoup_python.txt |
Q:
Could not build wheels for frozenlist, multidict, yarl
I am trying to make a discord bot with nextcord, but when I try to install it using command prompt, it gives me this error:
× Building wheel for yarl (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [37 lines of output]
C:\Users\klama\A... | Could not build wheels for frozenlist, multidict, yarl | I am trying to make a discord bot with nextcord, but when I try to install it using command prompt, it gives me this error:
× Building wheel for yarl (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [37 lines of output]
C:\Users\klama\AppData\Local\Temp\pip-build-env-pknvci1v\overlay\Lib\site-pa... | [
"Just instal python 3.10. I tried instal Microsoft Visual C++ 14.0... did not work out\n",
"The error message you posted says it all: you need Microsoft Visual C++ 14.0 or greater.\nFor those of you here because you got this error after updating your Python Docker image to Python 3.11, it may be because gcc and o... | [
0,
0
] | [] | [] | [
"discord.py",
"nextcord",
"python"
] | stackoverflow_0074187645_discord.py_nextcord_python.txt |
Q:
Python Constraints in a loop
I am working with the python-constraint library and a logical error has risen.
It seems to me that a similar question has been asked here but I don't understand how to apply it in my case
First I call this code
my_function(List):
from constraint import Problem , AllDifferentConstrain... | Python Constraints in a loop | I am working with the python-constraint library and a logical error has risen.
It seems to me that a similar question has been asked here but I don't understand how to apply it in my case
First I call this code
my_function(List):
from constraint import Problem , AllDifferentConstraint
problem = Problem()
people =... | [
"Following the guidelines from another post's answer, I came up with this solution and it works:\ndef generate_constrained_func(val_in_dict):\n def constraint_func(x):\n return (x == val_in_dict)\n return constraint_func\n\nfor person in List:\n if(person):\n problem.addConstraint(generate_co... | [
0
] | [] | [] | [
"constraints",
"python"
] | stackoverflow_0074265217_constraints_python.txt |
Q:
mlflow.pyfunc.load_model / mlflow.pyfunc.save_model - how to pass additional artifacts as parameters
In a previous post I asked about saving and loading models with custom myflow.pyfunc objects and received an excellent answer from Daniel Schneider explaining the difference between mlflow.pyfunc.PythonModel and ml... | mlflow.pyfunc.load_model / mlflow.pyfunc.save_model - how to pass additional artifacts as parameters | In a previous post I asked about saving and loading models with custom myflow.pyfunc objects and received an excellent answer from Daniel Schneider explaining the difference between mlflow.pyfunc.PythonModel and mlflow.pyfunc.PyFuncModel.
Here, I extend the question, as the proposed solution doesn't work for me when al... | [
"The solution is to pass all the model_input data including the artefacts into the model as one argument. This now correctly calls and returns output from the predict method.\n# dummy data\ndata = {'col1': [1, 2], 'col2': [3, 4]}\ndf = pd.DataFrame(data=data)\n\n# create class\nclass PredictSpeciality(mlflow.pyfunc... | [
0
] | [] | [] | [
"mlflow",
"python"
] | stackoverflow_0074257370_mlflow_python.txt |
Q:
Enable/disable popups lively in Plotly plot
Is it possible to somehow add the option to enable/disable the popups in plotly but lively? I mean, I don't want to remove them from the plot, but I would like to be able to enable/disable them with some kind of check box like I have drawn below:
Is this possible?
If an... | Enable/disable popups lively in Plotly plot | Is it possible to somehow add the option to enable/disable the popups in plotly but lively? I mean, I don't want to remove them from the plot, but I would like to be able to enable/disable them with some kind of check box like I have drawn below:
Is this possible?
If an example is needed, anyone from here can be used,... | [
"You can do that by using hovermode=False for disabling and hovermode=\"closest\" for enabling.\nFull code:\nimport plotly.express as px\ndf = px.data.iris()\nfig = px.scatter(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", symbol=\"species\")\n\n\nfig.update_layout(\n updatemenus=[\n dict(\... | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074267104_plotly_python.txt |
Q:
How to reduce called paramets in methods?
I have a class and in that class I have a method that calls multiple methods in it.
But the problem I am facing now is that when the method with the multiple methods in it duplicate parameter has.
And so when I am calling the method with the multiple methods in it, it retu... | How to reduce called paramets in methods? | I have a class and in that class I have a method that calls multiple methods in it.
But the problem I am facing now is that when the method with the multiple methods in it duplicate parameter has.
And so when I am calling the method with the multiple methods in it, it returns a empty list:[].
So this is the method with... | [
"@AndrewRyan has the right idea.\nI presume calling extract_text_from_image just adds the attribute list_fruit\nTwo routes you can go, from what you are commenting you'll probably just go with #1.. but I gave #2 as another option in case you'd ever want to call filter_verdi_total_fruit_cost by itself.\nPath 1, Jus... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074268102_django_python.txt |
Q:
How to count horseshoes in python?
I've completely stuck with this task and I really dunno how to make this program work properly, because I think I've already tried many possible options, but it still unfortunately didn't work properly.
The task is: "The blacksmith has to shoe several horses and needs to see if h... | How to count horseshoes in python? | I've completely stuck with this task and I really dunno how to make this program work properly, because I think I've already tried many possible options, but it still unfortunately didn't work properly.
The task is: "The blacksmith has to shoe several horses and needs to see if he has the correct number of horseshoes. ... | [
"Try checking if you have the correct number first:\ndef check(p, k):\n required_shoes = k * 4\n if p == required_shoes:\n # just right\n elif p < required_shoes:\n # not enough\n else:\n # too many\n\n",
"You could try this:\ndef check(shoes, horses):\n if shoes > 4*horses:\n ... | [
1,
1,
0
] | [] | [] | [
"function",
"numbers",
"python",
"python_3.x"
] | stackoverflow_0074268637_function_numbers_python_python_3.x.txt |
Q:
Get parents keys from nested dictionary
From the following nested dictionary, how can I get every parent dictionary key of 'value4ac'? By starting the 'value4ac' value, I want to get 'key4', 'key4a', 'Key4ac'.
example_dict = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3... | Get parents keys from nested dictionary | From the following nested dictionary, how can I get every parent dictionary key of 'value4ac'? By starting the 'value4ac' value, I want to get 'key4', 'key4a', 'Key4ac'.
example_dict = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3a': 'value3a' },
'key4' : { ... | [
"recursion to the rescue!\nexample_dict = { 'key1' : 'value1',\n 'key2' : 'value2',\n 'key3' : { 'key3a': 'value3a' },\n 'key4' : { 'key4a': { 'key4aa': 'value4aa',\n 'key4ab': 'value4ab',\n '... | [
19,
7,
0,
0
] | [] | [] | [
"dictionary",
"nested",
"python"
] | stackoverflow_0015210148_dictionary_nested_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.