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: How to get a normalized, grouped, ordered plot of counts How can I get in seaborn a chart of counts, per category, normalized, in a specified order? It seems like I could either do countplot like this: sns.countplot(data=df, y="category_1",hue='category_2', order = df['category_1'].value_counts().iloc[:10].in...
How to get a normalized, grouped, ordered plot of counts
How can I get in seaborn a chart of counts, per category, normalized, in a specified order? It seems like I could either do countplot like this: sns.countplot(data=df, y="category_1",hue='category_2', order = df['category_1'].value_counts().iloc[:10].index) Which gives me the counts, but countplot doesn't seem to...
[ "You can first groupby whatever you want to normalize.\nFor example,\nimport seaborn as sns\ndf = sns.load_dataset('mpg')\n\ndf_g = df \\\n .groupby('origin')['cylinders'] \\\n .value_counts(normalize=True) \\\n .rename('prop') \\\n .reset_index()\n\n\nthen you can use sns.barplot\nsns.barplot(data=df_g...
[ 0 ]
[]
[]
[ "bar_chart", "pandas", "python", "seaborn" ]
stackoverflow_0074183517_bar_chart_pandas_python_seaborn.txt
Q: IndexError: tuple index out of range when I try to create an executable from a python script using auto-py-to-exe I have been trying out an open-sourced personal AI assistant script. The script works fine but I want to create an executable so that I can gift the executable to one of my friends. However, when I try...
IndexError: tuple index out of range when I try to create an executable from a python script using auto-py-to-exe
I have been trying out an open-sourced personal AI assistant script. The script works fine but I want to create an executable so that I can gift the executable to one of my friends. However, when I try to create the executable using the auto-py-to-exe, it states the below error: Running auto-py-to-exe v2.10.1 Building ...
[ "This is a Python 3.10 issue.\nTo fix it:\nYou have to go to the folder \"Python310\\Lib\" and edit the file 'dis.py'.\nIn the 'dis.py' file you have to find this \"def _unpack_opargs\" and inside the else statement write a new line with this: \"extended_arg = 0\", then save the file.\nI did something like that:\ne...
[ 21, 10, 2, 2, 0 ]
[]
[]
[ "executable", "index_error", "pyinstaller", "python", "tuples" ]
stackoverflow_0069776492_executable_index_error_pyinstaller_python_tuples.txt
Q: How to loop through an API request for different parameters such as changing the month and header I have the following API request that I then clean and sort the data: Base_URL = "https://api.jao.eu/OWSMP/getauctions?" headers = { "AUTH_API_KEY": "06e690fb-697b-4ab2-9325-4268cbd14502" } params = { "h...
How to loop through an API request for different parameters such as changing the month and header
I have the following API request that I then clean and sort the data: Base_URL = "https://api.jao.eu/OWSMP/getauctions?" headers = { "AUTH_API_KEY": "06e690fb-697b-4ab2-9325-4268cbd14502" } params = { "horizon":"Daily", "corridor":"IF1-FR-GB", "fromdate":"2021-01-01" } data = "results" r = reque...
[ "Get all data:\nimport pandas as pd\nimport requests\nBase_URL = \"https://api.jao.eu/OWSMP/getauctions?\"\n\nheaders = {\n\"AUTH_API_KEY\": \"api_key\"\n}\n\nfinal_df=pd.DataFrame() #all data will store here.\n\n#create dates like 2022-01-01, 2022-08-01...\nyear=['2021','2022']\nmonth=list(range(1,13))\ndates=[]\n...
[ 2 ]
[]
[]
[ "json", "jupyter_notebook", "pandas", "python", "request" ]
stackoverflow_0074183111_json_jupyter_notebook_pandas_python_request.txt
Q: Removing elements from list of dictionaries based on condition Suppose I have a list of dictionaries lst = [{'match': 0, 'ref_title': ['dog2', 'title1'], 'matching_string': 'dog2', 'display_string': 'dog2'}, {'match': 0, 'ref_title': ['dog2', 'cat'], 'matching_string': 'dog2', 'display_string': 'dog2'...
Removing elements from list of dictionaries based on condition
Suppose I have a list of dictionaries lst = [{'match': 0, 'ref_title': ['dog2', 'title1'], 'matching_string': 'dog2', 'display_string': 'dog2'}, {'match': 0, 'ref_title': ['dog2', 'cat'], 'matching_string': 'dog2', 'display_string': 'dog2'}, {'match': 2, 'ref_title': ['dog2', 'dog'], 'matching_string'...
[ "newlst = [d for d in lst if d.get('match') in {1,2}]\n\nThis also handles the corner case (spurious data) where some of the dicts were somehow missing a 'match' key.\n", "lst = [{'match': 0,\n 'ref_title': ['dog2', 'title1'],\n 'matching_string': 'dog2',\n 'display_string': 'dog2'},\n {'match': 0,\n 'ref_tit...
[ 1, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074184528_dictionary_python.txt
Q: It doesn't return the index of everysingle letter? import re def capital_indexes(string): cap=[] for i in string: if i.isupper()==True: cap.append(string.find(i)) return cap print(capital_indexes("TEsT")) I want it to return the index of every single letter that is a ca...
It doesn't return the index of everysingle letter?
import re def capital_indexes(string): cap=[] for i in string: if i.isupper()==True: cap.append(string.find(i)) return cap print(capital_indexes("TEsT")) I want it to return the index of every single letter that is a capital letter.
[ "def capital_indexes(s):\n return [e for e,i in enumerate(s) if i.isupper()]\n\nprint(capital_indexes(\"TEsT\")) #[0, 1, 3]\n\n", "str.find returns the index of the first value found. You have 2 T s, but it will return 0 for each. The enumerate function gives you the index of the value iterated, use that inst...
[ 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074184093_python_python_3.x.txt
Q: Python datetime ValueError: year 0 is out of range I want to get the number of days since year 0, january 1st. When I use datetime(0, 1, 1).date() I get : ValueError: year 0 is out of range I want to find out the number of days passed since then. Code: from datetime import datetime date_1 = datetime(0, 1, 1).date...
Python datetime ValueError: year 0 is out of range
I want to get the number of days since year 0, january 1st. When I use datetime(0, 1, 1).date() I get : ValueError: year 0 is out of range I want to find out the number of days passed since then. Code: from datetime import datetime date_1 = datetime(0, 1, 1).date() date_2 = datetime.today().date() delta = None delta...
[ "You cannot use datetime for years <= 0.\nA solution would be to set the year to 1 and add 365 (or 366 if leap) days to the counter.\nfrom datetime import datetime\n\ndate_1 = datetime(1, 1, 1).date()\n\ndate_2 = datetime.today().date()\n\ndelta = None\ndelta = date_2 - date_1\nprint(\"Difference is\", delta.days +...
[ 0 ]
[]
[]
[ "date", "datetime", "python" ]
stackoverflow_0074184680_date_datetime_python.txt
Q: how can i exit for loop inside if statement i'm coding bulls and cows by python. here is my code. i want re-input if i get a not a number or over or under unit digit. for example if i input '1, a , 2', i need to go back to input line but other numbers but because of other numbers '1'and'2', it goes else line and ...
how can i exit for loop inside if statement
i'm coding bulls and cows by python. here is my code. i want re-input if i get a not a number or over or under unit digit. for example if i input '1, a , 2', i need to go back to input line but other numbers but because of other numbers '1'and'2', it goes else line and while statement will end.please help me.sorry abo...
[ "Something like this?\nwhile True:\n num=input('Input 3 numbers (ex: 1, 2, 3) : ').split(', ')\n\n if(len(num)==3):\n if num[0].isnumeric() and num[1].isnumeric() and num[2].isnumeric():\n break\n else:\n print('Input only numbers')\n else:\n print('Input 3 number...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074184568_python.txt
Q: How to edit help_text of a child in the parent class I made a mixin (same as the parent class) for my brand model, and I want to get the class name of the children and replace it with help_text in the parent class. Is there any solution? class TitleSlugMixin(models.Model): title = models.CharField( _('...
How to edit help_text of a child in the parent class
I made a mixin (same as the parent class) for my brand model, and I want to get the class name of the children and replace it with help_text in the parent class. Is there any solution? class TitleSlugMixin(models.Model): title = models.CharField( _('title'), max_length=255, help_text=_(f'{se...
[ "A lot of vars() later, it is possible:\nNote: I tested this on a similar inheritance setup, but my field was machine (No underscore) so you might have to add that underscore (See debugging __init__ & My commented line)\nModels.py\nclass TitleSlugMixin(models.Model):\n title = models.CharField(\n _('title...
[ 0 ]
[]
[]
[ "django", "oop", "python" ]
stackoverflow_0074181513_django_oop_python.txt
Q: Given a string, extract all the necessary information about the person In my homework, I need to extract the first name, last name, ID code, phone number, date of birth and address of a person from a given string using Regex. The order of the parameters always remains the same. Each parameter requires a separate p...
Given a string, extract all the necessary information about the person
In my homework, I need to extract the first name, last name, ID code, phone number, date of birth and address of a person from a given string using Regex. The order of the parameters always remains the same. Each parameter requires a separate pattern. Requirements are as follows: Both first and last names always begin...
[ "A single expression with some well-crafted capture groups will help you immensely:\nimport re\nstr1 = \"HeinoPlekk69712047623+3725688736412-09-2020Tartu mnt 183,Tallinn,16881,Eesti\"\npattern = r\"^(?P<first_name>[A-Z][a-z]+)(?P<last_name>[A-Z][a-z]+)(?P<id_code>\\d{11})(?P<phone>(?:\\+\\d{3})?\\s*\\d{7,8})(?P<dob...
[ 4 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0074184682_python_python_3.x_regex.txt
Q: Nested dictionary to nested tuple I know that it shouldn't be hard, however, I can't resolve my issue. I have a nested dictionary and I need to convert its values to the same structure tuple. dict1 = {'234':32,'345':7,'123':{'asd':{'pert': 600, 'sad':500}}} The result should be like: list1 = (32, 7, ((600, 500)))...
Nested dictionary to nested tuple
I know that it shouldn't be hard, however, I can't resolve my issue. I have a nested dictionary and I need to convert its values to the same structure tuple. dict1 = {'234':32,'345':7,'123':{'asd':{'pert': 600, 'sad':500}}} The result should be like: list1 = (32, 7, ((600, 500))) Do you have any suggestions how to do...
[ "Try:\ndict1 = {\"234\": 32, \"345\": 7, \"123\": {\"asd\": {\"pert\": 600, \"sad\": 500}}}\n\n\ndef get_values(o):\n out = []\n for k, v in o.items():\n if not isinstance(v, dict):\n out.append(v)\n else:\n out.append(get_values(v))\n return tuple(out)\n\n\nprint(get_va...
[ 1, 1 ]
[]
[]
[ "dictionary", "nested", "python", "tuples" ]
stackoverflow_0074184678_dictionary_nested_python_tuples.txt
Q: Restrict possible options of class attributes values How to limit possible options to be chosen when instantiating class objects? Let's say we have a class like below and we'd like to restrict value values only to be predefined as in the valueOptions list. My implementation attempt is as below. Is there more Pytho...
Restrict possible options of class attributes values
How to limit possible options to be chosen when instantiating class objects? Let's say we have a class like below and we'd like to restrict value values only to be predefined as in the valueOptions list. My implementation attempt is as below. Is there more Pythonic way to achieve the same result? class TestClass: v...
[ "Use Enum instead of str if you need a limited values\nThe core issue is that you (implicitly; your code isn't typed) define value as being a string type. But you don't need a string: you need a limited list of possible values. String is not the right variable type to code that.\nThe enum module allows you to defin...
[ 6 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074184600_python_python_3.x.txt
Q: How to convert Json format to Python format with appropriate types instead of values Can you please advice some library / any other tool or python code to convert Json format to Python format with appropriate types instead of values Given (JSON format): { "data": { "id": 8, "email"...
How to convert Json format to Python format with appropriate types instead of values
Can you please advice some library / any other tool or python code to convert Json format to Python format with appropriate types instead of values Given (JSON format): { "data": { "id": 8, "email": "ajent.j@mail.com", "first_name": "Agent", "last_name": "J", ...
[ "After fixing the mistakes in your JSON, this does what you asked. Note that this does not handle arbitrarily deep nesting; if you have nested objects, then first you have to decide whether you want to use \"dict\" or dive into them. If you do want to dive into them, then you'd need to make this recursive.\nimpo...
[ 0 ]
[ "I know it's not very convenient, but you could go through all of the classes you need converted using a for loop.\nimport json\n\nwith open('data.json') as f:\n data = json.load(f)\n for x in data:\n int(x[\"data\"][\"id\"])\n\n", "If you're using VSCode you can use the Paste JSON as Code extension....
[ -1, -1 ]
[ "json", "pytest", "python" ]
stackoverflow_0074184676_json_pytest_python.txt
Q: Python, SqlAlchemy. Or_ expected 2 arguments, got 3 I have this problem with my code. When Iinsert three or more params in the body request, I get this Error "POST Error: or_ expected 2 arguments, got 3." I can only pass one or two parameters in the body, in this case it works fine. But I don't understand where is...
Python, SqlAlchemy. Or_ expected 2 arguments, got 3
I have this problem with my code. When Iinsert three or more params in the body request, I get this Error "POST Error: or_ expected 2 arguments, got 3." I can only pass one or two parameters in the body, in this case it works fine. But I don't understand where is the mistake. Can someone help me? def read_uptime(logid,...
[ "import or_ from sqlalchemy instead of operators:\nfrom sqlalchemy import or_\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0073530821_python_sqlalchemy.txt
Q: Append not working after merging a dictionnary into a other nested dictonnary input first_dict = {"block_1": {"col_A": [], "col_B": []}, "block_2": {"col_D": [], "col_E": []}} second_dict = {"col_Z": []} initial manipulation...
Append not working after merging a dictionnary into a other nested dictonnary
input first_dict = {"block_1": {"col_A": [], "col_B": []}, "block_2": {"col_D": [], "col_E": []}} second_dict = {"col_Z": []} initial manipulations I added the second_dict to all blocks of first_dict (2nd level) # achieved with f...
[ "As you suspected, the issue you're having is related to Python not implicitly making copies of your dictionary when you assign it. Usually one would use dict.copy() or some other way of shallow copying the dictionary itself, however that wouldn't really work in this case.\nThis is because shallow copying only copi...
[ 2, 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0074184713_dictionary_nested_python.txt
Q: Additional Window After Only Creating 1 Window - Tkinter Main I have the code like the following. # Modules from tkinter import * from tkinter import ttk # Functions def information(): pass def main_page(): pass # Main Window style = ttk.Style() style.configure("TButton", background="white", foreground="...
Additional Window After Only Creating 1 Window - Tkinter
Main I have the code like the following. # Modules from tkinter import * from tkinter import ttk # Functions def information(): pass def main_page(): pass # Main Window style = ttk.Style() style.configure("TButton", background="white", foreground="black", padding = 15, font=("Arial", 10)) root = Tk() root.tit...
[ "Try calling root.mainloop() at the end of your file instead of just mainloop() since root is what is instantiating Tk().\nRealistically, this should also be wrapped in a guard clause like this\nif __name__ == '__main__':\n root.mainloop()\n\nbut that's a separate issue.\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074169009_python_tkinter.txt
Q: python enforce type hints How do I use enforce_typing with typing.Generic? basic usage of enforce_typing looks like this and works as expected, from enforce_typing import enforce_types @enforce_types def bar(val : float) -> None: print(val) bar(3.14) # PASS bar('3.14') # TypeError: Expected type '<class ...
python enforce type hints
How do I use enforce_typing with typing.Generic? basic usage of enforce_typing looks like this and works as expected, from enforce_typing import enforce_types @enforce_types def bar(val : float) -> None: print(val) bar(3.14) # PASS bar('3.14') # TypeError: Expected type '<class 'float'>' for attribute 'val' b...
[ "Your enforce_typing library (source) seems outdated.\nSince Python 3.5, Python supports the typing library, that allows for type hints.\nUsing a type checker, such as mypy, you can check if typing hints are provided in all times (using the option --strict).\nI recommend using Python version 3.5 or later, use the t...
[ 0 ]
[]
[]
[ "generics", "python" ]
stackoverflow_0074184800_generics_python.txt
Q: How would I make webdriver selenium open another tab, and do something? How would I make webdriver selenium open another tab, and copy something from that another tab, close it and paste it in the first tab? How would I do this? driver = webdriver.Chrome() wait = WebDriverWait(driver, 30) A: Here's an example th...
How would I make webdriver selenium open another tab, and do something?
How would I make webdriver selenium open another tab, and copy something from that another tab, close it and paste it in the first tab? How would I do this? driver = webdriver.Chrome() wait = WebDriverWait(driver, 30)
[ "Here's an example that opens a page, opens a new tab, copies something, closes the tab, and pastes the text into an input field on the new tab:\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://seleniumbase.io/demo_page\")\ndriver.switch_to.new_window(\"tab\")\ndriver.get(\"data:...
[ 1 ]
[]
[]
[ "python", "selenium", "tabs", "webdriver" ]
stackoverflow_0074184296_python_selenium_tabs_webdriver.txt
Q: knapsack problem using brute force method in python I am applying the following code to obtain the max CBU. Can I also get the list of selected items in a knapsack? Here is my code def knapsack(CBU, weight, Capacity): return knapsacksolution(CBU, weight, Capacity, 0) def knapsacksolution(CBU, weight, Capacity,...
knapsack problem using brute force method in python
I am applying the following code to obtain the max CBU. Can I also get the list of selected items in a knapsack? Here is my code def knapsack(CBU, weight, Capacity): return knapsacksolution(CBU, weight, Capacity, 0) def knapsacksolution(CBU, weight, Capacity, currentIndex): if Capacity <= 0 or currentIndex...
[ "Just recently I learned the itertools.combinations method (from reading solutions on SO). It seems like a simple tool for generating all of the various configurations of the knapsack.\nIn the code below, we use combinations to find all of the combinations of the knapsack configuration, throwing out all of the com...
[ 0, 0 ]
[]
[]
[ "brute_force", "dynamic_programming", "knapsack_problem", "python" ]
stackoverflow_0074174950_brute_force_dynamic_programming_knapsack_problem_python.txt
Q: NameError: name 'rank' is not defined even though i have mentioned it in global The code below is a simplified version of a bigger code. The main action i want to perform is to use and change rank and progress inside the inc_progress(self) function. class User: rank=-8 progress=0 def inc_progress(self)...
NameError: name 'rank' is not defined even though i have mentioned it in global
The code below is a simplified version of a bigger code. The main action i want to perform is to use and change rank and progress inside the inc_progress(self) function. class User: rank=-8 progress=0 def inc_progress(self): global rank, progress rank+=1 print(rank,progress) u=Use...
[ "By defining rank and progress outside of __init__, you've defined them as class variables, meaning that they belong to the class and will be available to all instances of that class. https://pynative.com/python-class-variables/\nHere's a modified version of your code that does what you're expecting (and probably s...
[ 0 ]
[]
[]
[ "class", "global", "nameerror", "python" ]
stackoverflow_0074184827_class_global_nameerror_python.txt
Q: Command for clicking on the items of a Tkinter Treeview widget? I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the Treeview objects to change when an item (i.e. a directory) is clicked twice. If Treeview items were buttons, I'd just be able to set comma...
Command for clicking on the items of a Tkinter Treeview widget?
I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the Treeview objects to change when an item (i.e. a directory) is clicked twice. If Treeview items were buttons, I'd just be able to set command to the appropriate function. But I'm having trouble finding a way ...
[ "If you want something to happen when the user double-clicks, add a binding to \"<Double-1>\". Since a single click sets the selection, in your callback you can query the widget to find out what is selected. For example:\nimport tkinter as tk\nfrom tkinter import ttk\n\nclass App:\n def __init__(self):\n ...
[ 44, 25, 4, 0 ]
[]
[]
[ "python", "tkinter", "treeview", "user_interface" ]
stackoverflow_0003794268_python_tkinter_treeview_user_interface.txt
Q: How to plot loss when using HugginFace's Trainer? While finetuning a model using HF's trainer. training_args = TrainingArguments(output_dir=data_dir + "test_trainer") metric = load_metric("accuracy") def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) r...
How to plot loss when using HugginFace's Trainer?
While finetuning a model using HF's trainer. training_args = TrainingArguments(output_dir=data_dir + "test_trainer") metric = load_metric("accuracy") def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) return metric.compute(predictions=predictions, reference...
[ "It is possible to get a list of losses. You can access the history of logs after training is complete with: trainer.state.log_history\n" ]
[ 1 ]
[]
[]
[ "deep_learning", "huggingface_transformers", "python", "pytorch" ]
stackoverflow_0072350835_deep_learning_huggingface_transformers_python_pytorch.txt
Q: Print an empty square using an argument in Python I want to draw the outer lines of a square. I am able to create a filled in square, using the shown code, however I am not sure how to make it empty on the inside. This is what I have: def square(size): for x in range(0, size): print("* " * size) squar...
Print an empty square using an argument in Python
I want to draw the outer lines of a square. I am able to create a filled in square, using the shown code, however I am not sure how to make it empty on the inside. This is what I have: def square(size): for x in range(0, size): print("* " * size) square(5) What should I change?
[ "If numpy is an option, here is an approach with it:\nimport numpy as np\ndef square(size):\n square = np.ones((size, size), dtype='object')\n square[1:-1, 1:-1] = ' '\n square[square==1] = '*'\n print('\\n'.join([' '.join([str(elem) for elem in row]) for row in square]))\n\nsquare(15)\n\nOutput:\n* * *...
[ 1, 0 ]
[]
[]
[ "python", "square" ]
stackoverflow_0074184852_python_square.txt
Q: Keep asking for numbers and find the average when user enters -1 number = 0 number_list = [] while number != -1: number = int(input('Enter a number')) number_list.append(number) else: print(sum(number_list)/ len(number_list)) EDIT: Have found a simpler way to get the average of the list but if for example ...
Keep asking for numbers and find the average when user enters -1
number = 0 number_list = [] while number != -1: number = int(input('Enter a number')) number_list.append(number) else: print(sum(number_list)/ len(number_list)) EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. U...
[ "Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.\nnumber_list = []\n\ndef average(mylist):\n return sum(mylist)/len(mylist)\n\nwhile True:\n number = int...
[ 1, 0, 0 ]
[]
[]
[ "input", "python", "while_loop" ]
stackoverflow_0074184660_input_python_while_loop.txt
Q: missing 1 required positional argument (IP checker) This is an IP address problem where I need to implement a function is_valid_IP that takes an arbitrary string and determines if it represents a valid IPv4 or IPv6 address. IPv4_STRING = "127.0.0.1" IPv4_INVALID_STRING = "300.0.0.1" IPv6_STRING = "2001:0db8:85a3:0...
missing 1 required positional argument (IP checker)
This is an IP address problem where I need to implement a function is_valid_IP that takes an arbitrary string and determines if it represents a valid IPv4 or IPv6 address. IPv4_STRING = "127.0.0.1" IPv4_INVALID_STRING = "300.0.0.1" IPv6_STRING = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" IPv6_INVALID_STRING = "2001:0db8...
[ "You are missing the arguments here:\ndef is_valid_IP(ip: str):\n#added ip\n if( is_valid_IPv4(ip) or is_valid_IPv6(ip) == True):\n print(\"Valid IP Address\")\n else:\n print(\"Invalid IP Address\")\n\nAlso since the functions already return True or False you can get rid of the == True\ndef is_valid_IP...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074185036_python.txt
Q: XGBoost multiple eval_metric in Sagemaker I'm trying to add multiple evaluation metrics to an XGBoost training job using Sagemaker, documentation says it is possible (https://github.com/dmlc/xgboost/blob/master/doc/parameter.rst#learning-task-parameters): User can add multiple evaluation metrics. Python users: re...
XGBoost multiple eval_metric in Sagemaker
I'm trying to add multiple evaluation metrics to an XGBoost training job using Sagemaker, documentation says it is possible (https://github.com/dmlc/xgboost/blob/master/doc/parameter.rst#learning-task-parameters): User can add multiple evaluation metrics. Python users: remember to pass the metrics in as list of parame...
[ "This might be the solution (untested, found here)\nparam['eval_metric'] = ['auc', 'ams@0']\n\n# alternatively:\n# plst = param.items()\n# plst += [('eval_metric', 'ams@0')]\n\nI guess that if you want more than two, you would go for the list of pairs\nplst = param.items()\nplst += [('eval_metric', 'ams@0'), ('eval...
[ 1, 0, 0 ]
[]
[]
[ "amazon_sagemaker", "python", "xgboost" ]
stackoverflow_0073980007_amazon_sagemaker_python_xgboost.txt
Q: Why is this sample of input in oop not returning the expected value? class Questionare: def ask_age(self): try: age = int(input('Type your age after the arrow -> ')) self.age = age print(['inside'], self.age) return self.age except ValueError: ...
Why is this sample of input in oop not returning the expected value?
class Questionare: def ask_age(self): try: age = int(input('Type your age after the arrow -> ')) self.age = age print(['inside'], self.age) return self.age except ValueError: print('Only use numbers to inform your age!') self.as...
[ "You need to return the value from the recursive call when a ValueError happens:\nclass Questionare:\n def ask_age(self):\n try:\n age = int(input('Type your age after the arrow -> '))\n self.age = age\n print(['inside'], self.age)\n return self.age\n exc...
[ 2 ]
[]
[]
[ "input", "oop", "python", "python_3.x", "return" ]
stackoverflow_0074185056_input_oop_python_python_3.x_return.txt
Q: Create a function, that is the derivative of a function I have in my code a function, let's say: def test_func(x): return(3*x**2) I want my code to calculate the derivative der_test_func of test_func, so that der_test_func is a function, too. Means, I should be able to do >>> print(der_test_func(5)) >>> 30 O...
Create a function, that is the derivative of a function
I have in my code a function, let's say: def test_func(x): return(3*x**2) I want my code to calculate the derivative der_test_func of test_func, so that der_test_func is a function, too. Means, I should be able to do >>> print(der_test_func(5)) >>> 30 Or I should be able to put it inside another function so that ...
[ "If you pass a SymPy Symbol into your function then it will be converted to a symbolic expression. You can then differentiate that and make a function to call it:\nIn [11]: def test_func(x):\n ...: return 3*x**2\n ...: \n\nIn [12]: x = sympy.symbols('x')\n\nIn [13]: f = test_func(x)\n\nIn [14]: f\nOut[14]...
[ 3 ]
[]
[]
[ "calculus", "derivative", "python", "sympy" ]
stackoverflow_0074184941_calculus_derivative_python_sympy.txt
Q: converts signed decimal numbers to signed binary and vice versa Can't Write Decimal To Binary and vice versa converter that works with the positive and negative numbers. This Decimal To Binary Converter works fine # decimal to binary def to2sCompStr(num): bitWidth = 8 num &= (2 << bitWidth-1)-1 forma...
converts signed decimal numbers to signed binary and vice versa
Can't Write Decimal To Binary and vice versa converter that works with the positive and negative numbers. This Decimal To Binary Converter works fine # decimal to binary def to2sCompStr(num): bitWidth = 8 num &= (2 << bitWidth-1)-1 formatStr = '{:0'+str(bitWidth)+'b}' ret = formatStr.format(int(num))...
[ "The call to int function with the base argument set to 2 in order to convert binary strings does not recognize input in two's-complement notation. It cannot assume that the leftmost \"bit\" (actually a character '0' or '1') of the input string is a sign bit. It does, however, recognize a leading '-' character.\nTh...
[ 0 ]
[]
[]
[ "number_systems", "python" ]
stackoverflow_0074181325_number_systems_python.txt
Q: viz_utils.visualize_boxes_and_labels_on_image_array get category i am a very practical civil engineer (very poor programmer). I want to detect objects on construction sites. Now i follow a tutorial and i get a picture with a bounding box with the detected object. My question here is: How can i get a string with th...
viz_utils.visualize_boxes_and_labels_on_image_array get category
i am a very practical civil engineer (very poor programmer). I want to detect objects on construction sites. Now i follow a tutorial and i get a picture with a bounding box with the detected object. My question here is: How can i get a string with the category name, index or id? with this code: input_tensor = tf.conve...
[ "I've got the same code, print(category_index[detections['detection_classes'][0]+label_id_offset][\"name\"]) worked perfectly\n", "You should initialize category_index variable as the following code:\nPATH_TO_LABELS = './models/research/object_detection/data/mscoco_label_map.pbtxt'\ncategory_index = label_map_uti...
[ 1, 0 ]
[]
[]
[ "object_detection", "opencv", "python" ]
stackoverflow_0068566244_object_detection_opencv_python.txt
Q: scipy minimize COBYLA callback not working I am using scipy.optimize's minimizefunction, and I would like to terminate the search as soon as the function value is below some threshold. I have tried using a callback that returns true when the above mentioned condition is met, but this in my code the search just con...
scipy minimize COBYLA callback not working
I am using scipy.optimize's minimizefunction, and I would like to terminate the search as soon as the function value is below some threshold. I have tried using a callback that returns true when the above mentioned condition is met, but this in my code the search just continues. I also have another "fundamental" issue ...
[ "I guess scipy.optimize.minimize's documentation is not 100% clear in regard to the callbacks. AFAIK, only the 'trust-constr' method gets terminated by the callback once the callback returns True. For all the remaining methods the callback can only be used for logging purposes.\nRegarding the second part of your qu...
[ 0 ]
[]
[]
[ "python", "scipy_optimize" ]
stackoverflow_0074182547_python_scipy_optimize.txt
Q: Can't find the first element of a dict I want to get the first element of a dict, "names(1)" doesn't work. names = {"John":20, "Marc":22, "Dwayne":23} print(names(1)) A: First use iter to get an iterator of keys out of the dict (this is based on insertion order as of python 3.6+). Then use next() to get the firs...
Can't find the first element of a dict
I want to get the first element of a dict, "names(1)" doesn't work. names = {"John":20, "Marc":22, "Dwayne":23} print(names(1))
[ "First use iter to get an iterator of keys out of the dict (this is based on insertion order as of python 3.6+). Then use next() to get the first item (first key) from that iterator:\nnames = {\"John\": 20, \"Marc\": 22, \"Dwayne\": 23}\nprint(next(iter(names)))\n\nResult:\nJohn # first according to insertion orde...
[ 5, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074185196_dictionary_python.txt
Q: Change datatype of a column that strictly only holds year in the format yyyy df.assign(Year=pd.to_datetime(df.Year, format='%Y')).set_index('Year') Consider the df['Year'] has n rows with data listed in YYYY format. How can I change this to date-time format without adding month and day, the above code converts YY...
Change datatype of a column that strictly only holds year in the format yyyy
df.assign(Year=pd.to_datetime(df.Year, format='%Y')).set_index('Year') Consider the df['Year'] has n rows with data listed in YYYY format. How can I change this to date-time format without adding month and day, the above code converts YYYY to 2015-01-01.
[ "extract the year using dt\n# Year with capital Y is column in DF\n# year with small letter y is a calculated year and is index\n\ndf=df.assign(year=pd.to_datetime(df['Year'],format='%Y').dt.year).set_index('year')\n\n Year height\nyear \n2014 2014 175\n2014 2014 180\n2014 2014 16...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074184786_pandas_python.txt
Q: Download excel file from NHL site in Python I want to download excel file from NHL.com. If you visit this link you can see the excel file, which can be downloaded. But when I try to scrap this website with BeautifulSoup, there is no link for this file. How can I find it and download?) A: The export button execut...
Download excel file from NHL site in Python
I want to download excel file from NHL.com. If you visit this link you can see the excel file, which can be downloaded. But when I try to scrap this website with BeautifulSoup, there is no link for this file. How can I find it and download?)
[ "The export button executes JavaScript function that reads the datatable and creates Excel file on-the-fly. beautifulsoup cannot execute JavaScript.\nBut you can use their Ajax api to download the data in Json format, parse it and save it to CSV for example:\nimport requests\nimport pandas as pd\n\napi_url = \"http...
[ 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074185206_beautifulsoup_python.txt
Q: Code not working when copying and pasting into jupyter notebook def get_first_name(): first_name = input("Enter your first name: ") print("Your first name is: ", first_name)      get_first_name() When copying and pasting this into jupyter notebook, I get the following error - SyntaxError: invalid non-...
Code not working when copying and pasting into jupyter notebook
def get_first_name(): first_name = input("Enter your first name: ") print("Your first name is: ", first_name)      get_first_name() When copying and pasting this into jupyter notebook, I get the following error - SyntaxError: invalid non-printable character U+00A0
[ "The problem with your code is that when you define a function you need to use the return statement in order to actually store the name in the variable and then, finally, be able to display it.\nSo I would change your code in the following way:\n\nCut the print function and replace it with a return function.\nPaste...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074175857_jupyter_notebook_python.txt
Q: python match : confusion about match testing I know there are other ways to do this, but I am want to use match here. In this snip, the break piece matches for all integers > 0, but I want it to match only n' I'm using the cast because it wasn't working without it. Not working with it either but... #times is a sim...
python match : confusion about match testing
I know there are other ways to do this, but I am want to use match here. In this snip, the break piece matches for all integers > 0, but I want it to match only n' I'm using the cast because it wasn't working without it. Not working with it either but... #times is a simple list of python datetimes n=len(times) for i,t...
[ "Thank you all for comments, but I'm no closer to understanding.\nBut after Pranav Hosangadi solution in Python 3.10 match/case with constants I managed to make this work.\nfrom types import SimpleNamespace\ncount = SimpleNamespace()\ncount.n = len(times)-1\n\nfor i,time in enumerate(times) :\n match i:\n ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074182057_python.txt
Q: Parse complex string structure into JSON I'm receiving a string structure from another process that I need to parse. I'm trying to parse a string structure into JSON. This structure is a non Json-compliant string: no quotes, no semicolums, no [] ... I1024 14:35:56.638165 623090 receive_app.cc:185] [ObjectDetectio...
Parse complex string structure into JSON
I'm receiving a string structure from another process that I need to parse. I'm trying to parse a string structure into JSON. This structure is a non Json-compliant string: no quotes, no semicolums, no [] ... I1024 14:35:56.638165 623090 receive_app.cc:185] [ObjectDetectionPredictionResult] { current_time { ...
[ "something like this comes to mind, does it suits you?\n# I assume that `payload` is str class or can be turned into str class \npayload = \"\"\"I1024 14:35:56.638165 623090 receive_app.cc:185] [ObjectDetectionPredictionResult] {\n current_time {\n seconds: 1666622156\n nanos: 170191872\n }\n identif...
[ 0 ]
[]
[]
[ "python", "text_parsing" ]
stackoverflow_0074183149_python_text_parsing.txt
Q: How do I append an item to the list when the item is a parameter of a class and is found in another variable? Click here to see my code I keep getting the error 'fellowship' is not defined. Why is this? A: The variable fellowship is not defined when you try to create the hobbit fiction. Reverse the order of the ...
How do I append an item to the list when the item is a parameter of a class and is found in another variable?
Click here to see my code I keep getting the error 'fellowship' is not defined. Why is this?
[ "The variable fellowship is not defined when you try to create the hobbit fiction. Reverse the order of the books in cell 9.\nAlso dont use variable names like next which are Python keywords.\nAnd your if-statement is not correct. If you want to check if sequel is of type Fiction use type or isinstance()\n" ]
[ 1 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0074185301_class_list_python.txt
Q: How to append to a specific line in textfile I have to make a program where someone has to approve or disapprove reviews from a text file and add if it is approved or not. The text file is structured like this: Dave;Good customerservice Suzan;Bad customerservice ... Now when I use the function all the approvals/d...
How to append to a specific line in textfile
I have to make a program where someone has to approve or disapprove reviews from a text file and add if it is approved or not. The text file is structured like this: Dave;Good customerservice Suzan;Bad customerservice ... Now when I use the function all the approvals/disapprovals get appended to the last line, when I ...
[ "append method always append's to the end of the file. instead, you can re-write the entire data after modification. it isn't just shorter code, but its way more performant as each opening and closing the storage I/O is very time-consuming compared to ordinary operations.\ndata = open(\"data.txt\", \"r\").read().sp...
[ 0 ]
[]
[]
[ "append", "function", "python", "text_files" ]
stackoverflow_0074185225_append_function_python_text_files.txt
Q: replicate values in a column I have the bellow df and I'm trying to replicate the single value present in the column(Per_Extract) in the rest of the column df IN Per_Extract 0 IN7395593 NaN 1 IN7444113 FROM : 2022-08-01 TO : 2022-10-20 2 IN7444613 FROM ...
replicate values in a column
I have the bellow df and I'm trying to replicate the single value present in the column(Per_Extract) in the rest of the column df IN Per_Extract 0 IN7395593 NaN 1 IN7444113 FROM : 2022-08-01 TO : 2022-10-20 2 IN7444613 FROM : 2022-08-01 TO : 2022-10-20 3 ...
[ "#replace NaN text with np.nan\n# ffill and bfill null values\n# Strip Per_extract with whitespaces, if present, they fail replace\n\ndf['Per_Extract']=df['Per_Extract'].str.strip().replace('NaN', np.nan).ffill().bfill()\ndf\n\nIN Per_Extract\n0 0 IN7395593 FROM : 2022-08-01 TO : 2022-10-20\n1 1 IN744411...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074185323_pandas_python.txt
Q: PySpark: Create New Column And Give similar value for each row with similar values of Other Columns Imagine having the following spark dataframe +---+----+----+ | Id|A_rk|B_rk| +---+----+----+ | a| 5| 4| | b| 7| 7| | c| 5| 4| | d| 1| 0| +---+----+----+ I want to create a column called Pair tha...
PySpark: Create New Column And Give similar value for each row with similar values of Other Columns
Imagine having the following spark dataframe +---+----+----+ | Id|A_rk|B_rk| +---+----+----+ | a| 5| 4| | b| 7| 7| | c| 5| 4| | d| 1| 0| +---+----+----+ I want to create a column called Pair that takes the value of B_rk if two rows have the same values for A_rk and B_rk and the value of 0 if there ...
[ "1.4 million rows is still fine with pandas.\ndata = [(randint(0, 1000000), randint(0, 100000)) for _ in range(1400000)]\ndf = pd.DataFrame(data, columns=['A_rk', 'B_rk'])\n\ndf['cnt'] = df.groupby(['A_rk', 'B_rk']).transform('size')\ndf.loc[df.cnt > 1, 'Pair'] = df.B_rk. # or df.cnt == 2 if you only count pair (2 ...
[ 1 ]
[]
[]
[ "pandas", "pyspark", "python" ]
stackoverflow_0074183846_pandas_pyspark_python.txt
Q: How can I redefine a subfunction of a JAX-jitted function? I have a function foo which is jitted with JAX. foo calls bar. from jax import jit def bar(x): return x ** 2 @jit def foo(x): return 1 + bar(x) print(f'foo(4) = {foo(4)}') Prints foo(4) = 17 as expected. If I redefine bar at runtime, what is the b...
How can I redefine a subfunction of a JAX-jitted function?
I have a function foo which is jitted with JAX. foo calls bar. from jax import jit def bar(x): return x ** 2 @jit def foo(x): return 1 + bar(x) print(f'foo(4) = {foo(4)}') Prints foo(4) = 17 as expected. If I redefine bar at runtime, what is the best way to re-jit foo? Bonus: Is it possible to just tell jax b...
[ "The reason this is not working as expected is because the function is not pure: that is, its output depends not just on the inputs, but also on some global state. JAX transforms like JIT only work correctly for pure functions; see JAX Sharp Bits: Pure Functions for more discussion of this.\nThe best way to approac...
[ 2 ]
[]
[]
[ "jax", "jit", "python" ]
stackoverflow_0074185207_jax_jit_python.txt
Q: Keeping trademark symbol in a dataframe column output I've been trying to use Python and Pandas to take a csv as input, clean the dataset, and assign the output to a new csv file. One of the columns in the original csv has trademark symbols. When I export the new csv, the columns sometimes have ™ instead of just ...
Keeping trademark symbol in a dataframe column output
I've been trying to use Python and Pandas to take a csv as input, clean the dataset, and assign the output to a new csv file. One of the columns in the original csv has trademark symbols. When I export the new csv, the columns sometimes have ™ instead of just the trademark symbol, or sometimes they're turned into â„...
[ "Just fixed this same problem. Answer and explanation can be found here\nQuick answer is to use encoding \"utf-8-sig\"\n" ]
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0069037572_csv_pandas_python.txt
Q: Upload a file to a folder in MS teams channel I have a simple .txt file and I would like to upload it to a folder created inside a MS teams channel using the pymsteams library or any other. What are the steps I should follow to achieve this? A: Use the Microsoft Graph API to achieve this. Microsoft Teams is ult...
Upload a file to a folder in MS teams channel
I have a simple .txt file and I would like to upload it to a folder created inside a MS teams channel using the pymsteams library or any other. What are the steps I should follow to achieve this?
[ "Use the Microsoft Graph API to achieve this. Microsoft Teams is ultimately using SharePoint behind the scenes for the Files section within Teams Channels.\nHere's a lot of reading for you on the topic: https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http\nUnderstand this,...
[ 0 ]
[]
[]
[ "microsoft_teams", "python" ]
stackoverflow_0074185410_microsoft_teams_python.txt
Q: Numpy find position in 3d array based on condition So I have a numpy array representing an opencv image and I want to get all positions where all values of a 1d array in the 3d array fulfill a condition like this: array1 = [[[186 123 231], [184 126 76]], [[224 187 97], [187 145 243]]] array2 = [150, 180, 250] the...
Numpy find position in 3d array based on condition
So I have a numpy array representing an opencv image and I want to get all positions where all values of a 1d array in the 3d array fulfill a condition like this: array1 = [[[186 123 231], [184 126 76]], [[224 187 97], [187 145 243]]] array2 = [150, 180, 250] the condition should be that the first element of array1 sh...
[ "\nnumpy solution. Create a mask and use np.where\n\nimport numpy as np\n\narray1 = np.array([[[186, 123, 231], [184, 126, 76]], [[224, 187, 97], [187, 145, 243]]])\narray2 = np.array([150, 180, 250])\n\nmask = (array1[:, :, 0] > array2[0]) & (array1[:, :, 1] < array2[1]) & (array1[:, :, 2] < array2[2])\n\nprint(ma...
[ 1 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0074184440_numpy_opencv_python.txt
Q: Python ValueError: too many values to unpack in class So when I try to run some tests for this code, it run into 'ValurError: too many values to unpack (expected 3)' Can someone look at it and try to fix this? Appreciate for your help. class BookDict: def __init__(self, filename): self.my_dict = {} ...
Python ValueError: too many values to unpack in class
So when I try to run some tests for this code, it run into 'ValurError: too many values to unpack (expected 3)' Can someone look at it and try to fix this? Appreciate for your help. class BookDict: def __init__(self, filename): self.my_dict = {} with open(filename) as f: for line in f: ...
[ "As Deepak has already pointed out, your error probably occurs because line.strip().split(\",\") does not return a list of three elements that you can unpack correctly.\n# working example\nline = \"a,b,c\"\n# line.strip().split(\",\") == ['a', 'b', 'c']\ntitle, author, ratings = line.strip().split(\",\")\n\nIf line...
[ 0 ]
[]
[]
[ "python", "valueerror" ]
stackoverflow_0074185242_python_valueerror.txt
Q: Jupyter Notebook not executing cells/code For some reason today my Jupyter Notebook has decided it doesn't want to execute the code in cells. However this isn't consistent. I'll restart the kernal, it will work for a while, but then when it runs into an error it then won't execute any code in any other cells after...
Jupyter Notebook not executing cells/code
For some reason today my Jupyter Notebook has decided it doesn't want to execute the code in cells. However this isn't consistent. I'll restart the kernal, it will work for a while, but then when it runs into an error it then won't execute any code in any other cells after that without a kernal restart. I've seen a pre...
[ "What kind of errors do you mean by \"when it runs into an error it then won't execute any code in any other cells after that without a kernal restart\"?\nI know that if you have In [*] instead of the run number of the cell for a long time probably you have an infinite loop in this cell or an open input (an input t...
[ 0, 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0063395039_jupyter_notebook_python.txt
Q: Python pandas to_csv causes OSError: [Errno 22] Invalid argument My code is the following: import pandas as pd import numpy as np df = pd.read_csv("path/to/my/infile.csv") df = df.sort_values(['distance', 'time']) df.to_csv("path/to/my/outfile.csv") this code reads from infile.csv which is a 3GB csv file succes...
Python pandas to_csv causes OSError: [Errno 22] Invalid argument
My code is the following: import pandas as pd import numpy as np df = pd.read_csv("path/to/my/infile.csv") df = df.sort_values(['distance', 'time']) df.to_csv("path/to/my/outfile.csv") this code reads from infile.csv which is a 3GB csv file successfully, sorts it and fails when trying to write to outfile.csv with th...
[ "After exploring a lot of options, including the pandas library update to the latest version (1.2.4 as of today), changing the engine to \"python\" or \"c\", debugging, etc. I finally discovered what the issue was:\nI had my CSV files stored in a folder that was constantly being synchronized in real-time with OneDr...
[ 14, 12, 3, 1, 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0054811910_csv_pandas_python.txt
Q: Create a loop to count 0-6 for 100 time Im trying to make a loop to fill a list with values ranging from 0 to 6 for 100 times. i tired it like this but i seems like it it multiply it self 100*6 ls = [] x = 0 i = 0 y = 0 while x != 10: for i in range (1,7): ls.append(i) x +=1 print(ls) Does ...
Create a loop to count 0-6 for 100 time
Im trying to make a loop to fill a list with values ranging from 0 to 6 for 100 times. i tired it like this but i seems like it it multiply it self 100*6 ls = [] x = 0 i = 0 y = 0 while x != 10: for i in range (1,7): ls.append(i) x +=1 print(ls) Does anybody knows any solution to this. Thanks in...
[ "You don't need a loop:\nN = 6\nlst = list(range(N+1))*100\n\nWith numpy/pandas:\nimport numpy as np\nimport pandas as pd\n\nN = 6\n\na = np.tile(np.arange(N+1), 100)\n\ns = pd.Series(a)\n\n", "You can use range.\n>>> list(range(7))*100\n\nOr you can use numpy.tile.\n>>> import numpy as np\n>>> np.tile(np.arange(...
[ 4, 2, 0, 0, 0, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074185475_numpy_pandas_python.txt
Q: TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection I have the following schema: class Query(graphene.ObjectType): all_questionnaires = DjangoFilterConnectionField(QuestionnaireType) I got the error when running the tests TypeError: Query fields cannot be resolved...
TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection
I have the following schema: class Query(graphene.ObjectType): all_questionnaires = DjangoFilterConnectionField(QuestionnaireType) I got the error when running the tests TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection What can be?
[ "You probably need to define a Connection, because for graphene>=2 it is not done implicitly.\nclass QuestionnaireConnection(graphene.relay.Connection):\n class Meta:\n node = QuestionnaireType\n\n" ]
[ 1 ]
[]
[]
[ "django", "graphene_django", "graphene_python", "python" ]
stackoverflow_0074163906_django_graphene_django_graphene_python_python.txt
Q: Copying a column from one dataframe to another and join it based on datetime index What I would like to do: I need to append values from a second dataframe to the first one based on the dates and forward-fill it using the ffill function on pandas. However I can't find a way to merge the data based on DateTime inde...
Copying a column from one dataframe to another and join it based on datetime index
What I would like to do: I need to append values from a second dataframe to the first one based on the dates and forward-fill it using the ffill function on pandas. However I can't find a way to merge the data based on DateTime index as the index are of different formats. I have an original dataframe with 5 min time se...
[ "If anyone get's into the same issue as mine in the future, here's how I worked through it:\nI managed to figure it out for now by appending 00:00:00 to the daily time frame day_df df and the trying to use merge by converting to datetime format.\ni.e by slightly modifying the day_df and appending HH:MM:SS to it so ...
[ 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074184613_dataframe_datetime_pandas_python.txt
Q: Opening SAP via python I have sucessfully managed to open SAP, but I am struggling to make python click on the logon button that appears when the program is opened. How could I achieve that? import subprocess subprocess.run(r'C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe') # I would like python to pres...
Opening SAP via python
I have sucessfully managed to open SAP, but I am struggling to make python click on the logon button that appears when the program is opened. How could I achieve that? import subprocess subprocess.run(r'C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe') # I would like python to press the logon button in the wi...
[ "This is what I use in python\nimport subprocess\n\nsubprocess.check_call(['C:\\\\Program Files (x86)\\\\SAP\\\\FrontEnd\\\\SAPgui\\\\sapshcut.exe', '-system=PE1', '-client=500', '-user=user', '-pw=password', '-language=EN'])\n\n", "In my opinion, python is not exactly the best language when it comes to automate ...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0072545836_python.txt
Q: How to set PIPENV_IGNORE_VIRTUALENVS=1? While trying to create a venv for a django project while beeing in the projects dir using pipenv, I noticed that after installing django with pipenv (pipenv install django), pipenv sent a message: Courtesy Notice: Pipenv found itself running within a virtual environment, so ...
How to set PIPENV_IGNORE_VIRTUALENVS=1?
While trying to create a venv for a django project while beeing in the projects dir using pipenv, I noticed that after installing django with pipenv (pipenv install django), pipenv sent a message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, i...
[ "Your question is equivalent to, how do I set persistent environment variables on Windows? Or, how do I set environment variables to be used by VS Code specifically? I encourage you to use those searches to learn more.\nIn this case, I believe you can do\nsetx PIPENV_IGNORE_VIRTUALENVS 1\n\nFor VS Code + Python, th...
[ 2 ]
[]
[]
[ "django", "pipenv", "powershell", "python", "python_3.x" ]
stackoverflow_0074167663_django_pipenv_powershell_python_python_3.x.txt
Q: I'm Getting Ngrok Error 6022 after doing everything properly You can refer to my images for details. This is the code I'm running on colab: from google.colab import drive drive.mount('/content/drive') cd /content/drive/MyDrive/mini !curl -s https://ngrok-agent.s3.amazonaws.com/ngrok.asc | sudo tee /etc/apt/trus...
I'm Getting Ngrok Error 6022 after doing everything properly
You can refer to my images for details. This is the code I'm running on colab: from google.colab import drive drive.mount('/content/drive') cd /content/drive/MyDrive/mini !curl -s https://ngrok-agent.s3.amazonaws.com/ngrok.asc | sudo tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null && echo "deb https://ngrok-agent.s3...
[ "I was having the same issue, ngrok updated to v3 and you can either use pyngrok or update your code\nSolution 1:\nRemove the curl commands, and add this instead:\n!pip install pyngrok==4.1.1\nSolution 2:\nUpdate your methods to bind authtoken by following the new documentation\nhttps://ngrok.com/docs/guides/upgrad...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "flask", "google_colaboratory", "ngrok", "pyngrok", "python" ]
stackoverflow_0071900716_flask_google_colaboratory_ngrok_pyngrok_python.txt
Q: How to randomly generate numbers each time the program is run and store those values in a list? I am writing a program that asks the user to input a list of students. Once the list is made the user can input a student's name that was listed before to show 4 random integers from 1 to 100 that represent 4 different ...
How to randomly generate numbers each time the program is run and store those values in a list?
I am writing a program that asks the user to input a list of students. Once the list is made the user can input a student's name that was listed before to show 4 random integers from 1 to 100 that represent 4 different marks on assignments. When I run this program, however, the mark is the same number each time. How do...
[ "It seems like the error is in print(\"A1:\" + str(studentMark) + \"\\nA2:\" + str(studentMark) + \"\\nA3:\" + str(studentMark) + \"\\nA4:\" + str(studentMark)).\nIf studentMark is a list, which is what I gather from my last moment research on random.sample, it seems like the problem is that you are using the same ...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0074185369_list_python_random.txt
Q: VSCode run without debugging doesn't work Using VSCode I can run my test python code by pressing the play icon top right. This should = run without debugging but I get no output I have tried adding python path to settings.json as per vscode "Run Without Debugging" doesn't open Python Debug Console but no change. N...
VSCode run without debugging doesn't work
Using VSCode I can run my test python code by pressing the play icon top right. This should = run without debugging but I get no output I have tried adding python path to settings.json as per vscode "Run Without Debugging" doesn't open Python Debug Console but no change. Not a big issue but any non workaround solutions...
[ "I Fixed: Re-installing the debugger (in my case IntelliSense)\n\nFile Menu \"Run\" - \"Install Additional Debuggers...\"\nThen in the actual debugger (Generally the first) select Uninstall\nRestart VScode\nFile Menu \"Run\" - \"Install Additional Debuggers...\"\nSearch and install the debugger again\nTry\n\n", ...
[ 1, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0073235684_python_visual_studio_code.txt
Q: Server in Android virtual device not receiving python client connection so it can't get past ServerSocket.accept() I'm currently trying to use sockets to send strings from a python client to a server socket inside an android app running in an android virtual device. The server waits at the point it reaches ServerS...
Server in Android virtual device not receiving python client connection so it can't get past ServerSocket.accept()
I'm currently trying to use sockets to send strings from a python client to a server socket inside an android app running in an android virtual device. The server waits at the point it reaches ServerSocket.accept() public class MyServer implements Runnable{ //EXECUTED IN A NEW THREAD ...
[ "You better stop trying this. As you need to be a network expert to connect a client running on a pc with a server running in an emulator that runs on the same pc. If you could reverse client and server it was easy to let the client connect. But not in this scenario. No, take a real Android device. Then you can use...
[ 0 ]
[]
[]
[ "android", "avd", "java", "python", "websocket" ]
stackoverflow_0074175797_android_avd_java_python_websocket.txt
Q: Question about Ranking of Documents using BM25 I'm trying to rank task sentences of an occupation using bm25. I'm following this tutorial, but getting to this part I get confused "Ranking of documents Now that we've created our document indexes, we can give it queries and see which documents are the most relevant...
Question about Ranking of Documents using BM25
I'm trying to rank task sentences of an occupation using bm25. I'm following this tutorial, but getting to this part I get confused "Ranking of documents Now that we've created our document indexes, we can give it queries and see which documents are the most relevant" i want that the queries be every sentence that i h...
[ "Basically you just need to iterate over your list of documents, for example like this:\nimport pandas as pd\nfrom rank_bm25 import BM25Okapi\nimport string\n\n\ndef argsort(seq, reverse):\n # http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python\n return...
[ 0 ]
[]
[]
[ "information_retrieval", "python" ]
stackoverflow_0074181413_information_retrieval_python.txt
Q: How to search url for date pattern and replace forward slash with period in JS or python Apologies if this has been asked and answered, but I can't see that it has. I have a hosted form that i want to prepopulate known data with a query string, which can contain multiple dates. The dates don't populate into the fo...
How to search url for date pattern and replace forward slash with period in JS or python
Apologies if this has been asked and answered, but I can't see that it has. I have a hosted form that i want to prepopulate known data with a query string, which can contain multiple dates. The dates don't populate into the form with a forward slash but do with a period; therefore, I'm looking to put a code step into Z...
[ "Here is a Python solution.\nI think this is more or less what you are looking for. Regex could be finetuned for your specific needs.\nThe re.sub function searches for a match in the string, parses it as a Match object and executes a function on the grouped Match object.\nIn this case I replaced the usual function ...
[ 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0074181292_javascript_python.txt
Q: How to detect button press within n seconds How would I determine if I pressed the x button within time_between_attacks[hits] with time between checks to be time_between_attacks[hits]/10 using pygame timer. def display_battle(self,screen,enemy_list): print(enemy_list) clock = pygame.time.Clock() ...
How to detect button press within n seconds
How would I determine if I pressed the x button within time_between_attacks[hits] with time between checks to be time_between_attacks[hits]/10 using pygame timer. def display_battle(self,screen,enemy_list): print(enemy_list) clock = pygame.time.Clock() #Addition amount hit = 0 ...
[ "I would simply create a variable that holds the time of the attack. Then, if x is pressed, and current time - time of attack < threshold, the x button has been pressed within the time allocated. Here's some pseudocode:\nhitTime = pygame.time.get_ticks() for point 1.\nif keys[pygame.K_x]:\n if py...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074185611_pygame_python.txt
Q: Is there any way to make this any more efficient? I'm a beginner to programming, I literally started programming like three days ago. Here is my program, it checks if you've passed all subjects, and as you guys can see, there are a lot of if conditions in it. I've read online that too many if conditions, or for lo...
Is there any way to make this any more efficient?
I'm a beginner to programming, I literally started programming like three days ago. Here is my program, it checks if you've passed all subjects, and as you guys can see, there are a lot of if conditions in it. I've read online that too many if conditions, or for loops can slow your program down, and that there is a mor...
[ "Well done! And welcome to StackOverflow.\nCodereview versus StackOverflow\nThis site (Stackoverflow) is for developers who are stuck at a problem. There is a sister-site, CodeReview, which does only that: reviewing code. Your question is a bit between both sites: you have a question (can this be more efficient / P...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074184723_python.txt
Q: How to display runes in pycharm? I want to write this in pycharm elder = 'ᚠᚢᚦᚨᚱᚲᚷᚹᚺᚾᛁᛃᛈᛇᛉᛊᛏᛒᛖᛗᛚᛜᛞᛟ' But it displays only empty squares elder = '□□□□□□□□□□□□□□□□□□□□□□□□' A: you're using some special characters (Unicode), and Pycharm doesn't support all charactersets out there out-of-the-box. yet, you can config...
How to display runes in pycharm?
I want to write this in pycharm elder = 'ᚠᚢᚦᚨᚱᚲᚷᚹᚺᚾᛁᛃᛈᛇᛉᛊᛏᛒᛖᛗᛚᛜᛞᛟ' But it displays only empty squares elder = '□□□□□□□□□□□□□□□□□□□□□□□□'
[ "you're using some special characters (Unicode), and Pycharm doesn't support all charactersets out there out-of-the-box. yet, you can configure it to do so if you like as instructed here. but keep in mind it always depends on the environment configuration whether a unicode character is defined and displayed correct...
[ 0 ]
[]
[]
[ "character", "pycharm", "python" ]
stackoverflow_0074185627_character_pycharm_python.txt
Q: stratify sklearn train_test_split using dummy vector for 'stratify parameter I want to split my data into train, val, and test sets, using the stratify parameter in the train_test_split library. I want to use a binary dummy vector (the vector name is prop) for the stratify parameter, making the test's labels prop...
stratify sklearn train_test_split using dummy vector for 'stratify parameter
I want to split my data into train, val, and test sets, using the stratify parameter in the train_test_split library. I want to use a binary dummy vector (the vector name is prop) for the stratify parameter, making the test's labels proportion the same as the binary vector proportion. However, it isn't working. The co...
[ "Stratify is used to balance the dataset, not to have class proportions as the input to the stratify parameter. Normally, you put in your targets into the Y parameter:\nself.train_data.X, self.test_data.X, self.train_data.y, self.test_data.y = train_test_split(X, y, test_size = (0.2) , random_state = 42, stratify=y...
[ 0 ]
[]
[]
[ "imbalanced_data", "python", "scikit_learn", "test_data", "training_data" ]
stackoverflow_0074184002_imbalanced_data_python_scikit_learn_test_data_training_data.txt
Q: What is the best approach to compute the trace of a (sparse) matrix product efficiently in python I'm trying to take the hilbert schmidt inner product of two matices. For two matrices A, B this operation requires the matrix product of the Hermitian conjugate of A times B followed by the trace (summing down the dia...
What is the best approach to compute the trace of a (sparse) matrix product efficiently in python
I'm trying to take the hilbert schmidt inner product of two matices. For two matrices A, B this operation requires the matrix product of the Hermitian conjugate of A times B followed by the trace (summing down the diagonal). As you only need the diagonal entries, it is pointless to find the full matrix product, as the ...
[ "Another option is (A.conj().multiply(B)).sum().\nIn [111]: Dimension = 2**12\n\nIn [112]: A = rand(Dimension, Dimension, density=0.001, format='csr')\n ...: B = rand(Dimension, Dimension, density=0.001, format='csr')\n\nCompare to sum((A.conj().T @ B).diagonal()):\nIn [113]: sum((A.conj().T @ B).diagonal())\nO...
[ 1 ]
[]
[]
[ "linear_algebra", "matrix", "numpy", "python", "scipy" ]
stackoverflow_0074185561_linear_algebra_matrix_numpy_python_scipy.txt
Q: Python library for dot product classification I have the following python pyseudo-code: A1 = "101000001111" A2 = "110000010101" B2 = "000111010000" B2 = "000110100000" # TODO get X = [x1, x2, ..., x12] assert(A1 * X > .5) assert(A2 * X > .5) assert(B1 * X < .5) assert(B2 * X < .5) So this will basically be a regr...
Python library for dot product classification
I have the following python pyseudo-code: A1 = "101000001111" A2 = "110000010101" B2 = "000111010000" B2 = "000110100000" # TODO get X = [x1, x2, ..., x12] assert(A1 * X > .5) assert(A2 * X > .5) assert(B1 * X < .5) assert(B2 * X < .5) So this will basically be a regression based classification. 0.5 is my threshold bu...
[ "\nYou need to find 12 coefficients. You can try to use LogisticRegression or LinearRegression\n\nWhen you have linear coefficients you can use np.dot or @ operator to get a dot product.\n\n\nExample:\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\nA1 = \"101000001111\"\nA2 = \"110000010...
[ 1 ]
[]
[]
[ "classification", "machine_learning", "multilabel_classification", "python" ]
stackoverflow_0074184767_classification_machine_learning_multilabel_classification_python.txt
Q: Why ist setuptools not installing install_requires My Python package is installed using setuptools configured with a setup.cfg file. In it requirements are specified: [options] packages = find: zip_safe = True include_package_data = True install_requires = gmsh >= 4.10.5 matplotlib >= 3.6.1 numpy >= 1....
Why ist setuptools not installing install_requires
My Python package is installed using setuptools configured with a setup.cfg file. In it requirements are specified: [options] packages = find: zip_safe = True include_package_data = True install_requires = gmsh >= 4.10.5 matplotlib >= 3.6.1 numpy >= 1.23.3 When installing the package via pip the package to...
[ "It is mentioned in the comments that you have a pyproject.toml file. If you use the toml configuration then you do not need the setup.cfg at all. Delete the setup.cfg and add in pyproject.toml:\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = ...\nversion...
[ 0 ]
[]
[]
[ "pip", "python", "setuptools" ]
stackoverflow_0074184728_pip_python_setuptools.txt
Q: How to set the default model to a variable if None was passed? Can I make a default model in Pydantic if None is passed in the field? I am new to pydantic and searched for relevant answers but could not find any. I have the following code, from typing import Optional,List from pydantic import BaseModel class Fiel...
How to set the default model to a variable if None was passed?
Can I make a default model in Pydantic if None is passed in the field? I am new to pydantic and searched for relevant answers but could not find any. I have the following code, from typing import Optional,List from pydantic import BaseModel class FieldInfo(BaseModel): value: Optional[str] = "" confidence: Opti...
[ "It should just include adding a default value in UserInfo.last_name like so:\nfrom typing import Optional\nfrom pydantic import BaseModel\n\nclass FieldInfo(BaseModel):\n value: Optional[str] = \"\"\n confidence: Optional[float] = -1.0\n\n\nclass UserInfo(BaseModel):\n first_name: Optional[FieldInfo]\n ...
[ 1 ]
[]
[]
[ "fastapi", "pydantic", "python", "rest" ]
stackoverflow_0074185763_fastapi_pydantic_python_rest.txt
Q: Pandas groupby after groupby not working how? I have df so: col1 col2 col3 0 a x 1 1 a x 2 2 a y 3 3 b x 4 4 b x 5 5 c y 6 and used groupby col1 and now groupby col2 but error is AttributeError: 'DataFrameGroupBy' object has no attribute 'groupby'. D...
Pandas groupby after groupby not working how?
I have df so: col1 col2 col3 0 a x 1 1 a x 2 2 a y 3 3 b x 4 4 b x 5 5 c y 6 and used groupby col1 and now groupby col2 but error is AttributeError: 'DataFrameGroupBy' object has no attribute 'groupby'. Did you mean: 'groups'? What can I do for fixing? I...
[ "You can pass a list to groupby if you have multiple indices. Try this:\ndf.groupby([\"col1\", \"col2\"])[\"col3\"].sum()\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "group", "group_by", "pandas", "python" ]
stackoverflow_0074185811_dataframe_group_group_by_pandas_python.txt
Q: How to do multiple plots like Matplotlib (e.g. 2x2) and save into PDF? I am trying to combine my 4 pages of 4 different graphs into 1 page of graphs organized in a 2x2 fashion. I am using 'Pdfpages' in Python. In Matplotlib I see that we can do the following to create multiple plots: # Initialise the subplot funct...
How to do multiple plots like Matplotlib (e.g. 2x2) and save into PDF?
I am trying to combine my 4 pages of 4 different graphs into 1 page of graphs organized in a 2x2 fashion. I am using 'Pdfpages' in Python. In Matplotlib I see that we can do the following to create multiple plots: # Initialise the subplot function using number of rows and columns figure, axis = plt.subplots(2, 2) # ...
[ "I believe you can use:\nfig, axes = plt.subplots(nrows=2, ncols=2)\n\nAnd use savefig() and close() after you use .plot() for the four dataframes. Hope this works!\nsource\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074185782_matplotlib_pandas_python.txt
Q: Plot count of unique values in Python I have a data frame that is similar to the following: Time Account_ID Device_ID Zip_Code 0 2011-02-02 12:02:19 ABC123 A12345 83420 1 2011-02-02 13:35:12 EFG456 B98765 37865 2 2011-02-02 13:54:57 EFG456 B98765 37865...
Plot count of unique values in Python
I have a data frame that is similar to the following: Time Account_ID Device_ID Zip_Code 0 2011-02-02 12:02:19 ABC123 A12345 83420 1 2011-02-02 13:35:12 EFG456 B98765 37865 2 2011-02-02 13:54:57 EFG456 B98765 37865 3 2011-02-02 14:45:20 EFG456 C245...
[ "You can combine groupby nunique and value_counts like this:\ndf.groupby(\"Account_ID\")[\"Device_ID\"].nunique().value_counts().plot.bar()\n\nEdit:\nCode used to recreate your data:\ndf = pd.DataFrame({'Time': {0: '2011-02-02 12:02:19', 1: '2011-02-02 13:35:12', 2: '2011-02-02 13:54:57',\n ...
[ 1 ]
[]
[]
[ "group_by", "pandas", "plot", "python", "unique" ]
stackoverflow_0074185746_group_by_pandas_plot_python_unique.txt
Q: Deleting files from folder I have files in folder with names 1.jpg, 2.jpg, 3.jpg ... etc. And I have list of names 2.jpg, 3.jpg, 4.jpg How can I delete files in folder according to names from this list? import os import glob fileList = glob.glob('/home/varung/Documents/python/logs/**/*.txt', recursive=True) for f...
Deleting files from folder
I have files in folder with names 1.jpg, 2.jpg, 3.jpg ... etc. And I have list of names 2.jpg, 3.jpg, 4.jpg How can I delete files in folder according to names from this list? import os import glob fileList = glob.glob('/home/varung/Documents/python/logs/**/*.txt', recursive=True) for filePath in fileList: try: os.rem...
[ "this code does what you've described:\nimport os\n\nremovals = ['a.txt', 'b.jpg']\n\nfor object in os.listdir('.'):\n if os.path.isfile(object) and object in removals:\n os.remove(object)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074185522_python.txt
Q: Pandas .replace inside a for i in range() I don't know why my .replace wont advance to the next value in my for loop. Code: import pandas as pd import numpy as np df1 = pd.read_csv("df1.csv") df2 = pd.read_csv("df2.csv") print(df1) print(df2) df3 = pd.merge(df1, df2, on='ID', how='left') print(df3) C = len(df...
Pandas .replace inside a for i in range()
I don't know why my .replace wont advance to the next value in my for loop. Code: import pandas as pd import numpy as np df1 = pd.read_csv("df1.csv") df2 = pd.read_csv("df2.csv") print(df1) print(df2) df3 = pd.merge(df1, df2, on='ID', how='left') print(df3) C = len(df3.index) for i in range(C): if pd.isnull(...
[ "You can try:\ndf3[\"Leg\"] = df3[\"Leg\"].combine_first(df3[\"ID\"])\ndf3[\"SAP\"] = df3[\"SAP\"].combine_first(df3[\"ID\"])\nprint(df3)\n\nPrints:\n ID Desc QTY Leg SAP\n0 100 Test1 1 165-8 142.0\n1 200 Test2 7 200 655.0\n2 300 Test3 1 300 300.0\n3 400 Test4 3 21-56 ...
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074185473_csv_dataframe_pandas_python.txt
Q: Slicing every second row and column of a 3d numpy array, making a new array I have a NumPy array of dimension 698x64x64 (64rows, 64columns) I would like to slice it into a new array of 698x32x32 by taking every second row and column of the original array. How do I do that? A: IIUC, You can use slicing like below...
Slicing every second row and column of a 3d numpy array, making a new array
I have a NumPy array of dimension 698x64x64 (64rows, 64columns) I would like to slice it into a new array of 698x32x32 by taking every second row and column of the original array. How do I do that?
[ "IIUC, You can use slicing like below. (You can read this : understanding-slicing)\nimport numpy as np\nnp.random.seed(123)\n# this array is a sample array for showing result\na = np.random.rand(2,4,4)\nprint(a)\n\nb = a[:, 1::2, 1::2] # <- you can use this for (698, 64, 64)\nprint(b)\n\nOutput:\n# a =>\narray([[[0...
[ 1 ]
[]
[]
[ "arrays", "numpy", "numpy_slicing", "python" ]
stackoverflow_0074185942_arrays_numpy_numpy_slicing_python.txt
Q: Numpy converting data I'm using numpy to retrieving data from csv file, it contains 3 columns with data: offer_id, sms_limit, sms_price. I want to add validation: offer_id - only positive integers sms_limit - only positive integers sms_price - positive float number. I've tried to write my own validator, somethin...
Numpy converting data
I'm using numpy to retrieving data from csv file, it contains 3 columns with data: offer_id, sms_limit, sms_price. I want to add validation: offer_id - only positive integers sms_limit - only positive integers sms_price - positive float number. I've tried to write my own validator, something like this: def int_valida...
[ "Here's a solution that correctly checks if the first two columns contain positive integers and if the last column contains positive floats.\n# This uses a try-except block to see if the given value is an integer, \n# and an if-else block to see if the value is >= 0.\n# Change the sign to > 0 if you want strictly p...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074185595_numpy_python.txt
Q: Respond an array of json objects in Django view I have this table or model: longitude latitude session 12 34 1 99 42 2 99 42 1 99 42 3 99 42 1 99 42 2 I need to make a query to get all data by session. So I get all the data from the table and apply 'distinct' to get the sessions: sessions= GPSData.objects....
Respond an array of json objects in Django view
I have this table or model: longitude latitude session 12 34 1 99 42 2 99 42 1 99 42 3 99 42 1 99 42 2 I need to make a query to get all data by session. So I get all the data from the table and apply 'distinct' to get the sessions: sessions= GPSData.objects.values('session_new_id').distinct() I ...
[ "I've followed the link @Mike Jones has commented and was able to do it using JsonResponse.\nfrom django.http import JsonResponse\nfrom .models import GPSData\n\ndef get_all_gps(request):\n data = [] \n for gps_data in GPSData.objects.all().order_by(\"session\").values():\n try:\n session_...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074185362_django_python.txt
Q: How can I extract a table from many Excel documents to Pandas? I have hundreds of similar Excel files, but containing descriptions and other informations too. (see Excel Screenshot) I would like to extract the tables or their data only for further works. I managed an iterative way to but it is inaccurate, and erro...
How can I extract a table from many Excel documents to Pandas?
I have hundreds of similar Excel files, but containing descriptions and other informations too. (see Excel Screenshot) I would like to extract the tables or their data only for further works. I managed an iterative way to but it is inaccurate, and error prone to even a cell of difference, and in some cases there are di...
[ "It seems that the common denominator is that the tables you want to extract have border styles. So you could open the file with openpyxl first, and filter out the cells that have border styles, then pass it to pandas.\nfrom openpyxl import load_workbook\nimport pandas as pd\nimport requests\nfrom io import BytesIO...
[ 0 ]
[]
[]
[ "excel", "pandas", "python" ]
stackoverflow_0074185338_excel_pandas_python.txt
Q: Select values from list based on bools in numpy array For each sublist in array b, return values from list a with same position as positive boolean in b sublist (i.e. where True). import pandas as pd import numpy as np a = pd.Series([1, 3, 5, 7, 9]) # values to choose from b = np.array([[False, True, False, True...
Select values from list based on bools in numpy array
For each sublist in array b, return values from list a with same position as positive boolean in b sublist (i.e. where True). import pandas as pd import numpy as np a = pd.Series([1, 3, 5, 7, 9]) # values to choose from b = np.array([[False, True, False, True, False], # based on bools [False, False, Fa...
[ "You can simple use:\na2 = a.to_numpy()\nout = [a2[x] for x in b]\n\noutput: [array([3, 7]), array([], dtype=int64)]\n", "Your Series is 1d; b is a 2d array. The Series also has row indices, which a plain array does not.\nIn [70]: a.shape, b.shape\nOut[70]: ((5,), (2, 5))\n\nIn [71]: a\nOut[71]: \n0 1\n1 3...
[ 1, 1, 0 ]
[]
[]
[ "arrays", "numpy", "pandas", "performance", "python" ]
stackoverflow_0074182969_arrays_numpy_pandas_performance_python.txt
Q: Expanding just last row of groupby I need get mean of expanding grouped by name. I already have this code: data = { 'id': [1, 2, 3, 4, 5, 6, 7, 8], 'name': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'], 'number': [1, 3, 5, 7, 9, 11, 13, 15] } df = pd.DataFrame(data) df['mean_number'] = df.groupby('name')['number...
Expanding just last row of groupby
I need get mean of expanding grouped by name. I already have this code: data = { 'id': [1, 2, 3, 4, 5, 6, 7, 8], 'name': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'], 'number': [1, 3, 5, 7, 9, 11, 13, 15] } df = pd.DataFrame(data) df['mean_number'] = df.groupby('name')['number'].apply( lambda s: s.expanding().mean...
[ "If you only need the last two mean numbers you can just take the sum and count per group and calculate the values like this:\ngroups = df.groupby('name').agg(name=(\"name\", \"first\"), s=(\"number\", \"sum\"), c=(\"number\", \"count\")).set_index(\"name\")\n\ngroups\n s c\nname \nA 28 4\nB 3...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074185732_pandas_python.txt
Q: Rename pandas column iteratively I have several columns named the same in a data frame. How can I rename the below normal and KIRC to normal_1, normal_2, KIRC_1, KIRC_2? import pandas as pd gene_exp.columns = gene_exp.iloc[-1] gene_exp = gene_exp.iloc[:-1] gene_exp # Append "_[number]" c = pd.Series(gene_exp.co...
Rename pandas column iteratively
I have several columns named the same in a data frame. How can I rename the below normal and KIRC to normal_1, normal_2, KIRC_1, KIRC_2? import pandas as pd gene_exp.columns = gene_exp.iloc[-1] gene_exp = gene_exp.iloc[:-1] gene_exp # Append "_[number]" c = pd.Series(gene_exp.columns) for dup in gene_exp.columns[gen...
[ "# set Gene and Name as Index, as we don't need these renamed\ndf.set_index(['Gene','NAME'], inplace=True)\n\n# create a dataframe from the columns\ndf2=pd.DataFrame(df.columns.values, columns=['col'])\n\n# create new columns by counting repeated names and adding 1 to count\n# assign columns to the dataframe\ndf.co...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074185864_pandas_python.txt
Q: How to use groupby to edit existing pandas dataframe Good afternoon. I have a dataframe: Date Name Count 10/1/2022 Mike 10 10/1/2022 Jen 15 10/1/2022 Carol 25 10/2/2022 Mike 7 10/2/2022 Jen 13 10/2/2022 Carol 30 I need to edit it to the followin...
How to use groupby to edit existing pandas dataframe
Good afternoon. I have a dataframe: Date Name Count 10/1/2022 Mike 10 10/1/2022 Jen 15 10/1/2022 Carol 25 10/2/2022 Mike 7 10/2/2022 Jen 13 10/2/2022 Carol 30 I need to edit it to the following df: 10/1/2022 10/2/2022 Mike 10 ...
[ "Try pivot instead of groupby\ndf.pivot(index=\"Name\", columns=\"Date\", values=\"Count\")\n\nDate 10/1/2022 10/2/2022\nName \nCarol 25 30\nJen 15 13\nMike 10 7\n\nEDIT: add .sort_values(\"10/1/2022\") to get the example\n" ]
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074186058_dataframe_group_by_pandas_python.txt
Q: Get date from weekday, month and year I have a column with the weekday, another with the month and another with the year. How do I get the actual date in python? A: import pandas as pd df = pd.DataFrame({"year": [2018], "month": [12], "day": [1]}) df["date"] = pd.to_datetime(df[["year", "month", "day"]]).dt.da...
Get date from weekday, month and year
I have a column with the weekday, another with the month and another with the year. How do I get the actual date in python?
[ "import pandas as pd\n\ndf = pd.DataFrame({\"year\": [2018], \"month\": [12], \"day\": [1]})\n\ndf[\"date\"] = pd.to_datetime(df[[\"year\", \"month\", \"day\"]]).dt.date\n\nprint(df)\n# year month day date\n# 0 2018 12 1 2018-12-01\n\n", "You can use the datetime library:\nimport datetime\n\n...
[ 2, 0, 0 ]
[]
[]
[ "date", "numpy", "pandas", "python" ]
stackoverflow_0074186039_date_numpy_pandas_python.txt
Q: apache beam inverse operation of util.BatchElements What is the inverse operation of apache_beam.transforms.util.BatchElements (python) ? My pipeline is generating some batches (PCollection of element type List[T]) and doing some operation on them. How do I put these back into a PCollection of elements type T? ...
apache beam inverse operation of util.BatchElements
What is the inverse operation of apache_beam.transforms.util.BatchElements (python) ? My pipeline is generating some batches (PCollection of element type List[T]) and doing some operation on them. How do I put these back into a PCollection of elements type T? with beam.Pipeline(options=options) as pipeline: ...
[ "BatchElements creates a PCollection[List[T]]. You can apply a beam.FlatMap to that PCollection to get a PCollection[T] again.\n" ]
[ 3 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074185577_apache_beam_google_cloud_dataflow_python.txt
Q: Create a DataFrame from a list of nested tuples using Pandas (Python) I'm struggling with a simple task and after reading a lot of StackOverflow posts e searching on Pandas documentation I've decided to ask for help here. Problem I have a list of nested tuples which looks like this: Terminal log of a list of neste...
Create a DataFrame from a list of nested tuples using Pandas (Python)
I'm struggling with a simple task and after reading a lot of StackOverflow posts e searching on Pandas documentation I've decided to ask for help here. Problem I have a list of nested tuples which looks like this: Terminal log of a list of nested tuples And I need to create a Pandas DataFrame with a column for each in...
[ "From what I understand, you have the following structure:\n[\n (\n (A1, B1, C1, D1, Y, Z),\n (A2, B2, C2, D2, W, X)\n ), ...\n]\n\nAnd you're trying to convert to a Dataframe with this structure:\nA B C D W X Y Z\n----------------------------------\nA1 B1 C1 D1 NaN NaN Y Z\nA2 ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074184562_dataframe_pandas_python.txt
Q: How to fill the bigger square with smaller squares effectively? I need to write in python3 a function that fills the bigger square with smaller squares basing on the input. The input is a list of positive integers. Each integer is the number of squares per row. So the list [3, 8, 5, 2] means I got 4 rows of square...
How to fill the bigger square with smaller squares effectively?
I need to write in python3 a function that fills the bigger square with smaller squares basing on the input. The input is a list of positive integers. Each integer is the number of squares per row. So the list [3, 8, 5, 2] means I got 4 rows of squares where first one has 3 squares, second one 8 and so on. All squares ...
[ "list = [3, 8, 5, 2] #As close to a Square as possible\n\ndef getSquare(list):\n \n for i in range(1, max(list)+1):\n\n output = []\n num = 0\n\n for j in list:\n\n output.append([i]*(j//i))\n\n num += j//i\n\n if j%i != 0:\n\n output[-1].ap...
[ 0, 0, 0 ]
[]
[]
[ "algorithm", "mathematical_optimization", "matrix", "python" ]
stackoverflow_0074180010_algorithm_mathematical_optimization_matrix_python.txt
Q: how to write output of one module in another module as csv file I am trying to write output of one module in a output file of another module. For example, first module : def sentence_token(): # some code sentences = sentence_tokenizer(tokens) count_sentence = f"total count of sentence is {len...
how to write output of one module in another module as csv file
I am trying to write output of one module in a output file of another module. For example, first module : def sentence_token(): # some code sentences = sentence_tokenizer(tokens) count_sentence = f"total count of sentence is {len(sentences)}" second module : def word_pos_definition(): # ...
[ "you can do multiple things to have both values in your CSV file.\n\nyou can append your data, so the content another file has made doesn't get deleted.\n\ndef sentence_token():\n \n # some code\n sentences = sentence_tokenizer(tokens)\n count_sentence = len(sentences)}\n\n with open('file.csv', 'a')...
[ 0 ]
[]
[]
[ "export", "import", "module", "python", "python_3.x" ]
stackoverflow_0074185881_export_import_module_python_python_3.x.txt
Q: valid xpath expression from html i ha ve this html <yt-formatted-string id="text" class="style-scope ytd-button-renderer style-primary size-default"> All </yt-formatted-string><paper-ripple class="style-scope tp-yt-paper-button"> this xpath works with selenium python //yt-formatted-string[text()='All'] but how c...
valid xpath expression from html
i ha ve this html <yt-formatted-string id="text" class="style-scope ytd-button-renderer style-primary size-default"> All </yt-formatted-string><paper-ripple class="style-scope tp-yt-paper-button"> this xpath works with selenium python //yt-formatted-string[text()='All'] but how can i include the part id="text" of the...
[ "You can use\n//yt-formatted-string[@id='text' and text()='All']\n\nor the more general approach\n//yt-formatted-string[@id='text' and contains(text(),'All')]\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0074185607_python_selenium_xpath.txt
Q: roboflow yoloV5 training same size problem i am trying to train model via roboflow yolov5 notebook on colab. i always use pre-labeled roboflow data. and the problem is : the all final pt weight files has the same size (14.6 mb). the big data or tiny data, there is no difference among sizes. i think it's ridiculous...
roboflow yoloV5 training same size problem
i am trying to train model via roboflow yolov5 notebook on colab. i always use pre-labeled roboflow data. and the problem is : the all final pt weight files has the same size (14.6 mb). the big data or tiny data, there is no difference among sizes. i think it's ridiculous. can someone explain it? colab notebook :https:...
[ "The size of weights file is proportional to the number of parameters in the model which is defined by the architecture. It doesn't have anything to do with the size of the dataset or the number of epochs/amount of time trained.\nThe only thing that will affect the filesize of the weights is what version of the mod...
[ 1 ]
[]
[]
[ "machine_learning", "python", "roboflow", "yolo" ]
stackoverflow_0074177309_machine_learning_python_roboflow_yolo.txt
Q: Sync PostgreSQL and Django project I had a legacy database which I uploaded to PostgreSQL and connected it with Django. Then, I changed DB with running SQL scripts directly in the PostgreSQL (I deleted few columns), then manually deleted few columns in django models.py. Since then, I cannot make any migrations, wh...
Sync PostgreSQL and Django project
I had a legacy database which I uploaded to PostgreSQL and connected it with Django. Then, I changed DB with running SQL scripts directly in the PostgreSQL (I deleted few columns), then manually deleted few columns in django models.py. Since then, I cannot make any migrations, whenever I try it, Django is trying to del...
[ "You should try to use migrations even for running custom SQL. This would prevent such situations.\nHowever, you can skip a single migration, if the changes are already applied to your database, using the --fake flag for ./manage.py migrate\nhttps://docs.djangoproject.com/en/4.1/ref/django-admin/#cmdoption-migrate-...
[ 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0074185328_django_postgresql_python.txt
Q: y-axis is messy when graphing I'm having trouble graphing in python. The data is in a dataframe and is 2 columns. The problem is that when graphing, the "y-axis" is disordered, it does not go from the origin (0, 0) to the maximum value which would be ~4. This is the code of the table: import matplotlib.pyplot as p...
y-axis is messy when graphing
I'm having trouble graphing in python. The data is in a dataframe and is 2 columns. The problem is that when graphing, the "y-axis" is disordered, it does not go from the origin (0, 0) to the maximum value which would be ~4. This is the code of the table: import matplotlib.pyplot as plt datosg = pd.DataFrame() datosg =...
[ "this can happen when your data is not a numeric type, but is made up of strings (regardless of whether the strings contain numbers). try using pd.to_numeric, i.e.:\nnochetotal[\"Hour\"] = pd.to_numeric(nochetotal[\"Hour\"])\nnochetotal[\"UV Index\"] = pd.to_numeric(nochetotal[\"UV Index\"])\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074186165_matplotlib_pandas_python.txt
Q: How to insert into a table the values from another table (sqlite3) My goal is to add 3 columns from my transactions table into my portfolio table. I am using sqlite3 in my python code and I am wondering what the correct statement for this is. The following mysql code works in mysql, but unfortunately I need to use...
How to insert into a table the values from another table (sqlite3)
My goal is to add 3 columns from my transactions table into my portfolio table. I am using sqlite3 in my python code and I am wondering what the correct statement for this is. The following mysql code works in mysql, but unfortunately I need to use sqlite3 for my python code. I hope that the mysql code gives you some k...
[ "well if i were you i'd do something like this: you first fetch all the rows into memory and then feed it to the executemany method.\ndata = cur.execute(\n 'select ticker, price, quantity from transactions'\n).fetchall()\n\ncur.executemany(\n 'INSERT INTO portfolio (ticker, purchase_price, quantity) VALUES (?...
[ 1 ]
[]
[]
[ "mysql", "python", "sqlite" ]
stackoverflow_0074186202_mysql_python_sqlite.txt
Q: Cannot connect PostgreSQL database with Flask app I recently started learning the Flask framework, but now I am stuck, because - according to internet tutorials and documentation - my project is not working as it should be. I have a larger project, but after seeing that problem I made a smaller one just to see why...
Cannot connect PostgreSQL database with Flask app
I recently started learning the Flask framework, but now I am stuck, because - according to internet tutorials and documentation - my project is not working as it should be. I have a larger project, but after seeing that problem I made a smaller one just to see why it is not working - but I still have no clue. That is ...
[ "In your terminal, run:\nflask shell\n\nand inside that interpreter run from app import db. From the docs:\n\nStarting with Flask 0.11 the recommended way to work with the shell is the flask shell command which does a lot of this automatically for you. For instance, the shell is automatically initialized with a loa...
[ 0 ]
[]
[]
[ "flask", "postgresql", "python" ]
stackoverflow_0074186257_flask_postgresql_python.txt
Q: pandas to_sql method not working when writing data from csv file I have a Postgres table built with: create table titanic ( PassengerId SERIAL PRIMARY KEY, Survived SMALLINT, Pclass SMALLINT, Name VARCHAR(82), Sex VARCHAR(10), Age REAL, SibSp SMALLINT, Parch SMALLINT, Ticket VAR...
pandas to_sql method not working when writing data from csv file
I have a Postgres table built with: create table titanic ( PassengerId SERIAL PRIMARY KEY, Survived SMALLINT, Pclass SMALLINT, Name VARCHAR(82), Sex VARCHAR(10), Age REAL, SibSp SMALLINT, Parch SMALLINT, Ticket VARCHAR(50), Fare REAL, Cabin VARCHAR(20), Embarked VARCHAR(1...
[ "A simple way to do this.\ncreate table titanic (\n \"PassengerId\" SERIAL PRIMARY KEY,\n \"Survived\" SMALLINT,\n \"Pclass\" SMALLINT,\n \"Name\" VARCHAR(82),\n \"Sex\" VARCHAR(10),\n \"Age\" REAL,\n \"SibSp\" SMALLINT,\n \"Parch\" SMALLINT,\n \"Ticket\" VARCHAR(50),\n \"Fare\" REAL,\...
[ 0 ]
[]
[]
[ "csv", "pandas", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0074183927_csv_pandas_postgresql_python_sqlalchemy.txt
Q: Cycle when merging two ListNodes This problem is from LeetCode # Definition for singly-linked list. # class ListNode # def __init__(self, val=0, next=None): # self.val = val # self.next = next In my solution, if I do the following, I get an error that a cycle has been found in the ListNode: elif (l1.val<l2.va...
Cycle when merging two ListNodes
This problem is from LeetCode # Definition for singly-linked list. # class ListNode # def __init__(self, val=0, next=None): # self.val = val # self.next = next In my solution, if I do the following, I get an error that a cycle has been found in the ListNode: elif (l1.val<l2.val): sol = ListNode sol.val = l1...
[ "The issue is with this line:\nsol = ListNode\n\nYou're not creating a new object of type ListNode, but instead creating a reference to the class definition itself. By adding the round brackets ListNode() you're instantiating this object. This let's you then interact with it by calling it's .val and .next propertie...
[ 0 ]
[]
[]
[ "linked_list", "merge", "python", "singly_linked_list" ]
stackoverflow_0074185975_linked_list_merge_python_singly_linked_list.txt
Q: How to make eaten numbers follow last eaten number I want to make the eaten number to become some sort of 'head' of snake, and the last number follows that head. Picture example: This is beggining of program. 0 is the head of my snake. If snake goes right, and right, and right again - it goes on the number 1. I w...
How to make eaten numbers follow last eaten number
I want to make the eaten number to become some sort of 'head' of snake, and the last number follows that head. Picture example: This is beggining of program. 0 is the head of my snake. If snake goes right, and right, and right again - it goes on the number 1. I want him to 'eat' this 1 and replace its head for that nu...
[ "You'll need code that moves all the snake's content with one position. Therefore you need to keep track of the coordinates that are part of the snake -- not just the last position. Also avoid code repetition, and try to deal with a move in one common way.\nI didn't quite get the input format, so I just limited the...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074182481_list_python.txt
Q: Is there better way to iterate over nested loop for rows (30000)? I would like to find rows in following table, which contain repeated email addresses. I create an extra column in the dataframe in the following code with value 'ja', when an email address is repeated. This is fine for a small number of rows (150). ...
Is there better way to iterate over nested loop for rows (30000)?
I would like to find rows in following table, which contain repeated email addresses. I create an extra column in the dataframe in the following code with value 'ja', when an email address is repeated. This is fine for a small number of rows (150). For large number of rows (30000), the script hangs. Any better ways to ...
[ "df.duplicated('Email', keep=False)\n\ncomputes exactly what you want (in boolean form)\nIf you insist on having 'ja'/None, you can keep your initial column creation\ndf['email_repeated']=None\ndf.loc[dfOrg.duplicated('Email', keep=False), 'email_repeated']='ja'\n\nAs for the literal question (is there better way t...
[ 6, 2, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074186093_dataframe_pandas_python.txt
Q: instead of day ago, minutes ago or hours ago I want to scrape the date published in today so date should be of today or date of published day scrapy Instead of a day ago, minutes ago, or hours ago I want to scrape the date if published today so the date should be of today or the date of published day in scrapy usi...
instead of day ago, minutes ago or hours ago I want to scrape the date published in today so date should be of today or date of published day scrapy
Instead of a day ago, minutes ago, or hours ago I want to scrape the date if published today so the date should be of today or the date of published day in scrapy using python. This the code I try. Published_Date = response.css('time::text').get().replace(",","").replace("Published ","")#Published Jul 30, 2019 if "AGO"...
[ "You can scrape the @datetime attribute directly from the <time> tag and use the datetime module to parse the date it was published and the timedelta to check how long ago it was published.\nimport scrapy\nimport datetime\n\nclass DTSpider(scrapy.Spider):\n name = 'dt'\n start_urls = ['https://simpleflying.co...
[ 1 ]
[]
[]
[ "python", "scrapy", "web_scraping", "xpath" ]
stackoverflow_0074185155_python_scrapy_web_scraping_xpath.txt
Q: Cannot connect SAS OnDemand for Academic - SASpy I follow the site: enter link description here My sascfg_personal.py SAS_config_names=['oda'] oda = {'java' : 'C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath\\java.exe', #US Home Region 1 'iomhost' : ['odaws01-usw2.oda.sas.com','odaws02-usw2.oda.sas.c...
Cannot connect SAS OnDemand for Academic - SASpy
I follow the site: enter link description here My sascfg_personal.py SAS_config_names=['oda'] oda = {'java' : 'C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath\\java.exe', #US Home Region 1 'iomhost' : ['odaws01-usw2.oda.sas.com','odaws02-usw2.oda.sas.com','odaws03-usw2.oda.sas.com','odaws04-usw2.oda.sas.c...
[ "Make sure that your sascfg_personal.py file in the right directory that is shown by the result the code below.\nimport saspy, os\nprint(saspy.__file__.replace('__init__.py', 'sascfg_personal.py'))\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "sas", "saspy" ]
stackoverflow_0073750818_jupyter_notebook_python_sas_saspy.txt
Q: Create a method that lists instances that were set to True in a previous class I have the following code that records job candidates' personal details in a class Employee: class Employee: def __init__(self, name, role, id): self.name = name self.role = role self.id = id self.interviewed ...
Create a method that lists instances that were set to True in a previous class
I have the following code that records job candidates' personal details in a class Employee: class Employee: def __init__(self, name, role, id): self.name = name self.role = role self.id = id self.interviewed = False def __str__(self): text = f'Candidate {self.name}; {self.id}. ' ...
[ "In your Database.list_interviewed_candidates method you are returning the first employee that was interviewed. Keep in mind that return exits from the current function (method in this case) as soon as is hit.\nSo it starts looking at your candidates and as soon as one interviewed is found, it returns that one.\nYo...
[ 1, 1 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0074186274_class_methods_python.txt
Q: Stuck after creating the dictionary, any guidance on what to do after? This is the question - '''Given a list of strings, create a dictionary, where keys are the strings and the values are the number of times the corresponding string repeats in the list. Do not use any additional libraries. Example: >>> problem1([...
Stuck after creating the dictionary, any guidance on what to do after?
This is the question - '''Given a list of strings, create a dictionary, where keys are the strings and the values are the number of times the corresponding string repeats in the list. Do not use any additional libraries. Example: >>> problem1(['Hello', 'Hello', 'Friends', 'Friends', 'Friends', 'Home']) {'Hello': 2, 'Fr...
[ "You could simply use collections.Counter\n>>> l = ['Hello', 'Hello', 'Friends', 'Friends', 'Friends', 'Home']\n>>> c = Counter(l)\n>>> c\nCounter({'Friends': 3, 'Hello': 2, 'Home': 1})\n>>> dict(c)\n{'Hello': 2, 'Friends': 3, 'Home': 1}\n\nso your function should be like\nfrom collections import Counter\n\ndef pro...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074186367_dictionary_python.txt
Q: Pandas comparing values following each other So the problem is to check are these values inside the same column are equal to each other i.e. df = pd.DataFrame(np.array([[1, 2, 3], [1, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c']) And if the following values of 'a' column are equal is there any c...
Pandas comparing values following each other
So the problem is to check are these values inside the same column are equal to each other i.e. df = pd.DataFrame(np.array([[1, 2, 3], [1, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c']) And if the following values of 'a' column are equal is there any chance to change the value of 'c' column for the sa...
[ "Since it's a dataframe, you could use duplicated\ndf.loc[df.duplicated('a', keep=False), 'c']='XXX'\n\nI mean, if your goal was to set column 'c' to 'XXX' for every row whose column 'a' is equal to value of column 'a' of another row.\nIt seems to be what you described. But your code attempt looks as if you were in...
[ 1 ]
[]
[]
[ "calculated_columns", "pandas", "python" ]
stackoverflow_0074185939_calculated_columns_pandas_python.txt
Q: Python: intersection indices numpy array How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d: import numpy as np a = np.array(xrange(11)) b = np.array([2, 7, 10]) inter = np.intersect1d(a, b) # inter == array([ 2, 7, 10]) But how can I get th...
Python: intersection indices numpy array
How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d: import numpy as np a = np.array(xrange(11)) b = np.array([2, 7, 10]) inter = np.intersect1d(a, b) # inter == array([ 2, 7, 10]) But how can I get the indices into a of the values in inter?
[ "You could use the boolean array produced by in1d to index an arange. Reversing a so that the indices are different from the values:\n>>> a[::-1]\narray([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])\n>>> a = a[::-1]\n\nintersect1d still returns the same values...\n>>> numpy.intersect1d(a, b)\narray([ 2, 7, 10])\n\...
[ 46, 2, 2, 1, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0011483863_arrays_numpy_python.txt