content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How do I target a ForeignKey attribute inside a loop?
I've a cart view and when a user is authenticated and has products in the cart view, I wanna check against product availability and if one product is found with availability set to False I wanna render Out of stock,
the code for not authenticated users works, b... | How do I target a ForeignKey attribute inside a loop? | I've a cart view and when a user is authenticated and has products in the cart view, I wanna check against product availability and if one product is found with availability set to False I wanna render Out of stock,
the code for not authenticated users works, but for authenticated users Traceback Error is 'OrderItem' o... | [
"You check the availability of the product, so:\ndef cart(request):\n data = cartData(request)\n items = data['items']\n\n orderitemlist = OrderItem.objects.select_related('product')\n\n if not request.user.is_authenticated:\n available = all(x['product']['availability'] for x in items)\n else... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074578557_django_python.txt |
Q:
How to assign points in a simple game
I am making a simple game, at the beginning you can choose the amount of players, which is between 2 and 5 (shown below) I am having problem with assigning the initial amount of points, which is 100 points. Also, not sure where to place the code regarding the points in my wori... | How to assign points in a simple game | I am making a simple game, at the beginning you can choose the amount of players, which is between 2 and 5 (shown below) I am having problem with assigning the initial amount of points, which is 100 points. Also, not sure where to place the code regarding the points in my woring code below.
When I start working on the ... | [
"I'd recommend to use dictionary where keys are player names (assuming player names will be unique) and values will be player's score:\nplayers_dict = {}\nscore = 100\n\nmax_players = -1\nwhile not (2 <= max_players <= 5):\n max_players = int(input(\"Please, insert the number of players: \"))\n\nwhile len(player... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074578272_list_python.txt |
Q:
recursive tree search create array of all paths
I have a dict {child, parent}
mydict = {'1': '0',
'2': '0',
'3': '1',
'4': '3',
'5': '3',
'6': '2',
'7': '6',
'8': '7' }
I don't know how many levels of grandchildren there are. I need to end up with a structure that has all unique parent,child,grandchild pa... | recursive tree search create array of all paths | I have a dict {child, parent}
mydict = {'1': '0',
'2': '0',
'3': '1',
'4': '3',
'5': '3',
'6': '2',
'7': '6',
'8': '7' }
I don't know how many levels of grandchildren there are. I need to end up with a structure that has all unique parent,child,grandchild paths.
path1:[0,1,3,4], path2:[0,1,3,5], path3:[0,2,6,7... | [
"Try:\nmydict = {\n \"1\": \"0\",\n \"2\": \"0\",\n \"3\": \"1\",\n \"4\": \"3\",\n \"5\": \"3\",\n \"6\": \"2\",\n \"7\": \"6\",\n \"8\": \"7\",\n}\n\n\ndef get_all_paths(dct, start=\"0\", curr_path=None):\n if curr_path is None:\n curr_path = [start]\n\n next_values = dct.get(... | [
0
] | [] | [] | [
"dictionary",
"python",
"tree"
] | stackoverflow_0074578143_dictionary_python_tree.txt |
Q:
Iterate through a folder which contains 5 more folders each with 500 text files to match words
I have a folder which contain 5 folders, with round 450-550 text files each. The text file has around 1-12 sentences varying in length, seperated by a tab, like this:
i love burgers
i want to eat a burger
etc
I want t... | Iterate through a folder which contains 5 more folders each with 500 text files to match words | I have a folder which contain 5 folders, with round 450-550 text files each. The text file has around 1-12 sentences varying in length, seperated by a tab, like this:
i love burgers
i want to eat a burger
etc
I want to create a code which asks the user to input a search term and then goes inside each folder, opens a... | [
"If you just want to count the number of occurrences of a word, for example, in a set of .txt files, something like this will do it:\nfrom pathlib import Path\n\nword = input('Enter the word you want to search for: ')\npath = Path('/some/folder')\ncounter = {}\n\nfor file in path.rglob('*.txt'):\n if file.is_fil... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074578521_python_python_3.x.txt |
Q:
How to change instance attributes in python class
I am starting up with python classes and I have some doubts about how to properly change values in instance attributes:
I have the following example:
import numpy as np
class myClass:
def __init__(self):
self.name = "none"
self.val = np.array([... | How to change instance attributes in python class | I am starting up with python classes and I have some doubts about how to properly change values in instance attributes:
I have the following example:
import numpy as np
class myClass:
def __init__(self):
self.name = "none"
self.val = np.array([])
Instances of myClass will have two attributes: name... | [
"The easiest would be to change your __init__ to require two arguments:\nimport numpy as np\n\nclass myClass:\n def __init__(self, name, val):\n self.name = name\n self.val = val\n\n# Create an instance of myClass\nobj1 = myClass(\"name1\", np.zeros(3))\n\nIf you want to change the values of name a... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074578631_python_python_3.x.txt |
Q:
Unique entries across multiple list
I am building a fixture manager for a sport event.
To simplify the program:
There are four teams in a group. They play both home and away matches. So, in total 6 matches, happens across 6 weeks. So, total combination of "possible matches" at the start would look like this. (I ha... | Unique entries across multiple list | I am building a fixture manager for a sport event.
To simplify the program:
There are four teams in a group. They play both home and away matches. So, in total 6 matches, happens across 6 weeks. So, total combination of "possible matches" at the start would look like this. (I have similar data structure in my code)
fro... | [
"This code gives you all 46080 possible calendars\nfrom itertools import combinations\nfrom itertools import permutations\n\nteams = [\"Swin\", \"Lon\", \"Key\", \"Stran\"]\ndates = [\"2023/05/17\", \"2023/05/22\", \"2023/05/29\", \"2023/05/17\", \"2023/05/22\", \"2023/05/29\"]\n\npossibilities = {}\nmbt={}\nmatche... | [
0
] | [] | [] | [
"loops",
"python",
"recursion",
"reduce"
] | stackoverflow_0074575434_loops_python_recursion_reduce.txt |
Q:
Are there any pure python game library(without c)?
Are there any pure python game library(without c)?
I created a game in pygame, but that's painful for releasing game because people must install pygame to run that game (specially my friends they are not programmers).
There are some PURE PYTHON libraries like requ... | Are there any pure python game library(without c)? | Are there any pure python game library(without c)?
I created a game in pygame, but that's painful for releasing game because people must install pygame to run that game (specially my friends they are not programmers).
There are some PURE PYTHON libraries like requests, but no pure python library for game dev
I tried to... | [
"PyOpenGl Im not sure if it's pure python but it's python!\n"
] | [
0
] | [] | [] | [
"platform",
"pygame",
"pyinstaller",
"python"
] | stackoverflow_0074578708_platform_pygame_pyinstaller_python.txt |
Q:
Round decimals of numbers in Python
I have a list, each row contains 4 floats (should represent a bounding box)
[[7.426758, 47.398349, 7.850835593464796, 47.68617800490421],
[7.850835593464796, 47.398349, 8.274913186929592, 47.68617800490421],
[8.274913186929592, 47.398349, 8.698990780394388, 47.68617800490421]]... | Round decimals of numbers in Python | I have a list, each row contains 4 floats (should represent a bounding box)
[[7.426758, 47.398349, 7.850835593464796, 47.68617800490421],
[7.850835593464796, 47.398349, 8.274913186929592, 47.68617800490421],
[8.274913186929592, 47.398349, 8.698990780394388, 47.68617800490421]]
I would like to round each float to 6 ... | [
"Try numpy.around:\n# lst is your list\nnp.around(lst, 6).tolist()\n\nOutput:\n[[7.426758, 47.398349, 7.850836, 47.686178],\n [7.850836, 47.398349, 8.274913, 47.686178],\n [8.274913, 47.398349, 8.698991, 47.686178]]\n\n"
] | [
1
] | [] | [] | [
"coordinates",
"dataframe",
"pandas",
"python",
"rounding"
] | stackoverflow_0074578723_coordinates_dataframe_pandas_python_rounding.txt |
Q:
Can you create a function with a specific signature without using eval?
I’ve written some code that inspects function signatures, and I would like to generate test cases for it. For this, I need to be able to construct objects that result in a given Signature object when signature is called on them. I want to avoi... | Can you create a function with a specific signature without using eval? | I’ve written some code that inspects function signatures, and I would like to generate test cases for it. For this, I need to be able to construct objects that result in a given Signature object when signature is called on them. I want to avoid just eval-ing spliced together strings for this. Is there some other method... | [
"You can assign a Signature object to the callable's .__signature__ attribute:\nimport inspect\nfrom inspect import Signature as S, Parameter as P\n\ndef f(x: int = 2): pass\nprint(inspect.signature(f))\n\nnew_param = P(name=\"y\", kind=P.KEYWORD_ONLY, default=\"abc\", annotation=str)\nf.__signature__ = S(parameter... | [
1
] | [] | [] | [
"python",
"python_hypothesis"
] | stackoverflow_0074526030_python_python_hypothesis.txt |
Q:
Confusion about crawler settigs, spider settings, project settings
I have confusion about crawler settings, spider settings, settings.py and project setting.I see the docunmention about scrapy while I haven't understand the difference.For example, in the function
process = CrawlerProcess(settings={
"FEEDS": {
... | Confusion about crawler settigs, spider settings, project settings | I have confusion about crawler settings, spider settings, settings.py and project setting.I see the docunmention about scrapy while I haven't understand the difference.For example, in the function
process = CrawlerProcess(settings={
"FEEDS": {
"items.json": {"format": "json"},
},
})
what does the diffe... | [
"The FEEDS setting is the output settings for your spider.\nIf you were to run\nscrapy crawl spidername -o file.json\n\nThat would be roughly the same as\nprocess = CrawlerProcess(settings={\"FEEDS\": {\"file.json\": {\"format\": \"json\"}})\n\nAnother example would be\nscrapy crawl spidername -o file2.csv\n\nis ro... | [
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0074546952_python_scrapy.txt |
Q:
Why does PyGad fitness_function not work when inside of a class?
I am trying to train a genetic algorithm but for some reason it does not work when it's stored inside of a class. I have two equivalent pieces of code but the one stored inside of a class fails. It returns this..
raise ValueError("The fitness functio... | Why does PyGad fitness_function not work when inside of a class? | I am trying to train a genetic algorithm but for some reason it does not work when it's stored inside of a class. I have two equivalent pieces of code but the one stored inside of a class fails. It returns this..
raise ValueError("The fitness function must accept 2 parameters:
1) A solution to calculate its fitness val... | [
"When you look at the pygad code you can see it's explicitly checking that the fitness function has exactly two parameters:\n # Check if the fitness function accepts 2 paramaters.\n if (fitness_func.__code__.co_argcount == 2):\n self.fitness_func = fitness_func\n else:\n s... | [
0
] | [] | [] | [
"genetic_algorithm",
"pygad",
"python",
"python_3.x",
"pytorch"
] | stackoverflow_0074578431_genetic_algorithm_pygad_python_python_3.x_pytorch.txt |
Q:
Python object orientated programming. Need to make my code shorter, I'm repeating myself quite a bit
I'm a few weeks into learning python and I'm trying to improve but my code looks very messy and way too long winded, I'm pretty sure I could greatly reduce the code used here. My code is just a very simple banking ... | Python object orientated programming. Need to make my code shorter, I'm repeating myself quite a bit | I'm a few weeks into learning python and I'm trying to improve but my code looks very messy and way too long winded, I'm pretty sure I could greatly reduce the code used here. My code is just a very simple banking program that can select account and deposit withdraw and transfer money ect. I am repeating myself quite o... | [
"There are quite a few things that can be improved but a few baby steps:\n\nYou can move the inner if-elif blocks that determine the account to outside. That way you don't have to ask for which account every time.\nYou should handle the case where user inputs an account number that is not 1 or 2. Your code only pri... | [
0
] | [] | [] | [
"bank",
"oop",
"python"
] | stackoverflow_0074578690_bank_oop_python.txt |
Q:
Scrapy cralwed 0 pages, scraped 0 item. What things should I check for the troubleshooting?
I'm trying to parse the post of this website to collect the texts for sentiment analysis. Here is the code that I'm working with.
# ~/dcscraper/dcscraper/spiders/spider.py
import scrapy
import pandas as pd
class dcscrape... | Scrapy cralwed 0 pages, scraped 0 item. What things should I check for the troubleshooting? | I'm trying to parse the post of this website to collect the texts for sentiment analysis. Here is the code that I'm working with.
# ~/dcscraper/dcscraper/spiders/spider.py
import scrapy
import pandas as pd
class dcscraper(scrapy.Spider):
name = "dcscraper"
def start_requests(self):
start_urls = ["ht... | [
"It tells you what the problem is in the logs.\n\nFile \"/home/luxiant/dcscraper/dcscraper/spiders/spider.py\", line 14, in parse for link in response.xpath('//[@id=\"container\"]/section/article/div/table/tbody/tr/td/a[contains(@href, \"/board/view\")'):\nFile \"/usr/lib/python3.10/site-packages/scrapy/http/respon... | [
0
] | [] | [] | [
"parsing",
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0074528684_parsing_python_scrapy_web_crawler.txt |
Q:
Trying to reorganize a random string so that all the letters are grouped up in the order that a different random string dictates
I am creating a matrix that will list these a random string of letters that are used for colors and they are to be organized so that, for example all of the G's will be together and then... | Trying to reorganize a random string so that all the letters are grouped up in the order that a different random string dictates | I am creating a matrix that will list these a random string of letters that are used for colors and they are to be organized so that, for example all of the G's will be together and then R, etc.
legoString = "YRRBRBYBGRBRGRRRYRGBRBGBBRBG"
shuffledColString = "YRBG"
for letter in shuffledColString:
for index in ran... | [
"try this\nlegoString = \"YRRBRBYBGRBRGRRRYRGBRBGBBRBG\"\nshuffledColString = \"YRBG\"\n\nns=\"\".join(sorted(legoString,key=lambda x:shuffledColString.index(x)))\nprint(ns)\n\n#OR IF ABOVE IS NOT CLEAR\nns=\"\"\nfor c in shuffledColString:\n ns=ns+ c*legoString.count(c)\n\nprint(ns)\n \n\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074578721_python.txt |
Q:
How to index the same char in different locations correctly
I was writing a program to loop through a string and index the capital letters in the string, but it keeps returning the first index of a same character
example:
AbcDeFgAiJ
will return
[0, 3, 5, 0, 9] instead of [0, 3, 5, 7, 9]
here is the code
def capita... | How to index the same char in different locations correctly | I was writing a program to loop through a string and index the capital letters in the string, but it keeps returning the first index of a same character
example:
AbcDeFgAiJ
will return
[0, 3, 5, 0, 9] instead of [0, 3, 5, 7, 9]
here is the code
def capitals(word):
arr = []
for i in word:
if i.isupper():... | [
"str.index will return first index found, so when you have for example two A in your string, it will return the index of first A.\nTry to use enumerate() instead:\nword = \"AbcDeFgAiJ\"\n\nout = [idx for idx, ch in enumerate(word) if ch.isupper()]\nprint(out)\n\nPrints:\n[0, 3, 5, 7, 9]\n\n"
] | [
0
] | [] | [] | [
"indexing",
"list",
"loops",
"python",
"string"
] | stackoverflow_0074578789_indexing_list_loops_python_string.txt |
Q:
Break a loop externally with the button that started the loop
I want to break a loop with the same button that I started the loop with.
For all intents and purposes, it does what I need it to, up until I click the button again. If I hit the button again, it crashes. Right now with the debug visual setup, I can hit... | Break a loop externally with the button that started the loop | I want to break a loop with the same button that I started the loop with.
For all intents and purposes, it does what I need it to, up until I click the button again. If I hit the button again, it crashes. Right now with the debug visual setup, I can hit q to break the loop. But down the road I obviously want to turn th... | [
"So I went and changed a majority of the code to use .after instead of using a while statement. Its not as clean looking, but it does what it needs to.\ncreated a function for on, and one for off and have the button cycle when the button is fixed. when the on button is pushed it calls to the start function which th... | [
0
] | [] | [] | [
"python",
"tkinter_button",
"while_loop"
] | stackoverflow_0074565110_python_tkinter_button_while_loop.txt |
Q:
Transformation and structuring of Excel file in Python
I ask you to help with the solution of the problem.
I recently started learning Python, and I don't have enough experience to solve it yet.
It is necessary to write a python script that transforms an Excel spreadsheet into a flat view for further work and anal... | Transformation and structuring of Excel file in Python | I ask you to help with the solution of the problem.
I recently started learning Python, and I don't have enough experience to solve it yet.
It is necessary to write a python script that transforms an Excel spreadsheet into a flat view for further work and analytics.
Source table: input ex.xlsx
Example of expected resul... | [
"Consider to find out more about pandas dataframe. We can then use pd.read_excel() and pd.read_csv() to read the data into memory and process the data using pandas.\n"
] | [
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074569013_excel_openpyxl_pandas_python_python_3.x.txt |
Q:
How to remove certain items that are not duplicate in 2 lists?
For example (here's the code I'm working on):
from bs4 import BeautifulSoup
from string import digits
import requests
joke_of_the_day = []
a = []
url_joke_of_the_day = "https://www.womansday.com/life/entertainment/a38635408/corny-jokes/"
page_joke_of_... | How to remove certain items that are not duplicate in 2 lists? | For example (here's the code I'm working on):
from bs4 import BeautifulSoup
from string import digits
import requests
joke_of_the_day = []
a = []
url_joke_of_the_day = "https://www.womansday.com/life/entertainment/a38635408/corny-jokes/"
page_joke_of_the_day = requests.get(url_joke_of_the_day)
soup_joke_of_the_day = B... | [
"To get question + responses you can use next example:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.womansday.com/life/entertainment/a38635408/corny-jokes/\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nfor n, joke in enumerate(soup.select(\"li:has(strong)\"), 1):\n... | [
0
] | [] | [] | [
"list",
"python",
"web_scraping"
] | stackoverflow_0074578792_list_python_web_scraping.txt |
Q:
Python script giving back error when attempting to load from file using JSON
I'm attempting to load two dictionaries using JSON. I save them with the following function:
def save_file(self):
print(save_dict['filename'])
with open(save_dict['filename'], 'w') as f:
save_list = [save_dict... | Python script giving back error when attempting to load from file using JSON | I'm attempting to load two dictionaries using JSON. I save them with the following function:
def save_file(self):
print(save_dict['filename'])
with open(save_dict['filename'], 'w') as f:
save_list = [save_dict, cad_dict]
json.dump(save_list, f)
I then attempt to load them using... | [
"I didn't look closely at my data and my ezdxf module was putting the coordinates as a an object that evidently doesn't work well with json. Converted those objects to strings and it now works.\n"
] | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074574489_json_python.txt |
Q:
Find the closest point to a line from an array of points
I have the problem of finding the point which is closest to a line from an array of x- and y-data.
The line is semi-infinite originating from the origin at (0,0) and running into the direction of a given angle.
The x,y data of the points are given in relati... | Find the closest point to a line from an array of points | I have the problem of finding the point which is closest to a line from an array of x- and y-data.
The line is semi-infinite originating from the origin at (0,0) and running into the direction of a given angle.
The x,y data of the points are given in relation to the origin.
How do I find the closest point (and its dis... | [
"Let P be a point from your know data set. Let Q be the projection of this point on the line. You can use an analytic approach to determine the exact location of Q:\n\nOQ is the segment from the origin to the Q point. It is aligned to the line.\nPQ is the distance of the point P to the line.\nfrom geometry, the dot... | [
1,
1
] | [] | [] | [
"geometry",
"matplotlib",
"python",
"scipy"
] | stackoverflow_0074577462_geometry_matplotlib_python_scipy.txt |
Q:
How can I add values to the begining and end of rows in a Pandas Dataframe?
I have a .csv file that lists a couple thousand names. If I read the csv file into a pandas data frame is there an easy what to add quotes around the names with a ',' at the end of each row?
Example below
This is what the output of the CSV... | How can I add values to the begining and end of rows in a Pandas Dataframe? | I have a .csv file that lists a couple thousand names. If I read the csv file into a pandas data frame is there an easy what to add quotes around the names with a ',' at the end of each row?
Example below
This is what the output of the CSV file looks like now.
name1
name2
name3
name4
What I would like the output to loo... | [
"\nAssume that the column has a name such as df['name']\n\nUse the following the add \"'\" \ndf['newName'] = df['name'].apply(lambda x : \"'\" + x + \"'\")\n\nA new column 'newName' is created where the quote is added.\n\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074578183_pandas_python.txt |
Q:
This function does not print
This function is supposed to recieve a string of text and tell if it is an isogram (a word with no repeated letters) or not. I do not understand why this does not work.
Here is the code.
String = input("input a string ");
def is_isogram(String):
String = String.lower()
counter ... | This function does not print | This function is supposed to recieve a string of text and tell if it is an isogram (a word with no repeated letters) or not. I do not understand why this does not work.
Here is the code.
String = input("input a string ");
def is_isogram(String):
String = String.lower()
counter = 0
while counter < 2:
... | [
"What you posted cannot work. You need a separate counter for each character to check this. But using a set seems to be better idea imho.\ndef is_isogram(s: str)->bool:\n unique_chars = set()\n for char in s:\n pre_add_len = len(unique_chars)\n unique_chars.add(char)\n post_add_len = len(... | [
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074575346_function_python.txt |
Q:
What is the error " TypeError: 'int' object is not callable"?
Substitute three numpy for the audio and combine them to get the max-min average. I am getting an error with this, what should I do?
import torch
import torchaudio
import torchaudio.transforms as T
import os
import requests
import librosa
import matplot... | What is the error " TypeError: 'int' object is not callable"? | Substitute three numpy for the audio and combine them to get the max-min average. I am getting an error with this, what should I do?
import torch
import torchaudio
import torchaudio.transforms as T
import os
import requests
import librosa
import matplotlib.pyplot as plt
# 音声の保存
_SAMPLE_DIR = "_sample_data"
SAMPLE_WAV_U... | [
"According to the docs for Torchaudio Spectrogram, the parameter that's passed to its return value (spectrogram() in your code) needs to be a PyTorch Tensor. In your code, you're giving it a Numpy array instead, because that's what your function synthesis() returns.\nYou can convert a Numpy ndarray into a Tensor wi... | [
1
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074573351_python_pytorch.txt |
Q:
PyTorch and torchvision compiled with different versions. How to solve?
PyTorch and Torchvision were compiled with different CUDA versions. PyTorch has CUDA version=11.6 and torchvision CUDA Version 11.3. Please reinstall the torchvision that matches your PyTorch install.
I've tried to reinstall torchvision so man... | PyTorch and torchvision compiled with different versions. How to solve? | PyTorch and Torchvision were compiled with different CUDA versions. PyTorch has CUDA version=11.6 and torchvision CUDA Version 11.3. Please reinstall the torchvision that matches your PyTorch install.
I've tried to reinstall torchvision so many times from the website as well as PyTorch and python.
I'm stuck I have no i... | [
"You need to upgrade your torchvision to one compiled with CUDA 11.6:\npip install --upgrade torchvision>=0.12.0\n\n",
"This worked for me:\npip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116\n"
] | [
0,
0
] | [] | [] | [
"python",
"pytorch",
"torch",
"torchvision"
] | stackoverflow_0074455445_python_pytorch_torch_torchvision.txt |
Q:
Filtering using a str array
I am trying to filter an ASCII list (which contains ASCII and other characters) by using an array that I have created. I am trying to remove any integer string within the list.
import pandas as pd
with open('ASCII.txt') as f:
data = f.read().replace('\t', ',')
print(data, file=o... | Filtering using a str array | I am trying to filter an ASCII list (which contains ASCII and other characters) by using an array that I have created. I am trying to remove any integer string within the list.
import pandas as pd
with open('ASCII.txt') as f:
data = f.read().replace('\t', ',')
print(data, file=open('my_file.csv', 'w'))
df = lis... | [
"Your if condition for numbers is broken.\nany checks if at least one element in the passed iterable is truthy, i.e. not an empty string in your case.\ntest = ['0','1','2','3','4','5','6','7','8','9']\nwhile any(test) in df: # Condition always evaluates to False\n df.remove('i') # Only removes the character 'i... | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074578882_python_string.txt |
Q:
Tkinter - "can not find channel named "stdout"
So I'm receiving the error,
_tkinter.TclError: can not find channel named "stdout"
by running this code:
from tkinter import Tcl
tcl = Tcl()
tcl.eval('''
puts hello
''')
For others it seems to work. I wonder if it is because I'm on windows and the distinction betw... | Tkinter - "can not find channel named "stdout" | So I'm receiving the error,
_tkinter.TclError: can not find channel named "stdout"
by running this code:
from tkinter import Tcl
tcl = Tcl()
tcl.eval('''
puts hello
''')
For others it seems to work. I wonder if it is because I'm on windows and the distinction between console and gui application ? An interesting app... | [
"I have found a sufficient solutions by combining two of Bryan's outstanding answers and the tutorial that I watch. To summarize the code below:\n\nwrap a python function into a tcl proc via register\noverwrite the tcl puts command\ntake a list as input and join the items with empty space between\ncall the wrapped ... | [
0
] | [] | [] | [
"python",
"tcl",
"tk_toolkit",
"tkinter"
] | stackoverflow_0074571933_python_tcl_tk_toolkit_tkinter.txt |
Q:
'NoneType' object has no attribute 'val' in Python Linked List
I have recently started to practice using LinkedList in Python and encountered the problem below. Both code seems like they are doing the same thing but 1 got the error while the other did not. Can someone let me know why this is the case?:
The ListNod... | 'NoneType' object has no attribute 'val' in Python Linked List | I have recently started to practice using LinkedList in Python and encountered the problem below. Both code seems like they are doing the same thing but 1 got the error while the other did not. Can someone let me know why this is the case?:
The ListNode class is defined as:
#Python Linked List
class ListNode:
def _... | [
"After your while loop finished you are at the last node in your linked list.\nSo node.next will point to None as per your definition:\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n",
"According to your code, you have set the default values for th... | [
0,
0
] | [] | [] | [
"linked_list",
"python"
] | stackoverflow_0074578957_linked_list_python.txt |
Q:
Concatenate two tensors of different shape from two different input modalities
I have two tensors:
a = torch.randn((1, 30, 1220)) # represents text embedding vector (30 spans, each with embedding size of 1220)
b = torch.randn((1, 128, 256)) # represents image features obtained from a pretrained CNN (object detecti... | Concatenate two tensors of different shape from two different input modalities | I have two tensors:
a = torch.randn((1, 30, 1220)) # represents text embedding vector (30 spans, each with embedding size of 1220)
b = torch.randn((1, 128, 256)) # represents image features obtained from a pretrained CNN (object detection)
How do I concatenate everything in b to each one of the 30 spans of a?
How to... | [
"You're looking to combine two tensors with different shapes, there is no trivial way of concatenating them. Both tensors hold information regarding the same instance: the element you want to characterize with features embeddings through two different modalities: textual and visual.\nThe only way that makes sense t... | [
1,
1,
0
] | [] | [] | [
"concatenation",
"deep_learning",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0069036172_concatenation_deep_learning_machine_learning_python_pytorch.txt |
Q:
Getting the Output of (ERROR: sequence item 0: expected str instance, bytes found) as a result of my function
I converted my code from python 2 to python 3, everything is working well except for this part of the code:
from binascii import unhexlify
def swap_endian_words(hex_words):
'''Swaps the endianness of a ... | Getting the Output of (ERROR: sequence item 0: expected str instance, bytes found) as a result of my function | I converted my code from python 2 to python 3, everything is working well except for this part of the code:
from binascii import unhexlify
def swap_endian_words(hex_words):
'''Swaps the endianness of a hexidecimal string of words and converts to binary string.'''
message = unhexlify(hex_words)
if len(message) % ... | [
"binascii.unhexlify returns a bytes object in Python 3, so the .join should also use a bytes string:\nfrom binascii import unhexlify\n\ndef swap_endian_words(hex_words):\n '''Swaps the endianness of a hexidecimal string of words and converts to binary string.'''\n message = unhexlify(hex_words)\n if len(message)... | [
1
] | [] | [] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074579045_python_python_2.7_python_3.x.txt |
Q:
'BatchDataset' object has no attribute 'shape'
Here is my code:
train_images = tf.keras.utils.image_dataset_from_directory(
'/content/drive/MyDrive/ArabicHandwritten2/train')
train_labels = tf.keras.utils.image_dataset_from_directory(
'/content/drive/MyDrive/ArabicHandwritten2/test')
train_images = tf.reshap... | 'BatchDataset' object has no attribute 'shape' | Here is my code:
train_images = tf.keras.utils.image_dataset_from_directory(
'/content/drive/MyDrive/ArabicHandwritten2/train')
train_labels = tf.keras.utils.image_dataset_from_directory(
'/content/drive/MyDrive/ArabicHandwritten2/test')
train_images = tf.reshape(train_images.shape[0], 256, 256, 3).astype('float3... | [
"Because image_dataset_from_directory returns a tf.data.Dataset which has no shape attribute. And you can see how to use the tf.reshape function here:\n"
] | [
0
] | [] | [] | [
"python",
"reshape",
"shapes",
"tensorflow"
] | stackoverflow_0074575411_python_reshape_shapes_tensorflow.txt |
Q:
Python typing validation
I would like to implement validation for Python 3.6 type annotation within my project.
I have a method that uses __annotations__ dict to check if all attributes of the class have the correct value. It works perfectly for basic types like int, str or bool, but fails for more sophisticated... | Python typing validation | I would like to implement validation for Python 3.6 type annotation within my project.
I have a method that uses __annotations__ dict to check if all attributes of the class have the correct value. It works perfectly for basic types like int, str or bool, but fails for more sophisticated elements like typing.Union or... | [
"Yes. isinstance and issubclass were killed some time ago for cases like Union. \nThe idea, as also stated in a comment on the issue by GvR is to implement your own version of issubclass/isinstance that use some of the extra metadata attached to types:\n>>> Union[int, str].__args__\n(int, str)\n>>> Union[int, str].... | [
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"python_3.6",
"python_3.x",
"type_hinting"
] | stackoverflow_0049067070_python_python_3.6_python_3.x_type_hinting.txt |
Q:
SEC_ERROR_UNKNOWN_ISSUER, playwright python inside docker
My code is quite simple:
from playwright.sync_api import sync_playwright
pw = sync_playwright().start()
firefox = pw.firefox.launch(headless=True)
context=firefox.new_context()
page= context.new_page()
page.goto("http://www.uaf.cl/prensa/sanciones_new.aspx... | SEC_ERROR_UNKNOWN_ISSUER, playwright python inside docker | My code is quite simple:
from playwright.sync_api import sync_playwright
pw = sync_playwright().start()
firefox = pw.firefox.launch(headless=True)
context=firefox.new_context()
page= context.new_page()
page.goto("http://www.uaf.cl/prensa/sanciones_new.aspx")
Every single time I get a SEC_ERROR_UNKNOWN_ISSUER.
Anyone ... | [
"Solved with:\ncontext=firefox.new_context(ignore_https_errors=True)\n\n"
] | [
1
] | [] | [] | [
"docker",
"playwright",
"playwright_python",
"python"
] | stackoverflow_0074551138_docker_playwright_playwright_python_python.txt |
Q:
fast way to find the related nets from a file (python)
try to find a fast way to find out the related nets of a net from a file.
R1 net net2
R2 net net3
R3 net2 net4
R4 net3 net5
R5 net6 net7
...
if a net is connected to another net through R, then these nets are considered as connected.
In above example, net/ne... | fast way to find the related nets from a file (python) | try to find a fast way to find out the related nets of a net from a file.
R1 net net2
R2 net net3
R3 net2 net4
R4 net3 net5
R5 net6 net7
...
if a net is connected to another net through R, then these nets are considered as connected.
In above example, net/net2/net3/net4/net5 are connected
i have a file containing ove... | [
"use networkx\nimport networkx as nx\n\ng=nx.Graph()\nwith open(file) as fi:\n for line in fi:\n if line[0].lower() == 'r':\n net1,net2 = line.split()[1:3]\n g.add_edge(net1.lower(),net2.lower())\n\n if net in g:\n related_nets = nx.descendants(g,net)\n\n"
] | [
0
] | [] | [] | [
"optimization",
"performance",
"python"
] | stackoverflow_0074558507_optimization_performance_python.txt |
Q:
Cartesian product of x and y array points into single array of 2D points
I have two numpy arrays that define the x and y axes of a grid. For example:
x = numpy.array([1,2,3])
y = numpy.array([4,5])
I'd like to generate the Cartesian product of these arrays to generate:
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]]... | Cartesian product of x and y array points into single array of 2D points | I have two numpy arrays that define the x and y axes of a grid. For example:
x = numpy.array([1,2,3])
y = numpy.array([4,5])
I'd like to generate the Cartesian product of these arrays to generate:
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
In a way that's not terribly inefficient since I need to do this many times... | [
"A canonical cartesian_product (almost)\nThere are many approaches to this problem with different properties. Some are faster than others, and some are more general-purpose. After a lot of testing and tweaking, I've found that the following function, which calculates an n-dimensional cartesian_product, is faster th... | [
191,
119,
63,
45,
21,
21,
12,
8,
4,
3,
3,
3,
1,
0,
0,
0,
0
] | [] | [] | [
"cartesian_product",
"numpy",
"python"
] | stackoverflow_0011144513_cartesian_product_numpy_python.txt |
Q:
I don't know how to process Python txt file input data
input.txt
3 3
1 3 3 | 3
2 7 8 | 4
1 5 1 | 5
I want to read it through Python file reading and then divide it into two matrices,
like
1 3 3
2 7 8
1 5 1
3
4
5
but I don't know how.
f=open("input.txt","r") # open input file
line = f.readline()
row = list(map(... | I don't know how to process Python txt file input data | input.txt
3 3
1 3 3 | 3
2 7 8 | 4
1 5 1 | 5
I want to read it through Python file reading and then divide it into two matrices,
like
1 3 3
2 7 8
1 5 1
3
4
5
but I don't know how.
f=open("input.txt","r") # open input file
line = f.readline()
row = list(map(int, line.split()))[0]
col = list(map(int, line.split()))[1]... | [
"Here is a better way to handle your input, using the suggestions from my comment.\nf=open(\"input.txt\",\"r\")\nline = f.readline().strip().split()\nrows = int(line[0])\ncols = int(line[1])\n\nprint(\"row = \",rows, \"col = \",cols)\nmain_matrix=[]\nsub_matrix=[]\n\nfor line in f:\n parts = line.strip().split()... | [
0
] | [] | [] | [
"input",
"matrix",
"python"
] | stackoverflow_0074579099_input_matrix_python.txt |
Q:
My search in python using tree view is not working/displaying the search results
This is my two functions which operate my search. The problem seems to occur with my search function when I binded it to my key releases on my search entries. However when I search with my button it works with no error messages .
... | My search in python using tree view is not working/displaying the search results | This is my two functions which operate my search. The problem seems to occur with my search function when I binded it to my key releases on my search entries. However when I search with my button it works with no error messages .
def SearchCustomer(self):
connection = sqlite3.connect("Guestrecord.... | [
"The function for a binding event expects an argument: the Event object. However you also use the same function for a button command which does not expect that extra argument.\nSo you need to add an optional argument to Search():\n# event argument is optional, if not provided, it will be None\ndef Search(self, eve... | [
0
] | [] | [] | [
"python",
"search",
"tkinter",
"treeview"
] | stackoverflow_0074579024_python_search_tkinter_treeview.txt |
Q:
Python opens new windows to run script?
print("test")
m = input("Name: ")
print(m)
I was getting ready to start programing. I opened cmd and ran my program and it opened a new cmd and printed out my code. Why is python opening a new cmd window to run my script unstead of using the cmd that was opened?
Also I rece... | Python opens new windows to run script? | print("test")
m = input("Name: ")
print(m)
I was getting ready to start programing. I opened cmd and ran my program and it opened a new cmd and printed out my code. Why is python opening a new cmd window to run my script unstead of using the cmd that was opened?
Also I recently updated python to python 3.10
| [
"When you type the name of a file, and the program associated with the file type is a console application (like python.exe) then Windows will open a new console window to run the application. When the application closes, the command window will close automatically.\nYou can get around this by opening Python yourse... | [
0,
0
] | [] | [] | [
"cmd",
"python",
"python_3.10"
] | stackoverflow_0074579088_cmd_python_python_3.10.txt |
Q:
How to calculate churn in Pyspark
Does anyone know how to apply a churn rule on the dataset below? The goal is to create a column called "churn" and use it to informing if it is true or false to whenever the Id remains "false" for more than 30 consecutive days in the "using" column
I already tried to work with wi... | How to calculate churn in Pyspark | Does anyone know how to apply a churn rule on the dataset below? The goal is to create a column called "churn" and use it to informing if it is true or false to whenever the Id remains "false" for more than 30 consecutive days in the "using" column
I already tried to work with window function but I didn't have success... | [
"Create a window function groupby by the id and ordering by date. Set the window to be between the current row and the previous 30 rows. To create the column, take the max of the using column which wil return True if any date has Using == True in the past 30 days. Finally, negate that value with ~ because you're in... | [
1
] | [] | [] | [
"pyspark",
"python"
] | stackoverflow_0074577969_pyspark_python.txt |
Q:
Simulate keyboard key press in Python to play games on Linux?
I'd like to simulate keyboard events, mainly WASD from Python to control games on Linux.
So far, I've tried PyKey and Keyboard module but unfortunately, they are unable to simulate the keypress in a way that games detect it as continuous movement and so... | Simulate keyboard key press in Python to play games on Linux? | I'd like to simulate keyboard events, mainly WASD from Python to control games on Linux.
So far, I've tried PyKey and Keyboard module but unfortunately, they are unable to simulate the keypress in a way that games detect it as continuous movement and so most games just don't work with these.
Are there any alternatives ... | [
"You could look into pyautogui and achieve your task with the following sample command:\npyautogui.press('w')\nI have not tried it for games specifically, but it may work!\n"
] | [
1
] | [] | [] | [
"gamecontroller",
"input",
"python",
"simulation"
] | stackoverflow_0074579109_gamecontroller_input_python_simulation.txt |
Q:
How to find missing elements between two elements in a list in Python?
I have a list as follows:
['1', '5', '6', '7', '10']
I want to find the missing element between two elements in the above list. For example, I want to get the missing elements between '1' and '5', i.e. '2', '3' and '4'. Another example, there ... | How to find missing elements between two elements in a list in Python? | I have a list as follows:
['1', '5', '6', '7', '10']
I want to find the missing element between two elements in the above list. For example, I want to get the missing elements between '1' and '5', i.e. '2', '3' and '4'. Another example, there are no elements between '5' and '6', so it doesn't need to return anything.
... | [
"If you iterate in pairs, it is easy to detect and fill in the gaps:\nL = ['1', '5', '6', '7', '10']\nresult = []\nfor left, right in zip(L, L[1:]):\n left, right = int(left), int(right)\n result += map(str, range(left + 1, right))\n\n",
"I would use the range() function to generate the missing numbers, and... | [
2,
2,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074579119_python.txt |
Q:
How best to append NetworkX Degree Value to original pandas dataframe?
I'm using NetworkX package for some network analysis, and I'm stuck on how best to append the degree of each node back to the original dataframe.
I have a dataframe that looks like this:
Focal_Coach
sibling_coach_id
years_under_focal
coach_nam... | How best to append NetworkX Degree Value to original pandas dataframe? | I'm using NetworkX package for some network analysis, and I'm stuck on how best to append the degree of each node back to the original dataframe.
I have a dataframe that looks like this:
Focal_Coach
sibling_coach_id
years_under_focal
coach_name
1
2
10
Bill Belichick
1
3
4
Bill Belichick
2
4
6
Andy Reid
... | [
"I needed to unpack the tuple first and turn it into a series.\nChanged the line to\n sibling_names,sibling_degrees = zip(*G_weighted.degree(sibling_df_agg['coach_name']))\n sibling_df_agg['degree_cnt'] = pd.Series(sibling_degrees)\n\nand it worked perfectly.\n"
] | [
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074578575_networkx_python.txt |
Q:
Is it possible to find the value of x in python? i.e asking python to solve an equation such as 2x + 23 - 7x when x is not a pre-defined variable
What I want is a program that can determine the value of x from an equation when x is not yet defined i.e. not a python variable.
Just an example below, not the real thi... | Is it possible to find the value of x in python? i.e asking python to solve an equation such as 2x + 23 - 7x when x is not a pre-defined variable | What I want is a program that can determine the value of x from an equation when x is not yet defined i.e. not a python variable.
Just an example below, not the real thing.
sol = eval("input please type the equation: ")
#i.e sol = 32x - 40
print(sol)
| [
"I am not aware of any built in way to do that but Sympy library is built exactly for this stuff. Solvers module in Sympy can be used to solve linear equations. (Here) is a link to its docs.\n",
"An explicit example using sympy\nimport sympy\nfrom sympy.abc import x\n\nprint sympy.solve(32*x-40,\"x\")\nprint symp... | [
2,
1,
0
] | [] | [] | [
"equation",
"equation_solving",
"eval",
"math",
"python"
] | stackoverflow_0029092649_equation_equation_solving_eval_math_python.txt |
Q:
How to send keyboard input in real time to server - python
I have a job that I need to make a tcp connection with socket. right. but I need that what the client type is sent to the server. that is, what is being typed at the client's prompt needs to be appearing at the server's prompt at the same time. includi... | How to send keyboard input in real time to server - python | I have a job that I need to make a tcp connection with socket. right. but I need that what the client type is sent to the server. that is, what is being typed at the client's prompt needs to be appearing at the server's prompt at the same time. including, if I delete a letter from the phrase or word in the client p... | [
"You may want to learn about the getch module\n"
] | [
0
] | [] | [] | [
"python",
"sockets",
"tcp",
"tcpclient",
"tcpserver"
] | stackoverflow_0074579177_python_sockets_tcp_tcpclient_tcpserver.txt |
Q:
How do you I get the value differently while looping for common prefix?
strs = ["cir","car"]
#strs = ["flower","flow","flight"]
def get_min_str(lst):
return min(lst, key=len)
str1 = get_min_str(strs)
lens = len(strs)
x = ""
mlen = len(str1)
if(lens == 1):
print(strs[0])
for i in range(0, mlen):
for ... | How do you I get the value differently while looping for common prefix? | strs = ["cir","car"]
#strs = ["flower","flow","flight"]
def get_min_str(lst):
return min(lst, key=len)
str1 = get_min_str(strs)
lens = len(strs)
x = ""
mlen = len(str1)
if(lens == 1):
print(strs[0])
for i in range(0, mlen):
for j in range(0, lens-1):
if( strs[j][i] == strs[j+1][i] ):
... | [
"Since you have two nested loops, the break keyword only exits the inner loop. Then, the third letter matches, so r is added to x. To fix this, set a variable when you should exit the outer loop and check it before each iteration.\nEdit: also, for readability's sake, you may want to explore the enumerate() function... | [
0
] | [] | [] | [
"arrays",
"prefix",
"python",
"range",
"string"
] | stackoverflow_0074579225_arrays_prefix_python_range_string.txt |
Q:
Printing out filenames of txt.-files that include at least one line of words, each starting with vowels. Only 1 line of code
My task is to write only one line of code in Python. The code should do the following: I need to print out filenames of txt.files, which include at least one line of words, starting with onl... | Printing out filenames of txt.-files that include at least one line of words, each starting with vowels. Only 1 line of code | My task is to write only one line of code in Python. The code should do the following: I need to print out filenames of txt.files, which include at least one line of words, starting with only vowels (each word needs to start with a vowel from at least one line). My code is:
[filename for filename in listdir(".")if file... | [
"You could try the following one-liner:\nprint([filename for filename in os.listdir(\".\") if filename.endswith('.txt') and [line for line in open(filename) if all(word.startswith(('a','e','i','o','u','A','E','I','O','U')) for word in line.split())]])\n\nOUTPUT:\n['file3.txt']\n\n\n\n\nTest files\nTested with file1... | [
1
] | [] | [] | [
"file",
"listdir",
"one_liner",
"python"
] | stackoverflow_0074567651_file_listdir_one_liner_python.txt |
Q:
Linear Regression not Defined
Previously had code and did not have any issues not it is giving an error of not having "Linear Regression" defined. Code below, not sure what I am missing.
from sklearn.preprocessing import PolynomialFeatures
model2 = PolynomialFeatures(degree = 2)
x_poly = model2.fit_transform(X_tr... | Linear Regression not Defined | Previously had code and did not have any issues not it is giving an error of not having "Linear Regression" defined. Code below, not sure what I am missing.
from sklearn.preprocessing import PolynomialFeatures
model2 = PolynomialFeatures(degree = 2)
x_poly = model2.fit_transform(X_train)
model2.fit(x_poly, y_train)
po... | [
"You need to import LinearRegression at the top of your code.\nfrom sklearn.linear_model import LinearRegression\n\n"
] | [
0
] | [] | [] | [
"knn",
"linear_regression",
"python"
] | stackoverflow_0074579292_knn_linear_regression_python.txt |
Q:
How to edit guild banner | discord.py
I have generated image, and i need to post it to the guild banner.
When i am trying to do this, is is not working and don't have errors.
My code:
@commands.command()
async def test(self, ctx):
await ctx.message.delete()
background = Editor('./assets/card_1.... | How to edit guild banner | discord.py | I have generated image, and i need to post it to the guild banner.
When i am trying to do this, is is not working and don't have errors.
My code:
@commands.command()
async def test(self, ctx):
await ctx.message.delete()
background = Editor('./assets/card_1.jpg').resize((900, 300))
background... | [
"You can't pass raw bytes into discord.File, as it needs a file-like object to read bytes from. Instead, wrap it in a BytesIO.\nfile = File(fp=io.BytesIO(background.image_bytes), filename='card.png')\n\n"
] | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074578488_discord.py_python.txt |
Q:
PyTorch RuntimeError: DataLoader worker (pid(s) 15332) exited unexpectedly
I am a beginner at PyTorch and I am just trying out some examples on this webpage. But I can't seem to get the 'super_resolution' program running due to this error:
RuntimeError: DataLoader worker (pid(s) 15332) exited unexpectedly
I search... | PyTorch RuntimeError: DataLoader worker (pid(s) 15332) exited unexpectedly | I am a beginner at PyTorch and I am just trying out some examples on this webpage. But I can't seem to get the 'super_resolution' program running due to this error:
RuntimeError: DataLoader worker (pid(s) 15332) exited unexpectedly
I searched the Internet and found that some people suggest setting num_workers to 0. But... | [
"There is no \"complete\" solve for GPU out of memory errors, but there are quite a few things you can do to relieve the memory demand. Also, make sure that you are not passing the trainset and testset to the GPU at the same time!\n\nDecrease batch size to 1\nDecrease the dimensionality of the fully-connected layer... | [
13,
11,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"pytorch"
] | stackoverflow_0060101168_python_python_3.x_pytorch.txt |
Q:
How can I improve recall value in Deep learning?
I'm applying vgg16 as feature extraction method, However my instructor require a high recall. (90%-95%). I will explain about my dataset my data are labeled videos of traffic sign in a foggy weather (they are labeled as visible, not visible, poor viability) I extrac... | How can I improve recall value in Deep learning? | I'm applying vgg16 as feature extraction method, However my instructor require a high recall. (90%-95%). I will explain about my dataset my data are labeled videos of traffic sign in a foggy weather (they are labeled as visible, not visible, poor viability) I extracted frames from the video as image and randomly stored... | [
"recognition rates depend on many variables not only the noises of the image when our recognition is about 80 percent but we also use some information for our recognition process as well. You talked about sign traffic and foggy image when you are local and foreigners who had well recognize the image sign, you had a... | [
0,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074577832_keras_python_tensorflow.txt |
Q:
do i need to use exactly same attribute names to properties in custom preprocessing class which inherit scikit learn BaseEstimator?
when writing custom classes inherit from BaseEstimator of the sklearn throwing AttributeError: object has no attribute . but that attribute is present and has values.
class BaseN... | do i need to use exactly same attribute names to properties in custom preprocessing class which inherit scikit learn BaseEstimator? | when writing custom classes inherit from BaseEstimator of the sklearn throwing AttributeError: object has no attribute . but that attribute is present and has values.
class BaseNull(BaseEstimator, TransformerMixin):
def __init__(self,
variables: Union[str, list[str]],
... | [
"\ndo i need to use exactly same attribute names to properties in custom preprocessing class which inherit scikit learn BaseEstimator?\n\nYes. See this part of the docs:\n\nAll scikit-learn estimators have get_params and set_params functions. The get_params function takes no arguments and returns a dict of the __in... | [
1
] | [] | [] | [
"class",
"python",
"scikit_learn"
] | stackoverflow_0074579336_class_python_scikit_learn.txt |
Q:
Rewriting loop without breaks
Below is the code that I want to replicate without using break
///
while True:
choice = input("Is it time to choose(Y/N)? ")
if choice.upper() == "N":
break
idx = random.randint(0, len(contents))
fnd = False
for i in range(3):
for j in range(3):
... | Rewriting loop without breaks | Below is the code that I want to replicate without using break
///
while True:
choice = input("Is it time to choose(Y/N)? ")
if choice.upper() == "N":
break
idx = random.randint(0, len(contents))
fnd = False
for i in range(3):
for j in range(3):
if table[i][j] == content... | [
"You can use a flag instead:\nw_flag = True\nwhile w_flag:\n choice = input(\"Is it time to choose(Y/N)? \")\n if choice.upper() == \"N\": \n w_flag = False\n \n if w_flag:\n idx = random.randint(0, len(contents))\n fnd = False\n i,j = 0,0\n i_flag = True\n whil... | [
0,
0
] | [] | [] | [
"break",
"loops",
"python"
] | stackoverflow_0074579272_break_loops_python.txt |
Q:
How do I get rid of labels in django Form?
I have dealt with only ModelForm previously, so it is my first time using Form.
I'd like to get rid of labels from my form, however, how I get rid of labels in ModelForm does not seem to work with Form.
Here is my code:
forms.py
class UserLoginForm(forms.Form):
email ... | How do I get rid of labels in django Form? | I have dealt with only ModelForm previously, so it is my first time using Form.
I'd like to get rid of labels from my form, however, how I get rid of labels in ModelForm does not seem to work with Form.
Here is my code:
forms.py
class UserLoginForm(forms.Form):
email = forms.CharField(max_length=255)
password =... | [
"As @Carcigenicate mentioned in the above comment that you can directly use {{form.email}} which would only render input tag instead of label tag.\nTo remove the label you should use inline labels not labels dict as they are defined in Meta class, so:\nclass UserLoginForm(forms.Form):\n email = forms.CharField(m... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_widget",
"python"
] | stackoverflow_0074578967_django_django_forms_django_templates_django_widget_python.txt |
Q:
customize html table of pytest with docstring of the test
I have a pytest test function as below.
def test_mytest():
''' this is my awesome test '''
assert 1==1
I'd like to print this test_mytest.docstring in the html report as a column between test and duration columns.
I could gather that the pytest_ru... | customize html table of pytest with docstring of the test | I have a pytest test function as below.
def test_mytest():
''' this is my awesome test '''
assert 1==1
I'd like to print this test_mytest.docstring in the html report as a column between test and duration columns.
I could gather that the pytest_runtest_makereport() pytest.mark.hookwrapper could help.
Is there... | [
"Fortunately the exact example is mention in the pytest-html user guide.\nhttps://pytest-html.readthedocs.io/en/latest/user_guide.html#modifying-the-results-table\nA mere copy paste of the example adds the docstring to the title\n"
] | [
0
] | [] | [] | [
"pytest",
"pytest_html",
"python"
] | stackoverflow_0074577151_pytest_pytest_html_python.txt |
Q:
Cannot import name '_png' from 'matplotlib'
I want to use matplotlib instead kivy_garden.graph. Actually, I tried this code to check if it works for me. I've had some problems with installing matplotlib but I have successfully(or not) done that.
When I started the code I got from matplotlib import _png ImportError... | Cannot import name '_png' from 'matplotlib' | I want to use matplotlib instead kivy_garden.graph. Actually, I tried this code to check if it works for me. I've had some problems with installing matplotlib but I have successfully(or not) done that.
When I started the code I got from matplotlib import _png ImportError: cannot import name '_png' from 'matplotlib' (D:... | [
"Reverting to matplotlib version 3.0.2 didn't work for me, but with 3.1.3 it did.\npython -m pip uninstall matplotlib\npip install matplotlib==3.1.3\n\nPython 3.8.2\n",
"I was having this problem in Google Colab and couldn't solve it. The simple solution that I found was to install the stable version that is pip ... | [
26,
5,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"kivy",
"matplotlib",
"python"
] | stackoverflow_0064862818_kivy_matplotlib_python.txt |
Q:
Cholesky factorisation not lower triangular
I am building a cholesky factorisation algorthim as proposed from the book:
Linear Algebra and Optimisation for Machine Learning
They provide the following algorthim:
I have attempted this with python with the following algorithm:
def CF(array):
array = np.array(a... | Cholesky factorisation not lower triangular | I am building a cholesky factorisation algorthim as proposed from the book:
Linear Algebra and Optimisation for Machine Learning
They provide the following algorthim:
I have attempted this with python with the following algorithm:
def CF(array):
array = np.array(array, float)
arr = np.linalg.eigvals(array)
... | [
"You don't even need to look at the detail of the algorithm.\nJust see that in your book algorithm you have\nfor j=1 to d\n L(j,j) = something\n for i=j+1 to d\n L(i,j) = something\n\nSo, necessarily, all elements whose line number i is greater or equal than column number j are filled. Rest is 0. Hence... | [
2
] | [] | [] | [
"linear_algebra",
"numpy",
"python"
] | stackoverflow_0074579332_linear_algebra_numpy_python.txt |
Q:
Replacing a string with NaN or 0
I have a data file that I'm cleaning, and the source uses '--' to indicate missing data.
I ultimately need to have this data field be either an integer or float. But I am not sure how to remove the string.
I specified the types in a type_dict statement before importing the csv fil... | Replacing a string with NaN or 0 | I have a data file that I'm cleaning, and the source uses '--' to indicate missing data.
I ultimately need to have this data field be either an integer or float. But I am not sure how to remove the string.
I specified the types in a type_dict statement before importing the csv file.
6 of my 8 variables correctly came ... | [
"try something like this cleaning input before antering into pandas\nimport sys\nfrom io import StringIO\nimport pandas as pd\n\nwith open('data.txt', 'r') as file:\n data = StringIO(file.read().replace('--', '0'))\n\ndf = pd.read_csv(data)\n\n\n\n",
"OK, we figured out two options to make this work:\nsolution... | [
0,
0
] | [] | [] | [
"dtype",
"nan",
"pandas",
"python",
"replace"
] | stackoverflow_0074578696_dtype_nan_pandas_python_replace.txt |
Q:
How to decode message_summary_info in macOS Messages chat.db
In the chat.db Messages database on macOS, in the message table there exist two binary blob columns:
attributedBody
message_summary_info
The message edit history (introduced with macOS Ventura) is stored in the message_summary_info.
I'm able to decode ... | How to decode message_summary_info in macOS Messages chat.db | In the chat.db Messages database on macOS, in the message table there exist two binary blob columns:
attributedBody
message_summary_info
The message edit history (introduced with macOS Ventura) is stored in the message_summary_info.
I'm able to decode and parse the attributedBody with python-typedstream, however atte... | [
"I believe I found at least a partial solution with python leveraging plistlib since the message_summary_info is a binary plist, but I'm open to better solutions if they exist.\nHere is some output of some test messages I sent with macOS Messages and edited. The message was originally \"Test BEFORE edit\", then was... | [
1
] | [] | [] | [
"imessage",
"macos",
"python"
] | stackoverflow_0074579463_imessage_macos_python.txt |
Q:
I cannot pass a parameter inside a function to another function (Python)
I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the... | I cannot pass a parameter inside a function to another function (Python) | I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the parameter cannot communicate with the whole program as far as I understand.
d... | [
"Since you've written the operations into functions and you're passing in the current subtotal, you just need to be updating the subtotal by saving the return value from appetizers() in main_menu(), like here:\n# ...\nif choice == 1:\n subtotal = appetizers(subtotal)\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074579462_python_python_3.x.txt |
Q:
python subprocess with gzip
I am trying to stream data through a subprocess, gzip it and write to a file.
The following works. I wonder if it is possible to use python's native gzip library instead.
fid = gzip.open(self.ipFile, 'rb') # input data
oFid = open(filtSortFile, 'wb') # output file
sort = subprocess.Pope... | python subprocess with gzip | I am trying to stream data through a subprocess, gzip it and write to a file.
The following works. I wonder if it is possible to use python's native gzip library instead.
fid = gzip.open(self.ipFile, 'rb') # input data
oFid = open(filtSortFile, 'wb') # output file
sort = subprocess.Popen(args="sort | gzip -c ", shell=T... | [
"subprocess writes to oFid.fileno() but gzip returns fd of underlying file object:\ndef fileno(self):\n \"\"\"Invoke the underlying file object's fileno() method.\"\"\"\n return self.fileobj.fileno()\n\nTo enable compression use gzip methods directly:\nimport gzip\nfrom subprocess import Popen, PIPE\nfrom thr... | [
6,
2,
0
] | [] | [] | [
"gzip",
"python"
] | stackoverflow_0007452427_gzip_python.txt |
Q:
dictionary of key, value from two lists without repeating items from either list
I am learning python and wanted to try and make a little script to handle "pulling names from a hat" to decide who has who for Christmas. I have no doubt that there is a more efficient way than this, but it works for the moment.
My is... | dictionary of key, value from two lists without repeating items from either list | I am learning python and wanted to try and make a little script to handle "pulling names from a hat" to decide who has who for Christmas. I have no doubt that there is a more efficient way than this, but it works for the moment.
My issue is that it's taking a very inconsistent amount of time to complete. I can run this... | [
"\nMy issue is that it's taking a very inconsistent amount of time to\ncomplete. I can run this once, and it spits out the results instantly,\nbut then the next time or few times it will just spin and I've let it\nsit for 5 minutes and it's still not complete.\n\nThis is because you end up with nothing but \"not al... | [
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074577651_dictionary_list_python.txt |
Q:
Highlight multiple characters in array with different colors
I'm fairly new to python so I'm wondering if anyone could help with my issue. I have a program that is reading an array of numbers and replacing the 1's with green coloured circles and the 4's with yellow coloured circles. The issue I'm having is I would... | Highlight multiple characters in array with different colors | I'm fairly new to python so I'm wondering if anyone could help with my issue. I have a program that is reading an array of numbers and replacing the 1's with green coloured circles and the 4's with yellow coloured circles. The issue I'm having is I would like for the array to print with the two changes applied but can ... | [
"I've never used colorama, don't know anything about it, and don't even have it installed, but I'm going to show you a better way to do it, anyway.\nI think it's obvious this is for coloring the console text, and in that you have a big issue. The formats that this is going to add to your text is full of numbers. Th... | [
0
] | [] | [] | [
"colorama",
"colors",
"highlight",
"python"
] | stackoverflow_0074579473_colorama_colors_highlight_python.txt |
Q:
Moviepy doubles the speed of the video without affecting audio. I suspect a framerate issue but I havent been able to fix it
Right now here is all I'm having moviepy do:
full_video = VideoFileClip(input_video_path)
full_video.write_videofile("output.mp4")
quit()
It just takes the video and writes it to another fi... | Moviepy doubles the speed of the video without affecting audio. I suspect a framerate issue but I havent been able to fix it | Right now here is all I'm having moviepy do:
full_video = VideoFileClip(input_video_path)
full_video.write_videofile("output.mp4")
quit()
It just takes the video and writes it to another file with no changes. But when the input video looks like this the output ends up looking like this with the video speed doubled but... | [
"I haven't been able to go deep down in the source code to figure out why this is, but I could indeed duplicate your bug with videos recorded with the Windows game bar.\nI also agree with you that it seems to be tied directly to the VideoFileClip method.\nI got my code to work by writing it like this:\nfull_video =... | [
0
] | [] | [] | [
"moviepy",
"python"
] | stackoverflow_0073341202_moviepy_python.txt |
Q:
Saving captured frames to separate folders
Currently working on extracting frames from videos and have noticed that the images get overwritten. Would be nice to create a folder for each of the captured frames but I'm unsure how to do that.
data_folder = r"C:\Users\jagac\Downloads\Data"
sub_folder_vid = "hmdb51_org... | Saving captured frames to separate folders | Currently working on extracting frames from videos and have noticed that the images get overwritten. Would be nice to create a folder for each of the captured frames but I'm unsure how to do that.
data_folder = r"C:\Users\jagac\Downloads\Data"
sub_folder_vid = "hmdb51_org"
path2videos = os.path.join(data_folder, sub_fo... | [
"The problem is that you're not incorporating name into your path, so each video is overwriting the previous. You can either add the file name to path2img, or add name to the path2store variable before you make the directory.\n"
] | [
0
] | [] | [] | [
"file",
"path",
"python"
] | stackoverflow_0074579529_file_path_python.txt |
Q:
Most recent previous business day in Python
I need to subtract business days from the current date.
I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday... | Most recent previous business day in Python | I need to subtract business days from the current date.
I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some pretty... | [
"Use pandas!\nimport datetime\n# BDay is business day, not birthday...\nfrom pandas.tseries.offsets import BDay\n\ntoday = datetime.datetime.today()\nprint(today - BDay(4))\n\nSince today is Thursday, Sept 26, that will give you an output of:\ndatetime.datetime(2013, 9, 20, 14, 8, 4, 89761)\n\n",
"If you want to ... | [
180,
21,
18,
13,
11,
8,
7,
3,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002224742_datetime_python.txt |
Q:
Python how to avoid a repeated dictionary key
So, I was trying to make a function to distribute tokens from a dictionary that works as a data base to other blank dictionaries. I use the random.randint() to obtain random tokens out of the big dict and transferred them to the other dict until they are filled with a ... | Python how to avoid a repeated dictionary key | So, I was trying to make a function to distribute tokens from a dictionary that works as a data base to other blank dictionaries. I use the random.randint() to obtain random tokens out of the big dict and transferred them to the other dict until they are filled with a len(dict) == 7. The problem occurs when the random ... | [
"To randomly select without repetition, you could instead use random.sample(), which returns n unique elements. We can take all the needed elements with this—7 tokens for the user, plus 7 tokens for the cpu.\nSince the results are random, it doesn't matter the order that they're selected, so we can take the first 7... | [
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074579558_dictionary_python.txt |
Q:
Send direct message to new members from target telegram group
i want to make a script, that get the user_id from new joined members in a target group, and send to new member a direct message, how i can do that?
I didn't know what to try.
A:
I think its a welcome message from new member. You can try this code. Co... | Send direct message to new members from target telegram group | i want to make a script, that get the user_id from new joined members in a target group, and send to new member a direct message, how i can do that?
I didn't know what to try.
| [
"I think its a welcome message from new member. You can try this code. Correct me if i wrong.\n@bot.on(events.ChatAction)\nasync def handler(event):\n\nif event.user_joined:\n await event.reply('Your Custom Message')\n print(event.sender.id)\n\nWith this code, will send a new message when nember joined to you... | [
0
] | [] | [] | [
"py_telegram_bot_api",
"python",
"reply",
"telegram",
"telethon"
] | stackoverflow_0074509906_py_telegram_bot_api_python_reply_telegram_telethon.txt |
Q:
display number on top or bottom of a candlestick chart with plotly or other charting libraries
Assume my data look like this:
With open/close/high/low/ I want to display a normal candlestick, but I also want to add the number in annotation column to top or bottom of the candlestick chart (like chart below), can a... | display number on top or bottom of a candlestick chart with plotly or other charting libraries | Assume my data look like this:
With open/close/high/low/ I want to display a normal candlestick, but I also want to add the number in annotation column to top or bottom of the candlestick chart (like chart below), can anyone help me potentially ways how to achieve it. Thank you!
I have tried mplfinance, but looking i... | [
"There are several ways to annotate, but in the case of this question it is easiest to use the text mode for scatter plots. After creating the candlestick, add a scatter plot. To link the position to be annotated in the string to the candlestick, the opening and closing prices are compared, with the price correspon... | [
1
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074572415_plotly_python.txt |
Q:
Can scrapy be used to scrape dynamic content from websites that are using AJAX?
I have recently been learning Python and am dipping my hand into building a web-scraper. It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.
Most of the issues are... | Can scrapy be used to scrape dynamic content from websites that are using AJAX? | I have recently been learning Python and am dipping my hand into building a web-scraper. It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.
Most of the issues are solvable and I'm having a good little mess around. However I'm hitting a massive hur... | [
"Here is a simple example of scrapy with an AJAX request. Let see the site rubin-kazan.ru.\nAll messages are loaded with an AJAX request. My goal is to fetch these messages with all their attributes (author, date, ...):\n\nWhen I analyze the source code of the page I can't see all these messages because the web pa... | [
104,
80,
44,
36,
11,
3,
3,
2,
0
] | [
"I handle the ajax request by using Selenium and the Firefox web driver. It is not that fast if you need the crawler as a daemon, but much better than any manual solution.\n"
] | [
-1
] | [
"ajax",
"javascript",
"python",
"scrapy",
"screen_scraping"
] | stackoverflow_0008550114_ajax_javascript_python_scrapy_screen_scraping.txt |
Q:
Airflow SimpleHttpOperator is not pushing to xcom
I have the following SimpleHttpOperator inside my dag:
extracting_user = SimpleHttpOperator(
task_id='extracting_user',
http_conn_id='user_api',
endpoint='api/', # Some Api already configured and checked
method="GET",
respons... | Airflow SimpleHttpOperator is not pushing to xcom | I have the following SimpleHttpOperator inside my dag:
extracting_user = SimpleHttpOperator(
task_id='extracting_user',
http_conn_id='user_api',
endpoint='api/', # Some Api already configured and checked
method="GET",
response_filter=lambda response: json.loads(response.text),
... | [
"I solved the problem changing to the version 2.0.0 of airflow. It seems that the SimpleHttpOperator doesn't store the request response on the xcom table on 2.3.0 version\n",
"the SimpleHttpOperator does return a XCOM. However, the command airflow tasks test does NOT create XComs anymore, whe\n"
] | [
1,
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0072232029_airflow_python.txt |
Q:
python argument and position on how to pass file
i need to pass the filename on a opencv img read how can i do that
class show_image:
def __init__(self, window):
self.window = window
frame = Frame(window)
frame.pack(side=BOTTOM, padx=15, pady=15)
def showimage(self):
self... | python argument and position on how to pass file | i need to pass the filename on a opencv img read how can i do that
class show_image:
def __init__(self, window):
self.window = window
frame = Frame(window)
frame.pack(side=BOTTOM, padx=15, pady=15)
def showimage(self):
self.filename = filedialog.askopenfilename(initialdir=os.g... | [] | [] | [
"Your Vehicle_Counting.__init__() only takes 2 parameters: the implicit self, and window.\nIn this line\nThesis.VehicleCounting.Vehicle_Counting(win, self.filename)\n\nYou're providing it with three parameters: the implicit self, win, and self.filename. Either add filename to the list of __init__ arguments, or don'... | [
-1
] | [
"arguments",
"file",
"python",
"tkinter"
] | stackoverflow_0074579218_arguments_file_python_tkinter.txt |
Q:
Rename the first index of data frame in Panadas
I created one new data frame by using one list and column value, and I successfully renamed the Index name but I'm not able to rename the first column name, I tried all the possible methods that I know
(I want to rename this column name O with date, I tried all metho... | Rename the first index of data frame in Panadas | I created one new data frame by using one list and column value, and I successfully renamed the Index name but I'm not able to rename the first column name, I tried all the possible methods that I know
(I want to rename this column name O with date, I tried all methods but it won't work as you can see in code snap)
dat... | [
"I tried to reproduce your case reading a .csv file, but I was able to rename the column.\nIt does seem to me that you'll catch the problem here:\nNewDf.rename(columns = {'0':'date'}, inplace = True)\nA good trick to debug this, according to the documentation would be to add the argument errors=\"raise\", so try to... | [
0
] | [] | [] | [
"dataframe",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074579406_dataframe_matplotlib_pandas_python.txt |
Q:
Can't convert all dates to timestamp in python
I'm trying to convert all the dates into timestamp from a url in json but I don't know what I'm doing wrong, it gives me the following error:
This is the code I'm using:
from datetime import datetime
from dateutil import relativedelta
from dateutil import parser
from... | Can't convert all dates to timestamp in python | I'm trying to convert all the dates into timestamp from a url in json but I don't know what I'm doing wrong, it gives me the following error:
This is the code I'm using:
from datetime import datetime
from dateutil import relativedelta
from dateutil import parser
from datetime import datetime
from dateutil.parser impo... | [
"As esqew said, isoparse doesn't take a sep argument. You should loop over the dates and parse them individually, like so:\nfor i in historialSKIN[\"data\"]:\n for datestr in i['shopHistory']:\n fecha = isoparse(datestr).timestamp()\n print(fecha)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074579684_python.txt |
Q:
Run Websocket in a separate Thread, updating class attributes
I want to implement a class with the possibility to start various websockets in different threads to retrieve market data and update the class attributes. I am using the kucoin-python-sdk library to that purpose.
The below works fine in spyder, however ... | Run Websocket in a separate Thread, updating class attributes | I want to implement a class with the possibility to start various websockets in different threads to retrieve market data and update the class attributes. I am using the kucoin-python-sdk library to that purpose.
The below works fine in spyder, however when I set my script to run via a conda batch it fails with the fol... | [
"I want to say it's your implementation but I haven't tried using that client the way you're doing it. Here's a pared down skeleton of what I'm doing to implement that kucoin-python in async.\nimport asyncio\nfrom kucoin.client import WsToken\nfrom kucoin.ws_client import KucoinWsClient\nfrom kucoin.client import ... | [
0
] | [] | [] | [
"conda",
"kucoin",
"nest_asyncio",
"python",
"websocket"
] | stackoverflow_0074302351_conda_kucoin_nest_asyncio_python_websocket.txt |
Q:
writing "dictionaries" to .csv file in a particular format after loading data allowing pickle
I saved a python dictionary with the numpy np.save() function. I had to load allow_pickle to load it back so I now have the dictionary in this format:
values = {(0, 0, 0): {0: -1421.05, 1: -1578.94, 2: -1473.65, 3: -1471.... | writing "dictionaries" to .csv file in a particular format after loading data allowing pickle | I saved a python dictionary with the numpy np.save() function. I had to load allow_pickle to load it back so I now have the dictionary in this format:
values = {(0, 0, 0): {0: -1421.05, 1: -1578.94, 2: -1473.65, 3: -1471.21},(0, 0, 1): {0: -142, 1: -157, 2: -147, 3: -147},(0, 0, 2): {0: 19, 1: 15, 2: 10, 3: 12}},
I wa... | [
"How about we try this?\nAs you represented the desired dataframe, I had to assume that the index would be a string and not a tuple.\nIn case I assumed wrong, please feel free to remove the single quotes from my dictionary.\nimport pandas as pd\n\n# Change the key to strings :)\n\nvalues = {'(0, 0, 0)': {0: -1421.0... | [
0
] | [] | [] | [
"csv",
"dictionary",
"numpy",
"pandas",
"python"
] | stackoverflow_0074578974_csv_dictionary_numpy_pandas_python.txt |
Q:
Python: fast aggregation of many observations to daily sum
I have observations with start and end date of the following format:
import pandas as pd
data = pd.DataFrame({
'start_date':pd.to_datetime(['2021-01-07','2021-01-04','2021-01-12','2021-01-03']),
'end_date':pd.to_datetime(['2021-01-16','2021-01-12'... | Python: fast aggregation of many observations to daily sum | I have observations with start and end date of the following format:
import pandas as pd
data = pd.DataFrame({
'start_date':pd.to_datetime(['2021-01-07','2021-01-04','2021-01-12','2021-01-03']),
'end_date':pd.to_datetime(['2021-01-16','2021-01-12','2021-01-13','2021-01-15']),
'value':[7,6,5,4]
})
data... | [
"I feel this problem comes back regularly as it’s not an easy thing to do. Some techniques would probably transform each row into a date range or otherwise iterate on rows. In this case there’s a smarter workaround, which is to use cumulative sums, then reindex.\n>>> starts = data.set_index('start_date')['value'].s... | [
3,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069194678_pandas_python.txt |
Q:
Python mypy: float and int are incompatible types with numbers.Real
I am new to Python's static typing module mypy. I am trying to append ints and floats to an array, which I typed statically to be Real. But mypy says that they are incompatible types with Real. I thought ints and floats are a subtype of Real?
from... | Python mypy: float and int are incompatible types with numbers.Real | I am new to Python's static typing module mypy. I am trying to append ints and floats to an array, which I typed statically to be Real. But mypy says that they are incompatible types with Real. I thought ints and floats are a subtype of Real?
from typing import List
from numbers import Real
data : List[Real] = []
with... | [
"As AChampion says you can just use float in place of numbers.Real. Pep 0484 (specifically here) basically says that in the context of type-checking the hierarchy complex > float > int is respected and that numbers.* doesn't need to be used.\nThis is a known 'issue' with mypy and was raised and discussed here. I ha... | [
0
] | [] | [] | [
"mypy",
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0063894187_mypy_python_python_typing_type_hinting.txt |
Q:
AttributeError: module 'yfinance' has no attribute 'download'
I'm trying to import yfinance and some stocks into pandas dataframe. Initially had major issues importing yfinance. I installed using pip but still had to manually put in the files to actually get rid of the no module error.
This is my code so far:
Now... | AttributeError: module 'yfinance' has no attribute 'download' | I'm trying to import yfinance and some stocks into pandas dataframe. Initially had major issues importing yfinance. I installed using pip but still had to manually put in the files to actually get rid of the no module error.
This is my code so far:
Now I'm getting attribute error when trying to download yfinance.
imp... | [
"I just been having the same error but the following code worked after deleting a local file named yahoofinance\n!pip install yfinance\nimport yfinance as yf\nimport pandas as pd\nimport datetime as dt\n\n",
"\nI installed using pip but still had to manually put in the files to actually get rid of the no module e... | [
1,
0,
0
] | [] | [] | [
"python",
"yfinance"
] | stackoverflow_0061509917_python_yfinance.txt |
Q:
Exception has occurred: TypeError unsupported operand type(s) for *: 'NoneType' and 'float'
Code is correct, has an output, but gets the error message.
import math
class Prelim:
def __init__(self):
self.LA1 = int(input('Enter your grade in Lab Activity #1: ')) #100
self.LA2 = int(input('Enter ... | Exception has occurred: TypeError unsupported operand type(s) for *: 'NoneType' and 'float' | Code is correct, has an output, but gets the error message.
import math
class Prelim:
def __init__(self):
self.LA1 = int(input('Enter your grade in Lab Activity #1: ')) #100
self.LA2 = int(input('Enter your grade in Lab Activity #2: ')) #100
self.LA3 = int(input('Enter your grade in Lab Act... | [
"just wrong usage of print command. use code below:\nimport math\nclass Prelim:\n def __init__(self):\n self.LA1 = int(input('Enter your grade in Lab Activity #1: ')) #100\n self.LA2 = int(input('Enter your grade in Lab Activity #2: ')) #100\n self.LA3 = int(input('Enter your grade in Lab Ac... | [
0
] | [] | [] | [
"class",
"function",
"python"
] | stackoverflow_0074579749_class_function_python.txt |
Q:
Python: Download video with Youtube and pytube - fix error (regex...)
When I try to run the code below, it gives me the response:
"Python: Download video with Youtube and pytube - fix error (regex...)"
Tried multiple solutions, all to no avail.
Here is my code:
link = "https://www.youtube.com/watch?v=vEQ8CXFWLZU... | Python: Download video with Youtube and pytube - fix error (regex...) | When I try to run the code below, it gives me the response:
"Python: Download video with Youtube and pytube - fix error (regex...)"
Tried multiple solutions, all to no avail.
Here is my code:
link = "https://www.youtube.com/watch?v=vEQ8CXFWLZU&t=475s&ab_channel=InternetMadeCoder"
yt = YouTube(link)
print(yt.title)
... | [
"I tried the following code:\nfrom pytube import YouTube\n\nlink = \"https://www.youtube.com/watch?v=vEQ8CXFWLZU&t=475s&ab_channel=InternetMadeCoder\"\nyt = YouTube(link)\nprint(yt.title)\n\n\nOUTPUT:\n3 PYTHON AUTOMATION PROJECTS FOR BEGINNERS\n\nPerhaps try creating a new python virtual environment - as you may b... | [
0,
0,
0
] | [] | [] | [
"python",
"pytube"
] | stackoverflow_0074579512_python_pytube.txt |
Q:
adjacency matrix map manipulation
0
I'm making a simple text based adventure game. My code uses an adjacency matrix as a map. I would like to navigate the map by direction ex(N,E,S,W) my current attempt can only navigate via the name of the location
current output
You are currently in Foyer.
From this location, yo... | adjacency matrix map manipulation | 0
I'm making a simple text based adventure game. My code uses an adjacency matrix as a map. I would like to navigate the map by direction ex(N,E,S,W) my current attempt can only navigate via the name of the location
current output
You are currently in Foyer.
From this location, you could go to any of the following:
Li... | [
"Maybe add North, South, East, West to exits conditionally if it's possible to move in that direction?\n"
] | [
0
] | [] | [] | [
"arrays",
"matrix",
"python"
] | stackoverflow_0074579808_arrays_matrix_python.txt |
Q:
I want to get the first string before comma on a csv file but also get the string for rows that have no commas (only one tag)
This is my original CSV file
enter image description here
I want to make the genre column only the first tag. when I use
dataframe['genre'] = dataframe['genre'].str.extract('^(.+?),')
it g... | I want to get the first string before comma on a csv file but also get the string for rows that have no commas (only one tag) | This is my original CSV file
enter image description here
I want to make the genre column only the first tag. when I use
dataframe['genre'] = dataframe['genre'].str.extract('^(.+?),')
it gets the string before the first comma but it also gets rid of columns without commas
enter image description here
how can I make it... | [
"Use a different regex:\ndataframe['genre'] = dataframe['genre'].str.extract('^([^,]+)')\n\nRegex:\n^ # match start of line\n([^,]+) # capture everything but comma\n\n",
"Close, but it's easier to split the strings than develop a regex in this case, because it's so simple. You can do this instead.\ndatafram... | [
2,
1
] | [] | [] | [
"csv",
"pandas",
"python",
"regex"
] | stackoverflow_0074579824_csv_pandas_python_regex.txt |
Q:
Enter the number of students – Enter the name, age, height of each student. Print list in sorted order Name(Abc)>Age(small-large)>Height (small-large)
This is my code i don't know what i'm doing wrong. TypeError: 'Students' object is not subscriptable
this is the error of this code and i don't know how to fix it i... | Enter the number of students – Enter the name, age, height of each student. Print list in sorted order Name(Abc)>Age(small-large)>Height (small-large) | This is my code i don't know what i'm doing wrong. TypeError: 'Students' object is not subscriptable
this is the error of this code and i don't know how to fix it i try many ways
import operator
from operator import itemgetter, attrgetter
class Students:
def __init__(self,name,age,height):
self.name = name
... | [
"In sort_list, you are using operator.itemgetter(0).\nIf you have a Students object like so:\ns = Students(...)\n\nThen operator.itemgetter(0) is performing something analogous to:\ns[0]\n\nThere is no value in a Students object that can be accessed with square brackets, which is why you're getting the error 'Stude... | [
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074579775_python_sorting.txt |
Q:
Stacking a lot of SVG images as layers issue
So I would like to stack a lot of svg images on top of each other in Python.
I am using this to do so:
import svgutils.transform as st
template = st.fromfile('firstLayer.svg')
second_svg = st.fromfile('secondLayer.svg')
template.append(second_svg)
template.save('merged... | Stacking a lot of SVG images as layers issue | So I would like to stack a lot of svg images on top of each other in Python.
I am using this to do so:
import svgutils.transform as st
template = st.fromfile('firstLayer.svg')
second_svg = st.fromfile('secondLayer.svg')
template.append(second_svg)
template.save('merged.svg')
It technically works.
Only problem is tha... | [
"If anyone found himself due to the same issue, I didn't find an already made Python solution that rewrites the class name in the elements and the class attribute of each path so I have created one myself:\nhttps://github.com/Amirh24/SVGAppender\nFeel free to use it :)\n",
"Hey I was running into the exact same ... | [
0,
0
] | [] | [] | [
"python",
"svg"
] | stackoverflow_0050652568_python_svg.txt |
Q:
python recursion for child parent grandparent etc hierarchy
I am trying to create the full hierarchy chain for every child. I have two dicts, the first contains all child-parent pairs to be used as lookup, and the second contains all children as keys, and their values starts off as a list containing the immediate ... | python recursion for child parent grandparent etc hierarchy | I am trying to create the full hierarchy chain for every child. I have two dicts, the first contains all child-parent pairs to be used as lookup, and the second contains all children as keys, and their values starts off as a list containing the immediate parent where then the grand parents, great garnd parents etc will... | [
"Some terminology. We're doing a transitive closure over a forest (a data structure containing the roots of many trees). By denoting the structure as a forest, I'm assuming there are no cycles in the graph.\ndef transitive_closure(forest):\n def recurse(root, path):\n if root in forest and forest[root]:\n... | [
1
] | [] | [] | [
"dictionary",
"python",
"recursion"
] | stackoverflow_0074543804_dictionary_python_recursion.txt |
Q:
Python Seleniume Multiple Buttons with same name
For the below HTML code, I want to select the button in the DIV for 2022 November
<div class="reportTitleNonMobile ng-binding">
2022 November
<button cla... | Python Seleniume Multiple Buttons with same name | For the below HTML code, I want to select the button in the DIV for 2022 November
<div class="reportTitleNonMobile ng-binding">
2022 November
<button class="myButton" ng-show="!gridFile.monthOpen" ng-click="... | [
"You can use the below XPath:\nFor the 'Open' button in '2022 November':\n(.//*[@class='reportTitleAreaNonMobile'])[1]//button[1]\n\nFor the 'Close' button in '2022 November':\n(.//*[@class='reportTitleAreaNonMobile'])[1]//button[2]\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074579838_python_selenium.txt |
Q:
How can I print the number of steps forward, backward, and total?
Here's my code:
import math
import random
while True:
fwd= random.randint(2,20)
bkwd= random.randint(2,fwd)
total=random.randint(10,85)
f= 0
b = 0
t= 0
if bkwd > fwd:
break
while total > 0:
f = 0
... | How can I print the number of steps forward, backward, and total? | Here's my code:
import math
import random
while True:
fwd= random.randint(2,20)
bkwd= random.randint(2,fwd)
total=random.randint(10,85)
f= 0
b = 0
t= 0
if bkwd > fwd:
break
while total > 0:
f = 0
while fwd > f:
if total > 0:
print("... | [
"For one thing, bkwd = random.randint(2,fwd) will generate a number between 2<=n<=fwd, when instead you want 2<=n<=fwd-1.\nTo answer your question, you just need to add a new variable to keep track of total steps taken. Maybe call it steps_taken? You should increment this counter once for every step taken.\n"
] | [
0
] | [] | [] | [
"iteration",
"loops",
"motion",
"python"
] | stackoverflow_0074579955_iteration_loops_motion_python.txt |
Q:
How do I check if a string represents a number (float or int)?
How do I check if a string represents a numeric value in Python?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
The above works, but it seems clunky.
If what you are testing comes from user... | How do I check if a string represents a number (float or int)? | How do I check if a string represents a numeric value in Python?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
The above works, but it seems clunky.
If what you are testing comes from user input, it is still a string even if it represents an int or a float... | [
"For non-negative (unsigned) integers only, use isdigit():\n>>> a = \"03523\"\n>>> a.isdigit()\nTrue\n>>> b = \"963spam\"\n>>> b.isdigit()\nFalse\n\n\nDocumentation for isdigit(): Python2, Python3\nFor Python 2 Unicode strings:\nisnumeric().\n",
"\nWhich, not only is ugly and slow\n\nI'd dispute both.\nA regex or... | [
1733,
770,
285,
79,
67,
48,
45,
31,
29,
17,
15,
14,
12,
11,
9,
9,
9,
8,
7,
5,
5,
4,
3,
3,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [
"I have a similar problem. Instead of defining a isNumber function, I want to convert a list of strings to floats, something that in high-level terms would be:\n[ float(s) for s in list if isFloat(s)]\n\nIt is a given we can not really separate the float(s) from the isFloat(s) functions: these two results should be... | [
-2,
-3
] | [
"casting",
"floating_point",
"python",
"type_conversion"
] | stackoverflow_0000354038_casting_floating_point_python_type_conversion.txt |
Q:
Compare 2 lists consisting of dictionaries by key python
there are 2 lists of dictionaries with the same keys, for example:
old = [{'key1': 'AAA', 'key2': 'value2', 'key3': 'value3'},{'key1': 'BBB', 'key2': 'value4', 'key3': 'value5'},{'key1': 'CCC', 'key2': 'value4', 'key3': 'value5'}]
new = [{'key1': 'BBB', 'ke... | Compare 2 lists consisting of dictionaries by key python | there are 2 lists of dictionaries with the same keys, for example:
old = [{'key1': 'AAA', 'key2': 'value2', 'key3': 'value3'},{'key1': 'BBB', 'key2': 'value4', 'key3': 'value5'},{'key1': 'CCC', 'key2': 'value4', 'key3': 'value5'}]
new = [{'key1': 'BBB', 'key2': 'value2', 'key3': 'value3'},{'key1': 'CCC', 'key2': 'valu... | [
"Use the nested loop the other way round:\nfor y in new:\n for x in old:\n if x['key1'] == y['key1']:\n old.remove(x)\nprint(old)\n\nwhich produces:\n[{'key1': 'AAA', 'key2': 'value2', 'key3': 'value3'}]\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074579817_dictionary_list_python.txt |
Q:
Why can I multiply string by int, but not variable with int value?
I am making a text-based geometry calculator, and I'm working on a perimeter calculator feature, using a for loop it will ask you for side length x amount of times, x being the side count or sideCnt, in order for the for loop to work, I believe I n... | Why can I multiply string by int, but not variable with int value? | I am making a text-based geometry calculator, and I'm working on a perimeter calculator feature, using a for loop it will ask you for side length x amount of times, x being the side count or sideCnt, in order for the for loop to work, I believe I need to set up a string that has characters equal to the amount of cycles... | [
"Are you sure you don't have:\nsideCnt = \"3\"\n\nSomewhere in your code, or something similar?\nMaybe you are reading 3 in from user input and not casting it to an int?\nThere is definitely something else happening in your code, you are not showing, what you have shown will work fine.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074580047_python.txt |
Q:
Should you decorate dataclass subclasses if not making additional fields
If you don't add any more fields to your subclass is there a need to add the @dataclass decorator to it and would it do anything?
If there is no difference, which is the usual convention?
from dataclasses import dataclass
@dataclass
class AA... | Should you decorate dataclass subclasses if not making additional fields | If you don't add any more fields to your subclass is there a need to add the @dataclass decorator to it and would it do anything?
If there is no difference, which is the usual convention?
from dataclasses import dataclass
@dataclass
class AAA:
x: str
y: str
...
# decorate?
class BBB(AAA):
...
| [
"If you don't decorate your class, the variables defined in the root of the class will be class attributes which would be shared between all instances of the class. The dataclass let's you define the variables there but they would be instance attributes so each instance can hold its own value. If you instantiate on... | [
1,
1
] | [] | [] | [
"conventions",
"python",
"python_dataclasses"
] | stackoverflow_0074563511_conventions_python_python_dataclasses.txt |
Q:
Libssl and libcrypto causing dyld: Library not loaded: /usr/lib/libpq.5.dylib
I recently uninstalled postgresql and installed pyscopg2 via pip.
I know there's some trickery involved with libcrypto and libssl
Currently i have them symlinked to:
$ ls -lah libssl.*
-rwxr-xr-x 1 root wheel 402K Aug 28 11:06 libssl... | Libssl and libcrypto causing dyld: Library not loaded: /usr/lib/libpq.5.dylib | I recently uninstalled postgresql and installed pyscopg2 via pip.
I know there's some trickery involved with libcrypto and libssl
Currently i have them symlinked to:
$ ls -lah libssl.*
-rwxr-xr-x 1 root wheel 402K Aug 28 11:06 libssl.0.9.7.dylib
-rwxr-xr-x 1 root wheel 589K Aug 28 11:06 libssl.0.9.8.dylib
lrwxr... | [
"Turns out /usr/lib/libpq.5.dylib was absent but /usr/lib/libpq.5.4.dylib was not. \nsudo ln -s /usr/lib/libpq.5.4.dylib /usr/lib/libpq.5.dylib\n\nfixed the issue. \n",
"just use the below commands in your terminal\n(use the proper postgresql version)\n$ brew unlink postgresql@14\n$ brew link libpq --force\nhttps... | [
16,
8,
3,
2,
2,
0
] | [] | [] | [
"libssl",
"pip",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0013643452_libssl_pip_postgresql_psycopg2_python.txt |
Q:
construct dataset for ner train
i have in input :
text = "Apple est une entreprise, James Alfred travaille ici"
spans = [
{
"start":0,
"end":5,
"label":"ORG"
},
{
"start":26,
"end":38,
"label":"PER"
}
]
correspondance_dict = {"PER":2, "ORG": 4 , "O" : 0}
i want to tokenize the text and construct label accord... | construct dataset for ner train | i have in input :
text = "Apple est une entreprise, James Alfred travaille ici"
spans = [
{
"start":0,
"end":5,
"label":"ORG"
},
{
"start":26,
"end":38,
"label":"PER"
}
]
correspondance_dict = {"PER":2, "ORG": 4 , "O" : 0}
i want to tokenize the text and construct label according to spans list i.e :
i want to hav... | [
"If you're trying to use a huggingface's pipeline in other parts of your program, it's easy to aggregate output text chunks using an appropriate strategy.\nThe documentation for a thorough explanation is available here!\nfrom transformers import pipeline\n\n# Initialize the NER pipeline\nner = pipeline(\"ner\", agg... | [
0
] | [] | [] | [
"nlp",
"python",
"python_3.x",
"spacy"
] | stackoverflow_0074577951_nlp_python_python_3.x_spacy.txt |
Q:
List Comprehension instead of a for loop not working
Udemy course: Loop over the items of the passwords list and in each iteration print out the item if the item contains the strings 'ba' or 'ab' inside.
passwords = ['ccavfb', 'baaded', 'bbaa', 'aaeed', 'vbb', 'aadeba', 'aba', 'dee', 'dade', 'abc', 'aae', 'dded', ... | List Comprehension instead of a for loop not working | Udemy course: Loop over the items of the passwords list and in each iteration print out the item if the item contains the strings 'ba' or 'ab' inside.
passwords = ['ccavfb', 'baaded', 'bbaa', 'aaeed', 'vbb', 'aadeba', 'aba', 'dee', 'dade', 'abc', 'aae', 'dded', 'abb', 'aaf', 'ffaec']
I know i could create the following... | [
"Even if that did work it wouldn't give you the results you desire. If you want to use that style you will have to join it.\ndef checker(passes):\n return '\\n'.join(x for x in passes if 'ab' in x or 'ba' in x)\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074580155_python_python_3.x.txt |
Q:
How to convert JSON data into a tree image?
I'm using treelib to generate trees, now I need easy-to-read version of trees, so I want to convert them into images. For example:
The sample JSON data, for the following tree:
With data:
>>> print(tree.to_json(with_data=True))
{"Harry": {"data": null, "children": [{"B... | How to convert JSON data into a tree image? | I'm using treelib to generate trees, now I need easy-to-read version of trees, so I want to convert them into images. For example:
The sample JSON data, for the following tree:
With data:
>>> print(tree.to_json(with_data=True))
{"Harry": {"data": null, "children": [{"Bill": {"data": null}}, {"Jane": {"data": null, "c... | [
"For a tree like this there's no need to use a library: you can generate the Graphviz DOT language statements directly. The only tricky part is extracting the tree edges from the JSON data. To do that, we first convert the JSON string back into a Python dict, and then parse that dict recursively.\nIf a name in the ... | [
16,
4,
0
] | [] | [] | [
"json",
"python",
"tree"
] | stackoverflow_0040118113_json_python_tree.txt |
Q:
I can't show the dates in the same embed with python from discord BOT
I have created a bot for discord that shows all the dates of any fortnite skin through the api, but my problem is that it does not show me all the dates inside the embed with the !skin command, it only shows me a date in timestamp format
this is... | I can't show the dates in the same embed with python from discord BOT | I have created a bot for discord that shows all the dates of any fortnite skin through the api, but my problem is that it does not show me all the dates inside the embed with the !skin command, it only shows me a date in timestamp format
this is the code:
@bot.command()
async def skin(ctx):
url = requests.get("http... | [
"Your variable \"fecha\" must be array or string to contain all your dates.\nHere's the code, it should work. I think I've shown you the problem and then you'll figure it out for yourself.\n@bot.command()\nasync def skin(ctx):\n url = requests.get(\"https://fortnite-api.com/v2/cosmetics/br/search/all?language=es... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074580125_python.txt |
Q:
simple flask application form, form page not functioning
form page not displaying response,
I left off some tags that were supposed to be closed. I changed that already. Basically, once i fill out the form and click on the submit button it should take me to the display page where it displays a string such as " Hel... | simple flask application form, form page not functioning | form page not displaying response,
I left off some tags that were supposed to be closed. I changed that already. Basically, once i fill out the form and click on the submit button it should take me to the display page where it displays a string such as " Hello" + string + "thank you for submitting!"
main.py code
#impo... | [
"If everything is ok with you except that feedback is not displaying then do this:\ndef form():\n#get the method of the post and the method of the get \n if request.method == \"POST\" and request.form.get('submit'):\n string = request.form.get('name')\n feedback = \"Hello\" + string + \"\\n Thank ... | [
0,
0
] | [] | [] | [
"flask",
"forms",
"python"
] | stackoverflow_0074576479_flask_forms_python.txt |
Q:
Form unicode character from label
I have a simple syntax related question that I would be grateful if someone could answer. So I currently have character labels in a string format: '0941'.
To print out unicode characters in Python, I can just use the command:
print(u'\u0941')
Now, my question is how can I conver... | Form unicode character from label | I have a simple syntax related question that I would be grateful if someone could answer. So I currently have character labels in a string format: '0941'.
To print out unicode characters in Python, I can just use the command:
print(u'\u0941')
Now, my question is how can I convert the label I have ('0941') into the un... | [
">>> chr(int('0941',16)) == '\\u0941'\nTrue\n\n"
] | [
0
] | [
"One way to accomplish this without fussing with your numeric keypad is to simply print the character and then copy/paste it as a label.\n >>> print(\"lower case delta: \\u03B4\")\n lower case delta: δ\n >>> δ = 42 # copy the lower case delta symbol and paste it to use it as a label\n >>> δδ = δ ** 2 ... | [
-1
] | [
"python",
"unicode",
"utf_8"
] | stackoverflow_0062114695_python_unicode_utf_8.txt |
Q:
What is the path that Django uses for locating and loading templates?
I'm following this tutorial on a Windows 7 environment.
My settings file has this definition:
TEMPLATE_DIRS = (
'C:/django-project/myapp/mytemplates/admin'
)
I got the base_template from the template admin/base_site.html from within the de... | What is the path that Django uses for locating and loading templates? | I'm following this tutorial on a Windows 7 environment.
My settings file has this definition:
TEMPLATE_DIRS = (
'C:/django-project/myapp/mytemplates/admin'
)
I got the base_template from the template admin/base_site.html from within the default Django admin template directory in the source code of Django itself (... | [
"I know this isn't in the Django tutorial, and shame on them, but it's better to set up relative paths for your path variables. You can set it up like so:\nimport os.path\n\nPROJECT_PATH = os.path.realpath(os.path.dirname(__file__))\n\n...\n\nMEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')\n\nTEMPLATE_DIRS = [\n ... | [
203,
41,
15,
9,
6,
4,
3,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003038459_django_django_templates_python.txt |
Q:
Python, Only allow a certain IP address to access get-request
Im fairly new to python and this may be a stupid question but have been working on a small project that will listen out for a get request and then strip off the useful information and disregard things like (IP of sender or port number). Had my server up... | Python, Only allow a certain IP address to access get-request | Im fairly new to python and this may be a stupid question but have been working on a small project that will listen out for a get request and then strip off the useful information and disregard things like (IP of sender or port number). Had my server up for less than a day and noticed a few failed attempts to access it... | [
"It's been two years now, but I'm putting the answer here for anyone who needs it.\nYou have to make you own handler, and only give access to the IPs:\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\n\nclass MyHttpHandler(SimpleHTTPRequestHandler):\n allowed_addresses = [\n '192.168.1.50',\n... | [
0
] | [] | [] | [
"get_request",
"python"
] | stackoverflow_0060689548_get_request_python.txt |
Q:
keras , val_accuracy, val_loss is loss: 0.0000e+00 val_loss: 0.0000e+00 - val_accuracy: 0.0000e+00 problem
first of all, i using 100class and use 150 videos per class and, i devide this 80% is training set, 20% is validation set.
and under is my code
def generator(filePath,labelList):
tmp = [[x,y] for x, y in... | keras , val_accuracy, val_loss is loss: 0.0000e+00 val_loss: 0.0000e+00 - val_accuracy: 0.0000e+00 problem | first of all, i using 100class and use 150 videos per class and, i devide this 80% is training set, 20% is validation set.
and under is my code
def generator(filePath,labelList):
tmp = [[x,y] for x, y in zip(filePath, labelList)]
np.random.shuffle(tmp)
Files = [n[0] for n in tmp]
Labels = [n[1] for n in tmp... | [
"it is the logits shape and categorizes mismatches you need to select 100 target classes with different shape, and forms it into ( 100, 0 ) or equivalent.\n\nSample: Identical is expecting of input types or compared among them, loss function and statistics matrix calculation from estimating and evaluation by step o... | [
0
] | [] | [] | [
"keras",
"lstm",
"python",
"tensorflow"
] | stackoverflow_0074580072_keras_lstm_python_tensorflow.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.