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:
Reserving datasets from top to bottom of a list (database-table) for users avoiding race conditions (Django 4.1)
I start developing a Django web app that ist going to be used by hundreds of user at the same time.
The app consits of a simple database table that lists unique tasks top-down. The first user that reque... | Reserving datasets from top to bottom of a list (database-table) for users avoiding race conditions (Django 4.1) | I start developing a Django web app that ist going to be used by hundreds of user at the same time.
The app consits of a simple database table that lists unique tasks top-down. The first user that request some tasks should get the tasks from the top of the list. The next user that asks for tasks should get the next tas... | [
"Try select_for_update or F expressions you can find more info here\nF Expression\nselect_for_update\nalso I think this question might help \n"
] | [
2
] | [] | [] | [
"django",
"python",
"race_condition"
] | stackoverflow_0074228628_django_python_race_condition.txt |
Q:
How to install/setup GridDB in Ubuntu?
Besides using DOCKER, downloading CentOS, and setting up GridDB, How to setup a GridDB client and server on Ubuntu? Its docs have RPM/YUM methods only.
I want to do a quick explore GridDB using Python to interface with JayDeBeApi on Jupyter-Notebook
pip3 install griddb-pytho... | How to install/setup GridDB in Ubuntu? | Besides using DOCKER, downloading CentOS, and setting up GridDB, How to setup a GridDB client and server on Ubuntu? Its docs have RPM/YUM methods only.
I want to do a quick explore GridDB using Python to interface with JayDeBeApi on Jupyter-Notebook
pip3 install griddb-python --user
Since the above command has griddb... | [
"you can use Ubuntu with the current docs: https://docs.griddb.net/latest/gettingstarted/using-apt/\nIt seems as though that since this question was asked until now, you can install GridDB on Ubuntu using APT:\n$ sudo sh -c 'echo \"deb https://www.griddb.net/apt griddb/5.0 multiverse\" >> /etc/apt/sources.list.d/g... | [
0
] | [] | [] | [
"database",
"griddb",
"python",
"time_series",
"ubuntu"
] | stackoverflow_0065524132_database_griddb_python_time_series_ubuntu.txt |
Q:
How do I detect and remove multiple substrings, which may vary?
Every week, my school makes us type which assignments we will be doing for the week. I want to do this automatically with python.
Below is a example of what an input I might want the program to take.
Unit 1 presentation - Due in 2 days - 40 minutes sp... | How do I detect and remove multiple substrings, which may vary? | Every week, my school makes us type which assignments we will be doing for the week. I want to do this automatically with python.
Below is a example of what an input I might want the program to take.
Unit 1 presentation - Due in 2 days - 40 minutes spent
English Unit 2 Test - Due in 3 days - 1 hour spent
History Essay ... | [
"I would try to take each line as line and process as\nassignment_name = line.split(\"-\")[0].strip()\n\n"
] | [
0
] | [] | [] | [
"python",
"string",
"substring"
] | stackoverflow_0074228009_python_string_substring.txt |
Q:
Randomly replace cells in a numpy array without replacement
I have a 25 x 25 numpy array filled with 0s. I want to randomly replace 0s within the array with 1s, with the number of 0s to be replaced defined by the user and ranging from 1 to 625. How can I do this without replacement becoming an issue given there ar... | Randomly replace cells in a numpy array without replacement | I have a 25 x 25 numpy array filled with 0s. I want to randomly replace 0s within the array with 1s, with the number of 0s to be replaced defined by the user and ranging from 1 to 625. How can I do this without replacement becoming an issue given there are two coordinate values, x and y?
Code for generating a 25 x 25 a... | [
"Notes:\n\nOne may generate a unique sequence of random integers from 0 to 624, and mutate the corresponding element of the flattened array according to the generated sequence. Working with the flattened array, in this specific case, enables the development of a (relatively) concise code.\n\nOne can use np.random.c... | [
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074228368_numpy_python.txt |
Q:
When I call two methods, one from the parent class and one from the child class, only the first call returns
class Smarthphone():
def __init__(self, tamanho, interface):
self.tamanho = tamanho
self.interface = interface
def print_test(self):
return "testing parent class"
c... | When I call two methods, one from the parent class and one from the child class, only the first call returns | class Smarthphone():
def __init__(self, tamanho, interface):
self.tamanho = tamanho
self.interface = interface
def print_test(self):
return "testing parent class"
class MP3Player(Smarthphone):
def __init__(self, tamanho, interface, capacidade):
super().__init__(tama... | [
"You aren't printing anything. Whatever UI you are using is just showing you the last value the script produced. Do it the right way:\nprint(ob1.print_test())\nprint(ob1.print_MP3Player())\n\n"
] | [
2
] | [] | [] | [
"call",
"methods",
"object",
"python"
] | stackoverflow_0074228770_call_methods_object_python.txt |
Q:
Matplotlib x-axis have n values
I have a big dataframe but the datas are not at the same time. Sometimes every few seconds, sometimes every some minutes.
I'm using plt.xticks(x[::24], rotation=30) (one label every 24 values), but sometimes i have a lot of labels on x axis. So, I want to have 12 (for example) label... | Matplotlib x-axis have n values | I have a big dataframe but the datas are not at the same time. Sometimes every few seconds, sometimes every some minutes.
I'm using plt.xticks(x[::24], rotation=30) (one label every 24 values), but sometimes i have a lot of labels on x axis. So, I want to have 12 (for example) labels.
Is it possible on x-axis labels ha... | [
"After a lot of try and error, finally I found the solution.\nFirst, take the length of the dataframe.\nnval = len(df.T1)\n\nSecond calculate the number of values (as step in xticks). Divide the number of dataframe length by the number of ticks you want in your diagram (for me is 8). In most of cases this number is... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0073921189_matplotlib_python.txt |
Q:
AttributeError 'float' object has no attribute 'replace'
I am getting the Attribute error:
'float' object has no attribute 'replace'
In my program i am reading 3 different files. When i run the code it works perfectly, but only for one of the files. I have no clue why the other 2 files give me this error. I was e... | AttributeError 'float' object has no attribute 'replace' | I am getting the Attribute error:
'float' object has no attribute 'replace'
In my program i am reading 3 different files. When i run the code it works perfectly, but only for one of the files. I have no clue why the other 2 files give me this error. I was excpecting to get the amount of days in a given month from a .c... | [
"I assume you're coding in Python.\nIn Python, you cannot write .replace('x', 'y') for floats, but you can for strings. Different types have different properties.\nA very basic way of replacing floats with another number is as follows:\na = 5.5\nif a == 5.5:\n a = 9.3\n\nThere are many ways to change a float, bu... | [
0
] | [] | [] | [
"attributes",
"csv",
"data_analysis",
"python",
"replace"
] | stackoverflow_0074228750_attributes_csv_data_analysis_python_replace.txt |
Q:
Is there a way I can save user sign up details in a model depending on the data they've inputted?
I have a Student model and a Teacher model and I have created a custom user form that takes in an email field and whether the user is a student or a teacher. I would like to make it so that if the user selects that th... | Is there a way I can save user sign up details in a model depending on the data they've inputted? | I have a Student model and a Teacher model and I have created a custom user form that takes in an email field and whether the user is a student or a teacher. I would like to make it so that if the user selects that they are a teacher in the sign-up form, their new account details are stored in the Teacher model. If the... | [
"Yes, you should be able to do this by overriding the save() Method.\nMight need some tweaking, but this is generally what I'd do:\nclass CustomSignUpForm(UserCreationForm):\n email = forms.EmailField() \n is_teacher = forms.BooleanField(label='I am a teacher')\n\n class Meta:\n fields = ['username'... | [
1,
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0074227075_django_django_forms_django_models_python.txt |
Q:
How can I take another variable from a def function and add it to another def function to get a new sum?
def room1(phone_charge):
phone_charge = 5
import random
randNum = random.randint(1,5)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.... | How can I take another variable from a def function and add it to another def function to get a new sum? | def room1(phone_charge):
phone_charge = 5
import random
randNum = random.randint(1,5)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
... | [
"Since the two functions return their values, you can add them together after calling.\np1 = room1(phone_charge)\np5 = room5(phone_charge)\n\nprint(f\"Total is {p1 + p5}\")\n\n",
"Since the two functions have the same functionality use one function with an extra parameter.\nimport random\n\ndef room(phone_charge,... | [
0,
0
] | [] | [] | [
"function",
"python",
"sum"
] | stackoverflow_0074228852_function_python_sum.txt |
Q:
Check which decorator was applied to a function
Following this question I have an idea how to check whether my function was decorated or not.
Only that I need further information, namely the decorators that were actually applied onto the function (or called when the function was called if it suits better).
For bei... | Check which decorator was applied to a function | Following this question I have an idea how to check whether my function was decorated or not.
Only that I need further information, namely the decorators that were actually applied onto the function (or called when the function was called if it suits better).
For being safe from the danger mentioned in this answer, I a... | [
"TL;DR\nRoll your own @wraps.\nimport functools\n\ndef update_wrapper(wrapper, wrapped, decorator, **kwargs):\n wrapper = functools.update_wrapper(wrapper, wrapped, **kwargs)\n if decorator is not None:\n __decorators__ = getattr(wrapper, \"__decorators__\", [])\n setattr(wrapper, \"__decorators... | [
1
] | [] | [] | [
"decorator",
"python",
"python_decorators"
] | stackoverflow_0074209534_decorator_python_python_decorators.txt |
Q:
Fastest way to reshape numpy 1D array to 4D in a specific sequence?
I want to reshape the flattened channels array of audio to a 4D array(because audio has 4 channels). Reshape example is below:
Input example: [a1,b1,c1,d1,a2,b2,c2,d2,...]
Output 4D array: [[a1,a2,...], [b1,b2,...], [c1,c2,...], [d1,d2,...]]
Each ... | Fastest way to reshape numpy 1D array to 4D in a specific sequence? | I want to reshape the flattened channels array of audio to a 4D array(because audio has 4 channels). Reshape example is below:
Input example: [a1,b1,c1,d1,a2,b2,c2,d2,...]
Output 4D array: [[a1,a2,...], [b1,b2,...], [c1,c2,...], [d1,d2,...]]
Each subarray of the 4D array must be one of the channels of audio.
How can I ... | [
">>> data = np.arange(20)\n>>> data\narray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n 17, 18, 19])\n\n>>> data.reshape((4, -1), order='F')\narray([[ 0, 4, 8, 12, 16],\n [ 1, 5, 9, 13, 17],\n [ 2, 6, 10, 14, 18],\n [ 3, 7, 11, 15, 19]])\n\n",
"Another possi... | [
0,
0
] | [] | [] | [
"arrays",
"numpy",
"numpy_ndarray",
"python",
"reshape"
] | stackoverflow_0074228860_arrays_numpy_numpy_ndarray_python_reshape.txt |
Q:
Run python http.server for IPv6 only
python3 -m http.server --bind :: launches a python web server, as shown in Python 3: Does http.server support ipv6?. However, it also supports IPv4, because I can visit the web server with localhost:8000 (edit: even 127.0.0.1:8000 works). I don't want that. The python http.serv... | Run python http.server for IPv6 only | python3 -m http.server --bind :: launches a python web server, as shown in Python 3: Does http.server support ipv6?. However, it also supports IPv4, because I can visit the web server with localhost:8000 (edit: even 127.0.0.1:8000 works). I don't want that. The python http.server is dual-stack even though I used --bind... | [
"There is no way to do this because the support for IPv4 is not provided by Python, but by the OS. I'm not 100% sure though.\n\nMore details\nThe output of lsof -nP -i4TCP | grep LISTEN (open network files/sockets on IPv4) include (notice the IPv6)\nPython 30838 ben 3u IPv6 0xb364e79e7fc44213 0t0 TCP ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074228836_python.txt |
Q:
permission denied error while reading an excel file
i got a permission denied error while i tried to open an excel file.
I dont have the ms excel complete version. I mean, im just using the trial version.
Could it be because of that?
my code has just 4 lines
import pandas as pd
import numpy as np
import matplotl... | permission denied error while reading an excel file | i got a permission denied error while i tried to open an excel file.
I dont have the ms excel complete version. I mean, im just using the trial version.
Could it be because of that?
my code has just 4 lines
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_excel("E:\\ML")
| [
"It's something about how file open function works. I successfully reproduced your problem and find the way.\nIt's believed that you have a directory named ML in E disk, and maybe there are some excels files (such as *.xls or *.xlsx) in ML(I bet you just started learning machine learning). Now you try to load the e... | [
0,
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0059025819_error_handling_python.txt |
Q:
nested dictionary comprehension - adding if condition
I need to add an in statement, something along the list of list(vs) if type(vs, str)
d={'int':["unit", "bool"], 'timestamp':"pruct"}
{v: k
for k, vs in d.items()
for v in vs}
I need this output
{'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}
but I'm g... | nested dictionary comprehension - adding if condition | I need to add an in statement, something along the list of list(vs) if type(vs, str)
d={'int':["unit", "bool"], 'timestamp':"pruct"}
{v: k
for k, vs in d.items()
for v in vs}
I need this output
{'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}
but I'm getting
{'unit': 'int',
'bool': 'int',
'p': 'timestamp',
... | [
"In addition to my comment to the original question, here you go:\ndef listify_if_necessary(x):\n return [x] if isinstance(x, str) else x\n\n{v: k for k, vs in d.items() for v in listify_if_necessary(vs)}\n\nOut:\n{'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}\n\nNote, as wjandrea pointed out, this listify... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074228847_python.txt |
Q:
pipenv --system option for docker. What is the suggested way to get all the python packages in docker
I use pipenv for my django app.
$ mkdir djangoapp && cd djangoapp
$ pipenv install django==2.1
$ pipenv shell
(djangoapp) $ django-admin startproject example_project .
(djangoapp) $ python manage.py runserver
Now... | pipenv --system option for docker. What is the suggested way to get all the python packages in docker | I use pipenv for my django app.
$ mkdir djangoapp && cd djangoapp
$ pipenv install django==2.1
$ pipenv shell
(djangoapp) $ django-admin startproject example_project .
(djangoapp) $ python manage.py runserver
Now i am shifting to docker environment.
As per my understanding pipenv only installs packages inside a virtua... | [
"A typical Docker deployment would involve having a requirements.txt (it's a file where you can store your pip dependencies, including Django itself) file and then in your Dockerfile you do something like:\nFROM python:3.7 # or whatever version you need\nADD requirements.txt /code/\nWORKDIR /code\n# install your P... | [
2,
0
] | [] | [] | [
"django",
"docker",
"pipenv",
"python"
] | stackoverflow_0055064812_django_docker_pipenv_python.txt |
Q:
Make pytest require code coverage only on full test suite run
I am using something like
# .coveragerc
fail_under = 100
and
# pytest.ini
[pytest]
addopts = --cov=modname/ --cov-report=term-missing
to make it so that my test suite runs the coverage and fails if it isn't 100%.
This works, but the problem is that if... | Make pytest require code coverage only on full test suite run | I am using something like
# .coveragerc
fail_under = 100
and
# pytest.ini
[pytest]
addopts = --cov=modname/ --cov-report=term-missing
to make it so that my test suite runs the coverage and fails if it isn't 100%.
This works, but the problem is that if I run only a subset of the tests, like
pytest some/specific/test.p... | [
"You can temporarily override your .coveragerc by adding the following flag to your command:\n--cov-fail-under=x\n\nwhere x is the percentage to fail under (if you set this to 0, it will never fail based on the code coverage)\nThus, in your case you would run:\npytest some/specific/test.py --cov-fail-under=x\n\n",
... | [
2,
0
] | [] | [] | [
"code_coverage",
"coverage.py",
"pytest",
"python",
"test_coverage"
] | stackoverflow_0061880294_code_coverage_coverage.py_pytest_python_test_coverage.txt |
Q:
Split string into list of two words, repeating the last word
I need to split a string into a list of each two words, but repeating the last word of each pair of words.
Here is what I tried, by using examples I found for other questions:
line = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eius... | Split string into list of two words, repeating the last word | I need to split a string into a list of each two words, but repeating the last word of each pair of words.
Here is what I tried, by using examples I found for other questions:
line = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."""
def sp... | [
"You can use zip on the following two slices of words:\nwords = line.split()\nprint(list(map(' '.join, zip(words[:-1], words[1:]))))\n\nThis outputs:\n['Lorem ipsum', 'ipsum dolor', 'dolor sit', 'sit amet,', 'amet, consectetur', 'consectetur adipiscing', 'adipiscing elit,', 'elit, sed', 'sed do', 'do eiusmod', 'eiu... | [
12,
4,
3,
2,
1,
1,
1,
0
] | [] | [] | [
"list",
"python",
"split",
"string"
] | stackoverflow_0051668340_list_python_split_string.txt |
Q:
write text from terminal of python code to a txt file?
I made a simple project in python that pings a server every few seconds and I want to store the ping data in a .txt file. (It might also be cool to put it in a GUI but I need it in a txt file for now). Also, it just shows the ping in the terminal so I have no ... | write text from terminal of python code to a txt file? | I made a simple project in python that pings a server every few seconds and I want to store the ping data in a .txt file. (It might also be cool to put it in a GUI but I need it in a txt file for now). Also, it just shows the ping in the terminal so I have no idea how I would make it go into a txt because I'm new at co... | [
"You'll have to run your code with Popen instead of os.system (which is a bad idea in most cases, anyway, for security reasons).\nWith Popen (python.org -> documentation is your friend!) you can capture the output of the programs you run. You can then write that to a file object. (That's a built-in type in python. ... | [
0
] | [] | [] | [
"ping",
"python",
"terminal",
"txt"
] | stackoverflow_0074229060_ping_python_terminal_txt.txt |
Q:
My code is the exact same as the output should look like, but for some reason it is wrong
I am trying to write a program in which a function accepts the name of a file and a list of tuples. Each tuple in the list will contain 5 entries, where the 1st, 3rd, and 4th entries are ints, 2nd entry is a string, and 5th e... | My code is the exact same as the output should look like, but for some reason it is wrong | I am trying to write a program in which a function accepts the name of a file and a list of tuples. Each tuple in the list will contain 5 entries, where the 1st, 3rd, and 4th entries are ints, 2nd entry is a string, and 5th entry is a float. The goal of the program is to write the 5 elements of each tuple on a separate... | [
"Your issue is that your manually writting each element individually and adding a space after each element. This means that when you write the last element you also add a trailing space. so your output looks like it matches but acutally your lines all have a trailing space.\nInstead you can use string join to join ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074229021_python.txt |
Q:
Error in building wheel for osqp because "No module named cmake' "
I'm trying to install the cvxpy package in my virtual environment of PyCharm. I typed C:\Users\<Username>\PycharmProjects\<projectName>\venv\Scripts>pip install cvxpy, and got:
Collecting cvxpy
Using cached cvxpy-1.2.1-cp311-cp311-win_amd64.whl
C... | Error in building wheel for osqp because "No module named cmake' " | I'm trying to install the cvxpy package in my virtual environment of PyCharm. I typed C:\Users\<Username>\PycharmProjects\<projectName>\venv\Scripts>pip install cvxpy, and got:
Collecting cvxpy
Using cached cvxpy-1.2.1-cp311-cp311-win_amd64.whl
Collecting ecos>=2
Using cached ecos-2.0.10-cp311-cp311-win_amd64.whl
C... | [
"Update: this has been resolved by uninstalling python version 3.11.0 and installing python version 3.10.7. This page suggested that OSQP developers have validated the build wheels properly for 3.10. So maybe they havn't done that for 3.11 yet.\n"
] | [
0
] | [] | [] | [
"cmake",
"cvxpy",
"python"
] | stackoverflow_0074226651_cmake_cvxpy_python.txt |
Q:
Import "flask" could not be resolved Pylance
I am getting this missing import error.
I tried installing flask and flask alchemy again but it says requirement satisfied
A:
Did you install the module?
You can do this by for example by writing pip install flask in your command line.
| Import "flask" could not be resolved Pylance | I am getting this missing import error.
I tried installing flask and flask alchemy again but it says requirement satisfied
| [
"Did you install the module?\nYou can do this by for example by writing pip install flask in your command line.\n"
] | [
0
] | [] | [] | [
"pylance",
"python",
"virtualenv",
"visual_studio_code"
] | stackoverflow_0074229065_pylance_python_virtualenv_visual_studio_code.txt |
Q:
How do I add a timer in my game, which directs the game state to "gameover" once it reaches the time limit?
My game never ends, you can basically click on the button forever. However I tried adding a time limit, but it never changes the game state to "gameover" it only stays in "game". I also want to add a scorebo... | How do I add a timer in my game, which directs the game state to "gameover" once it reaches the time limit? | My game never ends, you can basically click on the button forever. However I tried adding a time limit, but it never changes the game state to "gameover" it only stays in "game". I also want to add a scoreboard which tracks the amount of clicks per instance of game, which saves in the "gameover" state.
Here is my code:... | [
"Your program depends on states changing in response to events but your while True: design potentially blocks some or all of those events. Using timer events, I've reworked your program into design that you should be able to build upon to complete your game:\nfrom turtle import Screen, Turtle\n\nSCREEN_WIDTH = 800... | [
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074227934_python_python_turtle_turtle_graphics.txt |
Q:
my code keeps saying incorrect when i create my math game
the question: Create a math game where random addition, subtraction, multiplication or division
questions appear and the user has determine the answer.
My code keeps showing incorrect even thou the real answer is correct in my math game.
And i want to add w... | my code keeps saying incorrect when i create my math game | the question: Create a math game where random addition, subtraction, multiplication or division
questions appear and the user has determine the answer.
My code keeps showing incorrect even thou the real answer is correct in my math game.
And i want to add were the code tells the user to enter a number where it says ans... | [
"you shouldn't use a while loop for each option. Use a single loop for the whole program. Get the option, then use a series of if/elif statements to execute the code for that option.\nYou also have lots of duplicate code in each option. You can extract that out of the option processing into a single code block.\n#O... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074229040_python.txt |
Q:
OpenPyXL - Is it possible to add a Input message to a data validation list?
I have an excel spreadsheet (.xlsm) that gets generated using openpyxl. A number of fields are dropdown menus which are generated using the following code
#function to add validation drop down menu within xlsm file
def addValidationDropDow... | OpenPyXL - Is it possible to add a Input message to a data validation list? | I have an excel spreadsheet (.xlsm) that gets generated using openpyxl. A number of fields are dropdown menus which are generated using the following code
#function to add validation drop down menu within xlsm file
def addValidationDropDown(sheet,formulaLocation,dropdownLocation):
dataVal = DataValidation(type="lis... | [
"Thanks to Charlie Clark, works for me even in the old OpenPyXl version\n'promptTitle' can be skipped, but not 'prompt'\ndata_val_hint = DataValidation()\nvalRange = \"A1:A10\"\ndata_val_hint.prompt = 'hint'\ndata_val_hint.ranges.append(valRange)\nworksheet.add_data_validation(data_val_hint)\n \n\n"
] | [
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0065810204_openpyxl_python.txt |
Q:
Add field to json with condition
I'm trying to add a new json field conditionally looking for others fields values using python, like that:
{
"id":"x2342345ap",
"quantity":1,
"timestamp":"2022-09-26",
"details":[
{
"name":"robert",
"color":"red",
"age": 25
... | Add field to json with condition | I'm trying to add a new json field conditionally looking for others fields values using python, like that:
{
"id":"x2342345ap",
"quantity":1,
"timestamp":"2022-09-26",
"details":[
{
"name":"robert",
"color":"red",
"age": 25
}
]
}
And then looking into the... | [
"You can treat JSON similarly to how you interact with native dictionaries and lists. For example, I'll start with a string, convert to JSON, and then add a note to the list of problems:\nimport json\njsonstring = \"\"\"\n{\n \"id\":\"x2342345ap\",\n \"quantity\":1,\n \"timestamp\":\"2022-09-26\",\n \"detai... | [
0
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074229151_dictionary_python_python_3.x.txt |
Q:
Writing a function that uses a given recursive formula to return the nth number in the sequence
Given =1.5(−1)−0.5(−2) for=2,3,…. (0)=(0) (1)=(1)
I need to write a function that uses the given formula to return the nth number in the sequence. I was given the following starter code:
# function to produce n-th numbe... | Writing a function that uses a given recursive formula to return the nth number in the sequence | Given =1.5(−1)−0.5(−2) for=2,3,…. (0)=(0) (1)=(1)
I need to write a function that uses the given formula to return the nth number in the sequence. I was given the following starter code:
# function to produce n-th number of the following sequence:
# f0=s0, f1=s1 (s0, s1 -- preset parameters)
# f_n =1.5* f_{n-1} -0.5*f_... | [
"You don't need to store anything, just call the function recursively twice.\ndef get_n_value( n, s0, s1 ):\n # handle special cases for the first three elements\n if n<0:\n return 0\n elif n==0:\n return s0\n elif n==1:\n return s1\n\n # the general case, n>1\n else:\n ... | [
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074229238_python_recursion.txt |
Q:
Need specific sets of columns to be converted into a row and the rest of columns to repeat values
I have data in the following format
ID
SCHOOL
Name1
Name1 Subject1
Name1 Grade1
Name1 Subject2
Name1 Grade2
Name2
Name2 Subject1
Name2 Grade1
Name2 Subject2
Name2 Grade2
1
S1
Mr. ABC
Math
6
Science
7
Mr. XYZ
Social
... | Need specific sets of columns to be converted into a row and the rest of columns to repeat values | I have data in the following format
ID
SCHOOL
Name1
Name1 Subject1
Name1 Grade1
Name1 Subject2
Name1 Grade2
Name2
Name2 Subject1
Name2 Grade1
Name2 Subject2
Name2 Grade2
1
S1
Mr. ABC
Math
6
Science
7
Mr. XYZ
Social
8
EVS
9
2
S2
Mr. PQR
Math
10
Science
11
Mr. KLM
Social
8
EVS
9
Can I transform it in the fo... | [
"there might be a nicer solution but this also works:\ndf_1=df[['ID', 'SCHOOL','Name1', 'Name1 Subject1',\n 'Name1 Grade1']]\ndf_2=df[['ID', 'SCHOOL','Name1', 'Name1 Subject2',\n 'Name1 Grade2']]\n\ndf_3=df[['ID', 'SCHOOL','Name2', 'Name2 Subject1',\n 'Name2 Grade1']]\n\ndf_4=df[['ID', 'SCHOOL','N... | [
2,
0
] | [] | [] | [
"data_cleaning",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074078937_data_cleaning_dataframe_numpy_pandas_python.txt |
Q:
How to detect black contour in image using open-cv
I have an image showed below (this image is a result of pre-processing of original image I had):
What I am trying to do is to detect the contour for the Black region bounded by 2 white regions (please note that white regions are not always solid and there could b... | How to detect black contour in image using open-cv | I have an image showed below (this image is a result of pre-processing of original image I had):
What I am trying to do is to detect the contour for the Black region bounded by 2 white regions (please note that white regions are not always solid and there could be 2, 3,... disconnected white region on top - for most o... | [
"Here is how:\nimport cv2\nimport numpy as np\n\nimg = cv2.imread(r\"D:\\OpenCV Projects\\Black Contour\\image.jpg\")\n\nimg_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\nlower = np.array([0, 0, 75])\nupper = np.array([179, 179, 115])\nmask = cv2.inRange(img_hsv, lower, upper)\n\nmask_blur = cv2.GaussianBlur(mask, (3... | [
4,
3,
2
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074047007_image_processing_opencv_python.txt |
Q:
Pyinstaller produces massive folder
I'm using pyinstaller to pack a splash screen, these are the import of the python script:
import subprocess
import time
import sys
import os
import signal
from multiprocessing import Process, Queue
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pa... | Pyinstaller produces massive folder | I'm using pyinstaller to pack a splash screen, these are the import of the python script:
import subprocess
import time
import sys
import os
import signal
from multiprocessing import Process, Queue
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango
I use the following command to creat... | [
"Pyinstaller packs all your installed librarieswith pip ,so you need to create a clean new virtual environment and only install packages that you need in that environment, when you do that install pyinstaller inside and run it\n",
"If a .exe file (and no other folders/files) is acceptable (really just try it out ... | [
1,
0
] | [] | [] | [
"pyinstaller",
"python",
"splash_screen"
] | stackoverflow_0049220238_pyinstaller_python_splash_screen.txt |
Q:
Why does importing a module with the right name give me a ModuleNotFoundError?
I'm trying to run the main.py module, as the picture bellow shows, the name is correct, both Letra.py (which is importing from widgets.py) and widgets.py are in the same directory. Widgets.py is not importing anything but "pyglet" which... | Why does importing a module with the right name give me a ModuleNotFoundError? | I'm trying to run the main.py module, as the picture bellow shows, the name is correct, both Letra.py (which is importing from widgets.py) and widgets.py are in the same directory. Widgets.py is not importing anything but "pyglet" which is a library I'm using (and probably irrelevant to this problem).
The picture alrea... | [
"where is the __init__.py in the folder Widgets? For a folder or subfolder to be recognized as a package, it has to have __init__.py. Only then you can use the dot notation Widgets.letra or Widgets.widgets to import the required modules into other modules.\n",
"To import widgets from main.py, you wrote this line:... | [
0,
0
] | [] | [] | [
"directory",
"import",
"module",
"modulenotfounderror",
"python"
] | stackoverflow_0074229175_directory_import_module_modulenotfounderror_python.txt |
Q:
swapping position of two specific numbers in a text file python?
I want to swap two numbers position on each line of the text file after i replace equal symbol with this '|' and save it, but I'm having trouble to do that! For instance
123456789=123456789
i wanted it to look like this:
123453489=126756789
As you ca... | swapping position of two specific numbers in a text file python? | I want to swap two numbers position on each line of the text file after i replace equal symbol with this '|' and save it, but I'm having trouble to do that! For instance
123456789=123456789
i wanted it to look like this:
123453489=126756789
As you can see, I swapped 34 with 67!
This is my code:
with open('track.txt', '... | [
"Use a regular expression with capture groups, so you can copy to the replacement in a different order.\nimport re\n\nwith open('track.txt', 'r') as z:\n data = z.read()\n \ndata = re.sub(r'^(.{5})(.{2})(.*)=(.{2})(.{2})(.*)$', r'\\1\\5\\3|\\4\\2\\6', data, flags=re.MULTILINE)\n\nwith open('track2.txt', 'w') as ... | [
1
] | [] | [] | [
"list",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074229298_list_python_python_2.7_python_3.x.txt |
Q:
Optimization of this python function
def split_trajectories(df):
trajectories_list = []
count = 0
for record in range(len(df)):
if record == 0:
continue
if df['time'].iloc[record] - df['time'].iloc[record - 1] > pd.Timedelta('0 days 00:00:30'):
temp_df = reset_in... | Optimization of this python function | def split_trajectories(df):
trajectories_list = []
count = 0
for record in range(len(df)):
if record == 0:
continue
if df['time'].iloc[record] - df['time'].iloc[record - 1] > pd.Timedelta('0 days 00:00:30'):
temp_df = reset_index(df[count:record])
if not t... | [
"Maybe you can try this one below, you could use count if you want to keep track of number of df's or else the length of trajectories_list will give you that info.\ndef split_trajectories(df):\n trajectories_list = []\n df_difference = df['time'].diff()\n if not (df_difference.empty) and (df_difference.shape[0]>... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074229031_dataframe_pandas_python.txt |
Q:
Can't Run py2app on Mac big sur : Launch error See the py2app website for debugging launch issues
So im just trying to run a filemanager code and i want it to run as an application.
from setuptools import setup
APP = ['FileManager.py']
OPTIONS = {
'argv_emulation':True,
}
setup(
app = APP,
options = ... | Can't Run py2app on Mac big sur : Launch error See the py2app website for debugging launch issues | So im just trying to run a filemanager code and i want it to run as an application.
from setuptools import setup
APP = ['FileManager.py']
OPTIONS = {
'argv_emulation':True,
}
setup(
app = APP,
options = {'py2app':OPTIONS},
setup_requires = ['py2app']
)
But i am running into this error :
Launch error
... | [
"I got the same error. The command provided in the website where it says \"launch the application as follows\", is equivalent to the following:\n\nRight click on the application package created by py2app in \"dist\" folder, in your case it should be named FileManager.\nClick on \"Show Package Contents\".\nGo to con... | [
0,
0
] | [] | [] | [
"macos",
"py2app",
"python"
] | stackoverflow_0069573314_macos_py2app_python.txt |
Q:
Compare two columns using pandas
Using this as a starting point:
a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
which looks like
one two three
0 10 1.2 4.2
1 15 70 0.03
2 8 5 0
I want to use something like an if statem... | Compare two columns using pandas | Using this as a starting point:
a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
which looks like
one two three
0 10 1.2 4.2
1 15 70 0.03
2 8 5 0
I want to use something like an if statement within pandas.
if df['one'] >= df[... | [
"You could use np.where. If cond is a boolean array, and A and B are arrays, then\nC = np.where(cond, A, B)\n\ndefines C to be equal to A where cond is True, and B where cond is False.\nimport numpy as np\nimport pandas as pd\n\na = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]\ndf = pd.DataFrame(a,... | [
214,
121,
32,
12,
9,
5,
4,
3,
2,
0,
0
] | [] | [] | [
"dataframe",
"if_statement",
"pandas",
"python"
] | stackoverflow_0027474921_dataframe_if_statement_pandas_python.txt |
Q:
Why doesn't os.path.join() work in this case?
The below code will not join, when debugged the command does not store the whole path but just the last entry.
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
When I test this it only stores the /new_sandbox/ part of the code.
A:
The latter st... | Why doesn't os.path.join() work in this case? | The below code will not join, when debugged the command does not store the whole path but just the last entry.
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
When I test this it only stores the /new_sandbox/ part of the code.
| [
"The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an \"absolute path\" and everything before them is discarded.\nQuoting the Python docs for os.path.join:\n\nIf a component is an absolute path, all previous components are thrown away and joining continues from the... | [
529,
167,
89,
32,
25,
14,
11,
8,
3,
2,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0001945920_path_python.txt |
Q:
From printing a list how can I remove brackets, quotes and insert "and" before each last name
This code gives me the output: The names found are: ['Alba', 'Dawson', 'Oliver']
I would need to remove the brackets and quotes, and always print "and" before the last name (the number of names can be variable and for exa... | From printing a list how can I remove brackets, quotes and insert "and" before each last name | This code gives me the output: The names found are: ['Alba', 'Dawson', 'Oliver']
I would need to remove the brackets and quotes, and always print "and" before the last name (the number of names can be variable and for example I could have 3,4,5,6 names), so I would need this output:
The names found are: Alba, Dawson an... | [
"I see: you want to replace the final comma (' ) with and. This will do it.\nsplitted = [name.strip() for name in names.split(',')]\nas_string = ', '.join(splitted[:-1]) + ' and ' + splitted[-1]\n\nPrevious Answer\nIt sounds like you need to create a list, not assign to individual variables, and then index the list... | [
1,
1
] | [] | [] | [
"python",
"python_3.x",
"split",
"variables"
] | stackoverflow_0074229201_python_python_3.x_split_variables.txt |
Q:
add months in an existing data frame python
Year
Price
2017
200
2018
250
2019
300
Given the table above, is there a way to add months to each year ? For eg: 2017 should have months jan to dec and the same price carried forward in all of the 12 months for all the years listed in a data frame in Pandas?
Year
Pr... | add months in an existing data frame python |
Year
Price
2017
200
2018
250
2019
300
Given the table above, is there a way to add months to each year ? For eg: 2017 should have months jan to dec and the same price carried forward in all of the 12 months for all the years listed in a data frame in Pandas?
Year
Price
2017/01/01
200
2017/02/0... | [
"There's probably a better answer out there (I know very little Pandas), but one thing that comes to mind is:\nGet the date represented by your numeric \"Year\". That will give you January 1st at midnight in that Year. You can drop the time part (the \"hour\", if you may) and keep just the date (January 1st of that... | [
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074228901_pandas_python.txt |
Q:
Trying to count amount of occurences after a certain word from certain JSON file but am having trouble
ERROR numCraft = data['craft']
KeyError: 'craft'
I have tried to implement different counts and loops but am having trouble just count the amount of different crafts. The answer is two but just do not know ho... | Trying to count amount of occurences after a certain word from certain JSON file but am having trouble | ERROR numCraft = data['craft']
KeyError: 'craft'
I have tried to implement different counts and loops but am having trouble just count the amount of different crafts. The answer is two but just do not know how to implement or understand the concept of JSON
| [
"Here is a (shortened) version of the json content from that url:\n{\n \"message\": \"success\",\n \"people\": [\n {\n \"name\": \"Cai Xuzhe\",\n \"craft\": \"Tiangong\"\n },\n {\n \"name\": \"Chen Dong\",\n \"craft\": \"Tiangong\"\n },\n {\n \"name\": \"Anna Kikina\",\n ... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074229489_json_python.txt |
Q:
Tkinter, threads, several widgets to update periodically
I am trying to do an app using tkinter that gets information from some internet sources after entering stuff in an input box and then clicking a "load" button.
The button function reads the stuff string from the input box. After its loaded it retrieves some ... | Tkinter, threads, several widgets to update periodically | I am trying to do an app using tkinter that gets information from some internet sources after entering stuff in an input box and then clicking a "load" button.
The button function reads the stuff string from the input box. After its loaded it retrieves some info from the internet (which is blocking), and then update so... | [
"I would solve this by creating a data structure, creating a function that can update the display based on the current values in the data structure, and then binding to an event that calls this function. Then, create a thread that updates this data structure and emits the event when the data changes.\nHere's a cont... | [
1
] | [] | [] | [
"multithreading",
"python",
"tkinter"
] | stackoverflow_0074229125_multithreading_python_tkinter.txt |
Q:
Python count down timer for date, hour, minute and second
In this link on the second example i found a count down timer, but it only works for minutes and seconds, how can i make it work for hours and days too. This is the code
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
... | Python count down timer for date, hour, minute and second | In this link on the second example i found a count down timer, but it only works for minutes and seconds, how can i make it work for hours and days too. This is the code
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(... | [
"First things first:\nUsing .sleep() as a timer is not a good idea. Sleep() doesn't take into consideration the time necessary to run the code. So what you're in reality getting is not one second but code execution time + .sleep() + code execution time. This means that if send this code to someone it will calculate... | [
6,
3
] | [
"import time as t\ndef timer(x):\n # The while will make sure that the timer will end at 0\n while x > -1:\n # Seconds get the remainder of x/60 as the minutes will be truncated by int()\n mins = int(x/60)\n secs = x % 60\n print('{:02d}:{:02d}'.format(mins, secs))\n x = x -... | [
-1,
-2
] | [
"countdowntimer",
"python"
] | stackoverflow_0068283946_countdowntimer_python.txt |
Q:
line 1921 and 18 about callback?
Error msg:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\MISHIKA\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\MISHIKA\AppData\Roaming\Microsoft\Windows\Start... | line 1921 and 18 about callback? | Error msg:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\MISHIKA\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\MISHIKA\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\tkinter\cls... | [
"Take a look in my example.\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom functools import partial\n\ntemp_Val = \"Celsius\"\n\ndef store_temp(set_temp):\n global temp_Val\n temp_Val = set_temp\n\ndef call_convert(rlabel1, inputn):\n temp = inputn.get()\n \n if temp_Val == 'Celsius':\n ... | [
0
] | [] | [] | [
"command_line",
"python",
"tkinter"
] | stackoverflow_0074229465_command_line_python_tkinter.txt |
Q:
Python reading from a file and saving to utf-8
I'm having problems reading from a file, processing its string and saving to an UTF-8 File.
Here is the code:
try:
filehandle = open(filename,"r")
except:
print("Could not open file " + filename)
quit()
text = filehandle.read()
filehandle.close()
I then... | Python reading from a file and saving to utf-8 | I'm having problems reading from a file, processing its string and saving to an UTF-8 File.
Here is the code:
try:
filehandle = open(filename,"r")
except:
print("Could not open file " + filename)
quit()
text = filehandle.read()
filehandle.close()
I then do some processing on the variable text.
And then
... | [
"Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend alw... | [
223,
13,
5,
1,
0
] | [] | [] | [
"python",
"python_2.7",
"utf_8"
] | stackoverflow_0019591458_python_python_2.7_utf_8.txt |
Q:
How to properly round-up half float numbers?
I am facing a strange behavior of the round() function:
for i in range(1, 15, 2):
n = i / 2
print(n, "=>", round(n))
This code prints:
0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
I expected the floating values to be always rounded up, but in... | How to properly round-up half float numbers? | I am facing a strange behavior of the round() function:
for i in range(1, 15, 2):
n = i / 2
print(n, "=>", round(n))
This code prints:
0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
I expected the floating values to be always rounded up, but instead, it is rounded to the nearest even number.
W... | [
"The Numeric Types section documents this behaviour explicitly:\n\nround(x[, n])\nx rounded to n digits, rounding half to even. If n is omitted, it defaults to 0. \n\nNote the rounding half to even. This is also called bankers rounding; instead of always rounding up or down (compounding rounding errors), by roun... | [
96,
49,
31,
27,
11,
10,
9,
3,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [
"You can try this\ndef round(num):\n return round(num + 10**(-9))\n\nit will work since num = x.5 will always will be x.5 + 0.00...01 in the process which its closer to x+1 hence the round function will work properly and it will round x.5 to x+1\n"
] | [
-1
] | [
"floating_point",
"precision",
"python",
"python_3.x",
"rounding"
] | stackoverflow_0033019698_floating_point_precision_python_python_3.x_rounding.txt |
Q:
How to delete number of chat in discord by python
I would like to create a bot which can delete number of recently chat and history chat
import discord
import random
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self,... | How to delete number of chat in discord by python | I would like to create a bot which can delete number of recently chat and history chat
import discord
import random
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
channel = message.channel.name
... | [
"First off, personally, I would change the structure/ layout of your code. This is so that it is easier to read, and easier to change and add commands/ different functions to. This is the way I have my bot setup and how I have seen many other bots setup as well:\nimport discord\n\nclient = commands.Bot(command_pref... | [
0
] | [] | [] | [
"bots",
"discord.py",
"python"
] | stackoverflow_0074225452_bots_discord.py_python.txt |
Q:
Resetting generator object in Python
I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.
y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: pr... | Resetting generator object in Python | I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.
y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)
Of course, I'm taking in mind copy... | [
"Generators can't be rewound. You have the following options:\n\nRun the generator function again, restarting the generation:\ny = FunctionWithYield()\nfor x in y: print(x)\ny = FunctionWithYield()\nfor x in y: print(x)\n\nStore the generator results in a data structure on memory or disk which you can iterate over ... | [
182,
150,
43,
32,
29,
7,
5,
5,
4,
2,
1,
1,
1,
1,
1,
0,
0,
0
] | [
"It can be done by code object. Here is the example.\ncode_str=\"y=(a for a in [1,2,3,4])\"\ncode1=compile(code_str,'<string>','single')\nexec(code1)\nfor i in y: print i\n\n1\n2\n3\n4\nfor i in y: print i\n\n\nexec(code1)\nfor i in y: print i\n\n1\n2\n3\n4\n"
] | [
-3
] | [
"generator",
"python",
"yield"
] | stackoverflow_0001271320_generator_python_yield.txt |
Q:
How can I fix the problem, where when I try run the code, it doesn't respond, nor shows anything?
So, when I try to Run the code I made, it doesn't say, or show up anything, not even showing an error. I'm making a Discord Bot for a personal server with 3 files included (LBot.py, main.py, and LResponses.py). I'm us... | How can I fix the problem, where when I try run the code, it doesn't respond, nor shows anything? | So, when I try to Run the code I made, it doesn't say, or show up anything, not even showing an error. I'm making a Discord Bot for a personal server with 3 files included (LBot.py, main.py, and LResponses.py). I'm using PyCharm Community Edition 2022, and I don't know if it has an effect on it
LBot.py
import discord
i... | [
"One of the major problems I see here is that you have client.run(TOKEN) inside your on_message event. This is a paradox because in order to turn your bot online (client.run), you need to go through an event (on_message), which is impossible to get to because your bot is not online and therefore unable to receive/ ... | [
0
] | [] | [] | [
"bots",
"chatbot",
"discord",
"python",
"python_3.x"
] | stackoverflow_0074225195_bots_chatbot_discord_python_python_3.x.txt |
Q:
How do I sum up lines of string based on a dictionary value?
I am pretty new to python and coding. I am trying to write a code that will print out the total amount of each given wire type from a list of wires. This is a side project for work. I was able to come up with a code to sum up all of the wire for a user d... | How do I sum up lines of string based on a dictionary value? | I am pretty new to python and coding. I am trying to write a code that will print out the total amount of each given wire type from a list of wires. This is a side project for work. I was able to come up with a code to sum up all of the wire for a user defined wire type. Now I would like to make another code that print... | [
"Here is one simple way, with very little code, that uses the pandas library.\nimport pandas\n\ndf = pandas.read_csv(\"test.csv\")\ndf_out = df.groupby(\"TYPE\")[\"QTY\"].sum()\nprint(\"Output:\", df_out.to_dict())\n\n# Output: {'M22759/16-20-9': 12, 'M22759/16-22-9': 18}\n\nIt assumes that the input CSV file looks... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074229335_dictionary_python.txt |
Q:
tkinter scale slider value not showing
below is my code for a basic tkinter scale:
root = tk.Tk()
root.geometry('150x75')
root.resizable(width=False, height=False)
root.eval('tk::PlaceWindow . center')
v1 = tk.IntVar()
ttk.Scale(root, from_=0, to=100, orient='horizontal', variable=v1).pack(pady=20)
root.mainloo... | tkinter scale slider value not showing | below is my code for a basic tkinter scale:
root = tk.Tk()
root.geometry('150x75')
root.resizable(width=False, height=False)
root.eval('tk::PlaceWindow . center')
v1 = tk.IntVar()
ttk.Scale(root, from_=0, to=100, orient='horizontal', variable=v1).pack(pady=20)
root.mainloop()
below is the attached output :
why is ... | [
"The tkinter.ttk version of Scale does not support showing the value.\nBut the tkinter version of Scale DOES support showing the Scale value, by default. The showvalue option defaults to 1. You can set it to 0 to hide the value if so desired.\n",
"There is no error in your code. I think the answer is \"because it... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0070051869_python_tkinter.txt |
Q:
In Python, iterate over list representing a flat nested structure and create a new list with the index of each element
I have a list with generic words of generic length, representing a flat representation of a nested structure where each level is separated by "/".
['apple', 'apple/dog', 'apple/dog/banana', 'apple... | In Python, iterate over list representing a flat nested structure and create a new list with the index of each element | I have a list with generic words of generic length, representing a flat representation of a nested structure where each level is separated by "/".
['apple', 'apple/dog', 'apple/dog/banana', 'apple/dog/apple', 'apple/cat', 'cold', 'cold/banana', ....]
I want to, with respect to list input order, create a string represe... | [
"Sounds like an easy iterative problem:\n\nInitially, create an empty list lastitem\nInitially, create an empty list lastnumbering\nTake the next input element. Split it into a list along the \"/\" characters.\nCompare the list element-wise to the entries of lastitem.\n\nAs long as the elements are equal, keep the ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074229655_python.txt |
Q:
How to run code in the python interpreter from a python script?
I am trying to run code in the python interpreter from a python script (on windows, using the terminal build in to vsc), but I can't make anything work. I have spent a lot of time using the subprocess,and have also tried os module, but the issue with ... | How to run code in the python interpreter from a python script? | I am trying to run code in the python interpreter from a python script (on windows, using the terminal build in to vsc), but I can't make anything work. I have spent a lot of time using the subprocess,and have also tried os module, but the issue with those, is that they cannot run code in the interpreter. So, I can mak... | [
"Use the suprocess library like this.\nimport sys\nimport subprocess\n\np = subprocess.run(sys.executable, text=True, capture_output=True,\n input='print(1+1)')\nprint(p.stdout)\nprint(p.stderr)\n\nIf you want to reuse a single child process, you have to implement a client and server system. One easy method is t... | [
0
] | [] | [] | [
"python",
"subprocess",
"terminal"
] | stackoverflow_0074227721_python_subprocess_terminal.txt |
Q:
How do I convert a folder of images to a npy file?
I have a folder containing images of gestures. But to make it work on my code I need to change it to X.npy and Y.npy. I looked for many questions regarding this kinda problems but still in the dark. How do I evaluate this? How do I convert the folder to create npy... | How do I convert a folder of images to a npy file? | I have a folder containing images of gestures. But to make it work on my code I need to change it to X.npy and Y.npy. I looked for many questions regarding this kinda problems but still in the dark. How do I evaluate this? How do I convert the folder to create npy dataset of my own? Is there any code for this or any co... | [
"I found a piece of code for this purpose on github.\nfrom PIL import Image\nimport os, sys\nimport cv2\nimport numpy as np\n\n'''\nConverts all images in a directory to '.npy' format.\nUse np.save and np.load to save and load the images.\nUse it for training your neural networks in ML/DL projects. \n'''\n\n# Path ... | [
0,
0
] | [] | [] | [
"image",
"numpy",
"python"
] | stackoverflow_0073120561_image_numpy_python.txt |
Q:
Mean of monthly data on a yearly basis using groupie
I am trying to get the yearly average return (RET) column of this monthly data grouped on year and CUSIP.
I am expecting the average of the returns for that CUSIP for that year to be same for the month ranges.
For eg if for cusip 000307 and year 2018, I have ave... | Mean of monthly data on a yearly basis using groupie | I am trying to get the yearly average return (RET) column of this monthly data grouped on year and CUSIP.
I am expecting the average of the returns for that CUSIP for that year to be same for the month ranges.
For eg if for cusip 000307 and year 2018, I have average as 0.051, then the avg_return column should have the... | [
"One approach can be to split the process in two parts. Below code is not validated for syntax.\nimport pandas as pd \nmean_per_year_per_cusip = monthly_stock_data.groupby(by = ['CUSIP' \\\n,'year'])['RET'].mean())\n\nfinal = pd.merge(monthly_stock_data, mean_per_year_per_cusip, \\\nhow='left', left_on=['CUSIP' ,'y... | [
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074229384_pandas_python_python_3.x.txt |
Q:
VScode Type hints (Python-Pylance)
Help solve the problem with the type hints.
When I want to override a class parameter or method I get a suggestion from IntelliSense(Pylance)
When I choose a hint (because it suits me) editor itself adds a type hint.
I went through all the settings and can't find a solution to th... | VScode Type hints (Python-Pylance) | Help solve the problem with the type hints.
When I want to override a class parameter or method I get a suggestion from IntelliSense(Pylance)
When I choose a hint (because it suits me) editor itself adds a type hint.
I went through all the settings and can't find a solution to the problem.
Example:
typing show_change_l... | [
"This is a new feature added in the July update of Python extensions. You can add the following codes to your settings.json to close it:\n“python.analysis.inlayHints.functionReturnTypes”: false,\n“python.analysis.inlayHints.variableTypes”: false,\n\n"
] | [
1
] | [] | [] | [
"pylance",
"python",
"type_hinting",
"visual_studio_code"
] | stackoverflow_0074229061_pylance_python_type_hinting_visual_studio_code.txt |
Q:
tkinter yielding in a while loop
In the while loop below, I am trying to wait to display the CPUs move and then move on. Normally in this situation I would use time.sleep however since I am using tkinter I cannot do this. I have then used the .after function however this is not yielding the while loop and therefor... | tkinter yielding in a while loop | In the while loop below, I am trying to wait to display the CPUs move and then move on. Normally in this situation I would use time.sleep however since I am using tkinter I cannot do this. I have then used the .after function however this is not yielding the while loop and therefore not displaying the results.
I am loo... | [
"You can't have an infinite loop like this. You need to structure your code so the infinite loop is expressed as an unlooped function that calls itself via after (or a looped function that terminates the loop in favor of such a self-call when the work is done), e.g.:\n def quickReset(self):\n self.CPU.moveReset... | [
0
] | [] | [] | [
"python",
"sleep",
"tkinter",
"wait",
"yield"
] | stackoverflow_0074229763_python_sleep_tkinter_wait_yield.txt |
Q:
Is there a way to plot training and validation losses on the same graph with HuggingFace TrainerAPI?
I am fine-tuning a HuggingFace transformer model (PyTorch version), using the HF Seq2SeqTrainingArguments & Seq2SeqTrainer, and I want to display in Tensorboard the train and validation losses (in the same chart).
... | Is there a way to plot training and validation losses on the same graph with HuggingFace TrainerAPI? | I am fine-tuning a HuggingFace transformer model (PyTorch version), using the HF Seq2SeqTrainingArguments & Seq2SeqTrainer, and I want to display in Tensorboard the train and validation losses (in the same chart).
As far as I understand in order to plot the two losses together I need to use the SummaryWriter. The HF Ca... | [
"it's pretty simple. You mention it in the \"Seq2SeqTrainingArguments\". There is no need to define it explicitly in the \"Seq2SeqTrainer\" function.\nmodel_arguments = Seq2SeqTrainingArguments(output_dir= \"./best_model/\",\n num_train_epochs = EPOCHS, \n ... | [
0,
0
] | [] | [] | [
"huggingface_transformers",
"python",
"pytorch",
"tensorboard"
] | stackoverflow_0073281901_huggingface_transformers_python_pytorch_tensorboard.txt |
Q:
Module import errors with Virtual Environments and VSCode
I have created a virtual environment to install some Python modules. I am using mini-conda to manage and activate the environments.
One issue that I am facing is that the code runs fine when I run it through the terminal with the virtual environment activat... | Module import errors with Virtual Environments and VSCode | I have created a virtual environment to install some Python modules. I am using mini-conda to manage and activate the environments.
One issue that I am facing is that the code runs fine when I run it through the terminal with the virtual environment activated.
However, the same code does not run when I use the "Run Cod... | [
"You should use the same interpreter in VSCode;\nTo do this you should use Python: Select Interpreter option;\nCTRL+Shift+p(default key-bindings) and search for Python: Select Interpreter or search for it in the VSCode settings.\n",
"You must have the Code Runner extension installed because the Run Code option i... | [
2,
1
] | [] | [] | [
"python",
"virtualenv",
"visual_studio_code"
] | stackoverflow_0074220750_python_virtualenv_visual_studio_code.txt |
Q:
mysql.connector.errors.ProgrammingError: 3948 (42000): Loading local data is disabled; this must be enabled on both the client and server sides
I am working on a python project with MySQL connectivity. I have MySQL as a shell, i.e.,I need to use mysqlsh command in the Terminal to use MySQL(I am using MacOS Mojave... | mysql.connector.errors.ProgrammingError: 3948 (42000): Loading local data is disabled; this must be enabled on both the client and server sides | I am working on a python project with MySQL connectivity. I have MySQL as a shell, i.e.,I need to use mysqlsh command in the Terminal to use MySQL(I am using MacOS Mojave 10.14.6). I needed to use a csv file to store data taken from user and then transfer it to a MySQL database. After doing some research, I found the ... | [
"Add the statement:\nallow_local_infile when defining the connectivity.\nFinally it will look like:\n`mydb = mysql.connect(user='root', host='localhost', passwd='', allow_local_infile=True)'\nThis fixed it for me.(of course it is assuming that the local_infile variable it set to True in MySQL too)\n"
] | [
0
] | [] | [] | [
"mysql",
"mysql_python",
"python"
] | stackoverflow_0074219975_mysql_mysql_python_python.txt |
Q:
File-path not displaying on tkinter entry box
I've looked into multiple threads and I can't seem to find out why the stringVar is not displaying on the entry box, once the file has been selected. I can see the print(filePath.get()) has the selected file but entry box stays blank.
Can someone please help?
#import l... | File-path not displaying on tkinter entry box | I've looked into multiple threads and I can't seem to find out why the stringVar is not displaying on the entry box, once the file has been selected. I can see the print(filePath.get()) has the selected file but entry box stays blank.
Can someone please help?
#import libraries
import os
import paramiko
import tkinter ... | [
"It is because you did not set your entry text value in your function. Supposedly after you get your file path, you should assign the file path text value into the entry.\nYou can do so by inserting this code into your codes.\nentry1.insert(0, \"Test Value\")\n\nYour codes:\ndef getFilePath():\n file_selected = ... | [
1
] | [] | [] | [
"path",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074229853_path_python_tkinter_user_interface.txt |
Q:
Python Flask Redirect on another computer
I'm running a Flask server on my computer, with host = "0.0.0.0"
When I access the server from another computer it works fine, but when I redirect it redirects to "localhost:5000" which doesn't work on the other computer.
Heres my code
from flask import Flask, url_for, red... | Python Flask Redirect on another computer | I'm running a Flask server on my computer, with host = "0.0.0.0"
When I access the server from another computer it works fine, but when I redirect it redirects to "localhost:5000" which doesn't work on the other computer.
Heres my code
from flask import Flask, url_for, redirect, request, render_template
import pickle
... | [
"Think about this for a second:\nlocalhost refers to the current computer. So, on your computer localhost:5000 points to the server running on your computer on port 5000, however, on the other computer, it refers to the server running on another computer on port 5000. The server is not running on the other computer... | [
3
] | [] | [] | [
"flask",
"forms",
"html",
"python"
] | stackoverflow_0074229912_flask_forms_html_python.txt |
Q:
Sort the Fabrics Google Kickstart Challenge - Samples Passed, but Wrong Answer on Test 1 (Python)
Edit: Here’s the link to the original problem: https://codingcompetitions.withgoogle.com/kickstart/round/00000000008cb409/0000000000beefbb
On Round F of Google's 2022 Kick Start challenges, one of the tasks was to cre... | Sort the Fabrics Google Kickstart Challenge - Samples Passed, but Wrong Answer on Test 1 (Python) | Edit: Here’s the link to the original problem: https://codingcompetitions.withgoogle.com/kickstart/round/00000000008cb409/0000000000beefbb
On Round F of Google's 2022 Kick Start challenges, one of the tasks was to create an algorithm that sorts a list of fabrics through two methods: by color (in alphabetical order), an... | [
"You forgot to turn the number strings into numbers (using int() just like for T and N) so they get compared as such (instead of lexicographically). Also, you made it quite complicated. Just build a list of the split lines, sort them the two ways using each way's two criteria, and count equals:\nT = int(input())\nf... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0073766124_python.txt |
Q:
How to change from string to list when converting from CSV to JSON?
I found this code in order to convert a CSV file into JSON. What I need is to covert the Policy ID field to a list. Therefore, the PolicyID shouldn't be enclosed into the quote marks "" and should have a square bracket []. Here is the code I used:... | How to change from string to list when converting from CSV to JSON? | I found this code in order to convert a CSV file into JSON. What I need is to covert the Policy ID field to a list. Therefore, the PolicyID shouldn't be enclosed into the quote marks "" and should have a square bracket []. Here is the code I used:
import csv
import json
# Function to convert a CSV to JSON
# Takes the... | [
"Here is a for loop that works for what you are trying to accomplish:\nfor item in data:\n policy_id = []\n policy_id.append(int(data[item]['PolicyID']))\n data[item]['PolicyID'] = policy_id\n\n"
] | [
1
] | [] | [] | [
"csv",
"json",
"list",
"python",
"string"
] | stackoverflow_0074229627_csv_json_list_python_string.txt |
Q:
Use Variable in URL request on loop to collect data
I have a requests URL I am using to collect data for races for each day. I need to make one call to an API to get the race info for the day, then I need to use the race keys for each race to make another call to get the data for each race.
So far I have the code ... | Use Variable in URL request on loop to collect data | I have a requests URL I am using to collect data for races for each day. I need to make one call to an API to get the race info for the day, then I need to use the race keys for each race to make another call to get the data for each race.
So far I have the code below to collect the race info for the day.
def races_lis... | [
"You need to iterate over that data gathered by races_list(). Here is a basic example, although you might want to consider moving it into its own function.\nif __name__ == \"__main__\":\n for key in races_list():\n data = requests.get(f'{Base_url}events/{key}.json?app_id={AppID}&app_key={AppKey}').text ... | [
0
] | [] | [] | [
"json",
"multithreading",
"python"
] | stackoverflow_0074229509_json_multithreading_python.txt |
Q:
AttributeError: nonetype object has no attribute 'find'
from bs4 import BeautifulSoup
import requests
job_request = requests.get('https://www.google.com/search?q=Software+engineer+&sxsrf'
'=ALiCzsaeLLjcCHZk46ernxCkoay7ldkDsA:1666897166012&source=hp&ei=DdVaY-CHOvvgkPIPxc2m6Ag'
... | AttributeError: nonetype object has no attribute 'find' | from bs4 import BeautifulSoup
import requests
job_request = requests.get('https://www.google.com/search?q=Software+engineer+&sxsrf'
'=ALiCzsaeLLjcCHZk46ernxCkoay7ldkDsA:1666897166012&source=hp&ei=DdVaY-CHOvvgkPIPxc2m6Ag'
'&iflsig=AJiK0e8AAAAAY1rjHgG0CdqkcKPC3aVnmBv... | [
"The error is likely because listing has a value of None - because the first find returned nothing. When working with requests+beautifulsoup, you should make a habit of checking what requests returned when your code doesn't behave as expected. Use\nwith open('x.html', 'w', encoding=\"utf8\") as f:\n f.write(... | [
0
] | [] | [] | [
"attributeerror",
"beautifulsoup",
"html",
"python"
] | stackoverflow_0074228268_attributeerror_beautifulsoup_html_python.txt |
Q:
Combine and sort multiple array columns of values A and B where A is the common index
I have a n-long list of arrays. Each array consists of two columns:
A) index values between 1-500
B) measured values
Each A column is slightly different (i.e. missing or having extra values).
I want to create single large array w... | Combine and sort multiple array columns of values A and B where A is the common index | I have a n-long list of arrays. Each array consists of two columns:
A) index values between 1-500
B) measured values
Each A column is slightly different (i.e. missing or having extra values).
I want to create single large array where i) there is single A (index) column consisting of all the index values and ii) all the... | [
"It's quite simple using pandas:\nimport pandas as pd\n\narrs = [arr1, arr2, arr3]\n\nout = (pd\n .concat([pd.DataFrame(a).set_index(0) for a in arrs], axis=1)\n .fillna(0, downcast='infer')\n .sort_index().reset_index().to_numpy()\n)\n\noutput:\narray([[ 8, 0, 54, 0],\n [ 17, 0, 0, 530],\n [ ... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074229389_arrays_numpy_python_python_3.x_sorting.txt |
Q:
Formatting output of floats in a dictionary
Im currently running some correlation in test in python. I get the results I need but they're in x.01234567890 and I'm trying to format them to output them into percentage.
this is reading from a csv.
results = (
{
clean_df['NZDUSD_Close'].corr(clean_df['USDJ... | Formatting output of floats in a dictionary | Im currently running some correlation in test in python. I get the results I need but they're in x.01234567890 and I'm trying to format them to output them into percentage.
this is reading from a csv.
results = (
{
clean_df['NZDUSD_Close'].corr(clean_df['USDJPY_Close']),
clean_df['NZDUSD_Close'].cor... | [
"If the error your encountering is:\n\"AttributeError: 'set' object has no attribute 'keys'\"\n\nThen it's because your dictionary is inside a tuple and a tuple has no \"keys\" attribute. You would be best off if you used a tuple:\nresults = (...)\n\nand printing it like:\nprint(f\"{results:.2%}\")\n\nDoesn't work ... | [
1
] | [] | [] | [
"dictionary",
"format",
"output",
"printing",
"python"
] | stackoverflow_0074229980_dictionary_format_output_printing_python.txt |
Q:
Merging Django-CMS Edit and Publish Mode created two different Database entries with the same values
My CTO asked me to fix an "issue."
Apparently, whenever I add any plugin in the locally run DRF-based Django CMS project, it creates two database entries. One for edit mode, and the other when I hit publish.
My CT... | Merging Django-CMS Edit and Publish Mode created two different Database entries with the same values | My CTO asked me to fix an "issue."
Apparently, whenever I add any plugin in the locally run DRF-based Django CMS project, it creates two database entries. One for edit mode, and the other when I hit publish.
My CTO asked to find if there were any way to dynamically merge the edit mode entry with the merge mode and vic... | [
"There's no issue here. That's how the CMS works.\nIt has a draft version and a live version for all content. The live version is what your visitors will see, and when you publish the draft version it's copied over to the live version.\n"
] | [
0
] | [] | [] | [
"django",
"django_cms",
"django_rest_framework",
"python",
"web_development_server"
] | stackoverflow_0073430794_django_django_cms_django_rest_framework_python_web_development_server.txt |
Q:
python question about loops comparing string to string
I am trying to emulate a circumstance where i send information and only get a true or false as a return. So i can check each character and if it is true, that means that character is in the string. I would know there would be a position 0 to some number x. I w... | python question about loops comparing string to string | I am trying to emulate a circumstance where i send information and only get a true or false as a return. So i can check each character and if it is true, that means that character is in the string. I would know there would be a position 0 to some number x. I would receive a true result and eventually only receive false... | [
"Based on my understanding of the question, I've implemented a function which I believe emulates the interface you are talking to:\nspos = 0\ndef in_swoll(ch):\n global spos\n \n if spos == len(swoll) or ch != swoll[spos]:\n return False\n spos += 1\n return True\n\nThis will return True and i... | [
0
] | [] | [] | [
"compare",
"for_loop",
"loops",
"python",
"string"
] | stackoverflow_0074229983_compare_for_loop_loops_python_string.txt |
Q:
gensim error: ImportError: No module named 'gensim'
I trying to import gensim with
import gensim
but get the following error
ImportError Traceback (most recent call
last)
<ipython-input-5-50007be813d4> in <module>()
----> 1 import gensim
2 model = gensim.models.Word2Vec.load_word... | gensim error: ImportError: No module named 'gensim' | I trying to import gensim with
import gensim
but get the following error
ImportError Traceback (most recent call
last)
<ipython-input-5-50007be813d4> in <module>()
----> 1 import gensim
2 model = gensim.models.Word2Vec.load_word2vec_format('./model
/GoogleNews-vectors-negative300.bi... | [
"Install gensim using:\npip install -U gensim\n\nOr, if you have instead downloaded and unzipped the source tar.gz package, then run:\npython setup.py test\npython setup.py install\n\n",
"If using Python3 be sure to use pip3 instead of pip for installing gensim. \n",
"On Jupyter notebook, following worked for m... | [
40,
18,
9,
4,
3,
3,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"gensim",
"python",
"word2vec"
] | stackoverflow_0046168600_gensim_python_word2vec.txt |
Q:
Pass value of td element I click to python function flask
I have a table. So I am looking to get the value of a <td> tag and pass it on to the python function when I click that.
HTML CODE:
<table border=5 id="mytable">
<thead>
<td>Erp</td>
<td>Status</td>
<td>name</td>
<td>Days</td>
</thead>
... | Pass value of td element I click to python function flask | I have a table. So I am looking to get the value of a <td> tag and pass it on to the python function when I click that.
HTML CODE:
<table border=5 id="mytable">
<thead>
<td>Erp</td>
<td>Status</td>
<td>name</td>
<td>Days</td>
</thead>
{% for tr in df_excel_data%}
<tr>
<td onclick="passv... | [
"First understand this: your JavaScript code runs on the client completely separately from your Python code running on the server. Let this sink in until you understand it, then continue reading the question. This is something that trips up beginners a lot and ends up in a lot of poor design choices.\nThere are two... | [
1
] | [] | [] | [
"flask",
"html",
"javascript",
"python"
] | stackoverflow_0074229962_flask_html_javascript_python.txt |
Q:
Merging values with a same key
Tried to google how to merge multiple dictionaries, but could not find a solution to merge values under same key in a dictionary. Although the original data is list, the expected results should be dictionary. I am stacked here, and hope someone show me a way to get resolve this.
Orig... | Merging values with a same key | Tried to google how to merge multiple dictionaries, but could not find a solution to merge values under same key in a dictionary. Although the original data is list, the expected results should be dictionary. I am stacked here, and hope someone show me a way to get resolve this.
Original Data:
data = [
{'Supplement': ... | [
"You can do this by looping over the lists and dictionaries. Like this:\nimport collections\n\ndata = [\n {'Supplement': {'label': 'Protein - 25.0', 'value': 1}}, \n {'Fruit and vegetable': {'label': 'Test - 100.0', 'value': 2}},\n {'Fruit and vegetable': {'label': 'Peach - 10.0', 'value': 3}}, \n {'Protein': {'lab... | [
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074230097_dictionary_python.txt |
Q:
How to convert datetime object to milliseconds
I am parsing datetime values as follows:
df['actualDateTime'] = pd.to_datetime(df['actualDateTime'])
How can I convert this datetime objects to milliseconds?
I didn't see mention of milliseconds in the doc of to_datetime.
Update (Based on feedback):
This is the curre... | How to convert datetime object to milliseconds | I am parsing datetime values as follows:
df['actualDateTime'] = pd.to_datetime(df['actualDateTime'])
How can I convert this datetime objects to milliseconds?
I didn't see mention of milliseconds in the doc of to_datetime.
Update (Based on feedback):
This is the current version of the code that provides error TypeError... | [
"You can try pd.to_datetime(df['actualDateTime'], unit='ms')\nhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html\nsays this will denote in epoch, with variations 's','ms', 'ns' ...\nUpdate\nIf you want in epoch timestamp of the form 14567899..\nimport pandas as pd\nimport time\nt = pd.Tim... | [
19,
19,
6,
3,
1,
0
] | [
"from datetime import datetime\n\nprint datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n\n>>>> OUTPUT >>>>\n2015-11-02 18:04:32.926\n\n"
] | [
-1
] | [
"datetime",
"datetime_format",
"milliseconds",
"pandas",
"python"
] | stackoverflow_0033477604_datetime_datetime_format_milliseconds_pandas_python.txt |
Q:
Trying to download/install any python libraries
So I'm working on an app in VS Code and I'm trying to install the (pillow) and (kivy) libraries in python and I always get this same error. Does anyone have any answers to this. It would be greatly appreciated!!
The first line below is what I type into the terminal i... | Trying to download/install any python libraries | So I'm working on an app in VS Code and I'm trying to install the (pillow) and (kivy) libraries in python and I always get this same error. Does anyone have any answers to this. It would be greatly appreciated!!
The first line below is what I type into the terminal in VS Code.
python -m pip install kivy[full]
Collectin... | [
"Looks like you’re missing some gstreamer libraries that Kivy depends on. A quick google search led me to the PyPi package that matches what it’s asking for. Looks like the current version is 0.4 so you will need to specify 0.3.3 when you install via pip. PyPi package: gstreamer dep\nEdit: Here is the exact version... | [
0
] | [] | [] | [
"coding_style",
"python",
"windows"
] | stackoverflow_0074230037_coding_style_python_windows.txt |
Q:
numpy slicing using multiple conditions where one of the conditions searches the neighborhood of an element
the problem is to take a black-white image, detect all the places where white borders on black, keep that white, and turn all other white pixels black. I know how to do this using normal for-loops and lists,... | numpy slicing using multiple conditions where one of the conditions searches the neighborhood of an element | the problem is to take a black-white image, detect all the places where white borders on black, keep that white, and turn all other white pixels black. I know how to do this using normal for-loops and lists, but I want to do it w/ numpy, which I am not that familiar with. Here is what I have so far:
>>>from PIL Import ... | [
"With numpy and help of scipy, this can be achieved with a binary_erosion.\nOne can erode the pixels with a kernel of 3x3, then compare the original image to the erosion to find the difference:\nfrom scipy.ndimage import binary_erosion\n\nkernel = np.ones((3,3))\n\nedges = a_np - binary_erosion(a_np, kernel)*255\n\... | [
2
] | [] | [] | [
"arrays",
"image_processing",
"numpy",
"opencv",
"python"
] | stackoverflow_0074229978_arrays_image_processing_numpy_opencv_python.txt |
Q:
Replit error: /usr/bin/env: ‘./python3’: No such file or directory after using PIP
whenever I type, for an example: pip install aiohttp==3.7.3, it gives me: /usr/bin/env: ‘./python3’: No such file or directory is there any way to fix it? (The error is in REPLIT)
I had problems with using aiohttp in REPLIT, I tried... | Replit error: /usr/bin/env: ‘./python3’: No such file or directory after using PIP | whenever I type, for an example: pip install aiohttp==3.7.3, it gives me: /usr/bin/env: ‘./python3’: No such file or directory is there any way to fix it? (The error is in REPLIT)
I had problems with using aiohttp in REPLIT, I tried uninstalling package files. I "reinstalled" packages, such as "aiohttp" after doing the... | [
"I ran into this error as well and haven't been able to solve it.\nIn the meantime, I use python3 -m instead and it works:\npython3 -m <module-name> <args>\n\n",
"Well, go to .replit and delete the Variable called hidden = [\"venv\", \".config\", \"**/__pycache__\", \"**/.mypy_cache\", \"**/*.pyc\"]\nafter deleti... | [
0,
0
] | [] | [] | [
"python",
"replit"
] | stackoverflow_0071710004_python_replit.txt |
Q:
Plotly marginal histogram stack data instead of displaying different marginal histograms
I'm a bit lost with the plotly library.
I want to display a violin histogram close to my data display such as the one in example
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_w... | Plotly marginal histogram stack data instead of displaying different marginal histograms | I'm a bit lost with the plotly library.
I want to display a violin histogram close to my data display such as the one in example
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
marginal_x="box", marginal_y="violin",
... | [
"The difference is because the Plotly example is reading the categories as strings rather then numbers. The solution is to simply change the 'charge' column to strings.\nAlso, in the future please include sample data.\n#creating a sample database\ndf = pd.DataFrame({'x':[random.uniform(125, 175) for n in range(500)... | [
0
] | [] | [] | [
"histogram",
"plot",
"plotly",
"python",
"violin_plot"
] | stackoverflow_0074211812_histogram_plot_plotly_python_violin_plot.txt |
Q:
How to uninstall a .exe from a python script
Hello I can't get an app to self uninstall. After converting a .py script to .exe when I press the button it is supposed to delete/uninstall itself from my computer.
Actually I would like it to uninstall completely from my computer after pressing the button from the .ex... | How to uninstall a .exe from a python script | Hello I can't get an app to self uninstall. After converting a .py script to .exe when I press the button it is supposed to delete/uninstall itself from my computer.
Actually I would like it to uninstall completely from my computer after pressing the button from the .exe how to do it?
Here is the code:
from tkinter imp... | [
"After a lot of searching, I found a solution using this answer!\nThe trick is to start a separate external process that deletes the file after a delay\nfrom tkinter import Tk, Button, TOP\nimport subprocess\nimport sys\n\ndef func(*args):\n root.destroy()\n subprocess.Popen(f\"cmd /c ping localhost -n 3 > nu... | [
2
] | [] | [] | [
"operating_system",
"python",
"sys"
] | stackoverflow_0074229733_operating_system_python_sys.txt |
Q:
How to merge 2 pandas Series?
I have 2 pandas Series (s1, and s2) like this:
import pandas as pd
index1 = list(range(6))
index2 = list(range(2, 8))
data1 = [7, 6, 1, 9, 3, 4]
data2 = [1, 9, 3, 4, 10, 12]
s1 = pd.Series(data=data1, index=index1)
s2 = pd.Series(data=data2, index=index2)
s1 and s2 have some... | How to merge 2 pandas Series? | I have 2 pandas Series (s1, and s2) like this:
import pandas as pd
index1 = list(range(6))
index2 = list(range(2, 8))
data1 = [7, 6, 1, 9, 3, 4]
data2 = [1, 9, 3, 4, 10, 12]
s1 = pd.Series(data=data1, index=index1)
s2 = pd.Series(data=data2, index=index2)
s1 and s2 have some common indices. And they have the ... | [
"If your indices are already aligned, then you can use a simple combine_first:\nout = s1.combine_first(s2).convert_dtypes()\n\noutput:\n0 7\n1 6\n2 1\n3 9\n4 3\n5 4\n6 10\n7 12\ndtype: Int64\n\nsecond example output:\n0 7\n1 6\n2 1\n3 9\n4 3\n5 4\n8 7... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074230257_pandas_python.txt |
Q:
How do I include a histogram of the variables of my dataset to my dash app?
I want to add a histogram to my dash app where the user can select what variable they want to use from the given dataset. There are 11 variables and I want to have the user select a variable from the drop down menu and in response, a histo... | How do I include a histogram of the variables of my dataset to my dash app? | I want to add a histogram to my dash app where the user can select what variable they want to use from the given dataset. There are 11 variables and I want to have the user select a variable from the drop down menu and in response, a histogram will be created for said variable. I am having ALOT of trouble understanding... | [
"I don't have your dataframe so that I just make below code as referrence:\nimport dash\nimport pandas as pd\nimport plotly.express as px\nfrom dash import Input, Output\nfrom dash import dash_table\nfrom dash import dcc\nfrom dash import html\n\napp = dash.Dash(__name__)\napp.layout = html.Div([\n html.H1(\"Dia... | [
0
] | [] | [] | [
"dashboard",
"histogram",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074229969_dashboard_histogram_plotly_plotly_dash_python.txt |
Q:
python dataframe to dictionary problem iterate unique ID and pass as list with multiple entries
I have a sample like dataframe like this:
Start
end
value
A
B
1
A
C
2
B
D
3
C
A
2
How could I change it into a dict like this:
{
'A': [('B',1),('C',2)]
,'B': [('D',3)]
,'C': [('A',2)]
,'D':[]
}
thanks very much
... | python dataframe to dictionary problem iterate unique ID and pass as list with multiple entries | I have a sample like dataframe like this:
Start
end
value
A
B
1
A
C
2
B
D
3
C
A
2
How could I change it into a dict like this:
{
'A': [('B',1),('C',2)]
,'B': [('D',3)]
,'C': [('A',2)]
,'D':[]
}
thanks very much
| [
"d = {}\nfor i in df['Start'].unique():\n d[i] = [(df['end'][j], df['value'][j]) for j in df[df['Start']==i].index]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"dictionary",
"python"
] | stackoverflow_0074230288_dataframe_dictionary_python.txt |
Q:
Plotly bar plot colored by week?
I am trying to make a what is a simple plot in excel but can't figure out how to do it in plotly.
I've tried:
px.bar(df, x=['A','B','D','E'], color='date')
but it gives a key error.
A:
There are many different ways that you can make this happen. I'm not sure how you brought the... | Plotly bar plot colored by week? | I am trying to make a what is a simple plot in excel but can't figure out how to do it in plotly.
I've tried:
px.bar(df, x=['A','B','D','E'], color='date')
but it gives a key error.
| [
"There are many different ways that you can make this happen. I'm not sure how you brought the data into Python.\nIf you used a dictionary or a Pandas data frame, either of the two methods I'll show will work. The first uses Plotly Express, since that's what it appears you tried to use. The second method uses Plotl... | [
1,
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074210287_plotly_python.txt |
Q:
How can I add both text and image in a folium popup
I'm using ftft folium in python.
I created my map, with few points and I managed to add an image for every point in the map.
Nevertheless, I'm not able to add both image and text. Is it possible? How?
Is it possible to add both image and a link?
Thank you a lot! ... | How can I add both text and image in a folium popup | I'm using ftft folium in python.
I created my map, with few points and I managed to add an image for every point in the map.
Nevertheless, I'm not able to add both image and text. Is it possible? How?
Is it possible to add both image and a link?
Thank you a lot! :)
| [
"Folium enables passing any HTML object as a popup, including bokeh <https://bokeh.pydata.org/en/latest/>__ plots,\nbut there is a built-in support for vincent and altair visualizations to any marker type,\nwith the visualization as the popover. See example: https://python-visualization.github.io/folium/quickstart.... | [
0
] | [] | [] | [
"folium",
"image",
"python",
"text"
] | stackoverflow_0074127616_folium_image_python_text.txt |
Q:
Python cleaning text emoji-library django-error
I want to use the emoji library to replace emoji's in text, nothing fancy.
import os
import django
import emoji
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()
test = "This is a teststring test test :-) "
message_without_emoji ... | Python cleaning text emoji-library django-error | I want to use the emoji library to replace emoji's in text, nothing fancy.
import os
import django
import emoji
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()
test = "This is a teststring test test :-) "
message_without_emoji = emoji.demojize(test)
print(message_without_emoji)
... | [
"==> Solution I installed django-emoji and not the emoji library. I'm using PyCharm and in the menu \"Show Context Actions\" django-emoji was suggested as first in the list.\nI did pip uninstall django-emoji and pip install emoji. And now it works fine.\n"
] | [
0
] | [] | [] | [
"data_cleaning",
"django",
"python"
] | stackoverflow_0074202733_data_cleaning_django_python.txt |
Q:
How to train several NER models (Spacy)
I'm training a custom named entity recognition model, I created the config.cfg and train.spacy files, among all it has, I'm using this as pre-trained vectors en_core_web_lg
[paths]
train = null
dev = null
vectors = "en_core_web_lg"
init_tok2vec = null
I then train the model... | How to train several NER models (Spacy) | I'm training a custom named entity recognition model, I created the config.cfg and train.spacy files, among all it has, I'm using this as pre-trained vectors en_core_web_lg
[paths]
train = null
dev = null
vectors = "en_core_web_lg"
init_tok2vec = null
I then train the model using
!python -m spacy train config.cfg --ou... | [
"When you use a model as a source of vectors, or for that matter a source for any other part of a pipeline, spaCy will not modify it under any circumstances. Something else is going on.\nAre you perhaps using a different virtualenv? Does spacy.load(\"en_core_web_lg\") work?\nOne thing that could be happening (but s... | [
1
] | [] | [] | [
"python",
"spacy",
"spacy_3"
] | stackoverflow_0074224813_python_spacy_spacy_3.txt |
Q:
I want to delete a block every time i click one
I want to make a kind of level editor in a way, and I want to be able to click the blocks to delete them, one block gets destroyed when I run the code, but from there nothing works.
here's my code.
def update(self):
mouse_x, mouse_y = pygame.mouse.get_pos... | I want to delete a block every time i click one | I want to make a kind of level editor in a way, and I want to be able to click the blocks to delete them, one block gets destroyed when I run the code, but from there nothing works.
here's my code.
def update(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
mouse_hover = blocks.rect.collidepoint(mou... | [
"I've rearranged your code a little to check for collision in the event handler, on a left mouse click:\nimport pygame\npygame.init()\nscreen = pygame.display.set_mode((800, 600))\nclock = pygame.time.Clock()\n\nclass ground(pygame.sprite.Sprite):\n def __init__(self, x, y):\n super().__init__()\n ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074229448_pygame_python.txt |
Q:
Splitting Dates in 2 columns in a Dataframe
This question is actually very similar to my previous one (given here: Splitting Dates in a Dataframe into 2 separate Dataframes), but somewhat more complex, so after trying it for more than an hour I though I should ask.
I have a dataframe where two of the columns Start... | Splitting Dates in 2 columns in a Dataframe | This question is actually very similar to my previous one (given here: Splitting Dates in a Dataframe into 2 separate Dataframes), but somewhat more complex, so after trying it for more than an hour I though I should ask.
I have a dataframe where two of the columns Start and End are lists of dates. What I would like to... | [
"It is actually very different from your other question, and not so straightforward.\nI would use a merge_asof, with a little trick of temporarily replacing the NaN values of End with a dummy date (here I used '1970-01-01'):\n# pre-process the dataframe to split the strings into lists\ndf2 = df.set_index('Name').ap... | [
1
] | [] | [] | [
"date",
"datetime",
"pandas",
"python"
] | stackoverflow_0074230233_date_datetime_pandas_python.txt |
Q:
Show names of positional arguments inlayed
I've recently been doing some programming in Rust using Clion. This provides a utility whereby when you pass positional arguments to a function it will show you which argument will pick up each value (as if you had passed them in as keyword arguments) see below:
I've fou... | Show names of positional arguments inlayed | I've recently been doing some programming in Rust using Clion. This provides a utility whereby when you pass positional arguments to a function it will show you which argument will pick up each value (as if you had passed them in as keyword arguments) see below:
I've found this to be a very nice feature as it's made c... | [
"I think the Python Inlay Params plugin does what you want. It adds inlay hints both for callable parameters, values, and for types on variables.\nHere's a convenient snippet transcribed from the demo for testing:\nclass Dimens:\n width: int\n height: int\n\n def __init__(self, width, height):\n sel... | [
3
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0074185718_pycharm_python.txt |
Q:
unable to properly append data to df in pandas
I have a bunch of minute data like so:
index timestamp open high low ... trade_count vwap symbol cum_volume cum_volume_25k
0 2021-11-02 13:30:00+00:00 2021-11-02 13:30:00+00:00 12.000 12.... | unable to properly append data to df in pandas | I have a bunch of minute data like so:
index timestamp open high low ... trade_count vwap symbol cum_volume cum_volume_25k
0 2021-11-02 13:30:00+00:00 2021-11-02 13:30:00+00:00 12.000 12.055 12.00 ... 62 12.003693 AMCR ... | [
"Use a list to append all values in it. Then concat them in a single dataframe. Appending into a single df is not good approach. In your case, It'll be\nlist_of_df = []\nfor index, name in days:\n list_of_df.append(name)\n\n\nNow you can contact it.\npd.concat(list_of_df)\n\n"
] | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074230346_numpy_pandas_python.txt |
Q:
Struggling to get type hinting to work with Decorator on Class (vscode - python)
I have "borrowed" the following singleton decorator:
class Singleton:
def __init__(self, decorated: Callable) -> None:
self._decorated = decorated
self.initialized = False
def Instance(self) -> Call... | Struggling to get type hinting to work with Decorator on Class (vscode - python) | I have "borrowed" the following singleton decorator:
class Singleton:
def __init__(self, decorated: Callable) -> None:
self._decorated = decorated
self.initialized = False
def Instance(self) -> Callable:
"""
Returns the singleton instance. Upon its first call, it crea... | [
"Autocomplete depends highly on your IDE's builtin type-checker, and decorators are notorious for confusing the type-checker. One solution is to make your singleton explicitly typed:\nfrom collections.abc import Callable\nfrom pathlib import Path\n\nfrom typing import TypeVar, Generic, Type\n\nT = TypeVar('T')\n\n\... | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074220653_python_visual_studio_code.txt |
Q:
Inject different implementation based on yaml configuration
Using python package dependency injector, I need to instantiate/inject a different implementation of an interface based on a yaml configuration file.
class SomeInterface(abc.ABC):
@abc.abstractmethod
def some_method(self):
pass
class Impl... | Inject different implementation based on yaml configuration | Using python package dependency injector, I need to instantiate/inject a different implementation of an interface based on a yaml configuration file.
class SomeInterface(abc.ABC):
@abc.abstractmethod
def some_method(self):
pass
class Impl1(SomeInterface):
def some_method(self):
# e.g. file-... | [
"Ok never mind, of course it's in the docs. There are a number of approaches but in my case the Selector provider matches the code I'm refactoring:\nclass Container(containers.DeclarativeContainer):\n\n config = providers.Configuration()\n\n selector = providers.Selector(\n config.one_or_another,\n ... | [
0
] | [] | [] | [
"dependency_injection",
"inversion_of_control",
"python",
"python_3.x"
] | stackoverflow_0074201083_dependency_injection_inversion_of_control_python_python_3.x.txt |
Q:
How to get number and incrementing letter in a certain format?
I am writing a code that asks for the users input for the number of rows and columns. When given the integer values, the program will print out the number of the row and the letter that will increment will be next to it, just like seat numbers in a the... | How to get number and incrementing letter in a certain format? | I am writing a code that asks for the users input for the number of rows and columns. When given the integer values, the program will print out the number of the row and the letter that will increment will be next to it, just like seat numbers in a theatre or stadium. What I am trying to do is to use a for loop and a w... | [
"You could use a nested list comprehension to iterate the rows and columns, joining the results with a space on rows and newline on columns:\nseats = '\\n'.join(' '.join(f'{row+1}{chr(col+ord(\"A\"))}' for col in range(num_cols))\n for row in range(num_rows))\nprint(seats)\n\nOutput:\n1A 1B 1C\n2A ... | [
0,
0
] | [] | [] | [
"for_loop",
"input",
"loops",
"python",
"while_loop"
] | stackoverflow_0074230305_for_loop_input_loops_python_while_loop.txt |
Q:
Convert flattened list to list of dictionaries
I have the list containing strings and numbers. I am trying to convert into dictionary based on the type if it is string otherwise it would become a key.
Input:
lst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]
Output:
[{'A': [1, 3, 4]}, {'B': [5]}, {'C': [2]}, {'D': 4}]
... | Convert flattened list to list of dictionaries | I have the list containing strings and numbers. I am trying to convert into dictionary based on the type if it is string otherwise it would become a key.
Input:
lst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]
Output:
[{'A': [1, 3, 4]}, {'B': [5]}, {'C': [2]}, {'D': 4}]
This is my working code so far, I it is definitely ... | [
"It is much better to create an intermediate dictionary, then convert that dictionary to your desired result. Like this:\nimport collections\n\nlst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]\n\ndct = collections.defaultdict(lambda: [])\nkey = None\nfor el in lst:\n if type(el) == str:\n key = el\n co... | [
3,
2,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074230193_python_python_3.x.txt |
Q:
Cannot instantiate `BlobServiceClient` from within Azure App Services fastAPI application
I am trying to download data from an Azure Storage Account using azure-storage-blob's BlobServiceClient class.
When I run this snippet from a Jupyter notebook, I manage to retrieve the data without any problem:
from azure.sto... | Cannot instantiate `BlobServiceClient` from within Azure App Services fastAPI application | I am trying to download data from an Azure Storage Account using azure-storage-blob's BlobServiceClient class.
When I run this snippet from a Jupyter notebook, I manage to retrieve the data without any problem:
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_stri... | [
"I have used below sample code to get the file data from blob.\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\nreturn {\"Hello\": \"World\"}\n\n@app.get(\"/items\")\ndef download_blob():\n try:\n name = \"<Filename>\"\n container_name = \"<Container Name.\"\n connect_str = \"<Connec... | [
1
] | [] | [] | [
"azure_appservice",
"azure_blob_storage",
"fastapi",
"python"
] | stackoverflow_0074133744_azure_appservice_azure_blob_storage_fastapi_python.txt |
Q:
Enabled and disabled multiple checkboxes CustomTkinter
This might be a noob question.
But I have been raking my head on trying to enable the checkbox based on the radiobutton.
What I did is create a multiple checkboxes based on the array which is dc_ma1 and make it into the disable state. The radio button will ena... | Enabled and disabled multiple checkboxes CustomTkinter | This might be a noob question.
But I have been raking my head on trying to enable the checkbox based on the radiobutton.
What I did is create a multiple checkboxes based on the array which is dc_ma1 and make it into the disable state. The radio button will enable or disable the checkboxes based on the user choice.
Belo... | [
"Just to add, this the working code based on the comment here.\nAs per highlighted by @acw1668 I need to to use a list or dictionary to store those references of checkboxes:\nfrom tkinter import *\nimport customtkinter\n\ncustomtkinter.set_appearance_mode(\"System\") # Modes: \"System\" (standard), \"Dark\", \"Lig... | [
0
] | [] | [] | [
"customtkinter",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074221228_customtkinter_python_python_3.x_tkinter.txt |
Q:
Pandas fill two columns row by row recursively
I have a column (P0) with missing value that tracks the initial value of a metric and a column that tracks the percentage change (CHG). The goal is to create a new column (P1) that calculate the new metric after the CHG, as well as fill P0 with P1 when there is missin... | Pandas fill two columns row by row recursively | I have a column (P0) with missing value that tracks the initial value of a metric and a column that tracks the percentage change (CHG). The goal is to create a new column (P1) that calculate the new metric after the CHG, as well as fill P0 with P1 when there is missing value.
import pandas as pd
df = pd.DataFrame()
df[... | [
"A vectorial approach would be:\ndf['P1'] = (df\n .assign(val=df['P0'].ffill()) # propagate start values\n # group by stretches starting on non-NA values\n .groupby(df['P0'].notna().cumsum().shift().bfill(),\n group_keys=False)\n # compute the cumulated product with the first (propagated) value\n... | [
2
] | [] | [] | [
"dataframe",
"numba",
"pandas",
"python"
] | stackoverflow_0074230393_dataframe_numba_pandas_python.txt |
Q:
ValueError: Layer "model_1" expects 2 input(s), but it received 1 input tensors
I am trying to build a text classification model using the Bert pre train model, but I keep getting an error when I try to fit the model.
The error says
ValueError: Layer "model_1" expects 2 inputs but it received only 1 input tensor. ... | ValueError: Layer "model_1" expects 2 input(s), but it received 1 input tensors | I am trying to build a text classification model using the Bert pre train model, but I keep getting an error when I try to fit the model.
The error says
ValueError: Layer "model_1" expects 2 inputs but it received only 1 input tensor.
Inputs received: \[\<tf.Tensor 'IteratorGetNext:0' shape=(None, 309) dtype=int32\>\]... | [
"It's quite clear that your code is:\nmodel = tf.keras.models.Model(inputs = [input_ids,attention_masks], outputs = output)\n\nSo the inputs here you need 2 inputs (input_ids and attention_masks) but in the fit function you only pass 1 inputs to the model:\nmodel.fit(X_train, y_train, epochs=32, batch_size=32,verbo... | [
0
] | [] | [] | [
"deep_learning",
"machine_learning",
"python",
"tensorflow",
"valueerror"
] | stackoverflow_0074199540_deep_learning_machine_learning_python_tensorflow_valueerror.txt |
Q:
Use np.where to check if a column string exists in another list column
I have a large DataFrame with 100 million records, I am trying to optimize the run time by using numpy.
Sample data:
dat = pd.DataFrame({'ID' : [1,2,3,4,5],
'item' : ['beauty', 'beauty', 'shoe','shoe','handbag'],
... | Use np.where to check if a column string exists in another list column | I have a large DataFrame with 100 million records, I am trying to optimize the run time by using numpy.
Sample data:
dat = pd.DataFrame({'ID' : [1,2,3,4,5],
'item' : ['beauty', 'beauty', 'shoe','shoe','handbag'],
'mylist' : [['beauty','something'], ['shoe', 'something', 'else'], ['... | [
"You can't vectorize easily with Series of lists, you can use a list comprehension to be a bit faster than apply:\nout = dat.loc[[item in l for item,l in zip(dat['item'], dat['mylist'])]]\n\nA vectorial solution would be:\nout = dat.loc[dat.explode('mylist').eval('item == mylist').groupby(level=0).any()]\n\n# or\no... | [
2
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074230470_numpy_pandas_python.txt |
Q:
Python/Pyscript Erro with folium
i'm trying to make a simple code with pyScript and the folium library, but I'am continually getting this error
[pyscript/base] PythonError: Traceback (most recent call last):
File "/lib/python3.10/asyncio/futures.py", line 201, in result
raise self._exception
File "/lib/pyt... | Python/Pyscript Erro with folium | i'm trying to make a simple code with pyScript and the folium library, but I'am continually getting this error
[pyscript/base] PythonError: Traceback (most recent call last):
File "/lib/python3.10/asyncio/futures.py", line 201, in result
raise self._exception
File "/lib/python3.10/asyncio/tasks.py", line 232, i... | [
"Your code needs some update and corrections. Try this modified code.\n\n\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <script defe... | [
0
] | [] | [] | [
"folium",
"html",
"pyscript",
"python"
] | stackoverflow_0074139144_folium_html_pyscript_python.txt |
Q:
Issues using Choropleth
Currently trying to learn cloropleth - fairly a noob with this.
Problem:
I'm currently using a Michigan Counties GeoJSON file and am trying to draw a map of the state showcasing the percentage of people that opted for John. In return though, I only get an empty colorless map of the US with ... | Issues using Choropleth | Currently trying to learn cloropleth - fairly a noob with this.
Problem:
I'm currently using a Michigan Counties GeoJSON file and am trying to draw a map of the state showcasing the percentage of people that opted for John. In return though, I only get an empty colorless map of the US with a legend on the side. Like so... | [
"The association between user data and geojosn is incorrect. In your data example, Maker, not fips, is the county name, so associate the name with the geojson property. Also, you do not need to set the location mode in this case. Since you presented 3 user data, the attached image shows only 3 regions. Also the geo... | [
0
] | [] | [] | [
"choropleth",
"plotly",
"python",
"visualization"
] | stackoverflow_0074230256_choropleth_plotly_python_visualization.txt |
Q:
How to merge data with same data in pandas?
i have this following data:
Date_reported Country_code Country WHO_region New_cases Cumulative_cases New_deaths Cumulative_deaths
0 2020-01-03 AF Afghanistan EMRO 0 0 0 0
1 2020-01-04 AF Afghanistan EMRO 0 0 0 0
2 2020-01-05 AF Afghanistan E... | How to merge data with same data in pandas? | i have this following data:
Date_reported Country_code Country WHO_region New_cases Cumulative_cases New_deaths Cumulative_deaths
0 2020-01-03 AF Afghanistan EMRO 0 0 0 0
1 2020-01-04 AF Afghanistan EMRO 0 0 0 0
2 2020-01-05 AF Afghanistan EMRO 0 0 0 0
3 2020-01-06 AF Afghanis... | [
"You want to group the data by the date column and then sum each column:\ndf.groupby(['Date_reported'])['New_cases', 'Cumulative_cases', 'New_deaths', 'Cumulative_deaths'].sum()\n\n"
] | [
2
] | [] | [] | [
"date",
"merge",
"pandas",
"python"
] | stackoverflow_0074230587_date_merge_pandas_python.txt |
Q:
How to use figure attribute of mlab.surface in mayavi?
I am trying to use mayavi.mlab.surf() to create a 3D surface
The Mayavi documentation mentions the followng syntax of mayavi.mlab.surf() function.
I am trying to use the figure field as follows:
surf_3D = mlab.surf(data, figure="test.png", warp_scale=0.5 )
H... | How to use figure attribute of mlab.surface in mayavi? | I am trying to use mayavi.mlab.surf() to create a 3D surface
The Mayavi documentation mentions the followng syntax of mayavi.mlab.surf() function.
I am trying to use the figure field as follows:
surf_3D = mlab.surf(data, figure="test.png", warp_scale=0.5 )
However I get the following error:
Traceback (most recent cal... | [
"If the intension is to save the plot as an image use mlab.savefig\nThe figure parameter in surf is the figure object on which the surface has to be plotted.\n"
] | [
0
] | [] | [] | [
"mayavi",
"mayavi.mlab",
"python"
] | stackoverflow_0070695854_mayavi_mayavi.mlab_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.