- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
function foo(x = class { static prop: string }): string {
return undefined;
}
function main() {
foo(class { static prop = "hello" }).length;
print("done.");
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−1
function foo(x = class { static prop: string }): string {
return undefined;
}
function main() {
foo(class { static prop = "hello" }).length;
print("done.");
}
ну что С/C++ скушали? а ты так можешь говнокодить?
+4
#!/usr/bin/env bash
URL=https://foo.bar/baz.zip
PATH=/home/foo/bar/baz.zip
wget -O "$PATH" "$URL"
И только потом до мена дошло…
0
#include <string>
#include <iostream>
int foo() {
std::string str = "file://*";
std::cout << str << std::endl;
return 0;
}
/*
int bar() {
std::string str = "file://*"; // warning: '/*' within block comment [-Wcomment]
std::cout << str << std::endl;
return 0;
}
*/
int main() {
foo();
//bar();
}
Какой багор
https://ideone.com/NiXH2q
−2
В начале сентября Лицокнига представила т.н. "умные очки" - девайс в виде очков со встроенной камерой.
ФСБ России уже отнесли гаджет к УНПИ. Наказание за использование спецтехники - до 4 лет лишения свободы.
Не пойму, как можно назвать "шпионским устройством" предмет, который видит и слышит то же, что и его владелец.
+1
QSqlQuery& SQLConnect::get()
{
if ( makeConnection() ) {
query = QSqlQuery(mDb);
return query;
}
QSqlQuery empty;
return empty;
}
bool SQLConnect::makeConnection()
{
mDb = SQLConnectPool::Instance().get();
return true;
}
Раньше компилилось и не замечал, а тут на новом компиляторе начал кидать ошибки и решил посмотреть, что же там напроектировали
+2
/*
https://habr.com/ru/post/523688/
Так как мы работаем с макросистемой C/C++, то аналог функций — макрос, этой
абстракцией мы и будем пользоваться. Мы будем передавать идентификатор первого
рекурсивного макроса в следующий рекурсивный макрос, и тот, в свою очередь, по
мере завершения своего исполнения будет передавать поток исполнения в первый
рекурсивный макрос, так называемое продолжение. Нам также понадобиться терминальное
продолжение — ML99_PRIV_REC_STOP — оно будет являться продолжением, поставляющимся
в самый-самый первый рекурсивный макрос, ведь логично, что никуда, кроме как
закончить исполнение программы на данном месте, нам перепрыгивать не нужно. Жилка
двигателя рекурсии — это цепочка из макросов-раскрывателей следующего вида:
*/
#define ML99_PRIV_REC_0(choice, ...) ML99_PRIV_REC_NEXT(1, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_1(choice, ...) ML99_PRIV_REC_NEXT(2, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_2(choice, ...) ML99_PRIV_REC_NEXT(3, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_3(choice, ...) ML99_PRIV_REC_NEXT(4, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_4(choice, ...) ML99_PRIV_REC_NEXT(5, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_5(choice, ...) ML99_PRIV_REC_NEXT(6, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_6(choice, ...) ML99_PRIV_REC_NEXT(7, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_7(choice, ...) ML99_PRIV_REC_NEXT(8, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_8(choice, ...) ML99_PRIV_REC_NEXT(9, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_9(choice, ...) ML99_PRIV_REC_NEXT(10, choice)(__VA_ARGS__)
//...
//И так до 1023:
Интересно, этот чувак сидит на говнокоде?
0
public static boolean isMagicSquare(int[][] a) {
boolean isMagic = true;
boolean isSquare = true;
//square? checking here.
for(int i = 0; i < a.length; i++) {
if(a.length != a[i].length) {
isSquare = false;
}
}
if(isSquare) {
int sum = 0;
int nextSum = 0;
//first row
for(int i = 0; i < a.length; i++) {
sum += a[0][i];
}
//rows
for(int i = 1; i < a.length; i++) {
for(int j = 0; j < a.length; j++) {
nextSum += a[i][j];
}
if(nextSum != sum) {
isMagic = false;
break;
} else {
nextSum = 0;
}
}
//columns
if(isMagic) {
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a.length; j++) {
nextSum += a[j][i];
}
if(nextSum != sum) {
isMagic = false;
break;
} else {
nextSum = 0;
}
}
//diagonals
if(isMagic) {
for(int i = 0; i < a.length; i++) {
nextSum += a[i][i];
}
if(nextSum != sum) {
isMagic = false;
} else {
nextSum = 0;
}
if(isMagic) {
int j = a.length - 1;
for(int i = 0; i < a.length; i++) {
nextSum += a[i][j];
if(j > 0) {
j--;
}
}
if(nextSum != sum) {
isMagic = false;
}
}
}
}
} else {
isMagic = false;
}
return isMagic;
}
Write a method called isMagicSquare that accepts a two-dimensional array of integers as a parameter and returns true if it is a magic square. A square matrix is a magic square if it is square in shape (same number of rows as columns, and every row the same length), and all of its row, column, and diagonal sums are equal. For example, [[2, 7, 6], [9, 5, 1], [4, 3, 8]] is a magic square because all eight of the sums are exactly 15.
(https://practiceit.cs.washington.edu/problem/view/bjp3/chapter7/e20%2DisMagicSquare)
Работает, но код нечитаемый. Как сократить? Понятия не имею.
0
start_link(Shard, Subscriber) ->
gen_server:start_link(?MODULE, {server, Shard, Subscriber}, []).
start_link_client(Shard, RemoteNode, Parent) ->
gen_server:start_link(?MODULE, {client, Shard, RemoteNode, Parent}, []).
init({server, Shard, Subscriber}) ->
{ok, #server{ shard = Shard
, subscriber = Subscriber
}};
init({client, Shard, RemoteNode, Parent}) ->
{ok, #client{ parent = Parent
, shard = Shard
}}.
0
import math
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--type")
parser.add_argument("--principal", type=int)
parser.add_argument("--periods", type=int)
parser.add_argument("--interest", type=float)
parser.add_argument("--payment", type=float)
args = parser.parse_args()
choose = args.type
p = args.principal
n = args.periods
i = args.interest
a = args.payment
if i is None or p is None and a is None:
print("Incorrect parameters.")
exit(0)
i = (i * 0.01) / (12 * 1)
if choose == "diff":
m = 1
overpayment_all = 0
while m <= n:
d = math.ceil(p / n + i * (p - ((p * (m - 1)) / n)))
m += 1
overpayment_all += d
print(f"Month {m - 1}: payment is {d}")
print()
print(f"Overpayment = {overpayment_all - p}")
elif choose == "annuity" and a is None:
a = math.ceil(p * (i * math.pow((1 + i), n)) / (math.pow((1 + i), n) - 1))
print(f"Your monthly payment = {a}!")
over = a * n - p
print(f"Overpayment = {math.ceil(over)}")
elif choose == "annuity" and p is None:
p = int(a / (i * math.pow(1 + i, n) / (math.pow(1 + i, n) - 1)))
print(f"Your loan principal = {p}!")
m = 1
over = a * n - p
print(f"Overpayment = {math.ceil(over)}")
elif choose == "annuity":
n = math.ceil(math.log(a / (a - i * p), 1 + i))
zxc = math.ceil(math.log(a / (a - i * p), 1 + i))
years = 0
while n >= 12:
n -= 12
years += 1
if years == 0:
print(f"It will take {n} months to repay this loan!")
over = a * zxc - p
print(f"Overpayment = {math.ceil(over)}")
elif n == 0:
print(f"It will take {years} years to repay this loan!")
over = a * zxc - p
print(f"Overpayment = {math.ceil(over)}")
else:
print(f"It will take {years} years and {n} months to repay this loan!")
over = a * zxc - p
print(f"Overpayment = {math.ceil(over)}")
Ебучий универ и ебучее задание на питоне. Всё было бы збс, если бы не математика.
Прога считает проценты, бабки, переплаты и чёт ещё, наверное
−4
format pe console
include 'win32ax.inc'
macro call1 f,p1{
mov ebx,p1
call f}
macro call2 f,p1,p2{
mov ecx,p2
call1 f,p1}
macro call3 f,p1,p2,p3{
mov edx,p3
call2 f,p1,p2}
.data
lead_time dd ?
handle_input dd ?
handle_output dd ?
byte_read_write dd ?
.code
string db 'govnokod.ru ',13,10,0
array_procs dd __strlen,_strlen,strlen,0
putdword:;ebx-handle,ecx-byte
mov eax,esp
mov esi,eax
sub esp,16
xchg eax,ecx
mov edi,10
@@:xor edx,edx
div edi
add dl,'0'
dec ecx
mov [ecx],dl
test eax,eax
jnz @b
sub esi,ecx
mov edx,esi
invoke WriteFile,ebx,ecx,edx,byte_read_write,0
add esp,16
ret
align 4
strlen:;ebx-array of char
mov eax,12
ret
align 4
_strlen:;ebx-array of char
clc
xor ecx,ecx
dec ecx
mov edi,ebx
xor al,al
repne scasb
not ecx
dec ecx
mov eax,ecx
ret
align 4
__strlen:;ebx-array of char
xor eax,eax
dec eax
@@:inc eax
cmp byte[ebx+eax],0
jne @b
ret
start:
invoke GetStdHandle,STD_INPUT_HANDLE
mov [handle_input],eax
invoke GetStdHandle,STD_OUTPUT_HANDLE
mov [handle_output],eax
mov ebp,array_procs
next_step:
call [GetTickCount]
mov [lead_time],eax
xor ecx,
@@:push ecx
mov ebx,string
call dword[ebp]
pop ecx
loop @b
push eax
call [GetTickCount]
sub eax,[lead_time]
mov ecx,1000
xor edx,edx
div ecx
push edx
call2 putdword,[handle_output],eax
invoke WriteFile,ebx,string+8,1,byte_read_write,0
pop ecx
call2 putdword,[handle_output],ecx
invoke WriteFile,ebx,string+11,1,byte_read_write,0
pop ecx
call2 putdword,[handle_output],ecx
invoke WriteFile,[handle_output],string+12,2,byte_read_write,0
add ebp,4
cmp dword[ebp],0
jne next_step
call [GetTickCount]
mov [lead_time],eax
invoke SetConsoleMode,[handle_input],0
invoke ReadFile,[handle_input],byte_read_write,1,byte_read_write,0
invoke ExitProcess,0
.end start
Поговнокодим однако.
Зачем в процессоре занимают место команды типа repne scasb и прочее, если простые аналоги быстрее компактнее и проще встраивать в алгоритм без отдельной подпрограммы да и регистров в разы меньше требуется. Пустая подпрограмма для понимания сколько времени занимает лишний код. Есть предположение что раньше на заре развития они работали шустрее, но это только предположение.