- 1
%words = map { $_ => $hash{$_} } grep { !proper($_) } keys %words;
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−155.2
%words = map { $_ => $hash{$_} } grep { !proper($_) } keys %words;
Фильтрация хэша - удаление элементов, чьи ключи не удовлетворяют некому условию.
Конечно же использование православного for для Perl-истов ниже собственного достоинства.... :X
+72.9
public class CountUnique {
//here objects will be stored
private Object[] variants;
//temporaly array to store copying variants
private Object[] temparr;
private int total = 0;
public CountUnique() {}
public boolean test(Object obj) {
total++;
boolean hasSame = false;
if(variants == null) {
variants = new Object[1];
variants[0] = obj;
hasSame = false;
} else {
for(int i = 0; i < variants.length; i++) {
if(variants[i] == null) {} else {
if(variants[i].equals(obj)) {
hasSame = true;
break;
}
}
}
if(hasSame == false) {
temparr = variants;
variants = new Object[temparr.length+1];
for(int i = 0; i < temparr.length; i++) {
variants[i] = temparr[i];
}
variants[temparr.length] = obj;
temparr = null;
}
}
return hasSame;
}
public int unique() {
if(variants == null) {
return 0;
} else return variants.length;
}
public int total() {
return total;
}
public void free() {
variants = null;
temparr = null;
}
}
некий класс для подсчета уникальных обьектов.
особенно умиляет функция test()
+159.3
var res_html = "";
for (var i = 0; i < title_section.length; i++)
{
if (title_section[i].id == sel) {
res_html += '<div class="'+prefix+'section_title" onmouseover="section_sel(this,\''+ prefix +'\')" onmouseout="section_unsel(this,\''+ prefix +'\')"' +
'onclick="section_choise(this,'+'\''+url+'\'' + ')"' +
'id='+'"'+title_section[i].id+'" '
+'style='+'"font-weight: bold"'+'>'+
'<span class="'+ prefix +'dashed_anchor">' + title_section[i].name + '</span> ';
// res_html += '(' + number_section[i] + ')';
res_html += '</div>';
}
else{
res_html += '<div class="'+prefix+'section_title" onmouseover="section_sel(this,\''+ prefix +'\')" onmouseout="section_unsel(this,\''+ prefix +'\')"' +
'onclick="section_choise(this,'+'\''+url+'\'' + ')"' +
'id='+'"'+title_section[i].id+'" '
+'>'+
'<span class="'+ prefix +'dashed_anchor">' + title_section[i].name + '</span> ';
// res_html += '(' + number_section[i] + ')';
res_html += '</div>';
}
}
document.getElementById(prefix + "sections").innerHTML += res_html;
document.getElementById(prefix + "sections").innerHTML += '<a href='+'"?id=all"'+'><div class="'+prefix+'all_sections"><img src="media/img/01/arrow.jpg" alt=""/>' +
'<span style="color:black">Все разделы</span> </div></a>';
document.getElementById(prefix + "column_sections").style.width = (max_length + 7) + "ex";
/* document.getElementById(prefix + "green_sector").style.height = (document.getElementById(prefix + "column_other").offsetHeight - 14) + "px";*/
}
Яваскрипт от местного умельца:)
+133.3
<target name="test-boolean">
<condition property="if-true" value="true" else="false">
<!--
Попробуйте попереключайте true / false
и посмотрите на результат - вам однозначно понравится :)
-->
<istrue value="false"/>
</condition>
<antcall target="test-boolean-true"/>
<antcall target="test-boolean-false"/>
</target>
<target name="test-boolean-true" if="if-true">
<echo>The condition evaluates to "true"</echo>
</target>
<target name="test-boolean-false" unless="if-true">
<echo>The condition evaluates to "false"</echo>
</target>
Язык - Ant, для тех, кто не в курсе. Я думаю, можно спокойно зачислить в говноязыки.
+160.6
// всё ещё Wakaba Extension http://userscripts.org/scripts/review/23705
function optionValue(optionName)
{
var optionsString = (doOptionsPanel) ? get_cookie('wkExtOptions') : '';
if (optionsString == '')
{
switch (optionName)
{
case 'doQuickReply':
return doQuickReply;
break;
case 'doThreadExpansion':
return doThreadExpansion;
break;
case 'doPostExpansion':
return doPostExpansion;
break;
/*... еще 12 условий ... */
default:
return 0;
}
}
else
{
var optionsArray = optionsString.split(/,/);
switch (optionName)
{
case 'doQuickReply':
return parseInt(optionsArray[0]); // parseInt ensures that 0 is handled as an integer. lol, weak types
break;
case 'doThreadExpansion':
return parseInt(optionsArray[1]);
break;
case 'doPostExpansion':
return parseInt(optionsArray[2]);
break;
/*... еще 12 условий ... */
default:
return 0;
}
}
}
Естественно, я бы сделал это хэшами.
Но кому-то код, что выше понятнее...
function optionValue(optionName)
{
var optionsString = (doOptionsPanel) ? get_cookie('wkExtOptions') : '';
if(!optionsString){
return options[optionName]; // не установлена опция - возвращается undefined
}else{
return defaultOptions[optionName];
}
}
+112.1
public IEnumerator GetEnumerator()
{
for (int CurID = 0; CurID < (controls.Count + animations.Count) / 2; CurID++)
{
KeyValuePair<Control, Animation> kvp = new KeyValuePair<Control, Animation>(controls[CurID], animations[CurID]);
yield return kvp;
}
}
Писал я код, и задумался. А когда очнулся - уже было это.
ЗЫ. controls.Count == animations.Count
+75
import java.util.*;
public class Shell {
Shell(){
main();
}
private void main(){
boolean flag=true;
String c;
while(flag){
c=Kernel.stdin("#");
String out=exec(c);
Kernel.stdout(out);
}
}
public static String exec(String cmd){
String tmp="";
Lib_parse.line(cmd," ");
String c=Lib_parse.get(0).toLowerCase();
if(c=="help"){
tmp.concat("uname - get the OC version \n");
tmp.concat("echo - echo input phraze \n");
}
if(c=="uname"){
tmp.concat("L2ME Kernel v1.3 - Linux 2 Java ME (c) new_user \n");
}
if(c=="echo"){
tmp.concat(cmd.substring(4,cmd.length()-1)+"\n");
}
return tmp;
}
}
Правда мило? :)
+94.1
unit uboot;
procedure boot;
begin
delay(100);
output_buffer:='Uboot v0.1'+chr(10)+'Status: ...Ready!';
uboot_shell;
end;
procedure uboot_shell;
begin
showForm;
removeCommand(enter_cmd);
input_buffer_num:=formAddString(output_buffer);
enter_cmd:=createCommand('ok', CM_ITEM, 1);
input_buffer_num:=formAddTextField('boot >>', '', 256, TF_ANY);
addCommand(enter_cmd);
repaint;
repeat
delay(100);
until getClickedCommand=enter_cmd;
uboot_parse;
end;
procedure uboot_parse;
//Получаем буфер ввода в нижнем регестре
input_buffer:=locase(formGetText(input_buffer_num));
if input_buffer='shutdown' then shutdown;
else if input_buffer='help' then output_buffer:='shutdown, help, boot, clear';
else if input_buffer='boot' then os_boot;
else if input_buffer='clear' then clear;
else output_buffer:='Unsupported command';
uboot_shell;
end;
procedure shutdown;
begin
clearForm;
halt;
end;
procedure clear;
begin
clearForm;
output_buffer:='';
delay(100);
uboot_shell;
end;
procedure os_boot;
begin
input_buffer:='';
output_buffer:='';
clearForm;
kernel.kernel_start('');
+176.5
e=0.55;
c=e.toString().split('.')[0];
k=e.toString().split('.')[1].substr(0, 1);
r=parseInt(c);
if (k > 4) r=r+1;
Округление числа старинным индусским способом
−184.5
override public function toString():String
{
return Object(container).toString() + "." + super.toString();
}
Еще одно украшение Флексового фреймворка: mx.core::Repeater.
Для тех, кто не в курсе: toString() вызываетйса автоматически когда мы пытаемся вывести информацию об объекте в консоль. (Т.е. жизненно необходим для тестирования). Свойство container у репитера радко, но может буть null, но изза того, что флексовые разработчики не категорически никогда не кастуют ничего, то это должно было бы выкинуть исключение, но, конвертация используемая в примере (вместо каста) в силу особенностей языка вместо того чтобы просто умереть с исключением создаст новый динамический объект, врезультате получим что-то типа:
"[Object object].имяКомпонента".
т.е. на самом деле код должен был выглядеть примерно так:
return (this.container ? this.container.toString() + "." : "") + super.toString();