- 1
- 2
def __repr__(self) -> str:
return f"<User{return ', inactive!' if not self.active else ''} #{self.id} ({self.username}/{self.email})>"
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
def __repr__(self) -> str:
return f"<User{return ', inactive!' if not self.active else ''} #{self.id} ({self.username}/{self.email})>"
Когда очень хочется использовать красивый f"{ormat}" для строки, но модель БД становится все сложнее...
−2
Какой есть аналог класса для данных?
class Record():
pass
r = Record()
r. asd = 1
Заебало класс объявлять, неужели для такого элементарного случая ничего не придумали?
−3
from random import choice
noun = ['пони', 'анус', 'синхрофазатрон', 'погромист', 'хуй', 'шланг', 'гцц', 'соснолька', 'хуита', 'говно', 'питушня', 'лалка', 'питон', 'енот', 'ватник', 'пидорашка', 'шиндос', 'линупс', 'жопа', 'дед мороз']
verb = ['срёт', 'падает', 'бесит', 'пиздит', 'летает', 'сосёт', 'бегает']
adj = ['сраный', 'ёбаный', 'розовый', 'коричневый', 'охуенный', 'пиздатый', 'тупой', 'ебучий', '']
templates = [
[adj, noun, verb],
[adj, noun],
[noun, ['говно']],
[['У тебя'], adj, noun, verb],
[['У тебя'], adj, noun],
[['Какого хуя'], adj, noun, verb, ['\b?']],
[['Почему'], noun, verb, ['\b?']],
[['Что такое'], noun, ['\b?']],
[adj, noun, verb, 'и', verb],
[noun, verb, ['\b, a'], noun, verb],
]
bububu = lambda: (lambda s: s[0].capitalize() + s[1:] + (choice('.!?') if s[-1] not in '.!?' else ''))(' '.join(i for i in map(choice, choice(templates)) if i))
for _ in range(30):
print(bububu())
https://ideone.com/oOwyzI
Просто от неча делать...
0
Прыщеговно
Explanation: The issue stemmed from two issues one in normpath and the other in os.path.join. It turns out that when normpath (or abspath) gets an absolute path starting with a single slash or 3+ slashes, the result would have a single slash. However, if the input had exactly two leading slashes the output will retain them. This behavior conforms to an obscore passage in the POSIX standard (last paragraph):
A pathname that begins with two successive slashes may be interpreted in an implementation-defined manner, although more than two leading slashes shall be treated as a single slash.
normpath и abspath из os.path
+1
In [42]: os.path.join(r'c:\asd', r'c:\www')
Out[42]: 'c:\\www'
Нахуя???
0
def sql_select_filter(sql, flt, order=None, limit=None, offset=None, group_by=None, lock=None, withSelectWrapper=True):
if withSelectWrapper and group_by is None:
if re.search(r'^\s*select\s+', sql, flags=re.IGNORECASE | re.MULTILINE):
sql = "SELECT * FROM ( " + sql + " ) as z99 "
else:
sql = "SELECT * FROM " + sql + " "
sql = sql.replace("%", '%%')
where, vals = _make_where_conditions(flt)
if where is not None:
sql += " WHERE " + where
if group_by is not None and len(group_by):
sql += " GROUP BY " + ",".join(group_by)
if order is not None and len(order):
order_fields = []
for field, direction in order.items():
order_fields.append(field + " " + direction)
sql += " ORDER BY " + ",".join(order_fields)
if limit is not None:
sql += " LIMIT %s"
vals.append(limit)
if offset is not None:
sql += " OFFSET %s"
vals.append(offset)
if lock is not None:
sql += " FOR " + lock
return sql, vals
Конструктор SQL запроосов, все очень секурно!
0
try:
assert isinstance(tag, bs4.element.Tag)
except AssertionError:
raise TypeError
−2
import json
import time
import requests
from multiprocessing.dummy import Pool as ThreadPool
max_threads = 10
fname = "data.json"
headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36", "referer":"https://datmusic.xyz/?q=Home+resonance", "authority":"api-2.datmusic.xyz"}
def api(url):
while True:
try:
r = requests.get(url, headers=headers)
r = r.json()
if r['status'] == 'error':
pass
else:
return r['data'][0]['download']
except Exception as e:
pass
def download(a):
# open in binary mode
while True:
try:
with open(a[1]+".mp3", "wb") as file:
response = requests.get(a[0],headers=headers)
if not (response.status_code == 503):
file.write(response.content)
print(a[1],"downloaded")
break
else:
pass
except Exception as e:
pass
songs = []
with open(fname) as json_data:
data = json.load(json_data)
for mp3 in data['list']:
song = []
autor = mp3[4]
title = mp3[3][:-5]
song.append(autor)
song.append(title)
songs.append(song)
links = []
def linker(a):
song = []
link = api("https://api-2.datmusic.xyz/search?q=" + a[0] + "+" + a[1] + "&page=0")
song.append(link)
song.append(a[0] + ' - ' + a[1])
links.append(song)
print(a[1])
for a in songs:
linker(a)
#if len(links) > 10:
# break
pool = ThreadPool(max_threads)
results = pool.map(download, links)
pool.close()
pool.join()
#Наговнокодил загрущик плейлистов с контача. Как получить json плейлиста подумай сам (перейди в музыку, открой Network в f12 и мониторь запрос при открытии плейлиста)
#Парсер 1 поточный, загрущик многопоточный. Работает через апи datmusic.xyz спс им
#vk.com music downloader v1.0a
#загрущик музыки вк
json = https://gist.githubusercontent.com/alekxeyuk/a1ccd2c62ab56a71320a02582cfc06f9/raw/4f2622c4beeddfa7e3082c276e1c138c87478e83/data.json
−2
secs = 0
fsecs = 0.0
mins = 40
lastsecs = 0
prevsecs = 0
def getTimeStr() :
def f ( x ) :
if ( 10 <= x <= 19 ) : return ''
y = x % 10
if ( y == 1 ) : return 'а'
if ( 2 <= y <= 4 ) : return 'ы'
return ''
return 'Время: %d минут%s %d секунд%s' % ( mins , f ( mins ) , secs , f ( secs ) )
def updateTimer() :
global timeString , root , secs , fsecs , lastsecs , prevsecs , mins
if ( fin ) : return
prevsecs , lastsecs = lastsecs , clock()
t = secs
if ( fsecs > 0 ) :
fsecs -= lastsecs - prevsecs
secs = int ( fsecs )
elif ( mins > 0 ) :
mins -= 1
fsecs = 60 + fsecs - lastsecs + prevsecs
secs = int ( fsecs )
else :
finish()
if ( secs == t ) :
timeString [ 'text' ] = getTimeStr()
root.after ( 100 , updateTimer )
Святая Питония и tkinter
−1
from itertools import *
lines = tuple ( chain ( ( tuple ( product ( *g ( range ( 3 ) , ( i , ) ) ) ) for g in ( lambda i , j : ( i , j ) , lambda i , j : ( j , i ) ) for i in range ( 3 ) ) , ( ( ( 0 , 0 ) , ( 1 , 1 ) , ( 2 , 2 ) ) , ( ( 2 , 0 ) , ( 1 , 1 ) , ( 0 , 2 ) ) ) ) )
def aimove ( table , i , j ) :
from random import choice
possiblewin = ( lambda x : ( lambda f : ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : x , map ( f , lines ) ) ) ) ) ( lambda k : 2 == sum ( table.get ( i ) == x for i in k ) and ( lambda e : len ( e ) == 1 and e [ 0 ] ) ( tuple ( i for i in k if not table.get ( i ) ) ) ) )
return ( ( 1 , 1 ) if ( 1 , 1 ) not in table.keys() else possiblewin ( -1 ) or possiblewin ( 1 ) or ( lambda : ( lambda x : x if table.get ( x ) == None else ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : not table.get ( x ) , permutations ( ( 0 , 2 ) ) ) ) ) ) ( ( 2 * ( i == 0 ) , 2 * ( j == 0 ) ) ) ) () or ( lambda : choice ( tuple ( filter ( lambda x : x not in table.keys() , product ( *tee ( range ( 3 ) ) ) ) ) ) ) () )
iseog = lambda table : ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : abs ( x ) == 3 , ( sum ( table [ ij ] for ij in keys if table.get ( ij ) ) for keys in lines ) ) ) ) or len ( table ) >= 9
table = {}
eog = 0
while not eog :
i , j = map ( int , input ( "введите координаты: " ) .split() )
if ( i , j ) in table.keys() :
print ( "эта клетка занята" )
continue
if i not in range ( 3 ) or j not in range ( 3 ) :
print ( "неправильные координаты" )
continue
table [ i , j ] = 1
eog = iseog ( table )
if not eog :
table [ aimove ( table , i , j ) ] = -1
eog = iseog ( table )
for ij in product ( *tee ( range ( 3 ) ) ) :
print ( ( " " , "x" , "o" ) [ table.get ( ij ) or 0 ] , end = ( " | " , " | " , "\n" ) [ ij [ 1 ] ] )
if ij [ 0 ] < 2 and ij [ 1 ] == 2 :
print ( "--+---+--" )
print ( ( "ничья. тебе везёт ( пока что )" , "ты победил. ах ты жульник!" , "ты продул, а я победил. бе-бе-бе!" ) [ eog // 3 ] )
Лямбда. Лямбда. Хуямбда.