- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
function display(id:number, name:string)
{
print("Id = " + id + ", Name = " + name);
}
function main() {
display(1, "asd");
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
function display(id:number, name:string)
{
print("Id = " + id + ", Name = " + name);
}
function main() {
display(1, "asd");
}
А ваш говно компайлер умеет так делать?
>> Output:
Id = 1., Name = asd
0
template<typename T>
struct method_traits;
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...)> {
using this_type = T;
using ret_type = RetT;
template<size_t ArgIdx>
using arg_type = typename std::tuple_element<ArgIdx, std::tuple<Args...>>::type;
static constexpr size_t args_count = sizeof...(Args);
static constexpr bool is_const = false;
static constexpr bool is_lvalue = false;
static constexpr bool is_rvalue = false;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) const> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_const = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) &> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_lvalue = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) &&> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_rvalue = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) const &> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_const = true;
static constexpr bool is_lvalue = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) const &&> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_const = true;
static constexpr bool is_rvalue = true;
};
А вдруг в новом стандарте ещё модификаторов в тип завезут? Страшня стало...
0
// https://habr.com/ru/company/yandex_praktikum/blog/555704/
// Стандарт C++20: обзор новых возможностей C++. Часть 2 «Операция ''Космический Корабль''»
// Предположим, вы определили структуру, содержащую одно число:
struct X {
int a;
};
// Мы хотим сделать так, чтобы значения этой структуры можно было сравнивать друг с другом.
// Для этого придётся написать шесть операций:
bool operator== (X l, X r) { return l.a == r.a; }
bool operator!= (X l, X r) { return l.a != r.a; }
bool operator>= (X l, X r) { return l.a >= r.a; }
bool operator<= (X l, X r) { return l.a <= r.a; }
bool operator< (X l, X r) { return l.a < r.a; }
bool operator> (X l, X r) { return l.a > r.a; }
// А теперь представьте, что мы хотим сравнивать элементы этой структуры не только между собой,
// но также с числами int. Количество операций возрастает с шести до 18:
bool operator== (X l, int r) { return l.a == r; }
bool operator!= (X l, int r) { return l.a != r; }
bool operator>= (X l, int r) { return l.a >= r; }
bool operator<= (X l, int r) { return l.a <= r; }
bool operator< (X l, int r) { return l.a < r; }
bool operator> (X l, int r) { return l.a > r; }
bool operator== (int l, X r) { return l == r.a; }
bool operator!= (int l, X r) { return l != r.a; }
bool operator>= (int l, X r) { return l >= r.a; }
bool operator<= (int l, X r) { return l <= r.a; }
bool operator< (int l, X r) { return l < r.a; }
bool operator> (int l, X r) { return l > r.a; }
// Что делать? Можно позвать штурмовиков. Их много, и они быстро напишут 18 операций.
// Или воспользоваться «космическим кораблём». Эту новую операцию в C++ называют
// «космический корабль», потому что она на него похожа: <=>. Более формальное название
// «трёхстороннее сравнение» фигурирует в документах Стандарта.
А можно добавить гомоиконность, которой можно наметушить не только какой-то там космический корабль (ради которого в крестокомпиляторах надо синтаксический анализатор менять, чтоб добавить новое синтаксиальное говно для этого <=>), а хоть целую, блядь, эскадрилью космических кораблей, которая работает не только для "больше меньше равно", но и для любой вообразимой поебени
Но крестушкам конечно привычней добавить какой-то ad-hoc хуиты для частных случаев.
+1
// Define the module
define(function(require) {
// Require empty list error
var EmptyListError = require('../errors/property_errors').EmptyListError;
// Character-rank list class
function WeightedList(/* ...keys */) {
this._total = 0;
this._generateList.apply(this, arguments);
}
WeightedList.prototype._generateList = function() {
var collection;
if (typeof arguments[0] == 'object') {
collection = arguments[0];
} else {
collection = arguments;
}
for (var i = 0; i < collection.length; i++) {
this[collection[i]] = this[collection[i]] === undefined ? 1 : this[collection[i]] + 1;
this._total++;
}
}
WeightedList.prototype.getRandomKey = function() {
if (this._total < 1)
throw new EmptyListError();
var num = Math.random();
var lowerBound = 0;
var keys = Object.keys(this);
for (var i = 0; i < keys.length; i++) {
if (keys[i] != "_total") {
if (num < lowerBound + this[keys[i]] / this._total) {
return keys[i];
}
lowerBound += this[keys[i]] / this._total;
}
}
return keys[keys.length - 1];
};
WeightedList.prototype.increaseRank = function(key) {
if (key !== undefined && key != "_total") {
if (this[key] !== undefined) {
this[key]++;
} else {
this[key] = 1;
}
this._total++;
}
};
WeightedList.prototype.clearRanks = function() {
var keys = Object.keys(this);
for (var i = 0; i < keys.length; i++) {
if (keys[i] != "_total") {
this._total -= this[keys[i]] - 1;
this[keys[i]] = 1;
}
}
};
return WeightedList;
});
Вот почему я за четкое разделение объектов/структур и хэшей (ассоциативных массивов).
+1
if req.Lang != "" {
req.Lang = "EN"
}
Я сказал английский!
[Поставленная задача: если пришёл запрос без поля, поставить значение по умолчанию]
0
// Since C++20
struct A {
int&& r;
};
A a1{7}; // OK, lifetime is extended
A a2(7); // well-formed, but dangling reference
Удачной отладки!
0
//glsl vertex shader
attribute float mass;
uniform vec3 center;
#define RAD 10.0
const float D = RAD * 2.0;
///////////////////THIS///////////////////
float repeat(float x, float z) {
float dx = distance(x, z);
while(dx > RAD) {
if (x > z) {
x -= D;
} else {
x += D;
}
dx = distance(x, z);
}
return x;
}
///////////////////////////////////////////
vec3 repeat(vec3 x, vec3 y) {
return vec3(dr(x.x, y.x), dr(x.y, y.y), dr(x.z, y.z));
}
void main() {
vec3 pos = position;
pos.z += time;
pos = repeat(pos, center);
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
gl_PointSize = 70.0 * mass;
gl_Position = projectionMatrix * mvPosition;
}
По сути функция repeat должна повторять текстуру (как background-repeat: repeat в css) в зависимости от положения точки центра, короче: двигается центр, двигается и текстура за ним. Мне даже ума не хватает описать это, поэтому формулу сам искал, хватило ума только на это говно. Спустя несколько недель додумался до следующего говна, уже без цикла:
float repeat(float x, float z) {
float mp = x > z ? -1.0 : 1.0;
z += RAD * mp;
float dx = distance(x, z);
float n = floor(dx / D) * D;
x += n*mp;
return x;
}
Тяжело не знать математики. Может местные шизы подскажут как называется такое поведение и как нормальную формулу?
0
function test3()
{
const a = 10.5
switch (a)
{
case 10.5:
print("cool. 10.5");
break;
}
}
function test3()
{
switch ("kokoko")
{
case "kokoko":
print("pituh");
break;
}
}
Продолжаем говнокомпилить...
А ваш С такое прокомпилирует? мой - запросто :)
0
template<typename T>
class SharedPtr {
T* value;
int* ref_count;
public:
SharedPtr(T* value) : value(value) {
ref_count = new int;
*ref_count = 1;
}
SharedPtr(const SharedPtr& other) {
value = other.value;
ref_count = other.ref_count;
(*ref_count)++;
}
SharedPtr(SharedPtr&& other) {
value = other.value;
ref_count = other.ref_count;
other.ref_count = nullptr;
}
~SharedPtr() {
if (ref_count == nullptr) {
return;
}
if (*ref_count == 1) {
delete value;
delete ref_count;
} else {
(*ref_count)--;
}
}
T& operator *() const {
return *value;
}
T* operator ->() const {
return value;
}
};
Реалейзовал минимальную версию shared_ptr. Есть ошибки/замечания?
https://ideone.com/g7gqBM
0
class MediaWiki {
// Поля, другие методы
private function performRequest() {
global $wgTitle;
$request = $this->context->getRequest();
$requestTitle = $title = $this->context->getTitle();
$output = $this->context->getOutput();
$user = $this->context->getUser();
if ( $request->getVal( 'printable' ) === 'yes' ) {
$output->setPrintable();
}
$this->getHookRunner()->onBeforeInitialize( $title, null, $output, $user, $request, $this );
// Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
|| $title->isSpecial( 'Badtitle' )
) {
$this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
try {
$this->parseTitle();
} catch ( MalformedTitleException $ex ) {
throw new BadTitleError( $ex );
}
throw new BadTitleError();
}
// Check user's permissions to read this page.
// We have to check here to catch special pages etc.
// We will check again in Article::view().
$permissionStatus = PermissionStatus::newEmpty();
if ( !$this->context->getAuthority()->authorizeRead( 'read', $title, $permissionStatus ) ) {
// T34276: allowing the skin to generate output with $wgTitle or
// $this->context->title set to the input title would allow anonymous users to
// determine whether a page exists, potentially leaking private data. In fact, the
// curid and oldid request parameters would allow page titles to be enumerated even
// when they are not guessable. So we reset the title to Special:Badtitle before the
// permissions error is displayed.
// The skin mostly uses $this->context->getTitle() these days, but some extensions
// still use $wgTitle.
$badTitle = SpecialPage::getTitleFor( 'Badtitle' );
$this->context->setTitle( $badTitle );
$wgTitle = $badTitle;
throw new PermissionsError( 'read', $permissionStatus );
}
// Еще какая-то логика для хандлинга редиректов по заголовкам страниц
}
// ...
}
// ...
class MessageCache implements LoggerAwareInterface {
// ...
public function parse( $text, $title = null, $linestart = true,
$interface = false, $language = null
) {
global $wgTitle;
if ( $this->mInParser ) {
return htmlspecialchars( $text );
}
$parser = $this->getParser();
$popts = $this->getParserOptions();
$popts->setInterfaceMessage( $interface );
if ( is_string( $language ) ) {
$language = $this->langFactory->getLanguage( $language );
}
$popts->setTargetLanguage( $language );
if ( !$title || !$title instanceof Title ) {
$logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
$logger->info(
__METHOD__ . ' called with no title set.',
[ 'exception' => new Exception ]
);
$title = $wgTitle;
}
// Sometimes $wgTitle isn't set either...
if ( !$title ) {
# It's not uncommon having a null $wgTitle in scripts. See r80898
# Create a ghost title in such case
$title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
}
$this->mInParser = true;
$res = $parser->parse( $text, $title, $popts, $linestart );
$this->mInParser = false;
return $res;
} // ...
}
Зачем в методах класса вообще использовать глобальные изменяемые состояния, если это нарушает принцип инкапсуляции (для обеспечения чего и была введена абстракция класса в языки)? И сидишь гадаешь, при вызове какого метода у какого объекта у тебя слетела верстка, контент и пр. Это усложняет написание безопасных расширений для системы.