- 1
def neg(x): return int(bin(x)[2:].rjust(8, '0').replace('1','x').replace('0','1').replace('x','0'), 2)
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
Всего: 334
0
def neg(x): return int(bin(x)[2:].rjust(8, '0').replace('1','x').replace('0','1').replace('x','0'), 2)
Операция "NEG"
+1
/* Python:
def A004086(n):
return int(str(n)[::-1])
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int A004086(int n) {
char str[12]; // Enough to hold the string representation of an int
sprintf(str, "%d", n);
int len = strlen(str);
char reversed[12];
for (int i = 0; i < len; i++) {
reversed[i] = str[len - 1 - i];
}
reversed[len] = '\0'; // Null-terminate the string
return atoi(reversed);
}
Результат переписывание с "Python" на "C". A004086 это последовательность из OEIS https://oeis.org/A004086
0
// https://github.com/micropython/micropython/blob/1b89c503db690967d50699abe0bfa942f6f6b15e/ports/qemu/mcu/rv32/interrupts.c#L131
const char *lookup_cause(uint32_t mcause) {
if (mcause & 0x80000000) {
switch (mcause & 0x7FFFFFFF) {
case 1:
return exception_causes[1];
case 3:
return exception_causes[2];
case 5:
return exception_causes[3];
case 7:
return exception_causes[4];
case 9:
return exception_causes[5];
case 11:
return exception_causes[6];
default:
return (mcause >= 16) ?
exception_causes[7] :
exception_causes[0];
}
}
switch (mcause) {
case 0:
return exception_causes[8];
case 1:
return exception_causes[9];
case 2:
return exception_causes[10];
case 3:
return exception_causes[11];
case 4:
return exception_causes[12];
case 5:
return exception_causes[13];
case 6:
return exception_causes[14];
case 7:
return exception_causes[15];
case 8:
return exception_causes[16];
case 9:
return exception_causes[17];
case 11:
return exception_causes[18];
case 12:
return exception_causes[19];
case 13:
return exception_causes[20];
case 15:
return exception_causes[21];
default: {
if ((mcause >= 24 && mcause <= 31) ||
(mcause >= 48 && mcause <= 63)) {
return exception_causes[22];
}
return exception_causes[0];
}
}
}
Микропитухон
0
import std.stdio;
import std.conv;
bool[128][128] a;
int pow2(int x) { return x * x; }
string GenPw(string x, string y, string r)
{
return "pow2("~r~") > pow2("~x~") + pow2("~y~")";
}
string GenPat(int x_sz, int y_sz, string x_str, string y_str, string r_str, string pat)
{
string GenCond = "(";
foreach (y; 0 .. y_sz)
foreach (x; 0 .. x_sz)
{
if(pat[(y) * x_sz + x] == '1')
{
if(GenCond == "(") GenCond ~= "\n ";
else GenCond ~= " && ";
GenCond ~= "("~GenPw(to!string(x)~"+("~x_str~")",to!string(y)~"+("~y_str~")",r_str)~")\n";
}
}
return GenCond ~ ")";
}
bool checkCoordNeihb(int x, int y, int r)
{
if (pow2(r) > pow2(x) + pow2(y))
{
/// Паттерн-матчинг, если
/// 111
/// 101
/// 111
/// то пиксель 0
if (
mixin
(
GenPat
(
3,3,
"x-1",
"y-1",
"r",
"111"~
"101"~
"111"))
)
return false;
return true;
}
return false;
}
void drawCircle(ref bool[128][128] a, int x, int y, int r)
{
foreach (iy; y - r .. y + r)
{
foreach (ix; x - r .. x + r)
{
if (checkCoordNeihb(ix - x, iy - y, r))
a[ix][iy] = true;
}
}
}
void main()
{
drawCircle(a, 24, 24, 15);
writeln("\n\n");
foreach (ix; 0 .. 128)
{
foreach (iy; 0 .. 128)
{
write(a[ix][iy] ? '1' : '0');
}
writeln();
}
}
Переписал на "D" https://govnokod.ru/27990#comment1183758
+1
// https://github.com/torvalds/linux/blob/b6dad5178ceaf23f369c3711062ce1f2afc33644/rust/alloc/alloc.rs#L376
pub const fn handle_alloc_error(layout: Layout) -> ! {
const fn ct_error(_: Layout) -> ! {
panic!("allocation failed");
}
fn rt_error(layout: Layout) -> ! {
unsafe {
__rust_alloc_error_handler(layout.size(), layout.align());
}
}
unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
}
// https://github.com/torvalds/linux/blob/b6dad5178ceaf23f369c3711062ce1f2afc33644/rust/kernel/lib.rs#L96-L103
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
pr_emerg!("{}\n", info);
// SAFETY: FFI call.
unsafe { bindings::BUG() };
// Bindgen currently does not recognize `__noreturn` so `BUG` returns `()`
// instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
loop {}
}
// https://github.com/torvalds/linux/blob/master/include/asm-generic/bug.h#L51-L68
/*
* Don't use BUG() or BUG_ON() unless there's really no way out; one
* example might be detecting data structure corruption in the middle
* of an operation that can't be backed out of. If the (sub)system
* can somehow continue operating, perhaps with reduced functionality,
* it's probably not BUG-worthy.
*
* If you're tempted to BUG(), think again: is completely giving up
* really the *only* solution? There are usually better options, where
* users don't need to reboot ASAP and can mostly shut down cleanly.
*/
#ifndef HAVE_ARCH_BUG
#define BUG() do { \
printk("BUG: failure at %s:%d/%s()!\n", __FILE__, __LINE__, __func__); \
barrier_before_unreachable(); \
panic("BUG!"); \
} while (0)
#endif
О том, как в ядре Linux говнораст обрабатывает ошибку аллокации
0
// https://github.com/flipperdevices/flipperzero-firmware/blob/2a6a3a1bf7ba1ecb42b8cbfc1b1856a54f2878b7/applications/plugins/music_player/music_player.c#L74
static bool is_white_note(uint8_t semitone, uint8_t id) {
switch(semitone) {
case 0:
if(id == 0) return true;
break;
case 2:
if(id == 1) return true;
break;
case 4:
if(id == 2) return true;
break;
case 5:
if(id == 3) return true;
break;
case 7:
if(id == 4) return true;
break;
case 9:
if(id == 5) return true;
break;
case 11:
if(id == 6) return true;
break;
default:
break;
}
return false;
}
static bool is_black_note(uint8_t semitone, uint8_t id) {
switch(semitone) {
case 1:
if(id == 0) return true;
break;
case 3:
if(id == 1) return true;
break;
case 6:
if(id == 3) return true;
break;
case 8:
if(id == 4) return true;
break;
case 10:
if(id == 5) return true;
break;
default:
break;
}
return false;
}
Хуйня какая-то. То ли дело "паттерн матчинг".
+2
unsigned mul(unsigned a, unsigned b)
{
char arr[a][b];
return &arr[a][b] - (char *)arr;
}
Умножение через VLA
+1
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
void swap(uint8_t *x, uint8_t *y)
{
uint8_t tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
// эту хуйню тоже можно нагенерировать
uint64_t cmp_bits(uint8_t a[restrict 9])
{
return
((uint64_t)(a[0] < a[1]) << 0) |
((uint64_t)(a[0] < a[2]) << 1) |
((uint64_t)(a[0] < a[3]) << 2) |
((uint64_t)(a[0] < a[4]) << 3) |
((uint64_t)(a[0] < a[5]) << 4) |
((uint64_t)(a[0] < a[6]) << 5) |
((uint64_t)(a[0] < a[7]) << 6) |
((uint64_t)(a[0] < a[8]) << 7) |
((uint64_t)(a[1] < a[2]) << 8) |
((uint64_t)(a[1] < a[3]) << 9) |
((uint64_t)(a[1] < a[4]) << 10) |
((uint64_t)(a[1] < a[5]) << 11) |
((uint64_t)(a[1] < a[6]) << 12) |
((uint64_t)(a[1] < a[7]) << 13) |
((uint64_t)(a[1] < a[8]) << 14) |
((uint64_t)(a[2] < a[3]) << 15) |
((uint64_t)(a[2] < a[4]) << 16) |
((uint64_t)(a[2] < a[5]) << 17) |
((uint64_t)(a[2] < a[6]) << 18) |
((uint64_t)(a[2] < a[7]) << 19) |
((uint64_t)(a[2] < a[8]) << 20) |
((uint64_t)(a[3] < a[4]) << 21) |
((uint64_t)(a[3] < a[5]) << 22) |
((uint64_t)(a[3] < a[6]) << 23) |
((uint64_t)(a[3] < a[7]) << 24) |
((uint64_t)(a[3] < a[8]) << 25) |
((uint64_t)(a[4] < a[5]) << 26) |
((uint64_t)(a[4] < a[6]) << 27) |
((uint64_t)(a[4] < a[7]) << 28) |
((uint64_t)(a[4] < a[8]) << 29) |
((uint64_t)(a[5] < a[6]) << 30) |
((uint64_t)(a[5] < a[7]) << 31) |
((uint64_t)(a[5] < a[8]) << 32) |
((uint64_t)(a[6] < a[7]) << 33) |
((uint64_t)(a[6] < a[8]) << 34) |
((uint64_t)(a[7] < a[8]) << 35);
}
void printshit(uint8_t a[restrict 9])
{
size_t i = 0;
while(*a != 4)
{
a++;
i++;
}
printf("arr[%" PRIu64 "] = %zu\n", cmp_bits(a), i);
}
void permute(char *a, size_t l, size_t r)
{
size_t i;
if (l == r)
printshit(a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i));
}
}
}
int main()
{
uint8_t a[] = {0,1,2,3,4,5,6,7,8};
size_t n = 9;
permute(a, 0, n-1);
return 0;
}
https://govnokod.ru/24496#comment782476
Построение таблицы поиска для быстрого нахождения медианы. Там эту хуйню конечно можно улучшить, например запаковывать число от 0 до 8 в хуйни по 4 бита
0
// https://github.com/gcc-mirror/gcc/blob/ec03862f809e544a9b7d28067e51597dc92a0244/libstdc%2B%2B-v3/include/bits/forward_list.tcc#L391-L411
template<typename _Tp, typename _Alloc>
bool
operator==(const forward_list<_Tp, _Alloc>& __lx,
const forward_list<_Tp, _Alloc>& __ly)
{
// We don't have size() so we need to walk through both lists
// making sure both iterators are valid.
auto __ix = __lx.cbegin();
auto __iy = __ly.cbegin();
while (__ix != __lx.cend() && __iy != __ly.cend())
{
if (!(*__ix == *__iy))
return false;
++__ix;
++__iy;
}
if (__ix == __lx.cend() && __iy == __ly.cend())
return true;
else
return false;
}
из стандартной библиотеки крестоговна от GCC
0
// https://github.com/santiontanon/stransball2/blob/dff413c6ed236b4be23e0152557a26d7d902976c/sources/state_changepack.cpp#L67
bool state_changepack_cycle(SDL_Surface *screen,int sx,int sy,unsigned char *keyboard)
{
if (SUBSTATE==0) {
if (image!=0) SDL_FreeSurface(image);
image=IMG_Load("graphics/tittle.pcx");
{
levelpacks.Delete();
#ifdef _WIN32
/* Find files: */
WIN32_FIND_DATA finfo;
HANDLE h;
h=FindFirstFile("maps/*.lp",&finfo);
if (h!=INVALID_HANDLE_VALUE) {
char *tmp;
tmp=new char[strlen(finfo.cFileName)+1];
strcpy(tmp,finfo.cFileName);
levelpacks.Add(tmp);
while(FindNextFile(h,&finfo)==TRUE) {
char *tmp;
tmp=new char[strlen(finfo.cFileName)+1];
strcpy(tmp,finfo.cFileName);
levelpacks.Add(tmp);
} /* while */
} /* if */
#else
DIR *dp;
struct dirent *ep;
dp = opendir ("maps");
if (dp != NULL)
{
while (ep = readdir (dp))
{
char *tmp;
if (strlen(ep->d_name)>4 &&
ep->d_name[strlen(ep->d_name)-3]=='.' &&
ep->d_name[strlen(ep->d_name)-2]=='l' &&
ep->d_name[strlen(ep->d_name)-1]=='p') {
tmp=new char[strlen(ep->d_name)+1];
strcpy(tmp,ep->d_name);
levelpacks.Add(tmp);
} /* if */
}
(void) closedir (dp);
}
#endif
Super Transball 2 (супер трансшары 2)