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:
I want to keep asking the user for a filename input until the filename that the user inputs does not exist anymore
I am trying to create program that creates a csv file in python wherein the user inputs the day of the class and the name of the class. If the input exists it would say file exists. If it doesn't exis... | I want to keep asking the user for a filename input until the filename that the user inputs does not exist anymore | I am trying to create program that creates a csv file in python wherein the user inputs the day of the class and the name of the class. If the input exists it would say file exists. If it doesn't exist it will create the file and save it locally to where the python project folder is. I want it to keep repeating until t... | [
"It looks like you have confused the idea of a while loop with an if.\nWith your program you need a loop to make the program ask the user again. The if is needed to decide whether to create the file or not.\nYour first code uses the if correctly, but doesn't use a while at all. I shall add a while to the first code... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074373781_python.txt |
Q:
Remove special character (?, ()) from value in dataframe
I would like to have a code in order to remove special character such as ? from values in a column in a dataframe.
I would like to remove from
()?()()() hello world'
the () and the ?.
However, when I am using the following code:
Community_final_level_2_desc... | Remove special character (?, ()) from value in dataframe | I would like to have a code in order to remove special character such as ? from values in a column in a dataframe.
I would like to remove from
()?()()() hello world'
the () and the ?.
However, when I am using the following code:
Community_final_level_2_description = Community_final_level_2_description.replace('()', ' ... | [
"(/)/? are special characters for regex. Try to escape them:\ndf[\"column\"] = df[\"column\"].replace(r\"\\?|\\(\\)\", \"\", regex=True)\nprint(df)\n\nPrints:\n column\n0 hello world\n\n\nDataframe used:\n column\n0 ()?()()() hello world\n\n",
"If one has a dataframe df that looks like... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"replace",
"special_characters"
] | stackoverflow_0074374214_dataframe_pandas_python_replace_special_characters.txt |
Q:
Python Selenium find_element not working while Beautiful Soup find works
Im on python and I tried to get price data($25.99)from below Amazon webpage.
https://www.amazon.com/Guffercty-kred-Sublimation-Mechanical-Keyboard/dp/B09HWZQQZJ/ref=sr_1_14?crid=3UHD6OMRY6RYG&keywords=keycaps&qid=1667444474&qu=eyJxc2MiOiI4Ljc... | Python Selenium find_element not working while Beautiful Soup find works | Im on python and I tried to get price data($25.99)from below Amazon webpage.
https://www.amazon.com/Guffercty-kred-Sublimation-Mechanical-Keyboard/dp/B09HWZQQZJ/ref=sr_1_14?crid=3UHD6OMRY6RYG&keywords=keycaps&qid=1667444474&qu=eyJxc2MiOiI4Ljc5IiwicXNhIjoiOC41OCIsInFzcCI6IjcuOTMifQ%3D%3D&sprefix=keycap%2Caps%2C275&sr=8-... | [
"You probably need to wait for the page to finish rendering. Or you're finding some other element. I see 60 items that match that selector.\nI'd try a selector like:\ndiv#corePrice_feature_div span .a-offscreen\nAnd then wait for that element to be displayed and enabled.\nhttps://www.selenium.dev/documentation/webd... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074368811_beautifulsoup_python_selenium_selenium_chromedriver.txt |
Q:
How to get a list of all links from a dynamic web page?
I'm trying to scrape this page:
https://workspace.google.com/marketplace/search/word
I tried PhantomJS+BeautifulSoup (failed), then Playwright to scrape the whole content of the page but I can't see the links to the extensions. Do they get generated only when... | How to get a list of all links from a dynamic web page? | I'm trying to scrape this page:
https://workspace.google.com/marketplace/search/word
I tried PhantomJS+BeautifulSoup (failed), then Playwright to scrape the whole content of the page but I can't see the links to the extensions. Do they get generated only when the cursor hovers over them? Is there a way to get them?
Her... | [
"You can try the next example playwright with bs4.\nCode:\nfrom playwright.sync_api import sync_playwright\nfrom bs4 import BeautifulSoup\n\ndata = []\nwith sync_playwright() as p:\n browser = p.chromium.launch(headless=False)\n context = browser.new_context(viewport={\"width\": 1920, \"height\": 1080})\n ... | [
1
] | [] | [] | [
"beautifulsoup",
"playwright",
"playwright_python",
"python",
"web_scraping"
] | stackoverflow_0074373189_beautifulsoup_playwright_playwright_python_python_web_scraping.txt |
Q:
Removing all data Except Certain text using Regex
I am trying to remove all words from a string except certain words, for example I want to retain 'red' and 'black' including all combinations it has and remove all other strings.
For example
inputstring = "red => white => green => black,magenta"
outputstring = "red... | Removing all data Except Certain text using Regex | I am trying to remove all words from a string except certain words, for example I want to retain 'red' and 'black' including all combinations it has and remove all other strings.
For example
inputstring = "red => white => green => black,magenta"
outputstring = "red => black,magenta"
I have tried to replace string using... | [
"I would maybe create new string. I mean you do not have to remain the original one. You can simply look for words and their order.\nI am not experienced with xquery but I could help you with idea at least.\nWhat do I mean by that. If I understand you correctly then your input string contains => pattern indicating ... | [
1,
0,
0
] | [] | [] | [
"python",
"r",
"regex",
"xquery"
] | stackoverflow_0074372679_python_r_regex_xquery.txt |
Q:
Creating a dictionary from Excel in every sheet
I want to create a dictionary from the values I get from Excel cells.
This my Excel spreadsheet:
My expectation about the dictionary is like this:
{'Ancolmekar': array([ 3. , 20. , 6. , ..., 0.5, 0.5, 0.5]),
'Cidurian': array([0.5, 0.5, 0.5, ..., 0.5, 0.5, 6. ]... | Creating a dictionary from Excel in every sheet | I want to create a dictionary from the values I get from Excel cells.
This my Excel spreadsheet:
My expectation about the dictionary is like this:
{'Ancolmekar': array([ 3. , 20. , 6. , ..., 0.5, 0.5, 0.5]),
'Cidurian': array([0.5, 0.5, 0.5, ..., 0.5, 0.5, 6. ]),
'Dayeuhkolot': array([0.5, 0.5, 0.5, ..., 5.5, 1.... | [
"I guess you could go with :\npath = 'export_3.xlsx'\nfile = pd.ExcelFile(path)\nsheets = file.sheet_names\n\nfor sheet in sheets:\n sheet_dict = {}\n contoh = pd.read_excel(path, sheet_name=sheet)\n for col in contoh.columns:\n sheet_dict[col] = list(contoh[col])\n print(sheet_dict, \"\\n\\n\\n... | [
1,
0
] | [] | [] | [
"arrays",
"pandas",
"python"
] | stackoverflow_0074374178_arrays_pandas_python.txt |
Q:
How to type F5 to refresh a page using Playwright Python
I'm trying to refresh a webpage using F5 key. I know I can use:
self.page.reload()
But this is not a good solution for my problem. How to make the page to be refreshed using the F5 key? My code doesn't refresh the page and I don't know why.
self.page.keyboa... | How to type F5 to refresh a page using Playwright Python | I'm trying to refresh a webpage using F5 key. I know I can use:
self.page.reload()
But this is not a good solution for my problem. How to make the page to be refreshed using the F5 key? My code doesn't refresh the page and I don't know why.
self.page.keyboard.press('F5')
| [
"As you said we have page.keyboard.press('F5'). But it does not do what you want, I've tried several other examples but nothing.\nMaybe this is enough for you?\npage.evaluate('window.location.reload();')\n\nOr\npage.evaluate('location.reload();')\n\nAs you can see we are forcing the reload by evaluating a javascrip... | [
1,
1,
1
] | [] | [] | [
"playwright",
"playwright_python",
"python"
] | stackoverflow_0074260772_playwright_playwright_python_python.txt |
Q:
How do I write code for a 2d Gaussian Kernel?
I'm trying to make a nxn Gaussian kernel.
The formula I'm following is as given
Here is what I've got so far:
# sigma(standard deviation) and muu(mean) are the parameters of gaussian
def gkern(kernel_size, sigma=1, muu=0):
# Initializing value of x,y as grid of ... | How do I write code for a 2d Gaussian Kernel? | I'm trying to make a nxn Gaussian kernel.
The formula I'm following is as given
Here is what I've got so far:
# sigma(standard deviation) and muu(mean) are the parameters of gaussian
def gkern(kernel_size, sigma=1, muu=0):
# Initializing value of x,y as grid of kernel size
# in the range of kernel size
... | [
"I try to answer your initial question as well as the additional ones in your comment:\nOftentimes you want to normalize a filter kernel in order keep an average brightness. This step is missing in your function.\nYou have to change only the last line to:\nreturn gauss / np.sum(gauss)\n\nThat way your matrices also... | [
0
] | [] | [] | [
"gaussian",
"machine_learning",
"python",
"statistics"
] | stackoverflow_0074343085_gaussian_machine_learning_python_statistics.txt |
Q:
How to print line number for specific condition in xml using python
My xml is
<File>
<Sub_Function_1>
<Messages>
<Setting>
<Data>
<Label>Setting_1</Label>
<Value>
<Measure>
<Data>Area... | How to print line number for specific condition in xml using python | My xml is
<File>
<Sub_Function_1>
<Messages>
<Setting>
<Data>
<Label>Setting_1</Label>
<Value>
<Measure>
<Data>Area</Data>
<Bound>
... | [
"If I understand your conditions correctly, this should work:\nfor target in doc2.xpath('//Data//following-sibling::Bound[not(Value=Condition)]'):\n print(target.sourceline)\n\nOutput should be something like\n10\n18\n34\n42\n58\n66\n\nEDIT:\nAgain, if I understand you correctly, this should get you at least clo... | [
0
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0074372239_lxml_python_xml.txt |
Q:
why do numpy array arr3d[0,:,[0,1,2]] and arr3d[0][:,[0,1,2]] produce different result
example code:
import numpy as np
a=np.ones((1,4,4))
shape1=a[0,:,[0,1,2]].shape
shape2=a[0][:,[0,1,2]].shape
result:
shape1 is (3,4) and shape2 is (4,3)
Need help! I think they should have same results.
A:
Because in one you ... | why do numpy array arr3d[0,:,[0,1,2]] and arr3d[0][:,[0,1,2]] produce different result | example code:
import numpy as np
a=np.ones((1,4,4))
shape1=a[0,:,[0,1,2]].shape
shape2=a[0][:,[0,1,2]].shape
result:
shape1 is (3,4) and shape2 is (4,3)
Need help! I think they should have same results.
| [
"Because in one you are taking rows 0, 1 and 2 and in the other you are taking columns 0, 1 and 2.\nAn easy way to see this is by generating a matrix with different values.\na = np.array([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]])\n\n\na[0,:,[0,1,2]]\n\n\na[0][:, [0, 1, 2]]\n\n\nBasically, in... | [
0,
0
] | [] | [] | [
"indexing",
"numpy",
"python"
] | stackoverflow_0074371628_indexing_numpy_python.txt |
Q:
python3 - json.loads for a string that contains " in a value
I'm trying to transform a string that contains a dict to a dict object using json.
But in the data contains a "
example
string = '{"key1":"my"value","key2":"my"value2"}'
js = json.loads(s,strict=False)
it outputs json.decoder.JSONDecodeError: Expecting ... | python3 - json.loads for a string that contains " in a value | I'm trying to transform a string that contains a dict to a dict object using json.
But in the data contains a "
example
string = '{"key1":"my"value","key2":"my"value2"}'
js = json.loads(s,strict=False)
it outputs json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 13 (char 12) as " is a delimiter and ... | [
"This should work. What I am doing here is to simply replace all the expected double quotes with something else and then remove the unwanted double quotes. and then convert it back.\nimport re\nimport json\n\ndef fix_json_string(st):\n st = re.sub(r'\",\"',\"!!\",st)\n st = re.sub(r'\":\"',\"--\",st)\n st ... | [
1,
0,
0
] | [] | [] | [
"double_quotes",
"json",
"python"
] | stackoverflow_0074373561_double_quotes_json_python.txt |
Q:
check a list of strings with list comprehension
I want to filter a list of strings that includes any specific string with using list comprehension. I tried following the code, but it didn't work.
ignore_paths = ['.ipynb_checkpoints', 'New', '_calibration', 'images']
A = [x for x in lof1 if ignore_paths not in x]
... | check a list of strings with list comprehension | I want to filter a list of strings that includes any specific string with using list comprehension. I tried following the code, but it didn't work.
ignore_paths = ['.ipynb_checkpoints', 'New', '_calibration', 'images']
A = [x for x in lof1 if ignore_paths not in x]
but when I try with one string, it will work:
A = [x ... | [
"Do you have duplicates? if not, you can use sets which will be very fast\nallowed = set(lof1) - set(ignore_paths)\n\n",
"Try:\nA = [x for x in lof1 if x not in ignore_paths]\n\n"
] | [
1,
0
] | [] | [] | [
"list_comprehension",
"python",
"string"
] | stackoverflow_0074374611_list_comprehension_python_string.txt |
Q:
Convert an Integer into 32bit Binary Python
I am trying to make a program that converts a given integer(limited by the value 32 bit int can hold) into 32 bit binary number. For example 1 should return (000..31times)1. I have been searching the documents and everything but haven't been able to find some concrete wa... | Convert an Integer into 32bit Binary Python | I am trying to make a program that converts a given integer(limited by the value 32 bit int can hold) into 32 bit binary number. For example 1 should return (000..31times)1. I have been searching the documents and everything but haven't been able to find some concrete way. I got it working where number of bits are acco... | [
"'{:032b}'.format(n) where n is an integer. If the binary representation is greater than 32 digits it will expand as necessary:\n>>> '{:032b}'.format(100)\n'00000000000000000000000001100100'\n>>> '{:032b}'.format(8589934591)\n'111111111111111111111111111111111'\n>>> '{:032b}'.format(8589934591 + 1)\n'10000000000000... | [
27,
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0043024351_python.txt |
Q:
python: import class from a different subfolder in the parent folder (tests)
I moved my tests to a separate subfolder in the project, and now testing my classes does not work anymore.
|-- project
| |main.py
| |-- lib
| | |__init__.py
| | |myclass.py
| |-- tests
| | |__init__.py
| | |test_myc... | python: import class from a different subfolder in the parent folder (tests) | I moved my tests to a separate subfolder in the project, and now testing my classes does not work anymore.
|-- project
| |main.py
| |-- lib
| | |__init__.py
| | |myclass.py
| |-- tests
| | |__init__.py
| | |test_myclass.py
Both init files are empty.
but when I run the test (i'm in the tests fold... | [
"That's because once you are in tests folder your working directory dir is:\n.\\\n.\\test_mycalss.py\n\nYou should run tests from project so your working directory will cover whole tree:\n.\\\n.\\main.py\n.\\lib\\\nand so on\n\nYour project cannot view lib.myclass because in folder tests there is no folder lib.\n"
... | [
1
] | [] | [] | [
"dependencies",
"python",
"unit_testing",
"visual_studio_code"
] | stackoverflow_0074374641_dependencies_python_unit_testing_visual_studio_code.txt |
Q:
I want to make a function that circulates the elements in a list, but it changes the list globally
The function cycle removes the first element of a list puts it in the last position. I used pop and append to do so.
The problem is that if you use:
l=[1,2,3]
assert(cycle(l)== [2,3,1])
assert(cycle(cycle(l))== [3,1,... | I want to make a function that circulates the elements in a list, but it changes the list globally | The function cycle removes the first element of a list puts it in the last position. I used pop and append to do so.
The problem is that if you use:
l=[1,2,3]
assert(cycle(l)== [2,3,1])
assert(cycle(cycle(l))== [3,1,2])
it gives you an assertionerror, so i thought maybe the list is changed globally, but i do not want ... | [
"Well, this is because Python does pass pointer to the list, it does not creates its own copy. So, you can simply use this:\nfrom copy import deepcopy\n\ncycle(deepcopy(l))\n\nSo your list won't change globally.\n",
" print(cycle(l))\n print(cycle(cycle(l)))\n print(l)\n\n assert(cycle(l) == [2, 3, 1]... | [
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074374139_list_python.txt |
Q:
Why is pyautogui not working when running from terminal but fine when running from VSC’s terminal?
I’m trying to figure out why this very simple script only works when I run the command in VS Code’s terminal and not work when I open a normal terminal window (on my Mac), CD to the project and run the script from th... | Why is pyautogui not working when running from terminal but fine when running from VSC’s terminal? | I’m trying to figure out why this very simple script only works when I run the command in VS Code’s terminal and not work when I open a normal terminal window (on my Mac), CD to the project and run the script from there.
The script:
import pyautogui
def switch_to_vsc():
print("switching")
pyautogui.keyDown("co... | [
"Judging by the CMD Space shortcut, I assume you're on Mac.\nOn Mac, you need to allow your terminal to control you computer:\nPreferences > Privacy > Accessibility\nthen add Terminal in your list like so:\n\nYou should also have AEServer there, since it allows Apple Events to be performed programatically, which py... | [
0
] | [] | [] | [
"pyautogui",
"python"
] | stackoverflow_0074340166_pyautogui_python.txt |
Q:
Query cassandra table in Databricks using python cassandra driver
I'm trying to optimize a way to query a cassadnra table when working in databricks. After reading this article https://medium.com/@yoke_techworks/cassandra-and-pyspark-5d7830512f19, the author suggest to query the cassandra table one row at the time... | Query cassandra table in Databricks using python cassandra driver | I'm trying to optimize a way to query a cassadnra table when working in databricks. After reading this article https://medium.com/@yoke_techworks/cassandra-and-pyspark-5d7830512f19, the author suggest to query the cassandra table one row at the time and union each results.
My attempt, using the python cassandra driver,... | [
"You shouldn't do this - instead you need to use Spark Cassandra Connector that provides native access to Cassandra from Spark using DataFrame APIs (documentation for PySpark). You just need to install a version matching your Databricks Runtime (on Databricks you need to use assembly version due the reasons descri... | [
1
] | [] | [] | [
"cassandra",
"databricks",
"pyspark",
"python"
] | stackoverflow_0074373020_cassandra_databricks_pyspark_python.txt |
Q:
Is there any way of using for loop iterator in variable name?
I am looking for a way to dynamically use multiple dataframes in a for loop. Any ideas?
I generated 24 dataframes like this ("hour" is 0-23):
N = 24
for i in range(int(N)):
exec("df_hour{} = df_m_a_meaned[df_m_a_meaned['hour']=={}]".format(i, i))`
... | Is there any way of using for loop iterator in variable name? | I am looking for a way to dynamically use multiple dataframes in a for loop. Any ideas?
I generated 24 dataframes like this ("hour" is 0-23):
N = 24
for i in range(int(N)):
exec("df_hour{} = df_m_a_meaned[df_m_a_meaned['hour']=={}]".format(i, i))`
Now I want to use them in a for-loop to generate a plot, I tried ... | [
"don't EVER use exec to generate variables in your normal code, it will only make things harder see Why should exec() and eval() be avoided?, if you want to generate dynamically named variables use a dictionary instead.\nmy_dataframes = {}\nfor i in range(int(N)):\n my_dataframes[i] = df_m_a_meaned[df_m_a_meaned... | [
2
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074374683_for_loop_python.txt |
Q:
Optimising function to strip honorifics from names
Problem
I have a list of around ~1000 honorifics, see below for a sample.
Given an input string of a name, for example "her majesty queen elizabeth windsor", the function should return "elizabeth windsor". If there is no honorific present at the start of the name ... | Optimising function to strip honorifics from names | Problem
I have a list of around ~1000 honorifics, see below for a sample.
Given an input string of a name, for example "her majesty queen elizabeth windsor", the function should return "elizabeth windsor". If there is no honorific present at the start of the name (to simplify the problem), the function should simple re... | [
"I was able to improve the performance by >2x by reformatting the honorifics list into an alternative form.\ndef reformat_honorifics(honorifics):\n honorifics_by_letter_dct = {}\n for honorific in honorifics:\n honorifics_by_letter_dct[honorific[0]] = honorifics_by_letter_dct.get(honorific[0], {})\n ... | [
1,
1
] | [] | [] | [
"algorithm",
"optimization",
"performance",
"python",
"string"
] | stackoverflow_0074346078_algorithm_optimization_performance_python_string.txt |
Q:
name 'generateRandom' is not defined"
I'm trying to run this code but I'm getting an error msg ---> "NameError: name 'generateRandom' is not defined"
Can anyone help me please?
`import numpy as np
class Mul:
def __init__ (self,ra_result=None,rb_result=None):
self.ra_result = ra_result
self.rb... | name 'generateRandom' is not defined" | I'm trying to run this code but I'm getting an error msg ---> "NameError: name 'generateRandom' is not defined"
Can anyone help me please?
`import numpy as np
class Mul:
def __init__ (self,ra_result=None,rb_result=None):
self.ra_result = ra_result
self.rb_result = rb_result
def genera... | [
"The function you're trying to call, is itself a class function, I.E. it needs to be called like this:\nself.generateRandom()\n\nEdit:\nYou could make the generateRandom() an internal private function, by changing it to\ndef __generateRandom(self):\n...\nrng = self.__generateRandom()\n\nIn this case you can easily ... | [
0,
0,
0
] | [] | [] | [
"nameerror",
"numpy",
"object",
"python",
"self"
] | stackoverflow_0074374670_nameerror_numpy_object_python_self.txt |
Q:
Ordering a dataframe by each column
I have a dataframe that looks like this:
ID Age Score
0 9 5 3
1 4 6 1
2 9 7 2
3 3 2 1
4 12 1 15
5 2 25 6
6 9 5 4
7 9 5 61
8 4 2 12
I want to sort based on the first column, then the second... | Ordering a dataframe by each column | I have a dataframe that looks like this:
ID Age Score
0 9 5 3
1 4 6 1
2 9 7 2
3 3 2 1
4 12 1 15
5 2 25 6
6 9 5 4
7 9 5 61
8 4 2 12
I want to sort based on the first column, then the second column, and so on.
So I want my output t... | [
"You can use numpy.lexsort to improve performance.\nimport numpy as np\n\na = df.to_numpy()\nout = pd.DataFrame(a[np.lexsort(np.rot90(a))],\n index=df.index, columns=df.columns)\n\nAssuming as input a random square DataFrame of side n:\ndf = pd.DataFrame(np.random.randint(0, 100, size=(n, n)))\n\n... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074374366_pandas_python.txt |
Q:
Choose between Anaconda Python and other Python installation when Anaconda is set as the default Python - Windows 10
The case is really simple. I am using Anaconda and have registered it as the default Python. As it seems, Anaconda has some issues with confluent_kafka library, therefore I need to install and use P... | Choose between Anaconda Python and other Python installation when Anaconda is set as the default Python - Windows 10 | The case is really simple. I am using Anaconda and have registered it as the default Python. As it seems, Anaconda has some issues with confluent_kafka library, therefore I need to install and use Python alone for a specific case.
I ran the installation (Python 3.10), added Python to path as well (so both Python are ad... | [
"Use the full path of the executable, like c:/python3.10/python script.py\nEDIT:\nIt can be located in another directory, check that with where python and adapt the first command\n",
"Since I cannot comment on other answers, here is how you could install packages for different python versions\nc:/python3.10/pytho... | [
1,
1
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0074374558_anaconda_python.txt |
Q:
How To Minimize Window Using Python/PySimpleGUI
Dears,
How To Minimize Window Using Python/PySimpleGUI ?
Knowing that , I want to hide existing title bar from my Window and add my personal icons :Maximize, Minimize and Close, it's OK for 2 and not the case for Minimize.
I followed answer shared in : How to create ... | How To Minimize Window Using Python/PySimpleGUI | Dears,
How To Minimize Window Using Python/PySimpleGUI ?
Knowing that , I want to hide existing title bar from my Window and add my personal icons :Maximize, Minimize and Close, it's OK for 2 and not the case for Minimize.
I followed answer shared in : How to create a minimize button with pysimplegui?, unfortunately di... | [
"Check the document on https://www.pysimplegui.org/en/latest/ all the time.\nimport PySimpleGUI as sg\n\nsg.PySimpleGUI.SYMBOL_TITLEBAR_MINIMIZE = '.'\nsg.PySimpleGUI.SYMBOL_TITLEBAR_MAXIMIZE = 'O'\nsg.PySimpleGUI.SYMBOL_TITLEBAR_CLOSE = 'x'\n\nlayout = [\n [sg.Titlebar(\n title='TITLE',\n icon=... | [
2
] | [] | [] | [
"button",
"minimize",
"minimized",
"pysimplegui",
"python"
] | stackoverflow_0074373098_button_minimize_minimized_pysimplegui_python.txt |
Q:
Is there any special method on python class definition or metaclass about "After class is defined"
I am working on implementing a ctypes.Structure class with type hinting and this is my code:
import ctypes
_CData = ctypes.c_int.__mro__[2]
def set_fields_from_annotations(cls):
from typing import get_type_hint... | Is there any special method on python class definition or metaclass about "After class is defined" | I am working on implementing a ctypes.Structure class with type hinting and this is my code:
import ctypes
_CData = ctypes.c_int.__mro__[2]
def set_fields_from_annotations(cls):
from typing import get_type_hints
if annotations := getattr(cls, '__annotations__', {}):
cls._fields_ = [(n, t) for n, t in... | [
"It ended being more interesting than I thought initially... I can suggest the following decorator solution.\nimport ctypes\n\n_CData = ctypes.c_int.__mro__[2]\n\n\ndef set_fields_from_annotations(cls):\n from typing import get_type_hints\n globals().update({cls.__name__: cls}) # Define the name\n if anno... | [
2
] | [] | [] | [
"python",
"python_3.x",
"python_typing"
] | stackoverflow_0074370046_python_python_3.x_python_typing.txt |
Q:
python 3.11: debugger not working properly anymore
So I have just installed python version 3.11 and changed my python interpreter in pycharm and the code runs properly now after I reinstalled the packages to my new venv.
but when i debug my code I keep getting a long list of warnings and I have no idea how to fix ... | python 3.11: debugger not working properly anymore | So I have just installed python version 3.11 and changed my python interpreter in pycharm and the code runs properly now after I reinstalled the packages to my new venv.
but when i debug my code I keep getting a long list of warnings and I have no idea how to fix it:
----------------------------------------------------... | [
"Should be fixed in PyCharm 2022.3 (ticket https://youtrack.jetbrains.com/issue/PY-56939/CRITICAL-WARNING-error-debugging-Python-311-code).\nEarly Access Preview version is already available https://www.jetbrains.com/pycharm/nextversion/\n"
] | [
3
] | [] | [] | [
"pycharm",
"python",
"python_3.x",
"version"
] | stackoverflow_0074359505_pycharm_python_python_3.x_version.txt |
Q:
Django REST Framework update record mixin
I'm using Django 3.2 and the last version of djangorestframework.
I need to be able to update the values of JobStatus record already crated before.
As example I have
{
"id": 1,
"status_timestamp": "2022-04-07T10:51:42Z",
"status_activity": "Sync DDT",
"sta... | Django REST Framework update record mixin | I'm using Django 3.2 and the last version of djangorestframework.
I need to be able to update the values of JobStatus record already crated before.
As example I have
{
"id": 1,
"status_timestamp": "2022-04-07T10:51:42Z",
"status_activity": "Sync DDT",
"status_status": "running",
"launcher": 1
}
... | [
"You could do this:\nurls.py\nfrom apps.api_c import views\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\n\nrouter = DefaultRouter()\nrouter.register('alert', views.AlertViewSet,basename=\"alert\")\nrouter.register('jstatus', views.UpdateStatus, b... | [
2,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"python_3.x",
"rest"
] | stackoverflow_0071782880_django_django_rest_framework_python_python_3.x_rest.txt |
Q:
MQTT - Is there a way to check if the client is still connected
Is there a way to check if the client is still connected to the MQTT broker?
Something like
if client.isConnected(): # for example
# if True then do stuff
Edit: There was instance where my Raspberry Pi stopped receiving from the client although... | MQTT - Is there a way to check if the client is still connected | Is there a way to check if the client is still connected to the MQTT broker?
Something like
if client.isConnected(): # for example
# if True then do stuff
Edit: There was instance where my Raspberry Pi stopped receiving from the client although it was still (from the look of it, the code was still showing update... | [
"You can activate a flag in on_connect and deactivate it in on_disconnect. In this way you can know if the client is connected or not.\nimport paho.mqtt.client as mqtt\n\nflag_connected = 0\n\ndef on_connect(client, userdata, flags, rc):\n global flag_connected\n flag_connected = 1\n\ndef on_disconnect(client, ... | [
17,
3,
0,
0
] | [
"Here is the API available.\nYou just use client.is_connected() returns True or False.\n"
] | [
-1
] | [
"mqtt",
"python"
] | stackoverflow_0036093078_mqtt_python.txt |
Q:
How to change default language in qt designer
How to change the default language in qt designer anyone has solutions.
A:
you can make designer fail to find translation file (C:\5.15.2\mingw81_32\translations\designer_zh_CN.qm in my case) so it will fallback to english.
A:
until now there is no professional sol... | How to change default language in qt designer | How to change the default language in qt designer anyone has solutions.
| [
"you can make designer fail to find translation file (C:\\5.15.2\\mingw81_32\\translations\\designer_zh_CN.qm in my case) so it will fallback to english.\n",
"until now there is no professional solution so i will suggest to try my solution:\ngo to Qt Designer directory ex: (C:\\xxx\\Python\\Python37-32\\Lib\\site... | [
3,
0
] | [] | [] | [
"pyqt5",
"python",
"qt_designer"
] | stackoverflow_0070486148_pyqt5_python_qt_designer.txt |
Q:
How to determine which port aiohttp selects when given port=0
When I use aiohttp.web.run_app(. . ., port=0), I assume that it selects an arbitrary available port on which to serve. Is this correct? And if so, is there some way to figure out what port it's selected?
A:
You use server.sockets as in the following c... | How to determine which port aiohttp selects when given port=0 | When I use aiohttp.web.run_app(. . ., port=0), I assume that it selects an arbitrary available port on which to serve. Is this correct? And if so, is there some way to figure out what port it's selected?
| [
"You use server.sockets as in the following code:\n@asyncio.coroutine\ndef status(request):\n \"\"\"Check that the app is properly working\"\"\"\n return web.json_response('OK')\n\n\napp = web.Application() # pylint: disable=invalid-name\napp.router.add_get('/api/status', status)\n\n\ndef main():\n \"\"\"... | [
6,
0
] | [] | [] | [
"aiohttp",
"python"
] | stackoverflow_0044610441_aiohttp_python.txt |
Q:
How to extract randomically elements from a dictionary considerating a value's attribute in Python
I want to extract, randomically, an element from a dictionary considering the frequency value: I want the output to be one of the highest frequency value everytime BUT it's not excluded that an element with low frequ... | How to extract randomically elements from a dictionary considerating a value's attribute in Python | I want to extract, randomically, an element from a dictionary considering the frequency value: I want the output to be one of the highest frequency value everytime BUT it's not excluded that an element with low frequency value is extracted.
Like, if I have
"x": 4.5, "y": 7.1, "z": 9.3, "w": 1.2, "k": 5.8, "p": 2.3
I wa... | [
"You can do something like this:\nimport numpy as np\n\nkitchen_activity = {'near the bathroom sink':{'frequency': 0, 'average duration': 0, 'standard deviation': 0},\n 'near the fridge': {'frequency': 0.2631578947368421}, \n 'near the stove': {'frequency': 0.2631578947368421}... | [
0
] | [] | [] | [
"choice",
"dictionary",
"python",
"python_3.x",
"random"
] | stackoverflow_0074373082_choice_dictionary_python_python_3.x_random.txt |
Q:
textX Ignore Text Before First Record
I'm working on writing a parser for an existing file format, and the trouble is that the syntax does not have a way of indicating what is a comment other than the fact that everything that is not a record is treated as a comment. Records start with an ampersand & (must be the ... | textX Ignore Text Before First Record | I'm working on writing a parser for an existing file format, and the trouble is that the syntax does not have a way of indicating what is a comment other than the fact that everything that is not a record is treated as a comment. Records start with an ampersand & (must be the first character on a new line) and end with... | [
"\nComment rule from language comments is tried between each two consecutive tokens, thus can't be used in this case as it would be tried inside of records, and comments can be anything (actually, for this language comment can't be a part of the record).\nThe problem is BEG_OF_FILE_COMMENTS can't match \\A as befor... | [
1
] | [] | [] | [
"python",
"regex",
"textx"
] | stackoverflow_0074353050_python_regex_textx.txt |
Q:
Skip the default on onupdate defined, for specific update queries in SQLAlchemy
If I have a list of posts, which have created and updated dates with a default attached onupdate callback.
Sometimes I need to flag the post, for inappropriate reports or similar actions. I do not want the created and updated dates to ... | Skip the default on onupdate defined, for specific update queries in SQLAlchemy | If I have a list of posts, which have created and updated dates with a default attached onupdate callback.
Sometimes I need to flag the post, for inappropriate reports or similar actions. I do not want the created and updated dates to be modified.
How can I skip the defined onupdate, while making an update action?
| [
"SQLAlchemy will apply a default when\n\nno value was provided to the INSERT or UPDATE statement for that column\n\nhowever the obvious workaround - explicitly setting the column to its current value - won't work because the session checks whether the value has actually changed, and does not pass a value if it hasn... | [
5,
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0069625550_flask_flask_sqlalchemy_python_python_3.x_sqlalchemy.txt |
Q:
Function to return list and then clear
how could I make my function clear the list and return the inital list on the first execution, and then display a empty list on the second run? I have tried using.
Kind regards
def remove():
items = ["car", "plane", "bus"]
if len(items) != 0:
return i... | Function to return list and then clear | how could I make my function clear the list and return the inital list on the first execution, and then display a empty list on the second run? I have tried using.
Kind regards
def remove():
items = ["car", "plane", "bus"]
if len(items) != 0:
return items and items.clear()
print(remov... | [
"What you want is not directly possible as items is defined every time the function runs.\nAlso the None in your output is due to items and items.clear() giving the result of items.clear() which is None.\nWhat might come closest to what you want would be:\n# define \"items\" as a main scope variable\nitems = [\"car... | [
2,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074374893_python_python_3.x.txt |
Q:
How to get the current object in UpdateView?
To update the data in the table, I use the class o inherited from UpdateView, the fields are automatically filled from the database, but can I somehow in my class get the data from the user_guid field?
Here is my form and class code:
class CampaignEditor(UpdateView):
... | How to get the current object in UpdateView? | To update the data in the table, I use the class o inherited from UpdateView, the fields are automatically filled from the database, but can I somehow in my class get the data from the user_guid field?
Here is my form and class code:
class CampaignEditor(UpdateView):
model = Campaigns
template_name = 'mailsinfo... | [
"You can use self.object.user_guid to get the data of user_guid field so:\nclass CampaignEditor(UpdateView):\n model = Campaigns\n template_name = 'mailsinfo/add_campaign.html'\n form_class = CampaignsForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n ... | [
3
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074374709_django_django_forms_django_templates_django_views_python.txt |
Q:
Issue with using snowflake-connector-python with Python 3.x
I've spent half a day trying to figure it out on my own but now I've run out of ideas and googling requests.
So basically what I want is to connect to our Snowflake database using snowflake-connector-python package. I was able to install the package just ... | Issue with using snowflake-connector-python with Python 3.x | I've spent half a day trying to figure it out on my own but now I've run out of ideas and googling requests.
So basically what I want is to connect to our Snowflake database using snowflake-connector-python package. I was able to install the package just fine (together with all the related packages that were installed ... | [
"\nAttributeError: module 'snowflake' has no attribute 'connector'\n\nYour test code is likely in a file named snowflake.py which is causing a conflict in the import (it is ending up importing itself). Rename the file to some other name and it should allow you to import the right module and run the connector functi... | [
9,
4,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"attributeerror",
"python",
"snowflake_cloud_data_platform"
] | stackoverflow_0062658847_attributeerror_python_snowflake_cloud_data_platform.txt |
Q:
how to check if there are duplicate timestamps and add one separate them by one second
I have data with thousands of points. It records timestamps of when 100 people do a certain recurring activity in a day. It records everything in minute level so there are duplicates in the data.
I want to index my timestamp col... | how to check if there are duplicate timestamps and add one separate them by one second | I have data with thousands of points. It records timestamps of when 100 people do a certain recurring activity in a day. It records everything in minute level so there are duplicates in the data.
I want to index my timestamp column, but I cant do it because there are duplicate timestamps.
I want to separate duplicates ... | [
"You can de-duplicate using groupby.cumcount and pandas.to_timedelta:\ndf['timestamp'] = pd.to_datetime(df['timestamp'])\n\ndf['timestamp'] += pd.to_timedelta(df.groupby('timestamp').cumcount(), unit='s')\n\noutput:\n timestamp\n0 2022-10-10 01:05:00\n1 2022-10-10 01:05:01\n2 2022-10-10 01:23:00\n\nused ... | [
2
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074375119_dataframe_datetime_pandas_python.txt |
Q:
How to draw eplines on stereo images using `cv.computeCorrespondEpilines` with Fundamental Matrix
I am following this tutorial and trying to draw eplines on a stereo image pair using a fundamental matrix (Fmat) I obtained with cv2.stereoCalibrate. I am trying to use my imported Fmat.npy instead of cv.findFundament... | How to draw eplines on stereo images using `cv.computeCorrespondEpilines` with Fundamental Matrix | I am following this tutorial and trying to draw eplines on a stereo image pair using a fundamental matrix (Fmat) I obtained with cv2.stereoCalibrate. I am trying to use my imported Fmat.npy instead of cv.findFundamentalMat and cv.FM_RANSAC. However, both attempts at the code produce similar value errors.
Here's the cod... | [
"The line throwing the error is\nr, c = img1src.shape\n\nMost likely, the tutorial code was only tested with grayscale images, which just have a (row x col) shape. And I guess you are using an RGB image, having a (row x col x rgb) shape. Thus the shape has a third value in the tuple, which can't be unpacked into ju... | [
1
] | [] | [] | [
"fundamental_matrix",
"numpy",
"opencv",
"python"
] | stackoverflow_0074373035_fundamental_matrix_numpy_opencv_python.txt |
Q:
using pandas make a string column into multiple columns with True/False
I have this:
df = pd.DataFrame({'my_col' : ['red', 'red', 'green']})
my_col
red
red
green
I want this:
df2 = pd.DataFrame({'red' : [True, True, False], 'green' : [False, False, True]})
red green
True False
True False
False True
Is there... | using pandas make a string column into multiple columns with True/False | I have this:
df = pd.DataFrame({'my_col' : ['red', 'red', 'green']})
my_col
red
red
green
I want this:
df2 = pd.DataFrame({'red' : [True, True, False], 'green' : [False, False, True]})
red green
True False
True False
False True
Is there an elegant way to do this?
| [
"You can do this:\nfor color in df['my_col'].unique():\n df[color] = df['my_col'] == color\n\ndf2 = df[df['my_col'].unique()]\n\nIt will loop over each color in my_col and adds a column to df with the name of the color and True/False whether it is equal to the color. Finally extract df2 from df by selecting only... | [
1,
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074290852_pandas_python.txt |
Q:
Finding YTD Change and MoM Change
my table looks something like this:
Sector
4/1/2022
5/1/2022
6/1/2022
1Y Min
A
10
05
12
05
B
18
20
09
09
C
02
09
12
02
I want to add a new column "1m change" such that values of the new column is calculated using the formula: (Value as of the latest date - Value as of one mon... | Finding YTD Change and MoM Change | my table looks something like this:
Sector
4/1/2022
5/1/2022
6/1/2022
1Y Min
A
10
05
12
05
B
18
20
09
09
C
02
09
12
02
I want to add a new column "1m change" such that values of the new column is calculated using the formula: (Value as of the latest date - Value as of one month prior to the latest date... | [
"Try doing this:\nimport numpy as np\nimport pandas as pd\n\ndf['1M Change'] = np.nan\ndf['YTD Chg'] = np.nan\n\n\ndf['1M Change'] = df.iloc[:, -4] - df.iloc[:, -5]\ndf['YTD Chg'] = df.iloc[:, -4] - df.iloc[:, 1]\n\ndef aaa():\n df['1M Change'] = df.iloc[:, -4] - df.iloc[:, -5]\n df['YTD Chg'] = df.iloc[:, -4... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074364587_numpy_pandas_python.txt |
Q:
How to show only one object in django admin list view?
Problem
I wish to show only the last row of a QuerySet based on the ModelAdmin's ordering criteria. I have tried a couple of methods, but none has worked for me.
Model:
class DefaultConfig(models.Model):
created_at = models.DateTimeField()
...
Attempt... | How to show only one object in django admin list view? | Problem
I wish to show only the last row of a QuerySet based on the ModelAdmin's ordering criteria. I have tried a couple of methods, but none has worked for me.
Model:
class DefaultConfig(models.Model):
created_at = models.DateTimeField()
...
Attempt 1:
I tried overriding the ModelAdmin's get_queryset method ... | [
"Did you try to set list_per_page = 1?\nclass DefaultConfigAdmin(models.ModelAdmin):\n model = Config\n ordering = ('-created_at',)\n list_per_page = 1\n\nTechnically this will still return all Config objects, but only one per page and the latest one will be on the first page.\n\nAnother solution (similar ... | [
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0074374469_django_django_admin_python.txt |
Q:
Can you parameterize a template tag library on template directory?
Let's say I'm writing a form template tag library for Django, but want to be able to render both Bootstrap and UIKit forms.
The Python code will be identical, except for the template reference. Simplified
@register.inclusion_tag('myforms/bootstrap/... | Can you parameterize a template tag library on template directory? | Let's say I'm writing a form template tag library for Django, but want to be able to render both Bootstrap and UIKit forms.
The Python code will be identical, except for the template reference. Simplified
@register.inclusion_tag('myforms/bootstrap/formrow.html')
def form_row(fieldname, labelpos, labelsize, widgetsize):... | [
"From the documentation it's possible to register the inclusion tag using a django.template.Template instance, which means that you can do the following,\n# Pseudo code\nfrom django.template.loader import get_template\n\nbootstrap = get_template('myforms/bootstrap/formrow.html')\nuikit = get_template('myforms/uikit... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074375009_django_python.txt |
Q:
Paramiko authentication fails with "Agreed upon 'rsa-sha2-512' pubkey algorithm" (and "unsupported public key algorithm: rsa-sha2-512" in sshd log)
I have a Python 3 application running on CentOS Linux 7.7 executing SSH commands against remote hosts. It works properly but today I encountered an odd error executing... | Paramiko authentication fails with "Agreed upon 'rsa-sha2-512' pubkey algorithm" (and "unsupported public key algorithm: rsa-sha2-512" in sshd log) | I have a Python 3 application running on CentOS Linux 7.7 executing SSH commands against remote hosts. It works properly but today I encountered an odd error executing a command against a "new" remote server (server based on RHEL 6.10):
encountered RSA key, expected OPENSSH key
Executing the same command from the sys... | [
"Imo, it's a bug in Paramiko. It does not handle correctly absence of server-sig-algs extension on the server side.\nTry disabling rsa-sha2-* on Paramiko side altogether:\nssh_client.connect(\n server, username=ssh_user, key_filename=ssh_keypath,\n disabled_algorithms=dict(pubkeys=[\"rsa-sha2-512\", \"rsa-sha2-25... | [
21,
1,
0,
0
] | [] | [] | [
"linux",
"paramiko",
"python",
"ssh"
] | stackoverflow_0070565357_linux_paramiko_python_ssh.txt |
Q:
How do I copy a row from an existing dataframe df_a into a new dataframe df_b?
How do I copy a row from an existing dataframe df_a into a new dataframe df_b? Also, a cell from dataframe df_a into the new dataframe df_b? See the following example:
for index, row in df__data.iterrows():
for i in range(df__att... | How do I copy a row from an existing dataframe df_a into a new dataframe df_b? | How do I copy a row from an existing dataframe df_a into a new dataframe df_b? Also, a cell from dataframe df_a into the new dataframe df_b? See the following example:
for index, row in df__data.iterrows():
for i in range(df__attributes_to_compare.shape[0]):
if row[df__attributes_to_compare["in... | [
"You could try the following, which is bit more focused:\ndef select(row):\n col1, col2 = row\n df = df__data[[\"key1\", \"key2\", \"key3\"] + [col1, col2]]\n return df[df[col1] != df[col2]].rename(columns={col1: \"value1\", col2: \"value2\"})\n\nresult = pd.concat(\n map(select, df__attributes_to_compa... | [
1,
0
] | [] | [] | [
"dataframe",
"if_statement",
"iteration",
"pandas",
"python"
] | stackoverflow_0073715587_dataframe_if_statement_iteration_pandas_python.txt |
Q:
printing streaming result every 5min interval in python
The strategy1 method will be called for every record that comes every 1sec. I am trying to print the 5min mean value of column "ltt" every 5min. But with below code, the print is seen every 1sec. Can someone please suggest on how to do this.
The streaming inp... | printing streaming result every 5min interval in python | The strategy1 method will be called for every record that comes every 1sec. I am trying to print the 5min mean value of column "ltt" every 5min. But with below code, the print is seen every 1sec. Can someone please suggest on how to do this.
The streaming input i.e record has to captured every 1sec, only the print has ... | [
"The question is a bit vague. I interpret this to mean: 'I want to calculate mean every 5 minutes.'\nimport pandas as pd\nimport numpy as np\n\n#some sample data... \ndata = pd.DataFrame({'time':['11.11.2020 12:00:00', '11.11.2020 12:01:00', '11.11.2020 12:02:00', '11.11.2020 12:11:00', '11.11.2020 12:13:00'], 'val... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074370853_pandas_python.txt |
Q:
How can I map a dictionary onto a dataframe using conditions for the keys?
I have been able to successfully map a dictionary to a dataframe column using two categorical variables as keys, but I can't figure out how to do it if one of my target values should satisfy a condition rather than equal a value.
For exampl... | How can I map a dictionary onto a dataframe using conditions for the keys? | I have been able to successfully map a dictionary to a dataframe column using two categorical variables as keys, but I can't figure out how to do it if one of my target values should satisfy a condition rather than equal a value.
For example, consider the following dataframe:
df = pd.DataFrame({'F1': ['Y', 'N', 'N', 'N... | [
"You might use & (binary AND) for selecting row where numerous condition should be met, however beware its' stickiness, I would do it following way\nimport pandas as pd\ndf = pd.DataFrame({'F1': ['Y', 'N', 'N', 'N'],\n 'F2': ['HB', 'CP', '4D', 'CV'],\n 'F3': [10000, 5000, 15000, 2000]}... | [
0,
0
] | [] | [] | [
"conditional_statements",
"dictionary",
"mapping",
"python"
] | stackoverflow_0074375210_conditional_statements_dictionary_mapping_python.txt |
Q:
Update all matching keys in list of dictionaries with value in Python
key = 'take'
val = 5
dicts = [
OrderedDict([
(u'rt', 0),
(u'janoameezy', 0),
(u'calum', 0),
(u'is', 0),
(u'me', 0),
(u'whenever', 0),
(u'i', 0),
(u'take', 0),
(... | Update all matching keys in list of dictionaries with value in Python | key = 'take'
val = 5
dicts = [
OrderedDict([
(u'rt', 0),
(u'janoameezy', 0),
(u'calum', 0),
(u'is', 0),
(u'me', 0),
(u'whenever', 0),
(u'i', 0),
(u'take', 0),
(u'a', 0),
(u'selfie', 0),
(u'http', 0),
(u't', 0... | [
"You just loop through the list:\nfor od in dicts:\n if key in od:\n od[key] = val\n\nThe key in od tests for membership first; the key will only be updated if it was present before.\n",
"Since Python 3.3 you can use collections.ChainMap and subclass it to update all its maps\n>>> from collections impor... | [
2,
0
] | [] | [] | [
"dictionary",
"python",
"python_2.7"
] | stackoverflow_0024589539_dictionary_python_python_2.7.txt |
Q:
Jira api to search all issues in Jira using python
I want to list/search all the issues in Jira. I have a code like :
url = 'https://company.com/rest/api/2/search'
auth = HTTPBasicAuth("username", "password") // I tries token as well
headers = {
'Accept': 'application/json'
}
query = {
'jql': 'project=P... | Jira api to search all issues in Jira using python | I want to list/search all the issues in Jira. I have a code like :
url = 'https://company.com/rest/api/2/search'
auth = HTTPBasicAuth("username", "password") // I tries token as well
headers = {
'Accept': 'application/json'
}
query = {
'jql': 'project=PRKJECTKEY',
'startAt': 0
}
response = requests.requ... | [
"I can only describe my way of accessing the JIRA-API:\n1. I am using an API-key for this which one can easily create online, if one has the necessary permissions\n(https://developer.atlassian.com/cloud/jira/platform/basic-auth-for-rest-apis/)\n2. You need to set up the Jira-object to query issues first\nuser = 'fi... | [
1,
0
] | [] | [] | [
"jira",
"jira_rest_api",
"python",
"python_jira"
] | stackoverflow_0074373868_jira_jira_rest_api_python_python_jira.txt |
Q:
Function does not return value when used with decorators
When I call the function without the decorator a list of all files with the matching extension is returned. However, if I add the decorator @get_time, I do not get a return value from the function.
def get_time(func):
from time import perf_counter
fr... | Function does not return value when used with decorators | When I call the function without the decorator a list of all files with the matching extension is returned. However, if I add the decorator @get_time, I do not get a return value from the function.
def get_time(func):
from time import perf_counter
from functools import wraps
"""Times any function"""
@wr... | [
"The wrapper inside the decorator needs to return the result from func():\ndef get_time(func):\n from time import perf_counter\n from functools import wraps\n \"\"\"Times any function\"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n start_time = perf_counter()\n result = func(*arg... | [
4,
2
] | [] | [] | [
"python",
"python_decorators",
"return_value"
] | stackoverflow_0074375330_python_python_decorators_return_value.txt |
Q:
python - Joining two columns pandas - returning NA if any value is NA, however need to return real join
I have dataframe:
df = pd.DataFrame({'student_id': [71, 63, 23],
'student_name': [nan, 'Peter Andrews', 'Amy Powers'],
})
I am creating new column column which joins id + n... | python - Joining two columns pandas - returning NA if any value is NA, however need to return real join | I have dataframe:
df = pd.DataFrame({'student_id': [71, 63, 23],
'student_name': [nan, 'Peter Andrews', 'Amy Powers'],
})
I am creating new column column which joins id + name using
df['student_id_name'] = df['student_id'].astype(str) + ' ' + df['student_name']
Needed output:
{stu... | [
"Use Series.str.cat with na_rep parameter, last remove possible trailing spaces by Series.str.strip:\ndf['student_id_name'] = (df['student_id'].astype(str).str.cat(df['student_name'], \n sep=' ', na_rep='').str.strip())\nprint (df)\n student_id student_name s... | [
2,
0
] | [] | [] | [
"join",
"pandas",
"python"
] | stackoverflow_0074374395_join_pandas_python.txt |
Q:
Elasticserach with python: how to search for documents that do not equal
I am trying to get all the those documents where session is not "None". No matter which way try it, I get a error:
query = {
"bool" : {
"must_not" : {
"term" : {
"session" : "None"
}
}
}
... | Elasticserach with python: how to search for documents that do not equal | I am trying to get all the those documents where session is not "None". No matter which way try it, I get a error:
query = {
"bool" : {
"must_not" : {
"term" : {
"session" : "None"
}
}
}
}
#resp = es.search(index="test-sql-index", query={"must_not": {"session... | [
"you need to start your query by the term query\nquery = {\n\"query\":{\n \"bool\" : {\n \"must_not\" : [{\n \"term\" : {\n \"session.keyword\" : \"None\"\n }\n }]\n }\n }}\n\n"
] | [
0
] | [] | [] | [
"elasticsearch",
"python"
] | stackoverflow_0074375440_elasticsearch_python.txt |
Q:
clock/timer refresh times per second *tkinter
i'm making a clock but Click the time in seconds, for example, if the user clicks 2 hours, the timer will be like this:
2:00:00
1:59:59
but When it is refreshed, it replaces the previous label
that's mean:
2:00:00
refresh*
1:59:59
And the next feature is that if the us... | clock/timer refresh times per second *tkinter | i'm making a clock but Click the time in seconds, for example, if the user clicks 2 hours, the timer will be like this:
2:00:00
1:59:59
but When it is refreshed, it replaces the previous label
that's mean:
2:00:00
refresh*
1:59:59
And the next feature is that if the user hits the minute
Start with minutes and give an e... | [
"You should create a Label in the global scope and assign a tk.StringVar() variable to your label's textvariable and use that to update the label periodically instead of creating a new label at each interval\ntime_var = tk.StringVar(app, '00:00:00') # variable w/ default value\ntime = tk.Label(app, textvariable=ti... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074374761_python_tkinter.txt |
Q:
Read tabular data (rows and named columns) in Python - best practices
What is the best way to read data from txt/csv file, separate values based on columns to arrays (no matter how many columns there are) and how skip for example first row if file looks like this:
Considering existing libraries in python.
So far,... | Read tabular data (rows and named columns) in Python - best practices | What is the best way to read data from txt/csv file, separate values based on columns to arrays (no matter how many columns there are) and how skip for example first row if file looks like this:
Considering existing libraries in python.
So far, I've done it this way:
pareto_front_file = open("Pareto Front.txt")
data_p... | [
"Use the \"Pandas\" library (or something similar)\nFor tabular data, one of the most popular libraries is Pandas. Not only will this allow you to read the data easily, there are also methods for nearly all types of data transformation, filtering, visualization, etc. you can imagine.\nPandas is one of the most popu... | [
3
] | [] | [] | [
"data_science",
"python"
] | stackoverflow_0074374836_data_science_python.txt |
Q:
Python - add column and calculate value based on condition
I'm having a dataset that looks as follows:
data = {'Year':[2012, 2013, 2012, 2013, 2014, 2013],
'Quarter':[2, 2, 2, 2, 3, 1],
'ID':['CH7744', 'US4652', 'CA47441', 'CH1147', 'DE7487', 'US5174'],
'MC':[3348.22, 8542.55, 11851.2, 1571... | Python - add column and calculate value based on condition | I'm having a dataset that looks as follows:
data = {'Year':[2012, 2013, 2012, 2013, 2014, 2013],
'Quarter':[2, 2, 2, 2, 3, 1],
'ID':['CH7744', 'US4652', 'CA47441', 'CH1147', 'DE7487', 'US5174'],
'MC':[3348.22, 8542.55, 11851.2, 15718.1, 29914.7, 8731.78 ],
'PB': [2.74, 0.95, 1.57, 2.13, ... | [
"You can use groupby.rank and groupby.transform('size') combined with numpy.select:\ng = df.groupby(['Year', 'Quarter'])['MC']\n\ndf['SMB'] = np.select([g.rank(pct=True).le(0.5),\n g.transform('size').ge(2)],\n ['Small', 'Big'], np.nan)\n\noutput:\n Year Quarter I... | [
0
] | [] | [] | [
"dataframe",
"loops",
"pandas",
"python"
] | stackoverflow_0074375457_dataframe_loops_pandas_python.txt |
Q:
Error: Stale element is not attached to the page, after try statement
I have the following try statement, that basically finds a button that resets the current page I am in. In summary the page reloads,
try:
reset_button = D.find_element(By.XPATH,"//button[starts-with(@class,'resetBtn rightActionBarBtn ng-star... | Error: Stale element is not attached to the page, after try statement | I have the following try statement, that basically finds a button that resets the current page I am in. In summary the page reloads,
try:
reset_button = D.find_element(By.XPATH,"//button[starts-with(@class,'resetBtn rightActionBarBtn ng-star-inserted')]")
reset_button.click()
D.implicitly_wait(5)
ok_res... | [
"First of all, StaleElementReferenceException means that the web element reference you trying to access is no more valid. This normally happens after the page was reloaded. This is exactly what happens here.\nWhat happened is as following: you clicked on reset button and immediately after that you collecting the gr... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping",
"webdriverwait"
] | stackoverflow_0074375155_python_selenium_selenium_webdriver_web_scraping_webdriverwait.txt |
Q:
Returning the frequency of word list matched to a string
Here is an example of the problem with the result list as what I am aiming to obtain.
states = ["Montana", "New York", "Iowa", "Alabama", "Washington D.C."]
text = "Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montan... | Returning the frequency of word list matched to a string | Here is an example of the problem with the result list as what I am aiming to obtain.
states = ["Montana", "New York", "Iowa", "Alabama", "Washington D.C."]
text = "Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montana more than New York."
result = [Montana, Montana, New York]
O... | [
"\nlooking for the fastest way to perform this operation\n\nDue to this I suggest giving a try flashtext, you need to install it, which is done in standard way\npip install flashtext\n\nSimple usage example with your data\nfrom flashtext import KeywordProcessor\nstates = [\"Montana\", \"New York\", \"Iowa\", \"Alab... | [
2,
2,
0,
0,
0
] | [] | [] | [
"list",
"python",
"text"
] | stackoverflow_0074375079_list_python_text.txt |
Q:
Pandas groupby to to_csv
Want to output a Pandas groupby dataframe to CSV. Tried various StackOverflow solutions but they have not worked.
Python 3.6.1, Pandas 0.20.1
groupby result looks like:
id month year count
week
0 9066 82 32142 895
1 7679 84 30112 749
2 8368 126 ... | Pandas groupby to to_csv | Want to output a Pandas groupby dataframe to CSV. Tried various StackOverflow solutions but they have not worked.
Python 3.6.1, Pandas 0.20.1
groupby result looks like:
id month year count
week
0 9066 82 32142 895
1 7679 84 30112 749
2 8368 126 42187 872
3 11038 102 34... | [
"Try doing this:\nweek_grouped = df.groupby('week')\nweek_grouped.sum().reset_index().to_csv('week_grouped.csv')\n\nThat'll write the entire dataframe to the file. If you only want those two columns then, \nweek_grouped = df.groupby('week')\nweek_grouped.sum().reset_index()[['week', 'count']].to_csv('week_grouped.c... | [
26,
4,
3,
1,
1,
1,
0
] | [] | [] | [
"csv",
"pandas",
"pandas_groupby",
"python"
] | stackoverflow_0047602097_csv_pandas_pandas_groupby_python.txt |
Q:
ORA-01843: not a valid month error while loading data from csv to oracle db using python
CSV date column is in following format 'MM/DD/YYYY' while loading the data into db Iam seeing following error:
Oracle-Error-Code: 1843
Oracle-Error-Message: ORA-01843: not a valid month
Code:
csv_input=pd.read_csv(r"C:\python\... | ORA-01843: not a valid month error while loading data from csv to oracle db using python | CSV date column is in following format 'MM/DD/YYYY' while loading the data into db Iam seeing following error:
Oracle-Error-Code: 1843
Oracle-Error-Message: ORA-01843: not a valid month
Code:
csv_input=pd.read_csv(r"C:\python\test.csv",index_col=False,na_values=" ").fillna('')
try:
conn = orcCon.connect('scott/ti... | [
"You have only one problem, but is is serious. You use read_csv but your input data is not a csv file.\nt=\"\"\"Sample1 Sample2\n11/23/2022 abc\n11/23/2022 bcd\"\"\"\ncsv_input = pd.read_csv(io.StringIO(t))\nfor i,row in csv_input.iterrows():\n print(f'reading: {tuple(row)}')\n\nreading: ('1... | [
1
] | [] | [] | [
"cx_oracle",
"oracle",
"python"
] | stackoverflow_0074365871_cx_oracle_oracle_python.txt |
Q:
Pandas groupby sales item and count sales per month in column
Hi I have a pandas dataframe that looks roughly like this:
Date
Item
Sales
01-01-2022
iphone
$20
02-01-2022
iphone
$40
01-02-2022
iphone
$40
02-02-2022
macbook
$20
03-02-2022
macbook
$40
04-02-2022
macbook
$50
I am trying to get the count per it... | Pandas groupby sales item and count sales per month in column | Hi I have a pandas dataframe that looks roughly like this:
Date
Item
Sales
01-01-2022
iphone
$20
02-01-2022
iphone
$40
01-02-2022
iphone
$40
02-02-2022
macbook
$20
03-02-2022
macbook
$40
04-02-2022
macbook
$50
I am trying to get the count per item per month in a format like this:
Item
January
... | [
"Use a crosstab:\n(pd.crosstab(df['Item'], pd.to_datetime(df['Date'], dayfirst=True).dt.strftime('%B'))\n .assign(Average=lambda d: d.mean(axis=1))\n)\n\nOutput:\nDate February January Average\nItem \niphone 1 2 1.5\nmacbook 3 0 1.5\n\nA... | [
3,
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074375323_dataframe_group_by_pandas_python.txt |
Q:
Python: ImportError: lxml not found, please install it
I have the following code (in PyCharm (MacOS)):
import pandas as pd
fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
print(fiddy_states)
And I get the following error:
/Library/Frameworks/Python.framework/Versions/3.6/bin... | Python: ImportError: lxml not found, please install it | I have the following code (in PyCharm (MacOS)):
import pandas as pd
fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
print(fiddy_states)
And I get the following error:
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/user_name/PycharmProjects/PandasTest/Doc3.... | [
"Based on the fact that the error is:\n/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6\nThis means that you are working with python-3.6. Now usually the package manager for python-3.x is pip3. So you probably should install it with:\npip3 install lxml\n",
"For people reached here using Jupyter not... | [
48,
31,
5,
3,
2,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0044954802_macos_python.txt |
Q:
Unable to open LOCAL HTML page for scrapping using BS$ Python
I have written following code to open a local HTML file saved on my Desktop:
However while running this code I get following error:
I have no prior experience of handling this in Python or BS4. I tried various solutions online but couldn't solve it.
C... | Unable to open LOCAL HTML page for scrapping using BS$ Python | I have written following code to open a local HTML file saved on my Desktop:
However while running this code I get following error:
I have no prior experience of handling this in Python or BS4. I tried various solutions online but couldn't solve it.
Code:
import csv
from email import header
from fileinput import file... | [
"It's unicode error prefix the path with r (to produce a raw string):\nurl = r\"C:\\ Users\\ ASUS\\ Desktop\\ payment.html\"\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"offline",
"python"
] | stackoverflow_0074375625_beautifulsoup_html_parsing_offline_python.txt |
Q:
Deleted column in streamlit dropdown menu not updated immediately
I am trying to implement a "delete column" button for a csv file by means of a dropdownmenu form in streamlit. It works fine and removes the column, only the dropdownmenu list will not get updated until I refresh the page. I would like it to be done... | Deleted column in streamlit dropdown menu not updated immediately | I am trying to implement a "delete column" button for a csv file by means of a dropdownmenu form in streamlit. It works fine and removes the column, only the dropdownmenu list will not get updated until I refresh the page. I would like it to be done automatically.
File input.csv:
col1,col2,col3
x,x,x
x,x,x
x,x,x
x,x,x
... | [
"Just rerun it after col deletion.\nst.session_state.df.to_csv(r'./input.csv', index = False)\nst.experimental_rerun() # <======= here\n\n"
] | [
1
] | [] | [] | [
"drop_down_menu",
"python",
"session_state",
"streamlit"
] | stackoverflow_0074261867_drop_down_menu_python_session_state_streamlit.txt |
Q:
How can I fix the error AttributeError: 'Series' object has no attribute 'swifter'?
This is pretty direct, I was trying to replicate the example used in Swifter page https://github.com/jmcarpenter2/swifter. However, I keep getting the error AttributeError: 'Series' object has no attribute 'swifter'. What's up with... | How can I fix the error AttributeError: 'Series' object has no attribute 'swifter'? | This is pretty direct, I was trying to replicate the example used in Swifter page https://github.com/jmcarpenter2/swifter. However, I keep getting the error AttributeError: 'Series' object has no attribute 'swifter'. What's up with that?
Update - The example I tried:
import pandas as pd
import swifter
df = pd.DataFra... | [
"I faced the same problem and solved it like this:\nfrom swifter import swifter\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"swifter"
] | stackoverflow_0062843445_pandas_python_swifter.txt |
Q:
Is it possible to declare a function without arguments but then pass some arguments to that function without raising exception?
In python is it possible to have the above code without raising an exception ?
def myfunc():
pass
# TypeError myfunc() takes no arguments (1 given)
myfunc('param')
Usually in php in... | Is it possible to declare a function without arguments but then pass some arguments to that function without raising exception? | In python is it possible to have the above code without raising an exception ?
def myfunc():
pass
# TypeError myfunc() takes no arguments (1 given)
myfunc('param')
Usually in php in some circumstances I launch a function without parameters and then retrieve the parameters inside the function.
In practice I don't ... | [
">>> def myFunc(*args, **kwargs):\n... # This function accepts arbitary arguments:\n... # Keywords arguments are available in the kwargs dict;\n... # Regular arguments are in the args tuple.\n... # (This behaviour is dictated by the stars, not by\n... # the name of the formal parameters.)\n... print ar... | [
19,
16,
7,
5,
0
] | [] | [] | [
"arguments",
"exception",
"python"
] | stackoverflow_0002241200_arguments_exception_python.txt |
Q:
Check repeating number in every four numbers
I would like to find out how to find repeated numbers after every 4 numbers.
This is what I have.
arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]
size = len(arr)
for i in range(0,size,4):
if arr[i] == arr[i + 4] and arr[i + 4] == arr[i + 8] and... | Check repeating number in every four numbers | I would like to find out how to find repeated numbers after every 4 numbers.
This is what I have.
arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]
size = len(arr)
for i in range(0,size,4):
if arr[i] == arr[i + 4] and arr[i + 4] == arr[i + 8] and arr[i + 8] == arr[i + 12 :
print(arr[... | [
"arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]\n\nfor i in range(0, len(arr)):\n try:\n # checking the conditions\n if arr[i] == arr[i+4] and arr[i] == arr[i+8] and arr[i] == arr[i+12] :\n print(arr[i])\n except IndexError as e:\n # when you catch this exception,... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074375486_list_python.txt |
Q:
Why do I get "SyntaxError: invalid syntax" when using `match` in Python?
I tried to run a Python script using
python3 ds_main.py
but it returns the error:
Traceback (most recent call last):
File "ds_main.py", line 14 in <module>
import cmd_main
File "/home/me/discord/cmd_main.py", line 190
match actio... | Why do I get "SyntaxError: invalid syntax" when using `match` in Python? | I tried to run a Python script using
python3 ds_main.py
but it returns the error:
Traceback (most recent call last):
File "ds_main.py", line 14 in <module>
import cmd_main
File "/home/me/discord/cmd_main.py", line 190
match action:
^
SyntaxError: invalid syntax
In this section, I did add a match... | [
"Python 3.8.10 does not support structural pattern matching (match keyword).\nYou need Python ≥ 3.10:\nhttps://docs.python.org/3/whatsnew/3.10.html\n\nPEP 634, Structural Pattern Matching: Specification\n\n",
"If you need to stay compatible with older Python versions (because of not up to date production operatin... | [
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0071851501_python.txt |
Q:
VS Code: ModuleNotFoundError: No module named 'sklearn'
I am working in VS Code to run a Python script in conda environment named myenv where sklearn is already installed. However when I import it and run the script I get the following error:
Traceback (most recent call last):
File "d:\ML\Project\src\train.py",... | VS Code: ModuleNotFoundError: No module named 'sklearn' | I am working in VS Code to run a Python script in conda environment named myenv where sklearn is already installed. However when I import it and run the script I get the following error:
Traceback (most recent call last):
File "d:\ML\Project\src\train.py", line 5, in <module>
from sklearn.linear_models import Li... | [
"Have you tried https://code.visualstudio.com/docs/python/environments\nHad the same issue and solved it by setting vscode to use my conda environment.\n",
"I also have the same problem, but when I tried this command the error got fixed:\npip install sklearn\n",
"according to pypi:\nuse pip install scikit-learn... | [
1,
0,
0
] | [
"Click on the terminal in the VS Code and run the following command to create the virtual environment in VS Code.\npython -m venv path location of the working file\\myvenv\nin VS Code it will automatically activate.\nI have attached an image\n\n"
] | [
-2
] | [
"pip",
"python",
"python_3.x",
"scikit_learn",
"visual_studio_code"
] | stackoverflow_0066956197_pip_python_python_3.x_scikit_learn_visual_studio_code.txt |
Q:
Remove rows based on two groupby conditions
In my dataframe below I wish to remove rows based on two conditions:
has an id that appears two times
belong to group B
In the dataframe (data) below it would be row with index 1 and 6 that should be removed. How could this be solved in an elegant fashion?
data=pd.Data... | Remove rows based on two groupby conditions | In my dataframe below I wish to remove rows based on two conditions:
has an id that appears two times
belong to group B
In the dataframe (data) below it would be row with index 1 and 6 that should be removed. How could this be solved in an elegant fashion?
data=pd.DataFrame({'id':[1,1,2,3,4,5,5],
'group'... | [
"Use boolean indexing:\n# does the id appear more than once?\nm1 = data['id'].duplicated(keep=False)\n# is the row a group B?\nm2 = data['group'].eq('B')\n\n# keep the row if not both conditions are met\nout = data[~(m1&m2)]\n\nDe Morgan's equivalent:\nm1 = ~data['id'].duplicated(keep=False)\nm2 = data['group'].ne(... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074375847_pandas_python.txt |
Q:
numpy array with n prefilled columns
I need to specialized numpy arrays. Assume I have a function:
def gen_array(start, end, n_cols):
It should behave like this, generating three columns where each column goes from start (inclusive) to end (exclusive):
>>> gen_array(20, 25, 3)
array([[20, 20, 20],
[21... | numpy array with n prefilled columns | I need to specialized numpy arrays. Assume I have a function:
def gen_array(start, end, n_cols):
It should behave like this, generating three columns where each column goes from start (inclusive) to end (exclusive):
>>> gen_array(20, 25, 3)
array([[20, 20, 20],
[21, 21, 21],
[22, 22, 22],
[23... | [
"In addition to numpy.arange and numpy.reshape, use numpy.repeat to extend your data.\nimport numpy as np\n\ndef gen_array(start, end, n_cols):\n return np.arange(start, end).repeat(n_cols).reshape(-1, n_cols)\n\nprint(gen_array(20, 25, 3))\n# [[20 20 20]\n# [21 21 21]\n# [22 22 22]\n# [23 23 23]\n# [24 24 2... | [
2,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074364871_numpy_python.txt |
Q:
Not seeing spreadsheets created with Drive/Sheets API (Python)
I have looked all over the forums and documentation to try to understand what I am missing here, but I'm also very new to Python so could be making a simple mistake. I am trying to create a spreadsheet in a shared folder, then share that sheet with my ... | Not seeing spreadsheets created with Drive/Sheets API (Python) | I have looked all over the forums and documentation to try to understand what I am missing here, but I'm also very new to Python so could be making a simple mistake. I am trying to create a spreadsheet in a shared folder, then share that sheet with my main account (using a service account to create the sheet because no... | [
"I was missing .execute() after adjusting permissions. Here is the correct permissions portion with slight adjustment to grab the sheet id right before that works perfect to create a sheet and make it visible.\nsheet_id = results.get('id') \n\n\npermissions = service.permissions().create(\n fileId=sheet_id, bo... | [
0
] | [] | [] | [
"drive",
"google_sheets",
"python"
] | stackoverflow_0074369878_drive_google_sheets_python.txt |
Q:
Is there an easy oneliner to make out of a string with numbers multiple floats? Using python
I have for example a string that goes: 1234 4321 3412 Is there a way that I can using python have three floats like this:
float1: 1234 float2: 4321 float3: 3412
I searches the web but i dont know how to formulat the senten... | Is there an easy oneliner to make out of a string with numbers multiple floats? Using python | I have for example a string that goes: 1234 4321 3412 Is there a way that I can using python have three floats like this:
float1: 1234 float2: 4321 float3: 3412
I searches the web but i dont know how to formulat the sentence to find a solution,
| [
"We can split the string by its space characters to create a list of 3 strings, and then map the float conversion across each string value to convert it into a float.\ns = \"1234 4321 3412\"\nfloat1, float2, float3 = list(map(float, s.split(' ')))\n\n"
] | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074375935_python_string.txt |
Q:
Turning each element in a numpy array into its index in another array
How can I turn each element in a numpy array into its index in another array?
Take the following example. Let a = np.array(["a", "c", "b", "c", "a", "a"]) and b = np.array(["b", "c", "a"]). How can I turn each element in a into its index in b to... | Turning each element in a numpy array into its index in another array | How can I turn each element in a numpy array into its index in another array?
Take the following example. Let a = np.array(["a", "c", "b", "c", "a", "a"]) and b = np.array(["b", "c", "a"]). How can I turn each element in a into its index in b to obtain c = np.array([2, 1, 0, 1, 2, 2])?
| [
"We can solve this problem in easy way as follow using Dictionary in python\nimport numpy as np\na = np.array([\"a\", \"c\", \"b\", \"c\", \"a\", \"a\"])\n\nb = np.array([\"b\", \"c\", \"a\"])\n\n# Create hashmap/dictionary to store indexes \nhashmap ={}\nfor index,value in enumerate(b):\n hashmap[value]=index\n... | [
2,
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074375747_numpy_numpy_ndarray_python.txt |
Q:
PyCharm error: 'No Module' when trying to import own module (python script)
I have written a module (a file my_mod.py file residing in the folder my_module).
Currently, I am working in the file cool_script.py that resides in the folder cur_proj. I have opened the folder in PyCharm using File -- open (and I assume,... | PyCharm error: 'No Module' when trying to import own module (python script) | I have written a module (a file my_mod.py file residing in the folder my_module).
Currently, I am working in the file cool_script.py that resides in the folder cur_proj. I have opened the folder in PyCharm using File -- open (and I assume, hence, it is a PyCharm project).
In ProjectView (CMD-7), I can see my project cu... | [
"If your own module is in the same path, you need mark the path as Sources Root. In the project explorer, right-click on the directory that you want import. Then select Mark Directory As and select Sources Root.\n",
"So if you go to \n-> Setting -> Project:My_project -> Project Structure,\nJust the directory in w... | [
398,
68,
33,
11,
6,
6,
5,
4,
3,
2,
1,
1,
0,
0,
0
] | [
"Pycharm 2017.1.1\n\nClick on View->ToolBar & View->Tool Buttons\nOn the left pane Project would be visible, right click on it and\npress Autoscroll to source\nand then run your code.\n\nThis worked for me.\n",
"The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes ... | [
-1,
-2
] | [
"module",
"pycharm",
"python"
] | stackoverflow_0028705029_module_pycharm_python.txt |
Q:
Can anyone explain me the output of the below recursion?
I think the last output should be 5 but it is 6, why?, Kindly explain very simply
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("Recursion Example Results")
tri_recurs... | Can anyone explain me the output of the below recursion? | I think the last output should be 5 but it is 6, why?, Kindly explain very simply
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("Recursion Example Results")
tri_recursion(3)
output is -
Recursion Example Results
1
3
6
Desired o... | [
"Sorry, I got it! :)\nAt first I thought the recursion would happen this way, 3 + (3-1) = 5\nbut now I got it!\nrecusrion happens this way,\n3 + (3-1) + (2-1) + (1-1) = 63\nThis way we can solve the factorial of any natural number\n def fact_(n):\n if n == 0:\n return 1\n else:\n return n*fact_(n-1)\n\n... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074375884_python_python_3.x.txt |
Q:
Read data from kafka and print in apache beam
I am like super new to apache beam and i am trying to read data from a kafka topic and then print on screen.. here is what i am trying but i think i am not sure about the print part
class LogProcessor(beam.DoFn):
def process(self, element):
print(elemen... | Read data from kafka and print in apache beam | I am like super new to apache beam and i am trying to read data from a kafka topic and then print on screen.. here is what i am trying but i think i am not sure about the print part
class LogProcessor(beam.DoFn):
def process(self, element):
print(element)
(p
| 'read' >> ReadFromKafka(cluster='mykafka... | [
"You can use a beam.Map with a function thats logs then returns each element in the PCollection :\nimport logging\n\ndef log_element(elem):\n logging.info(elem)\n return elem\n \n\n(p\n | 'read' >> ReadFromKafka(cluster='mykafkacluster',topic='funny')\n | 'print' >> beam.Map(log_element)\n )\n\nThen you wil... | [
1
] | [] | [] | [
"apache_beam",
"python"
] | stackoverflow_0074371871_apache_beam_python.txt |
Q:
Why do I get an MKL error when running my python script on MacOS
I have a python script that was converted from an .ipynb notebook from Google Colab that I'm trying to run natively on my Mac running Big Sur.
When I try to run the script using python scriptname.py it gives me the following error:
NTEL MKL ERROR: dl... | Why do I get an MKL error when running my python script on MacOS | I have a python script that was converted from an .ipynb notebook from Google Colab that I'm trying to run natively on my Mac running Big Sur.
When I try to run the script using python scriptname.py it gives me the following error:
NTEL MKL ERROR: dlopen(/Users/MyUser/opt/anaconda3/lib/libmkl_core.dylib, 9): image not ... | [
"Try following, to make sure it's not something with your conda stuff.\n> python3 -m venv venv-38\n> source venv-38/bin/activate\n(venv-38) > pip3 install pandas\n...\n...\n(venv-38) > python\nPython 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53)\n[Clang 6.0 (clang-600.0.57)] on darwin\nType \"help\", \"copyright... | [
1,
0
] | [] | [] | [
"anaconda",
"intel_mkl",
"numpy",
"pandas",
"python"
] | stackoverflow_0065796554_anaconda_intel_mkl_numpy_pandas_python.txt |
Q:
Remove first values repeated in an array... Python, Numpy, Pandas, Arrays
so I do have this NumPy array result(final), and I want to reduce it, I mean, if the value is repeated, then I want to delete the first value and maintain the second,third value repeated and so on...
import hmac
import hashlib
import time
fr... | Remove first values repeated in an array... Python, Numpy, Pandas, Arrays | so I do have this NumPy array result(final), and I want to reduce it, I mean, if the value is repeated, then I want to delete the first value and maintain the second,third value repeated and so on...
import hmac
import hashlib
import time
from argparse import _MutuallyExclusiveGroup
from tkinter import *
import pandas ... | [
"df = pd.DataFrame([1, 2, 3, 4, 5, 1, 3, 5, 5])\n\n# keep the unique rows\nunique_mask = ~df.duplicated(keep=False)\n\n# keep the repeated rows (skipping the first for each non-unique)\nrepeated_mask = df.duplicated()\n\ndf.loc[unique_mask | repeated_mask]\n\n 0\n1 2\n3 4\n5 1\n6 3\n7 5\n8 5\n\n",
"Maybe ... | [
1,
0,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"pandas",
"python"
] | stackoverflow_0074374855_arrays_numpy_pandas_python.txt |
Q:
Define a procedure that finds the index of the second instance of a string in a a larger string
I am new to python, may i know
Define a procedure that finds the index of the second instance of a string in a larger string.
def find_second(findin, whattofind):
return
find_second('dance, dance, dance everyday... | Define a procedure that finds the index of the second instance of a string in a a larger string | I am new to python, may i know
Define a procedure that finds the index of the second instance of a string in a larger string.
def find_second(findin, whattofind):
return
find_second('dance, dance, dance everyday', 'dance')
find_second('learning about data, surprisingly, requires a lot of data','data')
| [
"Second index can be found by searching after the first index\nYou can use index() or find() for strings.\ndef find_second(findin, whattofind):\n return findin.index(whattofind,findin.index(whattofind)+1)\n\nfind_second('dance, dance, dance everyday', 'dance')\nfind_second('learning about data, surprisingly, req... | [
1,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074375887_function_python.txt |
Q:
been blocked by CORS policy: No 'Access-Control-Allow-Origin'
I am trying to send a GET request to my python flask server (running on 127.0.0.1:5000) from my javascript page (running on 127.0.0.1:80)
Python Flask server
import classifyGrade
from flask import Flask
from flask import request
from flask import Respo... | been blocked by CORS policy: No 'Access-Control-Allow-Origin' | I am trying to send a GET request to my python flask server (running on 127.0.0.1:5000) from my javascript page (running on 127.0.0.1:80)
Python Flask server
import classifyGrade
from flask import Flask
from flask import request
from flask import Response
from flask import jsonify
import json
app = Flask(__name__)
@a... | [
"When reqesting data from different URL origins , we need to allow CORS while using any browser.\nBut, POSTMAN is not a browser, so you don't need CORS.\ndef classify():\n ...\n # We can enable CORS, just by adding following header in Flask\n ...\n\n response.headers.add(\"Access-Control-Allow-Origin\", \"*... | [
0
] | [] | [] | [
"flask",
"get",
"javascript",
"python"
] | stackoverflow_0074373482_flask_get_javascript_python.txt |
Q:
Azure Python API to check if a VM has public IP
My use-case is:
Identify if a VM has public IP(T/F).
(Optional) Print the Public IP.
I have been trying out a lot of combinations mentioned here and here. My primary goal is to identify if a VM has public IP associated or not. Seems like the azure python sdk has ch... | Azure Python API to check if a VM has public IP | My use-case is:
Identify if a VM has public IP(T/F).
(Optional) Print the Public IP.
I have been trying out a lot of combinations mentioned here and here. My primary goal is to identify if a VM has public IP associated or not. Seems like the azure python sdk has changed over time and some of the old solutions are not... | [
"I tried to reproduce the same in my environment and got below results:\nI have one Azure VM named srivm with Public IP as below:\n\nTo fetch this via Python API, I created one service principal with client secret as below:\n\nI tried using below code to get Public IP address of virtual machine and got it successfu... | [
1
] | [] | [] | [
"azure",
"azure_rest_api",
"azure_vm",
"python"
] | stackoverflow_0074311879_azure_azure_rest_api_azure_vm_python.txt |
Q:
Tz Conversion Pandas/Yfinance
I've just made a fresh installation of Linux 18.04.6 LTS (Bionice Beaver) and can't get a python script to work. This script worked before the fresh installation and works on my Windows PC, but can't seen to work here. Here is the test code im running:
df = web.get_data_yahoo('^BVSP',... | Tz Conversion Pandas/Yfinance | I've just made a fresh installation of Linux 18.04.6 LTS (Bionice Beaver) and can't get a python script to work. This script worked before the fresh installation and works on my Windows PC, but can't seen to work here. Here is the test code im running:
df = web.get_data_yahoo('^BVSP', progress=False,show_errors=False)
... | [
"See section 'pandas_datareader override').\nAnd perhaps the syntax has changed.\nTry this for me it works:\nimport yfinance as yf\nfrom pandas_datareader import data as pdr\n\nyf.pdr_override()\n\nprint(pdr.get_data_yahoo('^BVSP', progress=False,show_errors=False))\n\nOr\nimport yfinance as yf\n\ndf = yf.download(... | [
0
] | [] | [] | [
"pandas",
"python",
"yfinance"
] | stackoverflow_0074361598_pandas_python_yfinance.txt |
Q:
Merging two data frames based on a common column with repeated values
I have 2 data frames with different lengths:
len(df1) 10104
len(df2) 15560
I want to merge these based on a common column (taskID) on both data frames. The Task ID has repeated IDs each ID represent an item belongs to the same task.
example:
df1... | Merging two data frames based on a common column with repeated values | I have 2 data frames with different lengths:
len(df1) 10104
len(df2) 15560
I want to merge these based on a common column (taskID) on both data frames. The Task ID has repeated IDs each ID represent an item belongs to the same task.
example:
df1:
TaskID
task duration
task 45
2 mins
task 45
5 mins
task 45
7 ... | [
"You can use groupby.cumcount to deduplicate the TaskIDs and merge in order:\ndf1.merge(df2, left_on=['TaskID', df1.groupby('TaskID').cumcount()],\n right_on=['TaskID', df2.groupby('TaskID').cumcount()])\n\nOutput:\n TaskID key_1 task duration gender\n0 task 45 0 2 mins male\n1 t... | [
2,
0
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074373425_dataframe_list_pandas_python.txt |
Q:
AWS CDK Python Create App Load Balancer Listner with default action
I'm trying to move over from Cloudformation to CDK and have been struggling here.
I'm trying to create a ELB listner and add a default action to it. Port 80 Listner with default action to redirect to 443. It seems like this should be easy but I c... | AWS CDK Python Create App Load Balancer Listner with default action | I'm trying to move over from Cloudformation to CDK and have been struggling here.
I'm trying to create a ELB listner and add a default action to it. Port 80 Listner with default action to redirect to 443. It seems like this should be easy but I can't see any way to hook in to the default actions for a listner. Some so... | [
"For anyone else struggling like i was here is the way to declare it on instantiation:\n listener80 = lb.add_listener(\n \"listener80\",\n port=80,\n default_action=elbv2.ListenerAction.redirect(host=\"#{host}\", path=\"/#{path}\", permanent=True, port=\"443\", protocol=\"HTTPS\", q... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_cdk",
"python"
] | stackoverflow_0074362583_amazon_web_services_aws_cdk_python.txt |
Q:
How to find path with filename
Im working on a program, that should make graphs based on json files. Most of the GUI is working and made with tkinter, i also know how to make graphs with matplotlib, the problem is finding the specific path for the files by clicking on them:
I want the program to make the graph wh... | How to find path with filename | Im working on a program, that should make graphs based on json files. Most of the GUI is working and made with tkinter, i also know how to make graphs with matplotlib, the problem is finding the specific path for the files by clicking on them:
I want the program to make the graph when i click on a specific filename.
... | [
"You could store your filenames and their associated parent directories in a dictionary when you fetch them (before you populate the listbox)\nfile_dict = { # example...\n '1D1.json': 'C:/parent/path/one/',\n '1D2.json': 'C:/parent/path/one/',\n '1D3.json': 'C:/parent/path/two/',\n '1D4.json': 'C:/pare... | [
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0074375495_matplotlib_python_tkinter.txt |
Q:
How to loop from a particular index of an array in Python?
I am using a nested loop, and I want my inner loop to start from the index of the outer loop.
How can I implement this?
I want j to run from i till the end of the array.
nums = [2,7,11,15]
for i in nums:
for j in nums:
print(j)
A:
nums = [2,... | How to loop from a particular index of an array in Python? | I am using a nested loop, and I want my inner loop to start from the index of the outer loop.
How can I implement this?
I want j to run from i till the end of the array.
nums = [2,7,11,15]
for i in nums:
for j in nums:
print(j)
| [
"nums = [2,7,11,15]\n\nfor i, val in enumerate(nums):\n for j in nums[i:]:\n print(j)\n\nThis output is interested for you?\n2\n7\n11\n15\n7\n11\n15\n11\n15\n15\n",
"Does it solve your problem?\nnums = [2, 7, 11, 15]\n\nfor i in range(len(nums)):\n for j in range(i, len(nums)):\n print(j)\n\n"... | [
1,
1,
0
] | [] | [] | [
"arrays",
"for_loop",
"loops",
"python"
] | stackoverflow_0074376091_arrays_for_loop_loops_python.txt |
Q:
How to select multiple dimensions in torch.any?
I have a (BxHxW) tensor with boolean values which makes sense of a semantic map in a semantic segmentation problem . For each semantic map in the batch, I need to understand whether this map contains some False or not.
I used torch.any(input, dim=(1, 2)), so that in ... | How to select multiple dimensions in torch.any? | I have a (BxHxW) tensor with boolean values which makes sense of a semantic map in a semantic segmentation problem . For each semantic map in the batch, I need to understand whether this map contains some False or not.
I used torch.any(input, dim=(1, 2)), so that in the end there was one dimension left - the size of th... | [
"You can use:\ntorch.any(input.view(input.shape[0], -1), dim=1)\n\n"
] | [
0
] | [] | [] | [
"any",
"python",
"pytorch",
"tensor"
] | stackoverflow_0074375584_any_python_pytorch_tensor.txt |
Q:
nextcord error, nextcord.ext.commands.errors.CommandNotFound
I started nextcord to develop a discord bot, but I don't understand it well from the beginning.
When I type !youtube with slash_command in discord, I get this result, but I don't know where I went wrong..
GUILD_ID & Token deleted for secure
from nextcord... | nextcord error, nextcord.ext.commands.errors.CommandNotFound | I started nextcord to develop a discord bot, but I don't understand it well from the beginning.
When I type !youtube with slash_command in discord, I get this result, but I don't know where I went wrong..
GUILD_ID & Token deleted for secure
from nextcord import Interaction, SlashOption, ChannelType
from nextcord.abc im... | [
"If you type / in your message field in discord should pop up something where you can select bots and commands. Click on your bot's icon and check if your 'youtube' command is there. If yes just click it and hit enter.\nAlso you can remove this line: bot = commands.Bot(command_prefix='!') if you only use Slash Comm... | [
0,
0
] | [] | [] | [
"bots",
"discord",
"nextcord",
"python"
] | stackoverflow_0071821662_bots_discord_nextcord_python.txt |
Q:
How do I visualize a net in Pytorch?
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg imp... | How do I visualize a net in Pytorch? | import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg import model_urls
from torchviz import make_d... | [
"Here are three different graph visualizations using different tools.\nIn order to generate example visualizations, I'll use a simple RNN to perform sentiment analysis taken from an online tutorial:\nclass RNN(nn.Module):\n\n def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim):\n\n super(... | [
87,
37,
16,
13,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0052468956_python_pytorch.txt |
Q:
Mean value of each channel of several images
I want to compute mean value for every RGB channel through all dataset stored in a numpy array. I know it's done with np.mean and I know its basic usage.
np.mean(arr, axis=(??))
But as the array has 4 dimensions, I'm a bit lost in setting the correct axis. All examples... | Mean value of each channel of several images | I want to compute mean value for every RGB channel through all dataset stored in a numpy array. I know it's done with np.mean and I know its basic usage.
np.mean(arr, axis=(??))
But as the array has 4 dimensions, I'm a bit lost in setting the correct axis. All examples I found were dealing with just 1-D or 2-D arrays.... | [
"For a generic ndarray, you could create a tuple to cover all axes except the last one corresponding to the color channel and then use that for the axis param with np.mean, like so -\nnp.mean(a, axis=tuple(range(a.ndim-1)))\n\nSample run to verify against a loop-comprehension version -\nIn [141]: np.random.seed(0)\... | [
16,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0047124143_arrays_numpy_python.txt |
Q:
How to transform a list of lists of strings to a frequency DataFrame?
I have a list of lists of strings (Essentially it's a corpus) and I'd like to convert it to a matrix where a row is a document in the corpus and the columns are the corpus' vocabulary.
I can do this with CountVectorizer but it would require quit... | How to transform a list of lists of strings to a frequency DataFrame? | I have a list of lists of strings (Essentially it's a corpus) and I'd like to convert it to a matrix where a row is a document in the corpus and the columns are the corpus' vocabulary.
I can do this with CountVectorizer but it would require quite a lot of memory as I would need to convert each list into a string that i... | [
"I would combine collections.Counter and the DataFrame constructor:\nfrom collections import Counter\n\ncorpus = [['a', 'b', 'c'],['a', 'a'],['b', 'c', 'c']]\n\ndf = pd.DataFrame(map(Counter, corpus)).fillna(0, downcast='infer')\n\nOutput:\n a b c\n0 1 1 1\n1 2 0 0\n2 0 1 2\n\n",
"Using only Pandas:\... | [
3,
2,
2
] | [] | [] | [
"data_science",
"nlp",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074375757_data_science_nlp_pandas_python_scikit_learn.txt |
Q:
Is tkwait wait_variable/wait_window/wait_visibility broken?
I recently started to use tkwait casually and noticed that some functionality only works under special conditions. For example:
import tkinter as tk
def w(seconds):
dummy = tk.Toplevel(root)
dummy.title(seconds)
dummy.after(seconds*1000, lamb... | Is tkwait wait_variable/wait_window/wait_visibility broken? | I recently started to use tkwait casually and noticed that some functionality only works under special conditions. For example:
import tkinter as tk
def w(seconds):
dummy = tk.Toplevel(root)
dummy.title(seconds)
dummy.after(seconds*1000, lambda x=dummy: x.destroy())
dummy.wait_window(dummy)
print(s... | [
"Basically, you need great care if you're using an inner event loop because:\n\nConditions that would terminate the outer event loop aren't checked for until the inner event loop(s) are finished.\nIt's really quite easy to end up recursively entering an inner event loop by accident.\n\nThe recursive entry problem i... | [
6
] | [] | [] | [
"event_driven",
"python",
"tcl",
"tkinter",
"wait"
] | stackoverflow_0074370984_event_driven_python_tcl_tkinter_wait.txt |
Q:
Map other categories in pandas dataframe column
I have a pandas dataframe, combined_copy which has a column, job_industry_category with multiple categories. I want to use a mapping function to restrict these categories to the top 3 by distribution, the rest form one other category. I intend to use numeric digits a... | Map other categories in pandas dataframe column | I have a pandas dataframe, combined_copy which has a column, job_industry_category with multiple categories. I want to use a mapping function to restrict these categories to the top 3 by distribution, the rest form one other category. I intend to use numeric digits as follows:
combined_copy['job_industry_category'].map... | [
"We can use mapping function\n>>> def com_map(x):\n... if x=='Manufacturing':\n... return 0\n... else:\n... return 3\n...\n\ninside map function\ndf['j_i_c'].map(com_map)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074376042_pandas_python.txt |
Q:
Convert SQL to peewee
How to convert this to peewee query?
_, storage, spaceLeft = db.execute('''
SELECT session, storage, storage - count(questID) FROM Hypos
INNER JOIN Quests ON Hypos.hypoID = Quests.hypoID
WHERE Hypos.hypoID = ?1 AND session = ?2
GROUP BY session
UNION SELECT NULL, max(stora... | Convert SQL to peewee | How to convert this to peewee query?
_, storage, spaceLeft = db.execute('''
SELECT session, storage, storage - count(questID) FROM Hypos
INNER JOIN Quests ON Hypos.hypoID = Quests.hypoID
WHERE Hypos.hypoID = ?1 AND session = ?2
GROUP BY session
UNION SELECT NULL, max(storage), storage FROM Hypos
... | [
"Try something like this:\nlhs = (Hypo\n .select(Quest.session, Hypo.storage, Hypo.storage - fn.COUNT(Quest.questID))\n .join(Quest)\n .where(\n (Hypo.hypoID == hypo_id) &\n (Quest.session == session))\n .group_by(Quest.session))\n\nrhs = (Hypo\n .select(Value(None)... | [
0
] | [] | [] | [
"peewee",
"python",
"sql",
"sqlite"
] | stackoverflow_0074344522_peewee_python_sql_sqlite.txt |
Q:
image_dataset_from_directory using a subset of sub-directories
I have downloaded the MINC dataset for material classification which consists of 23 cateogories. However, I am only interested in a subset of the categories (e.g. [wood, foliage, glass, hair])
Is it possible to get a subset of the data using tf.keras.p... | image_dataset_from_directory using a subset of sub-directories | I have downloaded the MINC dataset for material classification which consists of 23 cateogories. However, I am only interested in a subset of the categories (e.g. [wood, foliage, glass, hair])
Is it possible to get a subset of the data using tf.keras.preprocessing.image_dataset_from_directory?
I have tried tf.keras.pre... | [
"There are two ways of doing this the first way is to do this by generator, but that process is costly, there is another way of doing this called Using tf.data for finer control. You can check this out at this link\nhttps://www.tensorflow.org/tutorials/load_data/images\nBut, I will show you a brief demo that how yo... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074370328_keras_python_tensorflow.txt |
Q:
How to leave only three top rows for each index level in pandas DataFrame
I have a DataFrame which index has 2 levels: Name, SubName. What I would like to do is to truncate this DataFrame in such a way that for each Name-level index I will leave only top 3 rows. So for DataFrame
import pandas as pd
df = pd.DataFr... | How to leave only three top rows for each index level in pandas DataFrame | I have a DataFrame which index has 2 levels: Name, SubName. What I would like to do is to truncate this DataFrame in such a way that for each Name-level index I will leave only top 3 rows. So for DataFrame
import pandas as pd
df = pd.DataFrame()
df["Name"] = ["Name1", "Name1", "Name1", "Name1"]
df["SubName"] = ["SubNa... | [
"Use groupby.head with the level Name as grouper:\nout = df.groupby(level='Name').head(3)\n\noutput:\n Value\nName SubName \nName1 SubName1 1\n SubName2 2\n SubName3 3\n\nMore complex example:\nnames = ['Name1', 'Name2', 'Name3']\nsubnames = ['SubName1', 'SubName2', '... | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074376272_pandas_python.txt |
Q:
How to get the name of a button by clicking on it?
I am developing a telegram bot in the Python programming language using the telebot library (pyTelegramBotApi). At the moment when I'm making buttons, I decided to use InlineKeyboardMarkup. The following questions arise, how to get the name of this button by click... | How to get the name of a button by clicking on it? | I am developing a telegram bot in the Python programming language using the telebot library (pyTelegramBotApi). At the moment when I'm making buttons, I decided to use InlineKeyboardMarkup. The following questions arise, how to get the name of this button by clicking on the button. I need to get the index of an item in... | [
"There is no such thing as a button 'name'.\nThe only value that is returned by Telgram is the data attribute (called callback_data) that you've provided on the button. The text the user sees on the button is not given.\n\nThe data is available as call.data as you're already using in your code.\n\nFor a complete ex... | [
0,
0
] | [] | [] | [
"py_telegram_bot_api",
"python"
] | stackoverflow_0074363907_py_telegram_bot_api_python.txt |
Q:
Stringify a list to input it directly in hana_ml sql
I have established a DB connection using hana_ml library which has a function to query from the DB as
with ConnectionContext('address', port, 'user', 'password') as cc:
df = (cc.table('MY_TABLE', schema='MY_SCHEMA')
.filter('COL3 > 5')
... | Stringify a list to input it directly in hana_ml sql | I have established a DB connection using hana_ml library which has a function to query from the DB as
with ConnectionContext('address', port, 'user', 'password') as cc:
df = (cc.table('MY_TABLE', schema='MY_SCHEMA')
.filter('COL3 > 5')
.select('COL1', 'COL2'))
pandas_df = df.collect()
I... | [
"a = ['COL1','COL2']\n\nb = ','.join(\"'{0}'\".format(x) for x in a)\nprint(b)\n\nOutput:\n'COL1','COL2'\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"sql",
"string"
] | stackoverflow_0074376232_list_python_sql_string.txt |
Q:
Python - Determine Tic-Tac-Toe Winner
I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)
I have written the following function to do so:
This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bi... | Python - Determine Tic-Tac-Toe Winner | I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)
I have written the following function to do so:
This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardcoding.
def iswinner(board, decor... | [
"You can just make a set of each row, and check its length. If it contains only one element, then the game has been won.\ndef returnWinner(board):\n for row in board:\n if len(set(row)) == 1:\n return row[0]\n return -1\n\nThis will return \"O\" if there is a full line of \"O\", \"X\" if the... | [
11,
4,
2,
1,
1,
0,
0,
0
] | [
"There are a total of 3 states that a cell can have\n\n0 if it is not yet filled ( There is a possibility that the game gets over in 5 moves)\n1 if it is filled with 'X'\n-1 if it is filled with 'O'\n\nI will expand on @EfferLagan answer\ndef checkRows(board):\nfor row in board:\n if (len(set(row)) == 1) and (ro... | [
-1,
-2
] | [
"arrays",
"boolean",
"break",
"loops",
"python"
] | stackoverflow_0039922967_arrays_boolean_break_loops_python.txt |
Q:
Running kafka consumer with Django
I've setup a kafka server on AWS and I already have a Django project acting as the producer, using kafka-python.
I've also setup a second Django project to act as the consumer (kafka-python), but I'm trying to figure out a way to run the consumer automatically after the server ha... | Running kafka consumer with Django | I've setup a kafka server on AWS and I already have a Django project acting as the producer, using kafka-python.
I've also setup a second Django project to act as the consumer (kafka-python), but I'm trying to figure out a way to run the consumer automatically after the server has started without having to trigger the ... | [
"I did something like this on a Django project : I put the consumer launch into a daemon thread into a method and I call this method in the manage.py file.\nI'm not really sure about impacts of modify manage.py file, but it's work fine.\ndef run_consumers():\n thread = threading.Thread(name=my_consumer, target=m... | [
0
] | [] | [] | [
"apache_kafka",
"django",
"kafka_consumer_api",
"python"
] | stackoverflow_0073472324_apache_kafka_django_kafka_consumer_api_python.txt |
Q:
In Python, how do I write a loop to remove from character # n to a specific character (:) in parts of a list that match a condition?
I have a list like this:
test = ["Similar to Stxbp2: Syntaxin-binding protein 2 (Mus musculus)", "Protein of unknown function", "Similar to rab18b: Ras-related protein Rab-18-B (Dani... | In Python, how do I write a loop to remove from character # n to a specific character (:) in parts of a list that match a condition? | I have a list like this:
test = ["Similar to Stxbp2: Syntaxin-binding protein 2 (Mus musculus)", "Protein of unknown function", "Similar to rab18b: Ras-related protein Rab-18-B (Danio rerio)", "Protein of unknown function", "Protein of unknown function"]
This object is, in actuality, a lot longer than this, but just f... | [
"You can try using list comprehension by matching your condition using str.startswith and then use str.split to split on the :\n[x[11:].split(':', 1)[0] if x.startswith('Similar to') else 'Unknown' for x in test ]\n# -> ['Stxbp2', 'Unknown', 'rab18b', 'Unknown', 'Unknown']\n\n",
"Variation without regex if you do... | [
2,
2,
1
] | [] | [] | [
"list",
"python",
"replace"
] | stackoverflow_0074376174_list_python_replace.txt |
Q:
delete "sum of" from histogram px.df
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="day", y="total_bill", color='day', barmode='group')
fig.show()
well, i have a function like that
And it builds a histogram in plotly dash
but it makes with lable "sum of total_bill", but i need just "tot... | delete "sum of" from histogram px.df | import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="day", y="total_bill", color='day', barmode='group')
fig.show()
well, i have a function like that
And it builds a histogram in plotly dash
but it makes with lable "sum of total_bill", but i need just "total_bill", how to fix?
| [
"You can simply change the yaxis_title as follows:\nimport plotly.express as px\ndf = px.data.tips()\nfig = px.histogram(df, x=\"day\", y=\"total_bill\", category_orders=dict(day=[\"Thur\", \"Fri\", \"Sat\", \"Sun\"]))\nfig.update_layout( yaxis_title=\"total_bill\" )\nfig.show()\n\n\n"
] | [
1
] | [] | [] | [
"pandas",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074375394_pandas_plotly_plotly_dash_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.