- 1
assert(buf=malloc(BUF_SIZ));
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+108
assert(buf=malloc(BUF_SIZ));
А в релизе мы сэкономим памяти
+131
try
{
m = (int)Convert.ToInt32(num[1]);
}
catch
{
Console.WriteLine("Invalid parametr");
return true;
}
//...................................................
try
{
matrix[i, j] = (float)Convert.ToDouble(num[j]);
}
catch
{
Console.WriteLine("Invalid matrix");
return false;
}
Лаба одногруника...
+153
// Высота шрифта
$lenHdr = mb_strlen( strip_tags($header), 'UTF-8');
$maxDefaultStrLen = 38; // максимальное количество символов при заданном размере шрифта
$maxFontSize = 22; // заданный размер шрифта
$fontSize = $maxFontSize;
if ( $lenHdr > $maxDefaultStrLen ) {
$k = ceil(sqrt(($lenHdr - $maxDefaultStrLen) + 0.25) - 0.5) + 2 ;
$k = ($k<3)? 3:$k;
$fontSize = $maxFontSize - ($k - 2)*2;
$fontSize = ($fontSize<12)? 12:$fontSize;
}
Вот. Откопалось
+18
std::string MetaInfo::SetField() {
return m_value;
}
/* ... */
std::string value = meta.SetValue();
Йода-стайл. Переменную эту, хочешь установить ты.
+161
this.ShowHideNoticeDate = function () {
if ($("#associateNotice").is(':checked')) {
jsNoticeField.setFieldValue(1);
$("#associateNotice").parent().parent().parent().parent().parent().parent().next().show();
$("#associateNotice").parent().parent().parent().parent().parent().parent().next().children(1).children(0).children(0).children(0).children(0).children(0).children(1).val("");
} else {
jsNoticeField.setFieldValue(0);
$("#associateNotice").parent().parent().parent().parent().parent().parent().next().hide();
$("#associateNotice").parent().parent().parent().parent().parent().parent().next().children(1).children(0).children(0).children(0).children(0).children(0).children(1).val("");
}
};
Голландский джаваскриптик)))
+134
int t, max, x;
scanf("%d", &x);
for(t=x%10; max!=t; max=t);
for(t=x%100/10; max<t; max=t);
for(t=x%1000/100; max<t; max=t);
for(t=x/1000; max<t; max=t);
printf("Max: %d\n", max);
Нахождение максимальной цифры в 4-значном числе. Одна из первых лаб по Си. Предполагалось использование if, но студенты не ищут лёгких путей. (Сдвиги они пока не учили, так что на вычисление цифры не обращайте внимания.)
+68
public static AstRoot parse (String code) {
CompilerEnvirons env = new CompilerEnvirons();
env.setRecoverFromErrors(true);
env.setGenerateDebugInfo(true);
env.setRecordingComments(true);
// try to ignore errors - does not seem to work
env.setIdeMode(true);
IRFactory factory = new IRFactory(env);
AstRoot root = factory.parse(code, null, 0);
// work around rhino bug 800616 (not fixed in neither rhino nor closure)
root.visit(new NodeVisitor() {
@Override
public boolean visit(AstNode node) {
if (node instanceof NumberLiteral) {
NumberLiteral num = (NumberLiteral)node;
int from = num.getAbsolutePosition();
int to = from + num.getLength() + 2;
if (to < code.length()) {
String hex = "0x" + num.toSource();
if (code.substring(from, to).equals(hex)) {
// reset node value and length
num.setValue(hex); num.setLength(hex.length());
}
}
return false;
}
return true;
}
});
// work around rhino SwitchStatement.toSource() bug with empty switches
// https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ast/SwitchStatement.java#L96
// https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ast/SwitchStatement.java#L107-L109
// https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ast/SwitchStatement.java#L158
root.visit(new NodeVisitor() {
@Override
public boolean visit(AstNode node) {
if (node instanceof SwitchStatement) {
SwitchStatement ss = (SwitchStatement)node;
if (ss.getCases().isEmpty()) {
// need to add at least one node to make ss.cases non-null
ArrayList<SwitchCase> cases = new ArrayList<>();
cases.add(new SwitchCase());
ss.setCases(cases);
// set this back to empty list
cases.clear();
ss.setCases(cases);
}
return false;
}
return true;
}
});
return root;
}
И ещё немножко трудовыебуднев пользователей рино: правда клёво взять и распарсить джаваскрипт одним простым методом? Авотхуй.
+70
public static void replaceChild (AstNode parent, AstNode child, AstNode newChild) {
try {
parent.replaceChild(child, newChild)
} catch (NullPointerException e1) {
// this is one of those shitty nodes with default children handling broken
try {
// maybe it was assignment
Assignment ass = (Assignment)parent
if (ass.left == child) {
ass.left = newChild
} else {
ass.right = newChild
}
} catch (Throwable e2) {
// not assignment :S
try {
// maybe it's (...)
ParenthesizedExpression pae = (ParenthesizedExpression)parent
pae.expression = newChild
} catch (Throwable e3) {
// not (...) either :S
try {
// Function call?
FunctionCall fuc = (FunctionCall)parent
for (int i = 0; i < fuc.arguments.size(); i++) {
if (fuc.arguments.get(i) == child) {
fuc.arguments.set(i, newChild)
break;
}
}
} catch (Throwable e4) {
try {
// Expression statement?
ExpressionStatement est = (ExpressionStatement)parent
est.expression = newChild
} catch (Throwable e5) {
try {
// var foo = bar?
VariableInitializer vin = (VariableInitializer)parent
if (vin.initializer == child) {
vin.initializer = newChild
} else {
// should not happen in our useage
vin.target = newChild
}
} catch (Throwable e6) {
try {
// what if?
IfStatement ifs = (IfStatement)parent
if (ifs.condition == child) {
ifs.condition = newChild
} else if (ifs.thenPart == child) {
ifs.thenPart = newChild
} else {
ifs.elsePart = newChild
}
} catch (Throwable e7) {
try {
// while loop?
WhileLoop whl = (WhileLoop)parent
if (whl.condition == child) {
whl.condition = newChild
} else {
whl.body = newChild
}
} catch (Throwable e8) {
try {
// Infix expression?
InfixExpression iex = (InfixExpression)parent
if (iex.left == child) {
iex.left = newChild
} else {
iex.right = newChild
}
} catch (Throwable e9) {
try {
// do loop?
DoLoop dol = (DoLoop)parent
if (dol.condition == child) {
dol.condition = newChild
} else {
dol.body = newChild
}
} catch (Throwable e10) {
try {
// for loop?
ForLoop fol = (ForLoop)parent
if (fol.condition == child) {
fol.condition = newChild
} else if (fol.initializer == child) {
fol.initializer = newChild
} else if (fol.increment == child) {
fol.increment = newChild
} else {
fol.body = newChild
}
} catch (Throwable e11) {
try {
ConditionalExpression cex = (ConditionalExpression)parent
if (cex.testExpression == child) {
Есть такой жавоскриптопарсер рино. И есть в нём замечательный метод replaceChild, который заменяет в AstNode одного ребёнка другим. Вот только в большей части наследников AstNode он сломан нах.
(пс нету ; ибо груви)
−152
protected function get_resource_getter(xml:XML,name:String):Function {
try {
var getter:Function = this["get_"+name+"_xml"] as Function;
return function():int{ return getter(xml)};
} catch (e:*) {}
if(xml.attribute(name).length()==0){
return null;
}
return function():int{ return get_resource_xml(xml,name)};
}
Задача стояла предельно простая: получить количество некоторого игрового ресурса.
Автор подошел к решению неординарно.
+13
int offset;
/* где-то ниже */
if (offset <= NULL)
{
}
Антиматерия существует...