- 1
- 2
- 3
Автомобиль-русофоб
https://habr.com/ru/post/572984/
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
Автомобиль-русофоб
https://habr.com/ru/post/572984/
Я нашел статью про Насру (formerly Gologub).
0
// В одном файле
// Getting gif by url
const getGifUrl = (searchQuery, gifRating) => {
const fullUrl = `${giphyUrl}${giphyApiKey}&tag=${searchQuery}&rating=${gifRating}`;
let gifSource;
let girSourceOriginal;
fetch(fullUrl).then(response => {
return response.json();
}, networkError => {
console.log(networkError);
}).then(jsonResponse => {
if (!jsonResponse)
gifSource = '';
else {
gifSource = jsonResponse.data.images.preview_gif.url;
gifSoucreOriginal = jsonResponse.data.image_original_url;
}
renderGif(gifSource, gifSoucreOriginal);
});
};
// Где-то в другом файле
// incapsulating image
const incapsulateImage = (gifUrl, gifUrlOriginal) => {
// creating gif preview tile
const image = document.createElement('img');
image.src = gifUrl;
// create link to the original gif
const linkOriginal = document.createElement('a');
linkOriginal.href = gifUrlOriginal;
// incapsulating gif tile into link
linkOriginal.appendChild(image);
// create container-tile
const tile = document.createElement('div');
tile.className = "container-tile";
// incapsulating linked gif into tile
tile.appendChild(linkOriginal);
return tile;
}
// Rendering one gif image
const renderGif = (gifUrl, gifUrlOriginal) => {
if (gifUrl) {
const imageTile = incapsulateImage(gifUrl, gifUrlOriginal);
$gifContainer.append(imageTile);
} else if (!$gifContainer.html()) {
const notFoundHeading = document.createElement('h1');
notFoundHeading.innerHTML = NOT_FOUND_TEXT;
$gifContainer.append(notFoundHeading);
}
};
const render = () => {
// Rendering whole block of gifs
const renderContainer = (searchQuery, gifCount, gifRating) => {
for (let i = 0; i < gifCount; i++) {
getGifUrl(searchQuery, gifRating);
const heading = $gifContainer.find('h1');
if (heading && heading.text() == NOT_FOUND_TEXT) {
break;
}
}
}
// ...Сетап всяких обработчиков событий на элементы...
}
Когда толком не знал про промисы (а уж тем более про модули), городил такую дичь.
0
def generate_words(sample, phonemes, num=10):
global words, yd
gen = True
parens = 0
r = random.random()
word = ""
i = 0
while i < int(num):
for j in range(0, len(sample)):
if sample[j] == '(':
if gen:
gen = (random.randint(0,1) == 0)
if not gen:
parens += 1
elif sample[j] == ')':
if not gen:
parens -= 1
if parens == 0:
gen = True
elif sample[j] in phonemes.keys():
for n, phtype in enumerate(phonemes.keys()):
if gen and phtype == sample[j]:
#k = random.choice(phonemes[phtype])
n = yd.randomGen(phonemeRanks[phtype])
k = phonemes[phtype][n]
word += k
elif gen:
word += sample[j]
if (not word in words) and (not isExceptional(word)):
words.append(word)
i += 1
word = ""
# ...
"""parsing sound changes rule with the notation X>Y/Z, where X is a set of source phonemes
Y - a set of resulting phonemes, Z - a positional condition (optional)"""
def parsePhNotation(inline):
rule = inline.split('>')
if (not len(rule) == 2):
return []
source = rule[0].split(',')
final = rule[1].split('/')
result = final[0].split(',')
posCond = []
rule = []
if (len(final) > 2):
return False
elif (len(final) == 2):
posCond = final[1].split('_')
if (not len(posCond) == 2):
return []
posCond[0] = posCond[0].split('#')
posCond[1] = posCond[1].split('#')
if (len(posCond[0]) == 2) and len(posCond[0][0]) > 0:
return []
elif len(posCond[0]) == 2:
rule.append(" "+posCond[0][1])
else:
rule.append(posCond[0][0])
if (len(posCond[1]) == 2) and len(posCond[1][1]) > 0:
return []
rule.append(posCond[1][0])
if len(posCond[1]) == 2:
rule[1] += " "
rule[0] = rule[0].split(",")
rule[1] = rule[1].split(",")
final = []
if len(source) > len(result):
for i in range(len(result)-1, len(source)-1):
result.append("")
elif len(source) < len(result):
for i in range(len(source)-1, len(result)-1):
source.append("")
final.append(source)
final.append(result)
if (len(rule)>0):
final.append(rule)
return final
Рекурсивный спуск, автомат с магазинной памятью, top-down parsing, bottom-up parsing? Не, не слышал. В свое время время делал вот такие самопальные алгоритмы для рандомной генерации слов по фонетическим шаблонам (типа "CV(C)", "VC" и т.д.) и фонетического преобразования слов и при попытке починить чета наступал на новые баги, т.к. не до конца понимал как вообще парсятся компьютерные языки.
+1
$txtdd = $DI_Date;
$DI_Date = explode(".",$DI_Date);
$DI_YY = $DI_Date[2];
$DI_LYY = $DI_YY;
$DI_NYY = $DI_YY;
$MY = $DI_Date[1].".".$DI_Date[2];
$DI_MM = $DI_Date[1]-1;
$DI_LMM = $DI_MM-1;
if ($DI_LMM<0) $DI_LMM = 11;
$DI_NMM = $DI_MM+1;
if ($DI_NMM>11) $DI_NMM = 0;
if ($DI_MM==0) $DI_LYY = $DI_YY-1;
if ($DI_MM==11) $DI_NYY = $DI_YY+1;
$DI_DD = 1;
$lastM = $DI_MM;
$yy = $DI_YY;
if ($lastM<1) {
$lastM = 12+$lastM;
$yy = $yy - 1;
}
$lastM = $DI_DD.".".$lastM.".".$yy;
$nextM = $DI_MM+2;
$yy = $DI_YY;
if ($nextM>12) {
$nextM = $nextM-12;
$yy = $yy + 1;
}
$nextM = $DI_DD.".".$nextM.".".$yy;
$lastY = $DI_DD.".".($DI_MM+1).".".($DI_YY-1);
$nextY = $DI_DD.".".($DI_MM+1).".".($DI_YY+1);
0
let startMonth = Number(moment(payDate).startOf("month").format("DD"));
let endOfMonth = Number(moment(startMonth).endOf("month").format("DD"));
let dayOffMonth = (endOfMonth-startMonth +1)
Это так оказывается можно посчитать число дней в месяце
0
handleShowScheduler() {
console.log(this.$parent.$parent.$parent.showScheduler, 'sch')
if (this.$parent.$parent.$parent.showScheduler) {
this.$parent.$parent.$parent.showScheduler = false;
setTimeout(() => {
this.$parent.$parent.$parent.showScheduler = true;
}, 200)
} else {
this.$parent.$parent.$parent.showScheduler = true;
}
},
+1
https://core.telegram.org/constructor/passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow
Какой багор )))
0
Процедура ОбработкаПолученияПредставления(Данные, Представление, СтандартнаяОбработка)
СтандартнаяОбработка=Ложь;
Представление="";
Для Каждого Стр Из Данные.Ссылка.Состав Цикл
Представление=Представление+?(Представление="","",", ")+Стр.Автомобиль;
Если СтрДлина(Представление)>50 Тогда
Представление=Представление+"...";
Прервать
КонецЕсли;
КонецЦикла;
//Представление=""+Данные.Ссылка.Клиент+" ("+Представление+")";
КонецПроцедуры
А чё это списки у нас вдруг тормозить стали?
0
#include <stdio.h>
#include <csptr/smart_ptr.h>
#include <csptr/array.h>
void print_int(void *ptr, void *meta) {
(void) meta;
// ptr points to the current element
// meta points to the array metadata (global to the array), if any.
printf("%d\n", *(int*) ptr);
}
int main(void) {
// Destructors for array types are run on every element of the
// array before destruction.
smart int *ints = unique_ptr(int[5], {5, 4, 3, 2, 1}, print_int);
// ints == {5, 4, 3, 2, 1}
// Smart arrays are length-aware
for (size_t i = 0; i < array_length(ints); ++i) {
ints[i] = i + 1;
}
// ints == {1, 2, 3, 4, 5}
return 0;
}
Allocating a smart array and printing its contents before destruction.
C Smart Pointers
What this is
This project is an attempt to bring smart pointer constructs to the (GNU) C programming language.
Features: unique_ptr, shared_ptr macros, and smart type attribute
https://github.com/Snaipe/libcsptr
−1
updateTimer() {
requestAnimationFrame(() => {
this.timeLeft = this.resendTimeDuration - (Date.now() * 0.001 - this.lastTimeLeft);
if (this.timeLeft <= 0) {
this.resetTimer();
return;
} else {
this.lastTimeLeft = this.timeLeft;
this.updateTimer();
}
});
}
А как сделать таймер обратного отсчета?