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:
'pyglet.graphics' has no attribute 'vertex_list'
I'm trying to make a Triangle with pyglet but I keep seeing this error.
AttributeError: module 'pyglet.graphics' has no attribute 'vertex_list'
I not sure what is the problem exactly.
by the way this the code I'm trying to run
`
from pyglet.gl import *
class Trian... | 'pyglet.graphics' has no attribute 'vertex_list' | I'm trying to make a Triangle with pyglet but I keep seeing this error.
AttributeError: module 'pyglet.graphics' has no attribute 'vertex_list'
I not sure what is the problem exactly.
by the way this the code I'm trying to run
`
from pyglet.gl import *
class Triangle:
def __init__(self) -> None:
self.ver... | [
"Please check which version of pyglet you are using. Recently (on 01.11.2022) pyglet version 2.0 got released which changed how to use vertex based drawing majorly.\npyglet.graphics.vertex_list was used in earlier versions of pyglet (for information how to use this refer to https://pyglet.readthedocs.io/en/pyglet-1... | [
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0074446973_pyglet_python.txt |
Q:
Creating function that makes a dictionary from a list
The goal -> For each word in the text except the last one, a key should appear in the resulting dictionary, and the corresponding value should be a list of every word that occurs immediately after the key word in the text. Repeated words should have multiple va... | Creating function that makes a dictionary from a list | The goal -> For each word in the text except the last one, a key should appear in the resulting dictionary, and the corresponding value should be a list of every word that occurs immediately after the key word in the text. Repeated words should have multiple values:
example:
fun(["ONE", "two", "one", "three"]) ==
... | [
"Your code can't give you an EOF error, since you don't do any file reading in the code you've shown. Since you haven't shown any of that code, I can't help you with the EOF error. However, there are a bunch of things wrong with your approach to make your dictionary of predictions:\n\nword.index() is not a thing. I... | [
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074603960_dictionary_list_python.txt |
Q:
How do I convert date (YYYY-MM-DD) to Month-YY and groupby on some other column to get minimum and maximum month?
I have created a data frame which has rolling quarter mapping using the code
abcd = pd.DataFrame()
abcd['Month'] = np.nan
abcd['Month'] = pd.date_range(start='2020-04-01', end='2022-04-01', freq = 'MS... | How do I convert date (YYYY-MM-DD) to Month-YY and groupby on some other column to get minimum and maximum month? | I have created a data frame which has rolling quarter mapping using the code
abcd = pd.DataFrame()
abcd['Month'] = np.nan
abcd['Month'] = pd.date_range(start='2020-04-01', end='2022-04-01', freq = 'MS')
abcd['Time_1'] = np.arange(1, abcd.shape[0]+1)
abcd['Time_2'] = np.arange(0, abcd.shape[0])
abcd['Time_3'] = np.ara... | [
"Do this:\nabcd_map['Month_'] = pd.to_datetime(abcd_map['Month']).dt.strftime('%Y-%m')\nabcd_map['Time_Period'] = abcd_map['Month_'] = pd.to_datetime(abcd_map['Month']).dt.strftime('%Y-%m')\nabcd_map['Time_Period'] = abcd_map['Month'].apply(lambda x: x.strftime(\"%b'%y\"))\ndf = abcd_map.groupby(['Time']).agg(\n ... | [
1,
1
] | [] | [] | [
"datetime",
"group_by",
"pandas",
"python"
] | stackoverflow_0074603351_datetime_group_by_pandas_python.txt |
Q:
How to validate an integer with python that needs to be used in calculations
I'm trying to validate that a user input int is numbers only. This has been my most recent try:
while True:
NumCars = int(input("Enter the number of cars on the policy: "))
NumCarsStr = str(NumCars)
if NumCarsStr == "":
... | How to validate an integer with python that needs to be used in calculations | I'm trying to validate that a user input int is numbers only. This has been my most recent try:
while True:
NumCars = int(input("Enter the number of cars on the policy: "))
NumCarsStr = str(NumCars)
if NumCarsStr == "":
print("Number of cars cannot be blank. Please re-enter.")
elif NumCarsStr.i... | [
"Use try / except, and then break the loop if no exception is raised, otherwise capture the exception, print an error message and let the loop iterate again\nwhile True:\n try:\n NumCars = int(input(\"Enter the number of cars on the policy: \"))\n break\n except ValueError:\n print(\"You ... | [
1,
1,
0
] | [
"You can utilize the .isnumeric() function to determine if the string represents an integer.\ne.g;\n NumCarsStr = str(input(\"Enter the number of cars on the policy: \"))\n ...\n ...\n elif not NumCarsStr.isnumeric():\n print(\"Number of cars must be numbers only. Please re-enter.\")\n\n"
] | [
-1
] | [
"python",
"validation"
] | stackoverflow_0074603758_python_validation.txt |
Q:
Connecting Rows of Array to Date and Time formate
Im New to Python, it sounds easy- but i cant solve it, nether find a resolution with similar questions.
I have an Array where every row has one value ((...), Hour, Min., Sec., (...) ,D, M, Y) - Example:
arr = np.array([x, x,0, 0, 3, x, x,10, 8, 2022])
How can I co... | Connecting Rows of Array to Date and Time formate | Im New to Python, it sounds easy- but i cant solve it, nether find a resolution with similar questions.
I have an Array where every row has one value ((...), Hour, Min., Sec., (...) ,D, M, Y) - Example:
arr = np.array([x, x,0, 0, 3, x, x,10, 8, 2022])
How can I conect the rows by ID to create an Data.frame of Date and... | [
"Try:\narr = np.array([-1, -1, 0, 0, 3, -1, -1, 10, 8, 2022])\n\ndf = pd.DataFrame(\n [\n pd.to_datetime(\n f\"{arr[-1]}/{arr[-2]}/{arr[-3]} {arr[-8]}:{arr[-7]}:{arr[-6]}\"\n )\n ],\n columns=[\"DateTime\"],\n)\n\ndf[\"Date\"] = df[\"DateTime\"].dt.strftime(\"%Y/%m/%d\")\ndf[\"Time... | [
1
] | [] | [] | [
"concatenation",
"dataframe",
"datetime",
"extract",
"python"
] | stackoverflow_0074601701_concatenation_dataframe_datetime_extract_python.txt |
Q:
Django/Python "django.core.exceptions.ImproperlyConfigured: Cannot import 'contact'. Check that '...apps.contact.apps.ContactConfig.name' is correct"
Hopefully you all can give me a hand with this...
my work flow:
|.vscode:
|capstone_project_website:
| -_pycache_:
| -apps:
| -_pycache_
| -accounts:... | Django/Python "django.core.exceptions.ImproperlyConfigured: Cannot import 'contact'. Check that '...apps.contact.apps.ContactConfig.name' is correct" | Hopefully you all can give me a hand with this...
my work flow:
|.vscode:
|capstone_project_website:
| -_pycache_:
| -apps:
| -_pycache_
| -accounts:
| -contact: # app that is throwing errors
| -_pycache_:
| -migrations:
| -_init_.py
| -admin.py
| -... | [
"try changing this:\n\nclass ContactConfig(AppConfig):\nname = \"contact\"\n\nto this:\n\nclass ContactConfig(AppConfig):\nname = \"apps.contact\"\n\n",
"Check your django version. If you update your django version to 3.2, try to switch with the earliest one.\n\ndjango==3.1.8\n\n",
"This happens due to python v... | [
13,
2,
0
] | [] | [] | [
"configuration",
"django",
"docker_compose",
"modulenotfounderror",
"python"
] | stackoverflow_0067358268_configuration_django_docker_compose_modulenotfounderror_python.txt |
Q:
How to sum all values with equal dates so that I dont have duplicate date values
I would like to know how can I sum app the values for the same dates only.
(See Picture) like for example I would only like to have every date once with the corresponding values. Since some date are repeating I would like to know how ... | How to sum all values with equal dates so that I dont have duplicate date values | I would like to know how can I sum app the values for the same dates only.
(See Picture) like for example I would only like to have every date once with the corresponding values. Since some date are repeating I would like to know how I can some up the values with the same dates. Above you see the column name
| [
"You can use Groupby.sum with numeric_only=True.\nAssuming df is your dataframe, try this :\ndf.groupby(\"dt_COMP\", as_index=False).sum(numeric_only=True)\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074604110_pandas_python.txt |
Q:
Calculating embedding overload problems with BERT
I'm trying to calculate the embedding of a sentence using BERT. After I input the sentence into BERT, I calculate the Mean-pooling, which is used as the embedding of the sentence.
Problem
My code can calculate the embedding of sentences, but the computational cost ... | Calculating embedding overload problems with BERT | I'm trying to calculate the embedding of a sentence using BERT. After I input the sentence into BERT, I calculate the Mean-pooling, which is used as the embedding of the sentence.
Problem
My code can calculate the embedding of sentences, but the computational cost is very high. I don't know what's wrong and I hope some... | [
"You might be storing sentence embedding in the GPU. Try to move it to cpu before returning it.\n# get the word embedding from BERT\ndef get_word_embedding(text:str):\n input_ids = torch.tensor(tokenizer.encode(text)).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n last_hidden_states = outputs[... | [
0
] | [] | [] | [
"bert_language_model",
"embedding",
"nlp",
"python",
"pytorch"
] | stackoverflow_0074595449_bert_language_model_embedding_nlp_python_pytorch.txt |
Q:
create a dictionary showing connectivity between items of list python
I have a list as:
['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']
I want every element to be connected to element 'Title" before the element.
For example, Text at index 1 is connected to Tit... | create a dictionary showing connectivity between items of list python | I have a list as:
['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']
I want every element to be connected to element 'Title" before the element.
For example, Text at index 1 is connected to Title at index 0, Title at index 2 would not be connected to any element, beca... | [
"You can use a loop:\nl = ['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']\n\nlast = -1\nout = {}\nfor i, v in enumerate(l):\n if v == 'Title':\n last = i\n else:\n out[i] = last\nprint(out)\n\nOutput: {1: 0, 4: 3, 6: 5, 7: 5, 8: 5, 10: 9, 11:... | [
6,
0
] | [
"One way you can do this (not very efficient but I do not have much time at them moment):\nx = ['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']\nd = {}\nfor i, ele in enumerate(x):\n if ele != 'Title':\n d[i] = i - x[:i+1][::-1].index('Title')\n\n>>> pr... | [
-1,
-1
] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074598300_for_loop_list_python.txt |
Q:
python: regex to match pattern on multiple lines (apply to start of string)
I'm trying to create a pattern to match two lines in the following multi-line text:
Text of no interest.
TextOfInterest1, foobar of no interest
another foobar of no interest
AnotherText-of_Interest2 some foobar don't care
I need to match ... | python: regex to match pattern on multiple lines (apply to start of string) | I'm trying to create a pattern to match two lines in the following multi-line text:
Text of no interest.
TextOfInterest1, foobar of no interest
another foobar of no interest
AnotherText-of_Interest2 some foobar don't care
I need to match exactly TextOfInterest1 and AnotherText-of_Interest2, note that there might be mu... | [
"Try this:\npat = r\"^.*\\n([-_\\w]+).*\\n.*\\n([-_\\w]+).*$\"\nstring=\"\"\"Text of no interest.\nTextOfInterest1, foobar of no interest\nanother foobar of no interest\nAnotherText-of_Interest2 some foobar don't care\"\"\"\n\nre.search(pat,string).groups()\n\n('TextOfInterest1', 'AnotherText-of_Interest2')\n\nChec... | [
0
] | [] | [] | [
"python",
"string_matching"
] | stackoverflow_0074604099_python_string_matching.txt |
Q:
Are all JSON strings also syntactically valid Python string literals?
I am writing a JavaScript function that generates a Python program. Can I use JavaScript's JSON.stringify() on a string and expect a valid Python string every time or are there edge cases that mean I have to write my own toPythonString() functio... | Are all JSON strings also syntactically valid Python string literals? | I am writing a JavaScript function that generates a Python program. Can I use JavaScript's JSON.stringify() on a string and expect a valid Python string every time or are there edge cases that mean I have to write my own toPythonString() function?
| [
"The short answer is no.\nThe long answer is in practice, sort of yes. Almost. The difference is that JSON strings can have the forward slash backslash-escaped. So the string \"\\/\" is interpreted by JSON (and JavaScript) as a single forward slash '/' but as a backslash followed by a forward slash by Python '\\\\/... | [
2,
0
] | [] | [] | [
"code_generation",
"json",
"python",
"syntax",
"transpiler"
] | stackoverflow_0070499499_code_generation_json_python_syntax_transpiler.txt |
Q:
Launchd 'Invalid Property List'
I was hoping someone could point out where I might be going wrong with a launchctl script I'm trying to write and launch.
The intention is to run a python script I've managed to get working, everyday at 3.15am. (the computer it's going to run on is on 24/7 but if there is a way to i... | Launchd 'Invalid Property List' | I was hoping someone could point out where I might be going wrong with a launchctl script I'm trying to write and launch.
The intention is to run a python script I've managed to get working, everyday at 3.15am. (the computer it's going to run on is on 24/7 but if there is a way to incorporate this into it's everyday ru... | [
"I think the problem is that you are trying to specify an entire command line as program arguments, rather than specifying the program name separately from its arguments.\n<dict>\n <key>Label</key>\n <string>com.launch.phoneconfig</string>\n <key>Program</key>\n <string>/usr/local/bin/python3</strin... | [
1
] | [] | [] | [
"daemon",
"launchctl",
"launchd",
"plist",
"python"
] | stackoverflow_0074602252_daemon_launchctl_launchd_plist_python.txt |
Q:
Callable modules
Why doesn't Python allow modules to have a __call__ method? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using a(b) syntax find the __call__ attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules... | Callable modules | Why doesn't Python allow modules to have a __call__ method? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using a(b) syntax find the __call__ attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules?)
>>> print(open("mod... | [
"Python doesn't allow modules to override or add any magic method, because keeping module objects simple, regular and lightweight is just too advantageous considering how rarely strong use cases appear where you could use magic methods there.\nWhen such use cases do appear, the solution is to make a class instance ... | [
110,
46,
22,
10,
5,
2,
0
] | [] | [] | [
"module",
"python",
"python_import"
] | stackoverflow_0001060796_module_python_python_import.txt |
Q:
Running Jupyter Notebook in GCP on a Schedule
What is the best way to migrate a jupyter notebook in to Google Cloud Platform?
Requirements
I don't want to do a lot of changes to the notebook to get it to run
I want it to be scheduleable, preferably through the UI
I want it to be able to run a ipynb file, not a py... | Running Jupyter Notebook in GCP on a Schedule | What is the best way to migrate a jupyter notebook in to Google Cloud Platform?
Requirements
I don't want to do a lot of changes to the notebook to get it to run
I want it to be scheduleable, preferably through the UI
I want it to be able to run a ipynb file, not a py file
In AWS it seems like sagemaker is the no brai... | [
"I use Vertex AI Workbench to run notebooks on GCP. It provides two variants:\n\nManaged Notebooks\nUser-managed Notebooks\n\nUser-managed notebooks creates compute instances at the background and it comes with pre-built packages such as Jupyter Lab, Python, etc and allows customisation. I mainly use for developing... | [
1
] | [] | [] | [
"google_cloud_platform",
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0074603301_google_cloud_platform_jupyter_jupyter_notebook_python.txt |
Q:
[Azure SDK Python]How to check if a subnet has available IPs?
is there a way in Azure SDK Python to check if a subnet has still available IPs?
We need this info because we dinamically deploy VMs in different subnets and we have to know if there is still network availabiliy before provisioning in that subnet.
I tri... | [Azure SDK Python]How to check if a subnet has available IPs? | is there a way in Azure SDK Python to check if a subnet has still available IPs?
We need this info because we dinamically deploy VMs in different subnets and we have to know if there is still network availabiliy before provisioning in that subnet.
I tried to search on SO and on Azure docs but with no success.
I've just... | [
"I do not think Azure Python SDK offers such functionality out of the box; you can create a feedback item for this on the Azure Python SDK repository.\nIf it helps Azure Python SDK does offer a check_ip_address_availability module but it only validates if a given single private IP address is available for use. You ... | [
1
] | [] | [] | [
"azure",
"azure_sdk_python",
"azure_virtual_machine",
"azure_virtual_network",
"python"
] | stackoverflow_0074573188_azure_azure_sdk_python_azure_virtual_machine_azure_virtual_network_python.txt |
Q:
Extract the extra fields in logging call in log formatter
so I can add additional fields to my log message like so
logging.info("My log Message", extra={"someContext":1, "someOtherContext":2})
which is nice
but unclear how to extract all the extra fields in my log formatter
def format(self, record):
record_di... | Extract the extra fields in logging call in log formatter | so I can add additional fields to my log message like so
logging.info("My log Message", extra={"someContext":1, "someOtherContext":2})
which is nice
but unclear how to extract all the extra fields in my log formatter
def format(self, record):
record_dict = record.__dict__.copy()
print(record_dict)
in the above ... | [
"Two approaches come to mind:\n\nDump all of the extra fields into a dictionary within your main dictionary. Call the key \"additionalContext\" and get all the extra entries.\nCreate a copy of the original dictionary and delete all of your known keys: 'name','msg','args', etc. until you only have justYourExtra \n\n... | [
2,
1,
0
] | [] | [] | [
"logging",
"python",
"python_3.x"
] | stackoverflow_0059176101_logging_python_python_3.x.txt |
Q:
How to solve a Knapsack problem with extra constraints? (Or alternative algorithms)
Expanding upon a common dynamic programming solution for the knapsack problem:
def knapSack(W, wt, val, n):
results = []
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build tаble K[][] in bоttоm uр mаnner
... | How to solve a Knapsack problem with extra constraints? (Or alternative algorithms) | Expanding upon a common dynamic programming solution for the knapsack problem:
def knapSack(W, wt, val, n):
results = []
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build tаble K[][] in bоttоm uр mаnner
for i in range(n + 1):
for w in range(W + 1):
if (i == 0) or (w == ... | [
"Based on the top comment I found a package that is very fast and allows for this:\nfrom mip import Model, xsum, maximize, BINARY\n\nall = pd.read_csv('df_all.csv')\nX = pd.read_csv('df_x_only.csv')\nY = pd.read_csv('df_y_only.csv')\n\np = all.id.values # as we arent optimizing the value of the index, p is irreleva... | [
2
] | [] | [] | [
"knapsack_problem",
"matching",
"mathematical_optimization",
"optimization",
"python"
] | stackoverflow_0074602059_knapsack_problem_matching_mathematical_optimization_optimization_python.txt |
Q:
Python-check if the input which is a two lists of numbers from the user contains only numbers (all types, including fractions and negative numbers)
(in Python 3)
I neet to check if the input which is two lists of numbers from the user contains only numbers and than calculate pearson corelation.
requierments:
-All ... | Python-check if the input which is a two lists of numbers from the user contains only numbers (all types, including fractions and negative numbers) | (in Python 3)
I neet to check if the input which is two lists of numbers from the user contains only numbers and than calculate pearson corelation.
requierments:
-All types of numbers, including fractions and negative numbers.
-The user can type extra spaces or no spaces at all, it shouldn't metter.
-There must be a co... | [
"Try and except statements must be used if any unexpected input is given by user\ntry:\n list1=input(\"Enter list 1\")\n list2=input(\"Enter list 2\")\n lst1=list(map(float,[x.strip() for x in list1.split(',')]))\n lst2=list(map(float,[x.strip() for x in list2.split(',')]))\n corelation_function(list... | [
0
] | [] | [] | [
"input",
"python",
"type_conversion"
] | stackoverflow_0074603729_input_python_type_conversion.txt |
Q:
How to use pandas list as variable in SQL query using python?
I am using the Pandas library on Python and was wondering if there is a way to use a list variable (or perhaps series is better?), let's say uID_list, in an SQL query that is also executed within the same Python code. For example:
dict = {'a': 1, 'b': 2... | How to use pandas list as variable in SQL query using python? | I am using the Pandas library on Python and was wondering if there is a way to use a list variable (or perhaps series is better?), let's say uID_list, in an SQL query that is also executed within the same Python code. For example:
dict = {'a': 1, 'b': 2, 'c':3}
uID_series = pd.Series(data=dict, index=['a','b','c'])
uID... | [
"Are you just trying to pull the data? Will be easier outside of a stored procedure\nl1 = ['ad', 'dfgdf', 'htbgf', 'dtghyt']\n\nl1_str = \"('\" + \"', '\".join([str(item) for item in l1]) + \"')\"\n\n\nsql = \nf'''\n SELECT username\n FROM users_table\n WHERE uID in {l1_str}\n'''\n\n\n",
"You can start b... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"sql"
] | stackoverflow_0074603789_pandas_python_sql.txt |
Q:
Need update value passed by render_template with flask in html template td tag every 10 seconds
I have this:
@views.route('/')
def home():
while True:
try:
token=getToken()
if(token!='null' or token!=''):
plazas=getInfo(token,id)
except:
print... | Need update value passed by render_template with flask in html template td tag every 10 seconds | I have this:
@views.route('/')
def home():
while True:
try:
token=getToken()
if(token!='null' or token!=''):
plazas=getInfo(token,id)
except:
print('Conection failed')
time.sleep(secs)
return render_template("home.html", plazas... | [
"To refresh it with new text, you can fetch to your own flask route and update the information using setInterval\nHTML\n<td id=\"num\" style=\"color:#39FF00\">{{plazas}}</td>\n<script>\nvar element = document.findElementById(\"num\")\nasync function reload() {\n const promise = await fetch('/myroute')\n const dat... | [
2
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0074600858_flask_jinja2_python.txt |
Q:
How can adjust the size of doughnut chart using python's pptx module
I want to have multiple doughnut charts (max 3) using python's pptx module. As of now I'm able to add only one chart, how can I reduce the size of the doughnuts accordingly so that I can adjust 2 or 3 charts in one slide.
Also, how can I auto adj... | How can adjust the size of doughnut chart using python's pptx module | I want to have multiple doughnut charts (max 3) using python's pptx module. As of now I'm able to add only one chart, how can I reduce the size of the doughnuts accordingly so that I can adjust 2 or 3 charts in one slide.
Also, how can I auto adjust the size of doughnuts depending on number of graphs with different set... | [
"As you insert the chart, you can specify its position and size, as you already do:\nx, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)\nslide1.shapes.add_chart(XL_CHART_TYPE.DOUGHNUT, x, y, cx, cy, chart_data)\n\nIn the code above x and y are the coordinates of the top left corner of the chart, while cx a... | [
1
] | [] | [] | [
"aspose_slides",
"powerpoint",
"python",
"python_3.x",
"python_pptx"
] | stackoverflow_0074559304_aspose_slides_powerpoint_python_python_3.x_python_pptx.txt |
Q:
Pivot a dataframe keeping all the columns and assigning suffixes and values to each column based on another column
I have searched across SO and the internet but the closest I have gotten to my answer is that I may need to implement df.pivot(). However I can't seem to figure out what should I pass in the values an... | Pivot a dataframe keeping all the columns and assigning suffixes and values to each column based on another column | I have searched across SO and the internet but the closest I have gotten to my answer is that I may need to implement df.pivot(). However I can't seem to figure out what should I pass in the values and columns parameters in order to achieve the expected result.
Initial dataframe:
pd.DataFrame(
{'Date': ['8-Sep-22',
... | [
"Here is what you want to do to get the desired output:\nPivot the df, then sort the columns by level 1, which is A,B,C,.... Then join the multicolumn index to one level in the format you want.\nout = (\n df\n .pivot(index='Date', \n columns='CLASS', \n values=['CCY','SZE(M)','WAL','DR','T... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074604240_dataframe_pandas_python.txt |
Q:
Return the name of the maximum value for every column using Pandas
I am new to using Python and I am trying to use pandas to return the value of a name column for the name which has the maximum average grouped value for every numeric column.
Using the Pokemon dataset as an example, the below code loads the data.
i... | Return the name of the maximum value for every column using Pandas | I am new to using Python and I am trying to use pandas to return the value of a name column for the name which has the maximum average grouped value for every numeric column.
Using the Pokemon dataset as an example, the below code loads the data.
import pandas as pd
url = "https://raw.githubusercontent.com/UofGAnalytic... | [
"You can just add idxmax in the agg() method :\ndf4.groupby(\"Type 1\")[[\"Total\", \"HP\", \"Attack\", \"Defense\", \"Sp. Atk\", \"Sp. Def\", \"Speed\"]].agg(\"mean\").agg([\"max\", \"idxmax\"])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074604222_dataframe_pandas_python.txt |
Q:
Alphabetically sort with Python?
I am aware of the sorted() function but I am having a little trouble using it/implementing it in my code. I have a database containing student records such as Name, address, age etc. When the user selects "4" the program runs the function to Display all records saved in the databa... | Alphabetically sort with Python? | I am aware of the sorted() function but I am having a little trouble using it/implementing it in my code. I have a database containing student records such as Name, address, age etc. When the user selects "4" the program runs the function to Display all records saved in the database and I desire it to be sorted alphab... | [
"You already know you need the sorted function. Think about what you need to sort: all the records in your csv file, and the key to use to sort: Let's say by last name and then first name. See the documentation for more detail on the key argument to sorted. Since you want to sort by two items, you can create a tupl... | [
0,
0,
0
] | [] | [] | [
"alphabetical",
"python",
"sorting"
] | stackoverflow_0074604275_alphabetical_python_sorting.txt |
Q:
A way to detect empty cells in CSV and replace them with NULL in sql query
I have a dynamic csv file with cells that start out empty but over time will get filled with values. To get this csv file into a database I convert it on the fly to sql and upload to my database, however, empty cells in the CSV file are sho... | A way to detect empty cells in CSV and replace them with NULL in sql query | I have a dynamic csv file with cells that start out empty but over time will get filled with values. To get this csv file into a database I convert it on the fly to sql and upload to my database, however, empty cells in the CSV file are showing up with empty values in the database but are not set to NULL. Is there a wa... | [
"You could do the following:\nfor row in csv_data: \n if row['data_value'] == \"\" or row['data_value'] == \" \":\n row['data_value'] == None\n # row['data_value'] == \"Null\"\n else:\n cur.execute()\n\n"
] | [
0
] | [] | [] | [
"csv",
"database",
"mysql_python",
"python"
] | stackoverflow_0074595240_csv_database_mysql_python_python.txt |
Q:
How to permanently save a variable (login information)
I am trying to code a username and password system and was wondering if there was any way to save the variable so even when the code stops the username will work the next time.
I have not yet started coding it and was just wondering if this was possible. I saw... | How to permanently save a variable (login information) | I am trying to code a username and password system and was wondering if there was any way to save the variable so even when the code stops the username will work the next time.
I have not yet started coding it and was just wondering if this was possible. I saw a few things on saving it as a file but with no luck. Thank... | [
"You can try appending them to a file instead of writing a new one for each user. So each time a user logs in the creds will be saved to that file. This is what I have done in the past.\n",
"You can automaticly save everything in a simple text file.\nfile = open(\"Python.txt\", \"w\")\n\nmake sure the .txt exists... | [
0,
0,
0
] | [] | [] | [
"passwords",
"python",
"save",
"variables"
] | stackoverflow_0074604400_passwords_python_save_variables.txt |
Q:
Python) How to copy a row and paste it to all rows in another dataframe
How can I extract a specific row and paste it to all rows in another dataframe?
For example, when I have two dataframes as below:
df1={'category': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']}
df1=pd.DataFrame(df1)
df2={'value 1': [1, 1, 2,... | Python) How to copy a row and paste it to all rows in another dataframe | How can I extract a specific row and paste it to all rows in another dataframe?
For example, when I have two dataframes as below:
df1={'category': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']}
df1=pd.DataFrame(df1)
df2={'value 1': [1, 1, 2, 5, 3, 4, 4, 8, 7],
'value 2': [4, 2, 8, 5, 7, 9, 3, 4, 2]}
df2=pd.DataFr... | [
"Example #1: Create two data frames and append the second to the first one.\n# Importing pandas as pd\nimport pandas as pd\n\n# Creating the first Dataframe using dictionary\ndf1 = df = pd.DataFrame({\"a\":[1, 2, 3, 4],\n \"b\":[5, 6, 7, 8]})\n\n# Creating the Second Dataframe using dictionary\nd... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074604338_dataframe_pandas_python.txt |
Q:
Python Dataframes merge multi match
I'm new with Dataframe.
I would like to kwon how (if possible) can I merge 2 Dataframes with multiple match
For example
[df1]
date ZipCode Weather
2022-11-25 00:00:00 123456 34
2022-11-25 00:00:15 123456 35
2022-11-25 00:00:30 123456 36
[df2]
date ... | Python Dataframes merge multi match | I'm new with Dataframe.
I would like to kwon how (if possible) can I merge 2 Dataframes with multiple match
For example
[df1]
date ZipCode Weather
2022-11-25 00:00:00 123456 34
2022-11-25 00:00:15 123456 35
2022-11-25 00:00:30 123456 36
[df2]
date ZipCode host
2022-11-2... | [
"You could use the join function in pandas which joins one dataframe's index to the index of the other. Try something like\nimport pandas as pd\n\ndata1 = \\\n[['2022-11-25 00:00:00', 123456, 34],\n['2022-11-25 00:00:15', 123456, 35],\n['2022-11-25 00:00:30', 123456, 36]]\n\ncolumns1 =['date', 'ZipCode', 'Weathe... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"merge",
"multiple_columns",
"python"
] | stackoverflow_0074598005_dataframe_merge_multiple_columns_python.txt |
Q:
How to download Instagram reels, image, dp and stories using python without session?
I am trying to make instagram content downloader like this this website. But the problem is python wants cookies sessions id.
I want to download instagram reels, image, dp, stories, without session id.
A:
The question is not rel... | How to download Instagram reels, image, dp and stories using python without session? | I am trying to make instagram content downloader like this this website. But the problem is python wants cookies sessions id.
I want to download instagram reels, image, dp, stories, without session id.
| [
"The question is not related to Python generally.\nIf you want to scrape data from Instagram you have to pass session keys and simulate real client connection (try https://github.com/chris-greening/instascrape or similar libraries).\nOr you can use official Instagram Graph API (https://developers.facebook.com/docs/... | [
0
] | [] | [] | [
"instagram",
"python",
"python_3.x"
] | stackoverflow_0074604541_instagram_python_python_3.x.txt |
Q:
Is there a way to enumerate rows in temporal pandas data frame according to the date of an action?
I have a data frame with temporal data. Each row represents a purchase of a customer. It looks similar to this:
cli_id
date
item_purchased
1
2017-01-01
A
2
2017-01-04
C
3
2017-01-03
B
1
2017-02-01
B
2
2017-01-3... | Is there a way to enumerate rows in temporal pandas data frame according to the date of an action? | I have a data frame with temporal data. Each row represents a purchase of a customer. It looks similar to this:
cli_id
date
item_purchased
1
2017-01-01
A
2
2017-01-04
C
3
2017-01-03
B
1
2017-02-01
B
2
2017-01-31
B
3
2017-02-02
A
1
2017-02-15
A
2
2017-02-10
A
3
2017-02-16
C
2
2017-02-20
B
I... | [
"You can use GroupBy.cumcount.\ndf['date'] = pd.to_datetime(df['date'])\n\ndf= (\n df\n .join((df.sort_values(by=[\"cli_id\", \"date\"])\n .groupby(\"cli_id\").cumcount()+1)\n .to_frame(\"purchase_order\")) \n )\n\n# Output :\nprint(df)\n\n cli_id date ... | [
1
] | [] | [] | [
"dataframe",
"date",
"pandas",
"python"
] | stackoverflow_0074604399_dataframe_date_pandas_python.txt |
Q:
regex for repeating word to repeating two words
I am trying to write some regex pattern that will look through a sentence and remove any one or two sequentially repeated words
for example:
# R code below
string_a = "hello hello, how are you you?"
string_b = "goodbye world goodbye world, I am flying to the the moon... | regex for repeating word to repeating two words | I am trying to write some regex pattern that will look through a sentence and remove any one or two sequentially repeated words
for example:
# R code below
string_a = "hello hello, how are you you?"
string_b = "goodbye world goodbye world, I am flying to the the moon!"
gsub(pattern, "", string_a)
gsub(pattern, "", str... | [
"Try\n gsub(\"(\\\\S+(\\\\s+\\\\S+)?)\\\\s+\\\\1+\", \"\\\\1\", c(string_a, string_b))\n\n-output\n[1] \"hello, how are you?\" \n[2] \"goodbye world, I am flying to the moon!\"\n\n"
] | [
3
] | [] | [] | [
"javascript",
"python",
"r",
"regex"
] | stackoverflow_0074604589_javascript_python_r_regex.txt |
Q:
Is it possible to create a Rest API using Jupyter notebook?,if yes How to create Rest API for the following code interms of json format
I have built a model for the time series analysis which is going to predict the sail for the next days,the model is working fine,but i want to convert that into Rest API in JSON f... | Is it possible to create a Rest API using Jupyter notebook?,if yes How to create Rest API for the following code interms of json format | I have built a model for the time series analysis which is going to predict the sail for the next days,the model is working fine,but i want to convert that into Rest API in JSON format using the Anaconda jupyter notebook,Please let me know the way for that .Thanks in advance.
Here is the code:
from pandas import Series... | [
"There are hopeful google search results for this problem found by 'jupyter notebook rest api', e.g. https://blog.ouseful.info/2017/09/06/building-a-json-api-using-jupyer-notebooks-in-under-5-minutes/\nHave you tried using kernelgateway?\n",
"If you can install jupyter server proxy, this project allows to impleme... | [
3,
0,
0
] | [] | [] | [
"jupyter_notebook",
"mysql",
"python",
"time_series"
] | stackoverflow_0051018536_jupyter_notebook_mysql_python_time_series.txt |
Q:
Is one way of returning a user-input value, using a try-except clause, better than the other?
For context, I am new to Python, and somewhat new to programming in general. In CS50's "Little Professor" problem (details here, but not needed: https://cs50.harvard.edu/python/2022/psets/4/professor/) my program passes a... | Is one way of returning a user-input value, using a try-except clause, better than the other? | For context, I am new to Python, and somewhat new to programming in general. In CS50's "Little Professor" problem (details here, but not needed: https://cs50.harvard.edu/python/2022/psets/4/professor/) my program passes all correctness checks; but, unfortunately, programs aren't checked for efficiency, style or "cleanl... | [
"Generally, you should put as little code as possible inside a try, so that you don't misconstrue an unrelated error as the one you're expecting. It also makes sense to separate the code that obtains the level from the code that acts on it, so that level has known validity for as much code as possible. Both of th... | [
1
] | [] | [] | [
"python",
"try_except"
] | stackoverflow_0073992584_python_try_except.txt |
Q:
How to connect with oracle database?
I am using this code to connect with oracle database:
import cx_Oracle
conn_str = u"jbdc:oracle:thin:@****_***.**.com"
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
However, I am getting this error:
ORA-12560: TNS:protocol adapter error
How can I resolve it?
Thank you... | How to connect with oracle database? | I am using this code to connect with oracle database:
import cx_Oracle
conn_str = u"jbdc:oracle:thin:@****_***.**.com"
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
However, I am getting this error:
ORA-12560: TNS:protocol adapter error
How can I resolve it?
Thank you
| [
"You cannot use a JDBC thin connect string to connect with cx_Oracle (or the new python-oracledb). You must use either an alias found in a tnsnames.ora file, or the full connect descriptor (such as that found in a tnsnames.ora) file or an EZ+ Connect string. An example follows:\nconn_str = \"user/password@host:port... | [
1
] | [] | [] | [
"cx_oracle",
"python"
] | stackoverflow_0074604565_cx_oracle_python.txt |
Q:
Is it possible to convert a sympy expression to a pyomo expression?
I'm currently using sympy to parse a string equation and replace the variables with either values or Pyomo variables:
model = pe.ConcreteModel()
model.flow = pe.Var()
DEMAND = 100
equation = sympify('10 * DEMAND * FLOW', evaluate=False)
updated... | Is it possible to convert a sympy expression to a pyomo expression? | I'm currently using sympy to parse a string equation and replace the variables with either values or Pyomo variables:
model = pe.ConcreteModel()
model.flow = pe.Var()
DEMAND = 100
equation = sympify('10 * DEMAND * FLOW', evaluate=False)
updated_equation = equation.subs('DEMAND', DEMAND).subs('FLOW', model.flow)
Doe... | [
"Yes: if you look in pyomo.core.expr.sympy_tools, there are two methods:\n\nsympyify_expression(expr) will take a Pyomo expression and return a sympy expression, with all Pyomo Var objects replaced by sympy real Symbols, along with a PyomoSympyBimap object that maps the Pyomo Var objects to the corresponding sympy ... | [
3
] | [] | [] | [
"pyomo",
"python",
"sympy"
] | stackoverflow_0074601162_pyomo_python_sympy.txt |
Q:
How to split at uppercase and brackets
I'm trying to parse lyrics site and I need to collect song's lyrics. I have issues with my output
I need to have lyrics displayed as below enter image description here
I've figured out how to split text at uppercase, but there is one thing remains: the brackets are splitted u... | How to split at uppercase and brackets | I'm trying to parse lyrics site and I need to collect song's lyrics. I have issues with my output
I need to have lyrics displayed as below enter image description here
I've figured out how to split text at uppercase, but there is one thing remains: the brackets are splitted unproperly, here's my code:
import re
import ... | [
"As brackets have a meaning in regex you'll need to escape them. In python you should be able to use \\[ to get what you want.\n",
"You can .unwrap unnecessary tags (<a>, <span>), replace <br> with newlines and then get text:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://genius.com/Taylor-swi... | [
0,
0
] | [] | [] | [
"parsing",
"python",
"python_3.x",
"split"
] | stackoverflow_0074603507_parsing_python_python_3.x_split.txt |
Q:
Largest Perimeter Triangle Leetcode Problem Python
I have given the mentioned problem quite a thought but was not able to come up with a working solution on my own. So I found the following solution, but I want to understand why does it work. Here it is:
class Solution:
def largestPerimeter(self, nums: List[in... | Largest Perimeter Triangle Leetcode Problem Python | I have given the mentioned problem quite a thought but was not able to come up with a working solution on my own. So I found the following solution, but I want to understand why does it work. Here it is:
class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
# triange in-equality a+b > c
... | [
"\nBut isn`t this condition true for any value of a?\n\nNo, that condition is false for any value of a.\nIn the first iteration, a + b > c will resolve to n0 + inf > inf. Now, n0 + inf returns inf for any integer n0, so inf > inf is false.\nAlso, in the second iteration, you will have n1 + n0 > inf, which is also a... | [
0
] | [] | [] | [
"greedy",
"python"
] | stackoverflow_0074604424_greedy_python.txt |
Q:
Why a norm distribution does not plot a line on stats.probplot()?
The problem is with the resultant graph of function scipy.stats.probplot().
Samples from a normal distribution doesn't produce a line as expected.
I am trying to normalize some data using graphs as guidance.
However, after some strange results showi... | Why a norm distribution does not plot a line on stats.probplot()? | The problem is with the resultant graph of function scipy.stats.probplot().
Samples from a normal distribution doesn't produce a line as expected.
I am trying to normalize some data using graphs as guidance.
However, after some strange results showing that zscore and log transformations were having no effect, I started... | [
"Your synthesized data aren't normally distributed, they are uniformly distributed, this is what numpy.linspace() does. You can visualize this by adding seaborn.distplot(x, fit=scipy.stats.norm).\nimport math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\nimport seaborn as sns\n\n\... | [
0
] | [] | [] | [
"data_cleaning",
"feature_engineering",
"plot",
"python",
"scipy.stats"
] | stackoverflow_0074501950_data_cleaning_feature_engineering_plot_python_scipy.stats.txt |
Q:
Cost efficient way to test scalability of RS485 Modbus device read operation
We are fairly new to Modbus and RS485 communication and are currently in the process of writing a Python application to read specified registers from multiple smart meters. Our final python script shall be able to read registers from up t... | Cost efficient way to test scalability of RS485 Modbus device read operation | We are fairly new to Modbus and RS485 communication and are currently in the process of writing a Python application to read specified registers from multiple smart meters. Our final python script shall be able to read registers from up to 50-200 smart meters at a time via RS485 using Modbus.
For testing, performance a... | [
"In my opinion, there is no real need for testing. But you need to take into account several factors that you seem not to be aware of.\nConsider the following:\n\nHow many registers are you going to read from each meter? You can read a couple of registers (for instance, just total power) or many (50-100 or more if ... | [
0
] | [] | [] | [
"modbus",
"python",
"raspberry_pi",
"rs485",
"smartmeter"
] | stackoverflow_0074521448_modbus_python_raspberry_pi_rs485_smartmeter.txt |
Q:
Anaconda numpy: how to enable multiprocessing?
I am trying to enable multithreading/multiprocessing in an Anaconda installation of Numpy. My test program is the following:
import os
import numpy as np
from timeit import timeit
size = 1024
A = np.random.random((size, size)),
B = np.random.random((size, size))
prin... | Anaconda numpy: how to enable multiprocessing? | I am trying to enable multithreading/multiprocessing in an Anaconda installation of Numpy. My test program is the following:
import os
import numpy as np
from timeit import timeit
size = 1024
A = np.random.random((size, size)),
B = np.random.random((size, size))
print 'Time with %s threads: %f s' \
%(os.environ.... | [
"If you want to build parallel processing, you will have to break down the problem and use python's multi-threading or multi-processing tools to implement it. Here is a scipy doc on how to get started.\nIf you need to do more sophisticated calculations you can also consider using mpi4py. If most of your calculation... | [
0
] | [] | [] | [
"anaconda",
"anaconda3",
"numpy",
"openblas",
"python"
] | stackoverflow_0074603345_anaconda_anaconda3_numpy_openblas_python.txt |
Q:
Python storing output as variable
I'm working on some data parsing from text files, by running a for-loop/conditionacross the files and writing output to result file. I then run another for-loop on that result file to parse it further.
Is there a way to store this result in a variable rather than a file?
| Python storing output as variable | I'm working on some data parsing from text files, by running a for-loop/conditionacross the files and writing output to result file. I then run another for-loop on that result file to parse it further.
Is there a way to store this result in a variable rather than a file?
| [] | [] | [
"Yes but more context on what you want to accomplish would be helpful.\nSee below for what I think you want. This loop iterates over each item and then appends each one to a list which contains all outputs\nlst = []\nfor x in range(0,5):\n y = x\n lst.append(y)\n\n"
] | [
-1
] | [
"parsing",
"python",
"python_3.x"
] | stackoverflow_0074604797_parsing_python_python_3.x.txt |
Q:
how to ask a function to do something specific in its last call without using the help of the items in a for loop?
I have a complicated code of several classes and functions. one of the functions is called n times and I need to do something specific in the last call of the function. It is too complicated to use th... | how to ask a function to do something specific in its last call without using the help of the items in a for loop? | I have a complicated code of several classes and functions. one of the functions is called n times and I need to do something specific in the last call of the function. It is too complicated to use the iteratble of the for loop.
I need something that knows that this is the last call of the function, then it does what I... | [
"The function itself does not know and should not care about the context in which it is called. If you want the behavior to change, you do that by passing an appropriate argument.\nIn this case, perhaps the other multiplicand should be a second argument; it can default to 2, but the caller should be responsible for... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074604805_python.txt |
Q:
Pairing mutual values based on different column in Pandas
Suppose I have the next Data Set
NAME FRIEND
--------------
John Ella
John Ben
Ella John
Ella Ben
Dave Ben
...
More Values
I want to get a list of the mutual friends of John, Ella and Dave.
In ... | Pairing mutual values based on different column in Pandas | Suppose I have the next Data Set
NAME FRIEND
--------------
John Ella
John Ben
Ella John
Ella Ben
Dave Ben
...
More Values
I want to get a list of the mutual friends of John, Ella and Dave.
In this example the output should be ['Ben'].
I've tried achieving... | [
"You can use a crosstab:\nct = pd.crosstab(df['NAME'], df['FRIEND'])\n\nout = ct.columns[ct.all()].to_list()\n\nOr with set operations:\ns = df.groupby('FRIEND')['NAME'].agg(set)\nout = s.index[s.eq(set(df['NAME']))].to_list()\n\nOutput: ['Ben']\nIntermediate crosstab:\nFRIEND Ben Ella John\nNAME ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074604816_dataframe_pandas_python.txt |
Q:
Selenium Data scraping issue, unproper data scrapped
I am trying to scrape data from:- https://www.canadapharmacy.com/
below are a few pages that I need to scrape:-
https://www.canadapharmacy.com/products/abilify-tablet,
https://www.canadapharmacy.com/products/accolate,
https://www.canadapharmacy.com/products/abil... | Selenium Data scraping issue, unproper data scrapped | I am trying to scrape data from:- https://www.canadapharmacy.com/
below are a few pages that I need to scrape:-
https://www.canadapharmacy.com/products/abilify-tablet,
https://www.canadapharmacy.com/products/accolate,
https://www.canadapharmacy.com/products/abilify-mt
I need all the information from the page. I wrote t... | [
"Note: it's usually more reliable to build a list of dictionaries [rather than separate lists like you are in the selenium version.]\n\nWithout a sample/mockup of your desired output, I can't be sure this is the exact format you'd want it in, but I'd suggest something like this solution using requests+bs4 [on the 3... | [
1
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074601118_beautifulsoup_pandas_python_selenium_web_scraping.txt |
Q:
How to write Python if else in single line?
category.is_parent = True if self.request.get('parentKey') is not None else category.is_parent = False
Above is the code in which I am trying to write a if else in a single line and it is giving me this syntax error
SyntaxError: can't assign to conditional expression"
... | How to write Python if else in single line? | category.is_parent = True if self.request.get('parentKey') is not None else category.is_parent = False
Above is the code in which I am trying to write a if else in a single line and it is giving me this syntax error
SyntaxError: can't assign to conditional expression"
But if I write it in following way it works fine... | [
"Try this:\ncategory.is_parent = True if self.request.get('parentKey') else False\n\nTo check only against None:\ncategory.is_parent = True if self.request.get('parentKey') is not None else False\n\n",
"You can write:\ncategory.is_parent = True if self.request.get('parentKey') is not None else False\nOr even simp... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0040810139_python.txt |
Q:
How to list down all available python versions in my windows
When I type py --list in my cmd, it shows
C:\Users\Administrator>py --list
Installed Pythons found by py Launcher for Windows
-3.9-64 *
-3.8-64
But when I use the command python it shows Python 3.10.6
C:\Users\Administrator>python
Python 3.10.6 (main,... | How to list down all available python versions in my windows | When I type py --list in my cmd, it shows
C:\Users\Administrator>py --list
Installed Pythons found by py Launcher for Windows
-3.9-64 *
-3.8-64
But when I use the command python it shows Python 3.10.6
C:\Users\Administrator>python
Python 3.10.6 (main, Aug 12 2022, 18:00:29) [GCC 12.1.0 64 bit (AMD64)] on win32
Type... | [
"Use py -0 to find all installed versions of python on your PC.\nWallbloggerbeing explained how to change your default.\n",
"Advanced System Settings > Advance (tab) . On the bottom you'll find 'Environment Variables'\nDouble-click on the Path . You'll see path to one of the python installations, change that to p... | [
2,
1
] | [] | [] | [
"python",
"version"
] | stackoverflow_0074604557_python_version.txt |
Q:
Accessing training data during tensorflow graph execution
I'd like to use pre-trained sentence embeddings in my tensorflow graph execution model. The embeddings are available dynamically from a function call, which takes in an array of sentences and outputs an array of sentence embeddings. This function uses a pre... | Accessing training data during tensorflow graph execution | I'd like to use pre-trained sentence embeddings in my tensorflow graph execution model. The embeddings are available dynamically from a function call, which takes in an array of sentences and outputs an array of sentence embeddings. This function uses a pre-trained pytorch model so has to remain separate from the tenso... | [
"Tensorflow compiles models to an execution graph before performing the actual training process. The obvious side-effect that clues us into this is if we have a regular Python print() statement in e.g. our call() method, it will only get executed once as Tensorflow runs through your code to construct the execution ... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0066681053_keras_python_tensorflow.txt |
Q:
in nested dictionary dynamically test if the value is a dictionary or a dictionary list
I iterate through a nested dictionary taken from a json including one of the keys ("price") and sometimes a list sometimes a dictionary.
Data={"main": {"sub_main": [
{"id": "995", "item": "850", "price": {"ref": "razorb... | in nested dictionary dynamically test if the value is a dictionary or a dictionary list | I iterate through a nested dictionary taken from a json including one of the keys ("price") and sometimes a list sometimes a dictionary.
Data={"main": {"sub_main": [
{"id": "995", "item": "850", "price": {"ref": "razorback", "value": "250"}},
{"id": "953", "item": "763", "price": [{"ref": "razorback", "val... | [
"I hope I've understood your question right. In this code I distinguish if item['price'] is dict/list and create a new dict from ref/value keys:\nData = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref... | [
1,
0
] | [] | [] | [
"dictionary",
"list_comprehension",
"nested",
"python"
] | stackoverflow_0074604238_dictionary_list_comprehension_nested_python.txt |
Q:
Python turtle module
I'm currently new to python programming. Nowadays I'm building a snake game using the turtle module. I want to refresh the screen after every piece of snake object parts has moved. So I turned off the tracer and use the update function after the for loop.
But to do that I must import the time ... | Python turtle module | I'm currently new to python programming. Nowadays I'm building a snake game using the turtle module. I want to refresh the screen after every piece of snake object parts has moved. So I turned off the tracer and use the update function after the for loop.
But to do that I must import the time module and use the time.sl... | [
"What you describe is possible, but the problem isn't lack of use of the sleep() function but rather your use of (effectively) while True: which has no place in an event-driven world like turtle. Let's rework your code using ontimer() events and make the snake's basic movement a method of the snake itself:\nfrom t... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_turtle"
] | stackoverflow_0074580169_python_python_3.x_python_turtle.txt |
Q:
Python Need to build models for Linear regression and Decision Tree
I am trying to train the model
TreeReg = DecisionTreeRegressor()
TreeReg.fit(X_train, y_train)
y_pred_Train = TreeReg.predict(X_train) #predictions on Training set
y_pred_Test = TreeReg.predict(X_test) #predictions on testing set
It's giving me ... | Python Need to build models for Linear regression and Decision Tree | I am trying to train the model
TreeReg = DecisionTreeRegressor()
TreeReg.fit(X_train, y_train)
y_pred_Train = TreeReg.predict(X_train) #predictions on Training set
y_pred_Test = TreeReg.predict(X_test) #predictions on testing set
It's giving me an error message: ValueError: could not convert string to float: '3/1/201... | [
"Linear models need continuous values, (example 4 or 3.5)\nYou're passing a datetime/string value into it and model can't use this.\nThe model you used converts each line to a float value. Since that datetime thing can't converted to a float it raises an error.\nIf your all column Is like that value, a datetime col... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074604988_python.txt |
Q:
Jinja elif not working even though condition is true
The fourth elif statement is the one causing me the issue. I have swapped the third elif statement with the fourth and every time the fourth is in third place it works.
{% block content%}
{% load static %}
<link rel="stylesheet" href="{% static 'css/home_page.c... | Jinja elif not working even though condition is true | The fourth elif statement is the one causing me the issue. I have swapped the third elif statement with the fourth and every time the fourth is in third place it works.
{% block content%}
{% load static %}
<link rel="stylesheet" href="{% static 'css/home_page.css' %}">
<link rel="stylesheet" href="{% static 'css/home_... | [
"You can't do:\n{% elif first_hour_d == 'overcast clouds' or 'broken clouds' %}\n\nbecause the second string will always evaluate to True.\nYou must do:\n{% elif first_hour_d == 'overcast clouds' or first_hour_d == 'broken clouds' %}\n\n"
] | [
1
] | [] | [] | [
"django",
"jinja2",
"python"
] | stackoverflow_0074605002_django_jinja2_python.txt |
Q:
how to make one dictionary from several arrays. PYTHON
I want to make one dictionary out of several arrays in a loop
a = ["hello","hi"]
b = ["day","night"]
#And these arrays were transformed into a dictionary
c = {"a": "hello, hi", "b": "day, night"}
dictt = dict.fromkeys(a, b)
print(dictt)
A:
What you want is ... | how to make one dictionary from several arrays. PYTHON | I want to make one dictionary out of several arrays in a loop
a = ["hello","hi"]
b = ["day","night"]
#And these arrays were transformed into a dictionary
c = {"a": "hello, hi", "b": "day, night"}
dictt = dict.fromkeys(a, b)
print(dictt)
| [
"What you want is a dictionary with the variable name as key, and the contents of the lists joined together as the values.\nIt is unusual to retrieve the variable names and use them as keys, so you could do it manually like this:\na = [\"hello\",\"hi\"]\nb = [\"day\",\"night\"]\n\nc = {\n 'a': ', '.join(a),\n ... | [
0
] | [] | [] | [
"arraylist",
"dictionary",
"python"
] | stackoverflow_0074605006_arraylist_dictionary_python.txt |
Q:
S3 Upload Invoke Lambda Fails - Cross Account Access
I have a lambda that triggers off an S3 bucket upload (it basically converts a PDF to a dataframe and writes it to a different s3 bucket). Both of these belong to AWS account A. I would like to allow cross-account s3 access to trigger this lambda from another IA... | S3 Upload Invoke Lambda Fails - Cross Account Access | I have a lambda that triggers off an S3 bucket upload (it basically converts a PDF to a dataframe and writes it to a different s3 bucket). Both of these belong to AWS account A. I would like to allow cross-account s3 access to trigger this lambda from another IAM user from account B (Administrator), however I am having... | [
"It appears that your situation is:\nAccount A contains:\n\nAn AWS Lambda function\nA 'source' bucket used to trigger the Lambda function\nA 'destination' bucket used by the Lambda function to store output\n\nYou want to allow the Administrator IAM User in Account B to upload a file to the source bucket in Account ... | [
1,
1,
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"python",
"terraform"
] | stackoverflow_0074593918_amazon_s3_amazon_web_services_aws_lambda_python_terraform.txt |
Q:
Upload multiple images to a post in Django View Error(Cannot resolve keyword 'post' into field.)
My Model :
class Gallary (models.Model):
ProgramTitle = models.CharField(max_length=200, blank = False)
Thum = models.ImageField(upload_to='Gallary/Thumb/',default = "", blank = False, null=False)
VideoLink... | Upload multiple images to a post in Django View Error(Cannot resolve keyword 'post' into field.) | My Model :
class Gallary (models.Model):
ProgramTitle = models.CharField(max_length=200, blank = False)
Thum = models.ImageField(upload_to='Gallary/Thumb/',default = "", blank = False, null=False)
VideoLink = models.CharField(max_length=200, blank = True,default = "")
updated_on = models.DateTimeField(a... | [
"Change\nphotos = GallaryDetails.objects.filter(post=post)\nto\nphotos = GallaryDetails.objects.filter(Gallary=post)\nGallaryDetails has no field called post. It's called Gallary.\nAlso it's a good practive to only name Class names with uppercase letters. Field names should start with lowercase letters.\n"
] | [
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"list",
"python"
] | stackoverflow_0074605064_django_django_templates_django_views_list_python.txt |
Q:
why others recipients are not able to see the image from my html? using win32 python
Hello guys i'm tryng to send an image in my html, when im testing sending it to myself is working fine But, if try to send to other recepients they don't receive it how can i fix that:
any suggestion, thank you
my code is this:
... | why others recipients are not able to see the image from my html? using win32 python | Hello guys i'm tryng to send an image in my html, when im testing sending it to myself is working fine But, if try to send to other recepients they don't receive it how can i fix that:
any suggestion, thank you
my code is this:
import win32com.client as win32
olApp = win32.Dispatch('Outlook.Application')
olNS... | [
"They do see the image because they cannot possibly have access to your local file (E:\\html5.gif).\nYou need to add the image as an attachment and set its content-id appropriately, then reference the image by that content id in your HTML.\nSee https://stackoverflow.com/a/28272165/332059\n"
] | [
0
] | [] | [] | [
"html_email",
"image",
"outlook",
"python",
"win32com"
] | stackoverflow_0074604833_html_email_image_outlook_python_win32com.txt |
Q:
How to calculate R squared on monthly frequency for daily data?
Currently I calculate the R squared for the whole dataset and for monthly R squared I slice the dataframe into smaller dataframes with the corresponding month and this is really unwieldy for a large dataset. Is there a way to easy calculate R squared ... | How to calculate R squared on monthly frequency for daily data? | Currently I calculate the R squared for the whole dataset and for monthly R squared I slice the dataframe into smaller dataframes with the corresponding month and this is really unwieldy for a large dataset. Is there a way to easy calculate R squared for each month?
I use this for the whole dataset:
from sklearn.metric... | [
"First, I did a pre-processing step which may or may not be necessary for you. I converted the date column from object to datetime. (You can check df.dtypes to see if this step is necessary.)\ndf['date'] = pd.to_datetime(df['date'])\n\nNext, I group the dataframe by month, using pd.Grouper() to select the grouping ... | [
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074604920_group_by_pandas_python.txt |
Q:
Access Azure EventHub with WebSocket and proxy
I'm trying to access Azure EvenHub but my network makes me use proxy and allows connection only over https (port 443)
Based on https://learn.microsoft.com/en-us/python/api/azure-eventhub/azure.eventhub.aio.eventhubproducerclient?view=azure-python
I added proxy configu... | Access Azure EventHub with WebSocket and proxy | I'm trying to access Azure EvenHub but my network makes me use proxy and allows connection only over https (port 443)
Based on https://learn.microsoft.com/en-us/python/api/azure-eventhub/azure.eventhub.aio.eventhubproducerclient?view=azure-python
I added proxy configuration and TransportType.AmqpOverWebsocket parametr ... | [
"you should be able to set up a proxy that the SDK uses to access EventHub. Here is a sample that shows you how to set the HTTP_PROXY dictionary with the proxy information. Behind the scenes when proxy is passed in, it automatically goes over websockets.\nAs @BrunoLucasAzure suggested checking the ports on the prox... | [
1
] | [] | [] | [
"azure_eventhub",
"python",
"websocket"
] | stackoverflow_0074563693_azure_eventhub_python_websocket.txt |
Q:
Hide all channels except one for everyone except some roles discord.py
How can I hide all channels except one (the one can be excluded with role id or name) except for admin with discord.py.
hide all channels except one (by making it private) with a command
Return all channels back to normal with a command
A:
I'... | Hide all channels except one for everyone except some roles discord.py | How can I hide all channels except one (the one can be excluded with role id or name) except for admin with discord.py.
hide all channels except one (by making it private) with a command
Return all channels back to normal with a command
| [
"I'm assuming you meant channel id and not \"role id\", given such you can make every channel hidden by setting the permissions for @everyone \"read messages\" to False in every channel, except for the excluded channel.\nI'm personally using discord.app_commands.CommandTree so it looks like this:\n@tree.command(nam... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074483979_discord_discord.py_python.txt |
Q:
Wrong output in function
Hi I'am totally new to programmering and i have just jumped into it.
The problem i am trying to solve is to make a function that standardized an adress as input.
example:
def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.... | Wrong output in function | Hi I'am totally new to programmering and i have just jumped into it.
The problem i am trying to solve is to make a function that standardized an adress as input.
example:
def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.split():
if word. isdi... | [
"Issues\n\nstrings are immutable so you need to keep the replace result, so do a = a.replace('_', ' ') or chain it before the split call\n\nYou need to concatenate the lists into one numbers + letters then join the elements with \" \".join()\n\ndon't convert the numeric to int, that's useless and would force you to... | [
2,
0
] | [] | [] | [
"append",
"function",
"loops",
"python"
] | stackoverflow_0074605167_append_function_loops_python.txt |
Q:
Pandas column split ValueError: Columns must be same length as key
I have dataframe structured like:
Location_Identifier
Location_Name
Location_Type
Observed_Property
5728
place 1
Groundwater
39398 - ETHION IN WHOLE WATER SAMPLE (UG/L)
535
place 2
Groundwater
946 - SULFATE, DISSOLVED (MG/L AS SO4)
1003
place 3... | Pandas column split ValueError: Columns must be same length as key | I have dataframe structured like:
Location_Identifier
Location_Name
Location_Type
Observed_Property
5728
place 1
Groundwater
39398 - ETHION IN WHOLE WATER SAMPLE (UG/L)
535
place 2
Groundwater
946 - SULFATE, DISSOLVED (MG/L AS SO4)
1003
place 3
Groundwater
1145 - SELENIUM, DISSOLVED (UG/L AS SE)
12151
pla... | [
"I ran your code and I am fairly certain you have some values in \"Observed_Property\" That have more than one '-' so when you split the values, you get more than 2 columns.\nfrom io import StringIO\nimport pandas as pd\n\n\ndfstr = \"\"\"Location_Identifier Location_Name Location_Type Observed_Property\n5728 ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074604902_dataframe_pandas_python.txt |
Q:
How to add Thread Name to each request context to Flask
In creating a python thread with name, we can do it by
t = threading.Thread(target=func,name="my_thread")
In flask, each request spawns its own thread holding the context until the process is completed. How do i assign dynamic name to these threads being cre... | How to add Thread Name to each request context to Flask | In creating a python thread with name, we can do it by
t = threading.Thread(target=func,name="my_thread")
In flask, each request spawns its own thread holding the context until the process is completed. How do i assign dynamic name to these threads being created by flask?
| [
"can try this one chain-logging\nfrom flask import Flask\nfrom chain_logging.flask import setup_chained_logger, logger\n\napp = Flask(__name__)\n\nsetup_chained_logger(app)\n\n@app.get(\"/home\")\ndef home():\n logger.info(\"this is a trial 1\")\n logger.error(\"this is a trial 2\")\n logger.warning(\"this... | [
0,
0
] | [] | [] | [
"flask",
"multithreading",
"python"
] | stackoverflow_0074308792_flask_multithreading_python.txt |
Q:
How to get output layer values during training tensorflow
Is it possible to get the output layer values during the training in order to build a custom loss function.
to be more specific i want to get the output value and compute the loss using external method
my problem is I can't pass tf.eval() before initialize... | How to get output layer values during training tensorflow | Is it possible to get the output layer values during the training in order to build a custom loss function.
to be more specific i want to get the output value and compute the loss using external method
my problem is I can't pass tf.eval() before initialize variables using tf.global_variables_initializer()
def run_com... | [
"If your model has a single output value, you can subclass tf.keras.losses.Loss. For example, a trivial custom loss function (which wouldn't be very good in training) implementation:\nimport tensorflow as tf\n\nclass LossCustom(tf.keras.losses.Loss):\n def __init__(self, some_arg):\n super(LossCustom, sel... | [
0
] | [] | [] | [
"deep_learning",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0060041546_deep_learning_machine_learning_python_tensorflow.txt |
Q:
Are line breaks possible in Python match case patterns?
I want a match pattern with a rather long OR-pattern something like:
match item:
case Really.Long.Qualified.Name.ONE | Really.Long.Qualified.Name.TWO | Really.Long.Qualified.Name.THREE | Some.Other.Patterns.Here:
pass
This is obviously very annoyin... | Are line breaks possible in Python match case patterns? | I want a match pattern with a rather long OR-pattern something like:
match item:
case Really.Long.Qualified.Name.ONE | Really.Long.Qualified.Name.TWO | Really.Long.Qualified.Name.THREE | Some.Other.Patterns.Here:
pass
This is obviously very annoying to have on a single line. However, PyCharm doesn't seem t... | [
"You can wrap such chain expressions within a pair of parenthesis.\nmatch item:\n case (\n Really.Long.Qualified.Name.ONE |\n Really.Long.Qualified.Name.TWO |\n Really.Long.Qualified.Name.THREE |\n Some.Other.Patterns.Here\n ):\n pass\n\n"
] | [
1
] | [] | [] | [
"code_formatting",
"match",
"python"
] | stackoverflow_0074605197_code_formatting_match_python.txt |
Q:
How can I include the relative path to a module in a Python logging statement?
My project has a subpackage nested under the root package like so:
mypackage/
__init__.py
topmodule.py
subpackage/
__init__.py
nested.py
My goal is to get logging records formatted like:
mypackage/topmodule.py:123: First log message... | How can I include the relative path to a module in a Python logging statement? | My project has a subpackage nested under the root package like so:
mypackage/
__init__.py
topmodule.py
subpackage/
__init__.py
nested.py
My goal is to get logging records formatted like:
mypackage/topmodule.py:123: First log message
mypackage/subpackage/nested.py:456: Second log message
so that the paths become ... | [
"You'd have to do additional processing to get the path that you want here.\nYou can do such processing and add additional information to log records, including the 'local' path for your own package, by creating a custom filter.\nFilters don't actually have to do filtering, but they do get access to all log records... | [
8,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0052582458_logging_python.txt |
Q:
FutureWarning in using iteritems() in use .iloc() pandas
When I use s.iteritems() in using .iloc I see the below warning:
FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for item in s.iteritems()
While I'm using this function:
temp3 = temp2.iloc[:, 0]
I am usin... | FutureWarning in using iteritems() in use .iloc() pandas |
When I use s.iteritems() in using .iloc I see the below warning:
FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for item in s.iteritems()
While I'm using this function:
temp3 = temp2.iloc[:, 0]
I am using python 3.8 and don't know why I'm getting this warning.
I a... | [
"By the way, I solved my problem with:\ntemp3 = temp2[0].values\n\nBut I don't have any idea why I'm getting this warning!\n",
"You could edit the module directly, since it gives the line number as 606 in this file (and wait for a fix later from JetBrains):\nC:\\Program Files\\JetBrains\\PyCharm 2022.2.4\\plugins... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074442073_pandas_python_python_3.x.txt |
Q:
Confusion about multithreading in Python sockets and FastAPI
Problem:
I am trying to figure out if I really need to implement any thread safe mechanism when dealing with a client with multiple threads accessing the same (client) socket, and the information I find seems contradictory.
Every implementation I find c... | Confusion about multithreading in Python sockets and FastAPI | Problem:
I am trying to figure out if I really need to implement any thread safe mechanism when dealing with a client with multiple threads accessing the same (client) socket, and the information I find seems contradictory.
Every implementation I find consist basically in a server spawning new threads to hanlde each c... | [
"If I understand correctly you have a single FastAPI server. This server can handle multiple client connections simultaneously. Each connection has its own socket and thread. To handle requests, the FastAPI server communicates with another, back-end server. You use a single socket to communicate with the back-end s... | [
1
] | [] | [] | [
"fastapi",
"python",
"python_multithreading",
"sockets"
] | stackoverflow_0074599213_fastapi_python_python_multithreading_sockets.txt |
Q:
Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized
Operating System: Window10
I use spyder (python3.8) in anaconda and after run the code, I get the following error:
[SpyderKernelApp] WARNING | No such comm: df7601e106dd11eba18accf9e4a3c0ef
OMP: Error #15: Initializing libiomp5md... | Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized | Operating System: Window10
I use spyder (python3.8) in anaconda and after run the code, I get the following error:
[SpyderKernelApp] WARNING | No such comm: df7601e106dd11eba18accf9e4a3c0ef
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple cop... | [
"import os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\n",
"This error occurs when there are multiple \"libiomp5.dll\" files within a python interpreter. I fixed it by deleting all of the versions of the file that were not within the module I was using (PyTorch). I would like to point out that this could cause a... | [
8,
7,
3,
2
] | [
"Had the same problem with\n\nAnaconda Navigator 2.3.2\nSpyder version: 5.3.3 (conda)\nPython version: 3.9.15 64-bit\nQt version: 5.15.2\nPyQt5 version: 5.15.7\nOperating System: Windows 10\n\nI detected libiomp5md.dll in:\n\n..\\anaconda3\\envs\\My_Env\\Library\\bin\n..\\anaconda3\\pkgs\\tensorflow-base-2.9.1-mkl... | [
-1,
-1
] | [
"python"
] | stackoverflow_0064209238_python.txt |
Q:
Convert '00:00' to '00:00:00' pandas
I have a DataFrame that has a column with time data like ['25:45','12:34:34'], the initial idea is: first convert this column to a list called "time_list". Then with a for, iterate and convert it to minutes
time_list = df7[' Chip Time'].tolist()
time_mins = []
for i in time_li... | Convert '00:00' to '00:00:00' pandas | I have a DataFrame that has a column with time data like ['25:45','12:34:34'], the initial idea is: first convert this column to a list called "time_list". Then with a for, iterate and convert it to minutes
time_list = df7[' Chip Time'].tolist()
time_mins = []
for i in time_list:
h, m, s = i.split(':')
math = ... | [
"Instead of using h, m, s = i.split(':') you should be using t = i.split(':') because the first expects the i.split to always return 3 values, but in cases where i = [aa:bb] it will only return two. From there you use the length of t to decide if you need to calculate the seconds or not.\nYour code is converting ev... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074604221_dataframe_pandas_python.txt |
Q:
How to add data from tk.Entry to f'string in Python 3?
I need to make a text generator in which user input is added to f'string. What I get in result is that data typed in entry can be printed in PyCharm console, but doesn't show up in generated strings in tk.Text. Thank you in advance!
Here is the code of my rand... | How to add data from tk.Entry to f'string in Python 3? | I need to make a text generator in which user input is added to f'string. What I get in result is that data typed in entry can be printed in PyCharm console, but doesn't show up in generated strings in tk.Text. Thank you in advance!
Here is the code of my randomizer:
Simple GUI interface:
import tkinter as tk
import ra... | [
"The issue is that you're essentially calling anchor.get() immediately after declaring it with anchor = tk.StringVar(). It seems like what you really want is entry_1.get(), in which case you can do away with the anchor variable entirely.\nentry_1 = tk.Entry(win)\n\nYou'll also probably want to move the definition o... | [
1
] | [] | [] | [
"python",
"python_3.8",
"tkinter"
] | stackoverflow_0074605365_python_python_3.8_tkinter.txt |
Q:
having trouble using functions to break up my code
I have a monthly budget code that shows the user if they are over/under the budget for a certain month. I am having trouble breaking the code up into def functions. here is what I have
print("""\
This program uses a for loop to monitor your budget.
The program wil... | having trouble using functions to break up my code | I have a monthly budget code that shows the user if they are over/under the budget for a certain month. I am having trouble breaking the code up into def functions. here is what I have
print("""\
This program uses a for loop to monitor your budget.
The program will prompt you to enter your budget, and amount spent
for ... | [
"You could extract the user interaction like\ndef get_nb_months():\n value = int(input(\"Enter the number of months you would like to monitor:\"))\n while value < 0:\n print(\"Negative value detected!\")\n value = int(input(\"Enter the number of months you would like to monitor\"))\n return v... | [
0
] | [] | [] | [
"function",
"python",
"void"
] | stackoverflow_0074605296_function_python_void.txt |
Q:
How to query multiple tables using join in sqlalchemy
select count(DISTINCT(a.cust_id)) as count ,b.code, b.name from table1 as a inner join table2 as b on a.par_id = b.id where a.data = "present" group by a.par_id order by b.name asc;
How to write this in sqlalchemy to get as expected results
The above query whic... | How to query multiple tables using join in sqlalchemy | select count(DISTINCT(a.cust_id)) as count ,b.code, b.name from table1 as a inner join table2 as b on a.par_id = b.id where a.data = "present" group by a.par_id order by b.name asc;
How to write this in sqlalchemy to get as expected results
The above query which is writen in sql should be right in sqlalchemy.
Thanks fo... | [
"Hope this works...\nsession.query(\n func.count(distinct(table1.cust_id)).label('count'),\n table2.code,\n table2.name\n).join(\n table2,\n table1.par_id == table2.id\n).filter(\n table1.data == \"present\"\n).group_by(\n table1.par_id\n).order_by(\n table2.name.asc()\n).all()\n\n"
] | [
0
] | [] | [] | [
"distinct",
"fastapi",
"join",
"python",
"sqlalchemy"
] | stackoverflow_0074568646_distinct_fastapi_join_python_sqlalchemy.txt |
Q:
How to clean a textfile to export like JSON - Python
I have the following textfile from an LFT command.
2 [14080] [100.0.0.0 - 100.255.255.255] 100.5.254.150 6.3ms
3 [14080] [100.0.0.0 - 100.255.255.255] 100.8.254.149 5.7ms
4 [15169] [GOOGLE] 142.250.164.139 17.5ms
5 [15169] [GOOGLE] 142.250.164.138 10.9ms
6 ... | How to clean a textfile to export like JSON - Python | I have the following textfile from an LFT command.
2 [14080] [100.0.0.0 - 100.255.255.255] 100.5.254.150 6.3ms
3 [14080] [100.0.0.0 - 100.255.255.255] 100.8.254.149 5.7ms
4 [15169] [GOOGLE] 142.250.164.139 17.5ms
5 [15169] [GOOGLE] 142.250.164.138 10.9ms
6 [15169] [GOOGLE] 72.14.233.63 12.8ms
7 [15169] [GOOGLE] 1... | [
"You can try to parse the text with re module:\ntext = \"\"\"\\\n2 [14080] [100.0.0.0 - 100.255.255.255] 100.5.254.150 6.3ms\n3 [14080] [100.0.0.0 - 100.255.255.255] 100.8.254.149 5.7ms\n4 [15169] [GOOGLE] 142.250.164.139 17.5ms\n5 [15169] [GOOGLE] 142.250.164.138 10.9ms\n6 [15169] [GOOGLE] 72.14.233.63 12.8ms... | [
1,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074604906_json_python.txt |
Q:
Find_element_by_name for multiple names
I want to find right element name by calling more element names at a time. Is that possible?
try:
G= driver.find_element_by_name("contact[Name]")
G.send_keys("name")
except:
pass
try:
H= driver.find_element_by_name("contact[name]"... | Find_element_by_name for multiple names | I want to find right element name by calling more element names at a time. Is that possible?
try:
G= driver.find_element_by_name("contact[Name]")
G.send_keys("name")
except:
pass
try:
H= driver.find_element_by_name("contact[name]")
H.send_keys("name")
elem = d... | [
"I don't think there's a way to pass multiple names to find_element_by_name(). You'll have to call it with the first name, and if that raises an exception, call it with the second name.\nelem = None\n\ntry:\n elem = driver.find_element_by_name(\"contact[Name]\")\nexcept selenium.common.exceptions.NoSuchElementE... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074605370_python_selenium.txt |
Q:
How is argument unpacking working in this function?
I'm still a beginner in learning python but I came across this function :
def show_skills (name , *skills ,**skillswithprogress) :
print (f'hello {name} \n skills without progress is :')
for skill in skills :
print (f'-{skills}')
print ('skill... | How is argument unpacking working in this function? | I'm still a beginner in learning python but I came across this function :
def show_skills (name , *skills ,**skillswithprogress) :
print (f'hello {name} \n skills without progress is :')
for skill in skills :
print (f'-{skills}')
print ('skills with progress is :')
for skill_key , skills_value in... | [
"It is the concept of *args and **kwargs\n*args is the list or tuple\n**kwargs is the dictionary\nyou put the parameter for the function as like\nshow_skills('H', python = '95%',css = '95%')\nwould be python='95%', css='95%' => {python:'95%', css:'95%'}\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074605400_python.txt |
Q:
How can I stop iterating once a certain number of SMS messages have been sent?
I'm making a telegram bot that will send SMS through a parser and I need to loop until about 20 SMS are sent.
I am using the telebot library to create a bot and for the parser I have requests and BeautifulSoup.
import telebot
import req... | How can I stop iterating once a certain number of SMS messages have been sent? | I'm making a telegram bot that will send SMS through a parser and I need to loop until about 20 SMS are sent.
I am using the telebot library to create a bot and for the parser I have requests and BeautifulSoup.
import telebot
import requests
from bs4 import BeautifulSoup
from telebot import types
bot = telebot.TeleBot... | [
"Don't bother with the stopping the loop or slicing the array, tell bs4 to limit the result:\ndata = soup.find_all(\"div\", class_=\"dict-word\", limit=20)\n\n",
"you can try\nfor indx,i in enumerate(data):\n if index == 19: # including zero, 20th will be the 19th.\n break\n -code here-\n\nenumerate ... | [
1,
0
] | [] | [] | [
"python",
"telebot"
] | stackoverflow_0074605337_python_telebot.txt |
Q:
How to get pairwise combinations of words?
Given a string I want pair wise combinations of the words present in the string with blank spaces. For instance for the following string:
string = "This is cat"
I want the following output:
str1 = "This is cat"
str2 = "Thisis cat"
str3 = "This iscat"
str4 = "Thisiscat"
... | How to get pairwise combinations of words? | Given a string I want pair wise combinations of the words present in the string with blank spaces. For instance for the following string:
string = "This is cat"
I want the following output:
str1 = "This is cat"
str2 = "Thisis cat"
str3 = "This iscat"
str4 = "Thisiscat"
I tried something with itertools. Basically gett... | [
"i like the idea using combinations of True and False, and it actualy works (if we may use '_' as a replacement):\nfrom itertools import product\n\nstring = \"This is a cat\"\nstrings = []\n\npermutations = list(product([False, True], repeat=string.count(' ')))\nfor permutation in permutations:\n s = string\n ... | [
0
] | [] | [] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074604864_python_python_2.7_python_3.x.txt |
Q:
404 Error with mybinder.org when I try to deploy a Jupyter Notebook with voila from GitHub
I have a problem deploying my Jupyter Notebook from Github to mybinder.org.
I configured everything according to several tutorials I found, but everytime I try to build the page mybinder.org gives me this error afterwards:
4... | 404 Error with mybinder.org when I try to deploy a Jupyter Notebook with voila from GitHub | I have a problem deploying my Jupyter Notebook from Github to mybinder.org.
I configured everything according to several tutorials I found, but everytime I try to build the page mybinder.org gives me this error afterwards:
404 : Not Found,
You are requesting a page that does not exist!
The building process seems to wor... | [
"You didn't have the correct name of the notebook in the 'URL to open' portion of the form.\nThe resulting correct address should be: https://mybinder.org/v2/gh/MkengineTA/VoilaDemo/main?urlpath=voila%2Frender%2FTestVoila.ipynb , that's https://mybinder.org/v2/gh/MkengineTA/VoilaDemo/main?urlpath=voila%2Frender%2FT... | [
0
] | [] | [] | [
"github",
"jupyter_notebook",
"mybinder",
"python",
"voila"
] | stackoverflow_0074604898_github_jupyter_notebook_mybinder_python_voila.txt |
Q:
Failing to install Sparkmagic using pip
I am trying to install sparkmaic in jupyter notebook through pip but getting below error:
Command:
pip install sparkmagic
error:
Collecting gssapi>=1.6.0
Using cached gssapi-1.8.1.tar.gz (94 kB)
Installing build dependencies ... done
Getting requirements to build whee... | Failing to install Sparkmagic using pip | I am trying to install sparkmaic in jupyter notebook through pip but getting below error:
Command:
pip install sparkmagic
error:
Collecting gssapi>=1.6.0
Using cached gssapi-1.8.1.tar.gz (94 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-e... | [
"It looks like your system is missing a tool named krb5-config. You might be able to install it with:\nsudo apt install krb5-config\n\n",
"Thanks @bernhard\nbut, I had to install dev tools too (ubuntu 20.04).\nsudo apt-get install libkrb5-dev\n\n"
] | [
0,
0
] | [] | [] | [
"pip",
"pyspark",
"python",
"ubuntu",
"unix"
] | stackoverflow_0074031328_pip_pyspark_python_ubuntu_unix.txt |
Q:
first argument must be an iterable of pandas objects, you passed an object of type "Series"
I have the following dataframe:
s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'... | first argument must be an iterable of pandas objects, you passed an object of type "Series" | I have the following dataframe:
s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'Current balance': {1998: -6.7953,
1999: -2.9895,
2000: -3.9694,
2001: 1.1716,
2002: 5.743... | [
"You need to use a list of the DataFrames to merge and to concat on axis=1:\ndf_2 = pd.concat([df.iloc[:,0], df.iloc[:,3:]], axis=1)\n\nOr, better, use slicing:\ndf_2 = df.iloc[:, [0,3,4]]\n# or\ndf_2 = df.iloc[:, np.r_[0,3:df.shape[1]]]\n\nOutput:\n BoP transfers Effective exchange rate RoR (foreign liabili... | [
0
] | [] | [] | [
"concatenation",
"pandas",
"python",
"slice"
] | stackoverflow_0074605469_concatenation_pandas_python_slice.txt |
Q:
How to print unicode character from a string variable?
I am new in programming world, and I am a bit confused.
I expecting that both print result the same graphical unicode exclamation mark symbol:
My experiment:
number = 10071
byteStr = number.to_bytes(4, byteorder='big')
hexStr = hex(number)
uniChar = byte... | How to print unicode character from a string variable? | I am new in programming world, and I am a bit confused.
I expecting that both print result the same graphical unicode exclamation mark symbol:
My experiment:
number = 10071
byteStr = number.to_bytes(4, byteorder='big')
hexStr = hex(number)
uniChar = byteStr.decode('utf-32be')
uniStr = '\\u' + hexStr[2:6]
print(... | [
"An escape code evaluated by the Python parser when constructing literal strings. For example, the literal string '马' and '\\u9a6c' are evaluated by the parser as the same, length 1, string.\nYou can (and did) build a string with the 6 characters \\u9a6c by using an escape code for the backslash (\\\\) to prevent ... | [
0
] | [] | [] | [
"printf",
"python",
"string",
"unicode"
] | stackoverflow_0074599920_printf_python_string_unicode.txt |
Q:
Unique Variable Constraint in Gurobi
I am using Gurobi in Jupyter notebook with 9 variables. I want to add constraints so that each variable has a unique value. How do I code this in Gurobi Linear programming solver?
m.addConstr(i1 - i2 + y*a >= 1)
Based on my online research, the above is what I am currently try... | Unique Variable Constraint in Gurobi | I am using Gurobi in Jupyter notebook with 9 variables. I want to add constraints so that each variable has a unique value. How do I code this in Gurobi Linear programming solver?
m.addConstr(i1 - i2 + y*a >= 1)
Based on my online research, the above is what I am currently trying to enforce but it is not working.
| [
"To be a bit more constructive, this is called an all-different constraint. This is part of many Constraint Programming (CP) solvers. Implementing this constraint in a Mixed-Integer Programming model is not totally trivial or cheap. For some formulations see for instance: https://pubsonline.informs.org/doi/abs/10.1... | [
0
] | [] | [] | [
"gurobi",
"jupyter_notebook",
"linear_programming",
"optimization",
"python"
] | stackoverflow_0074605285_gurobi_jupyter_notebook_linear_programming_optimization_python.txt |
Q:
Rock, Paper, Scissors in Functions
I need to write rock, paper, scissors only using functions.
I have not done this before so my try at it is below. I am not able to get it to run fully through. Any pointers in the right direction would be very helpful!
Code below:
import random
def user_choice():
user_choic... | Rock, Paper, Scissors in Functions | I need to write rock, paper, scissors only using functions.
I have not done this before so my try at it is below. I am not able to get it to run fully through. Any pointers in the right direction would be very helpful!
Code below:
import random
def user_choice():
user_choice = input("Choose rock, paper, or scisso... | [
"You need to pass results of \"input\" functions to \"get_winner\" function as arguments.\nIt should be defined like that:\ndef get_winner(user_choice, computer_choice):\n\n\nThen in your code:\nuc = user_choice()\ncc = computer_choice()\nget_winner(uc, cc)\n\n"
] | [
1
] | [] | [] | [
"function",
"python",
"python_3.x"
] | stackoverflow_0074605505_function_python_python_3.x.txt |
Q:
How to continue a while loop in python
I am building a python dice game where two players are supposed to play a vs. The code runs correctly and the first player is able to play his/her round however am having a bit of a problem looping through the while statement so as to make the second player play his/her round... | How to continue a while loop in python | I am building a python dice game where two players are supposed to play a vs. The code runs correctly and the first player is able to play his/her round however am having a bit of a problem looping through the while statement so as to make the second player play his/her round. I thought I would add a continue at if st... | [
"Your if block is outside the while block (indentation). You are not executing this if within the while block, hence the error.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074605535_python.txt |
Q:
How to avoid "AttributeError: cls not available in session-scoped context" using request.cls and scope="session"?
I have next construction:
1. BaseClass with fixture
class BaseClass:
instance = None
@pytest.fixture(scope="session", autouse=True)
def setup_and_teardown(self, request):
request.c... | How to avoid "AttributeError: cls not available in session-scoped context" using request.cls and scope="session"? | I have next construction:
1. BaseClass with fixture
class BaseClass:
instance = None
@pytest.fixture(scope="session", autouse=True)
def setup_and_teardown(self, request):
request.cls.instance = AnotherClass()
request.cls.instance.open_session()
yield
self.instance.close_se... | [
"It is not a good idea to have session-scoped fixture as a method in a class - this creates the impression that it have access to the class or a class instance, which it has not.\nInstead, write the session-scoped fixture outside the class and yield the created object. Pytest will cache the object and pass it to an... | [
0
] | [] | [] | [
"automated_tests",
"fixtures",
"pytest",
"python"
] | stackoverflow_0074573662_automated_tests_fixtures_pytest_python.txt |
Q:
Pip can't build wheels for pyproject.toml projects because it can't find "--plat-name."
I'm trying to install moderngl using pip. Of course,
python -m pip install moderngl
It failed to build wheels for moderngl and one of its dependencies, glcontext. In both cases, it gave me the same error message:
error: --plat... | Pip can't build wheels for pyproject.toml projects because it can't find "--plat-name." | I'm trying to install moderngl using pip. Of course,
python -m pip install moderngl
It failed to build wheels for moderngl and one of its dependencies, glcontext. In both cases, it gave me the same error message:
error: --plat-name must be one of ('win32', 'win-amd64', 'win-arm32', 'win-arm64')
I am certainly, certai... | [
"Still don't know what the problem was precisely, but now I know vaguely, and the solution.\nI had installed Python 3.10.8, pip, pipenv, etc. through mingw64. This seems to lag behind on providing the latest versions of things. It couldn't give me the newest pip or pipenv at the time of this question. And although ... | [
0
] | [] | [] | [
"pip",
"python",
"python_moderngl"
] | stackoverflow_0074596436_pip_python_python_moderngl.txt |
Q:
How to collect terms of given powers of multivariable polynomials using sympy?
I have a polynomial like this:
3*D*c1*cos_psi**2*p**2*u/(d*k**4*kappa**2) + 3*D*c1*cos_psi*p*q*u/(2*k**4*kappa**2) - 3*D*c1*cos_psi*p*q*u/(d*k**4*kappa**2) - 3*D*c1*u/(2*k**2*kappa**2) - 3*D*c1*p**2*u/(2*k**4*kappa**2) - 3*D*c1*q**2*u/(... | How to collect terms of given powers of multivariable polynomials using sympy? | I have a polynomial like this:
3*D*c1*cos_psi**2*p**2*u/(d*k**4*kappa**2) + 3*D*c1*cos_psi*p*q*u/(2*k**4*kappa**2) - 3*D*c1*cos_psi*p*q*u/(d*k**4*kappa**2) - 3*D*c1*u/(2*k**2*kappa**2) - 3*D*c1*p**2*u/(2*k**4*kappa**2) - 3*D*c1*q**2*u/(4*k**4*kappa**2) + 3*D*c1*p**2*u*(1 - cos_psi**2)/(d*k**4*kappa**2) + 3*D*c1*q**2*u/... | [
"If Poly does what you want then you can get the expression part of a Poly as follows:\n>>> Poly(3*x+y*x+4+z,x).as_expr()\nx*(y + 3) + z + 4\n\n",
"It seems like this solved it:\n expr = collect(simplify(expr),(q,p,p*q))\n\n"
] | [
1,
0
] | [] | [] | [
"poly",
"python",
"sympy"
] | stackoverflow_0074599601_poly_python_sympy.txt |
Q:
I got the "AttributeError: 'OutStream' object has no attribute 'buffer'" when i run the below python code that are from w3school in the google colab
Here I mention the code that I saw in the w3school.
# w3school code
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pypl... | I got the "AttributeError: 'OutStream' object has no attribute 'buffer'" when i run the below python code that are from w3school in the google colab | Here I mention the code that I saw in the w3school.
# w3school code
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
health_data = pd.read_csv("data.csv", header=0, sep=",")
health_data.plot(x ='Average_Pulse', y='Calorie_Burnage', kind='line'),
plt.ylim(ymin... | [
"I had this same issue on W3schools as well!\nUse matplotlib inline in you notebook like this:\n%matplotlib inline\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('data.csv')\n\ndf.plot()\n\nplt.show()\n\nsys.stdout.flush()\n\n"
] | [
0
] | [] | [] | [
"attributes",
"buffer",
"object",
"python"
] | stackoverflow_0073956763_attributes_buffer_object_python.txt |
Q:
How to store image input given by Pi Camera directly into a variable rather than to a file?
I want to store the input given by my pi camera directly into a variable, rather than storing it in a file. I want to do this so that it takes less processing power of the pi, as I am working on a autonomus car project and ... | How to store image input given by Pi Camera directly into a variable rather than to a file? | I want to store the input given by my pi camera directly into a variable, rather than storing it in a file. I want to do this so that it takes less processing power of the pi, as I am working on a autonomus car project and it takes alot of processing. When I try to store the image to a variable it gives me the followin... | [
"Came across the same issue but the answers proposed around the web were not clear enough for my issue. Also, this is the first result that came up during my research, and yet there are no answers to it. Hopefully my summary helps answer this problem properly. Here is how I figured it out:\n\ncamera.capture(output,... | [
1
] | [] | [] | [
"python",
"raspberry_pi"
] | stackoverflow_0054869329_python_raspberry_pi.txt |
Q:
Python: Why is this recursion failing?
Why am I getting maximum recursion results of [] in this simple recursion example?
# generate data
df = pd.DataFrame({'id': [1, 2, 2, 3, 4, 5, 6, 7],
'parent': [np.nan, 1, 2, 2, np.nan, 1, 1, 5]})
parents = df.parent.dropna().unique().astype(int)
def fin... | Python: Why is this recursion failing? | Why am I getting maximum recursion results of [] in this simple recursion example?
# generate data
df = pd.DataFrame({'id': [1, 2, 2, 3, 4, 5, 6, 7],
'parent': [np.nan, 1, 2, 2, np.nan, 1, 1, 5]})
parents = df.parent.dropna().unique().astype(int)
def find_parent(init_parent):
init_parent = [in... | [
"def find_parent(init_parent):\n init_parent = [init_parent] if isinstance(init_parent, int) else [init_parent]\n if len(init_parent) == 0: # this only returns true on an empty array\n return init_parent # you're getting [] because this return\n else:\n return find_parent(d... | [
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074605789_python_recursion.txt |
Q:
operation parameter must be str
I need to insert with using only SQLAlchemy. Stack of technologies is only sqlite, sqlachemy for this.
`
# запись работника в таблицу users(ФИО, рандом др, роль(рандом из таблицы roles)
# вывод последних добавленных 5 работников
import json
import sqlalchemy as sa
import sqlite3
fro... | operation parameter must be str | I need to insert with using only SQLAlchemy. Stack of technologies is only sqlite, sqlachemy for this.
`
# запись работника в таблицу users(ФИО, рандом др, роль(рандом из таблицы roles)
# вывод последних добавленных 5 работников
import json
import sqlalchemy as sa
import sqlite3
from sqlalchemy import Table, MetaData
m... | [
"Thanks https://stackoverflow.com/users/5320906/snakecharmerb\nanswer: https://docs.sqlalchemy.org/en/14/tutorial/data_insert.html#inserting-rows-with-core\nengine = create_engine(\"sqlite:///database.db\", echo=True, future=True)\n\n...\nwith engine.connect() as conn:\nresult = conn.execute(stmt)\nconn.commit()\n\... | [
0
] | [] | [] | [
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0074604509_python_sqlalchemy_sqlite.txt |
Q:
How to open a window by clicking on a column in a tree view table?
How would you double click on a column in a tree view table to then display the specific records on entry fields on a new window.
def SearchCustomer(self):
connection = sqlite3.connect("Guestrecord.db")
cursor = connection.c... | How to open a window by clicking on a column in a tree view table? | How would you double click on a column in a tree view table to then display the specific records on entry fields on a new window.
def SearchCustomer(self):
connection = sqlite3.connect("Guestrecord.db")
cursor = connection.cursor()
columnID = ["GuestID","title","firstName","surname"... | [
"You should be able to grab the selected Treeview item from the mouse event being passed to your OnDoubleClick() function. If you want to open a new window that's a child of your root window, you'll want a Toplevel widget. You can treat that Toplevel window pretty much just like you would a root Tk window.\n# side ... | [
0
] | [] | [] | [
"python",
"tkinter",
"treeview"
] | stackoverflow_0074605379_python_tkinter_treeview.txt |
Q:
How to merge pandas dataframes after renaming columns?
I have a code that merged 2 dataframes that had all columns in uppercase. I need to adjust the code to merge the dataframes but now 1 comes with columns in lowercase and the other doesn't.
I wrote the following code to change the columns names to lowercase, an... | How to merge pandas dataframes after renaming columns? | I have a code that merged 2 dataframes that had all columns in uppercase. I need to adjust the code to merge the dataframes but now 1 comes with columns in lowercase and the other doesn't.
I wrote the following code to change the columns names to lowercase, and then changed the merge to lowercase also, but no i get a K... | [
"First to 'lower' the column names you can use:\ndf_small.columns = df_small.columns.str.lower()\n\nI think that your code for lowercasing the column names is doing something wrong. Try mine above\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074605887_pandas_python.txt |
Q:
Snowflake UDF returns "Unknown user-defined function" For Existing UDF
I have a UDF that I can call within my snowflakecomputing.com console.
SELECT DECODE_UTF8('some string')
Works great, until I try to call it programmatically from a Python script. I receive this...
snowflake.connector.errors.ProgrammingError: ... | Snowflake UDF returns "Unknown user-defined function" For Existing UDF | I have a UDF that I can call within my snowflakecomputing.com console.
SELECT DECODE_UTF8('some string')
Works great, until I try to call it programmatically from a Python script. I receive this...
snowflake.connector.errors.ProgrammingError: 002141 (42601):
or:
Unknown user-defined function CS_QA.CS_ANALYTICS.DECODE_... | [
"Most likely the user(and role assigned) used to connect from Python does not have access to that UDF. This hypothesis could be validated by using INFORMATION_SCHEMA.FUNCTIONS:\n\nThe view only displays objects for which the current role for the session has been granted access privileges.\n\nSELECT *\nFROM CS_QA.IN... | [
1,
0
] | [] | [] | [
"python",
"snowflake_cloud_data_platform",
"user_defined_functions"
] | stackoverflow_0072504545_python_snowflake_cloud_data_platform_user_defined_functions.txt |
Q:
How to use ArrayFire batched 2D convolution
Reading through ArrayFire documentation, I noticed that the library supports batched operations when using 2D convolution. Therefore, I need to apply N filters to an image using the C++ API.
For easy testing, I decided to create a simple Python script to assert the convo... | How to use ArrayFire batched 2D convolution | Reading through ArrayFire documentation, I noticed that the library supports batched operations when using 2D convolution. Therefore, I need to apply N filters to an image using the C++ API.
For easy testing, I decided to create a simple Python script to assert the convolution results. However, I couldn't get proper re... | [
"ArrayFire is column-major, whereas OpenCV and NumPy are row-major. This can cause issues. We provide an interop function to handle this for you, as follows.\nimport arrayfire as af\nimport cv2\nimport numpy as np\n \nnp.random.seed(1)\n \nnp.set_printoptions(precision=3)\naf.set_backend('cuda')\n \nn_kernels = 2\n... | [
1
] | [] | [] | [
"arrayfire",
"arrays",
"gpu",
"python"
] | stackoverflow_0074605090_arrayfire_arrays_gpu_python.txt |
Q:
turtle.textinput() is not working in one of my codes but it works in the other
I am currently working on a game in python using the turtle library import. Before I add anything to the main game always test it in another python file to make sure it works.
I came across the turtle.textinput()
It worked in my test co... | turtle.textinput() is not working in one of my codes but it works in the other | I am currently working on a game in python using the turtle library import. Before I add anything to the main game always test it in another python file to make sure it works.
I came across the turtle.textinput()
It worked in my test code but not in my actual game. When I tried to put it in the actual game it says
Attr... | [
"textinput() is a method in Screen class\n",
"Note that textinput() is a method in the Screen instance, and not in the turtle.\nfrom turtle import Screen\n\nscreen = Screen()\n\nscreen.textinput(\"Title Example\", \"Prompt example\")\n\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0067451474_python.txt |
Q:
A faster solution for Project Euler question 10
I have solved the question 10 regarding sum of all primes under 2 million, however my code takes over a few minutes to calculate the result.
I was just wondering if there is any way to optimise it to make it run faster ?
The code takes an upper limit
Generates an ar... | A faster solution for Project Euler question 10 | I have solved the question 10 regarding sum of all primes under 2 million, however my code takes over a few minutes to calculate the result.
I was just wondering if there is any way to optimise it to make it run faster ?
The code takes an upper limit
Generates an array
Iterates through it and removes multiples of a nu... | [
"Thanks for the input. I was able to improve the code by changing how a number is checked for prime.\nThe code finishes under 2 seconds instead of minutes.\nInstead of counting from beginning to end for array, it counts from the prime number to the end of the array with increments of the prime number.\nThanks again... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074603473_python_python_3.x.txt |
Q:
Argument of type "datetime" cannot be assigned to parameter "value" of type "str"
I am currently working on a Python and SQL project.
There I am building a GUI that takes information from user input and stores them in a MySQL database locally.
There are a few warnings/errors that I am trying to resolve.
This is my... | Argument of type "datetime" cannot be assigned to parameter "value" of type "str" | I am currently working on a Python and SQL project.
There I am building a GUI that takes information from user input and stores them in a MySQL database locally.
There are a few warnings/errors that I am trying to resolve.
This is my code
Annotated the error-raising lines by comments.
elif (x == "Learn Python The Hard ... | [
"In order to cast your datetime object to string you can call the .strftime method builtin to the datetime package\ne.g. use:\nd3.strftime(\"%d.%m.%y\")\n\ninstead of just\nd3\n\nsame goes for d1 - (\"%d.%m.%y\") represents the format in which your datetime is being represented.\nResults would look like this:\nself... | [
0
] | [] | [] | [
"datetime",
"mysql",
"python"
] | stackoverflow_0074605853_datetime_mysql_python.txt |
Q:
Store password in Ansbile Vault and retrieve that key from Python script using API
I have a requirement where I should not store any passwords in the script files in plain text. So I have created an Ansible vault file called "vault.yml" which contains username and password.
Is there some kind of API that I can use... | Store password in Ansbile Vault and retrieve that key from Python script using API | I have a requirement where I should not store any passwords in the script files in plain text. So I have created an Ansible vault file called "vault.yml" which contains username and password.
Is there some kind of API that I can use to look up this value from python script called for example "test.py"?
What I would lik... | [
"Yes, ansible-vault is the Python library that you can use for this purpose.\nvault.py\n#!/usr/bin/env python3\n''' get secrets from ansible-vault file with gpg-encrypted password '''\nimport os\nimport sys\nfrom subprocess import check_output\nimport yaml\nfrom ansible_vault import Vault\n\nvault_file = sys.argv[1... | [
0
] | [] | [] | [
"ansible",
"ansible_vault",
"python",
"python_2.7"
] | stackoverflow_0053601810_ansible_ansible_vault_python_python_2.7.txt |
Q:
Finding when a value in a pandas Series crosses multiple threshold values from another Series
I have two Pandas Series, say sensor_values and thresholds. thresholds are defined in increasing order. How do I identify that in the sensor_value series, at what instances do the values cross any of the thresholds define... | Finding when a value in a pandas Series crosses multiple threshold values from another Series | I have two Pandas Series, say sensor_values and thresholds. thresholds are defined in increasing order. How do I identify that in the sensor_value series, at what instances do the values cross any of the thresholds defined in the other Series thresholds?
What I'm trying to do is basically what has been done in this ans... | [
"I'm thinking you could pd.cut the sensors values into intervals between thresholds and then compare those thresholds:\nimport numpy as np\nimport pandas as pd\n\nsensors = pd.Series([0.1, 1.3, 2.1, 1.7, 2.6, 3.8, 4.1, 5.1, 4.4, 3.2, 1.6, 7.2])\nthresholds = pd.Series([2, 5, 7])\n\nbins = pd.concat([pd.Series(-np.i... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_3.x",
"time_series"
] | stackoverflow_0074605380_numpy_pandas_python_python_3.x_time_series.txt |
Q:
Why is pip install missing source of my package?
I have a private package which I have uploaded to my private devpi server. When I use pip to install it, only the egg folder is installed. The source is missing and hence I am unable to use any code or libraries in my package.
My setup.py:
from setuptools import set... | Why is pip install missing source of my package? | I have a private package which I have uploaded to my private devpi server. When I use pip to install it, only the egg folder is installed. The source is missing and hence I am unable to use any code or libraries in my package.
My setup.py:
from setuptools import setup, find_packages
setup(
name='my-package',
versi... | [
"This fixed it:\ndevpi upload dist/pkg-ver.tar.gz\nBasically, run it from root of my project.\n"
] | [
-1
] | [] | [] | [
"devpi",
"pip",
"pypi",
"python",
"setuptools"
] | stackoverflow_0055525800_devpi_pip_pypi_python_setuptools.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.