- 1
http://open-life.org/blog/algorithm/1627.html
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+145
http://open-life.org/blog/algorithm/1627.html
Красивое наглядное видео алгоритмов сортировки.
Новичкам может быть полезно, да и просто эстетически приятно.
+162
if(!empty($arResult["Post"])>0)
Как вы думаете, что это? Правильно, Битрикс!
+134
if (!(string.IsNullOrEmpty("")))
...
+155
#include <iostream>
#include <memory>
#include <assert.h>
using namespace std;
template <class T>
class megaClass
{
public:
void hello()
{
assert(dynamic_cast<T*>(this)!=NULL);
static_cast<T*>(this)->hello();
}
virtual ~megaClass() {}
};
class cleft : public megaClass<cleft>
{
public:
void hello()
{
std::cout << "left::hello()" << std::endl;
}
};
class cright : public megaClass<cright>
{
public:
void hello()
{
std::cout << "right::hello()" << std::endl;
}
};
int main()
{
scoped_ptr<megaClass<cleft> > a1=new cleft;
a1->hello();
scoped_ptr<megaClass<cright> > a2=new cright;
a2->hello();
return 0;
}
Пытался продемонстрировать статический полиморфизм TarasB и получилась такая какашка. Кто действительно крут и может сабдж продемонстрировать? Я где-то видел пример, но не помню где...
Ещё продемонстрировал статический полиморфизм через стратегии:
struct Strategy1
{
static void do(){printf("Lol1");}
};
struct Strategy2
{
static void do(){printf("Lol2");}
};
template<class Strategy>
class MegaClass
{public:
void do()
{
printf("Mega");
Strategy::do();//Класс Strategy можно было и создать для хранения состояния.
printf("/n\");
}
};
//...
Дальше в разных частях кода создаем:
MegaClass<Strategy1> o;
o.do();
//...
MegaClass<Strategy2> o;
o.do();
"Один" класс ведёт себя по разному. Понятно, что это не совсем полиморфизм. Но очень часто именно в таком контексте используют динамический полиморфизм, хотя такого статического здесь достаточно выше крыши.http://govnokod.ru/8025#comment110773
Class1 o1;
foo(o1);
Class2 o2;
foo(o2);
void foo(Class1 o){/*...*/};
void foo(Class2 o){/*...*/};
+30
$files = file_scan_directory(dirname(__FILE__) .'/modes/', '^([^\.].*)\.inc$', array('.', '..', 'CVS'), 0, FALSE);
foreach ($files as $file) {
require_once($file->filename);
$mode = $file->name;
if (function_exists('advpoll_info_'. $mode)) {
$advpoll_modes[$mode] = call_user_func('advpoll_info_'. $mode);
}
}
+169
function echeck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
// var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID");
return false;
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID");
return false;
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID");
return false;
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID");
return false;
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID");
return false;
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID");
return false;
}
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID");
return false;
}
return true;
}
если честно, дочитал где-то только до 15 строки
+159
var resizeTimer,calWidth,$BlockPath,widthLeftPart,widthRightPart,count;
var $headBlock = $('div.hdr');
var $rightBlock = $('li.userFullName');
var $leftBlock = $('li.subMenu-title');
$(document).ready(resizeLabels);
$(window).resize(resizeLabels);
function doResizeLabels($typeBlock) {
count = 2;
resultWidth = 0;
if ($typeBlock==$leftBlock) {
$BlockPath=$('ul.subMenu li:not(.subMenu-title)');
} else {
$BlockPath=$('ul.usersLink li:not(.userFullName)');
};
$BlockPath.each(function() {
eachPosition = $(this).position();
eachWidth = $(this).width();
eachOuterWidth = $(this).outerWidth();
count++;
if ($typeBlock==$leftBlock) {
widthLeftPart = eachPosition.left + eachWidth;
widthPadding = eachOuterWidth - eachWidth;
} else {
if (count==3) widthPadding = eachPosition.left;
widthRightPart = widthRightPart + eachOuterWidth;
};
});
if ($typeBlock==$leftBlock) {
widthLeftPart = widthLeftPart + ((widthPadding / 2) * count);
resultWidth = headWidth/2 - widthLeftPart;
} else {
rightWidth = headWidth/2 - widthRightPart;
resultWidth = rightWidth-(headWidth/2-widthPadding/2)/2;
};
$typeBlock.width(resultWidth);
}
function resizeLabels() {
$leftBlock.width(0);
$rightBlock.width(0);
headWidth = $headBlock.width();
widthLeftPart = widthRightPart = 0;
headWidth = $headBlock.width();
doResizeLabels($leftBlock);
doResizeLabels($rightBlock);
};
+158
<?php
function bkconnect($login=FALSE,$update=FALSE){
function get_bk_inf($content){
if (strlen($content) > 0){
preg_match("#align=(.*)#i", $content, $returnarray['align']);
preg_match("#gamecity=(.*)#i", $content, $returnarray['gamecity']);
preg_match("#room_name=(.*)#i", $content, $returnarray['room_name']);
preg_match("#gamecity_url=(.*)#i", $content, $returnarray['gamecity_url']);
preg_match("#level=(.*)#i", $content, $returnarray['level']);
preg_match("#klan=(.*)#i", $content, $returnarray['klan']);
preg_match("#login_online=(.*)#i", $content, $returnarray['login_online']);
foreach($returnarray as $array_name => $array_data){
$returnarray[$array_name] = $returnarray[$array_name][1];
}
}
return $returnarray;
}
function bklogin($login){
$tmp=rawurlencode(trim(strip_tags($login)));
$url="http://sandcity.combats.com/inf.pl?login=".$tmp."&short=1";
$response=get_headers($url,1);
if (strpos($response[0],'302'))
{$url=str_replace(" ","%20",$login);
return file_get_contents($url);}
elseif (strpos($response[0],'200'))
{return file_get_contents($url);}
else {return"";}
return file_get_contents($url);
}
if($update==TRUE){
$myrow = mysql_query("select id,bk_login FROM black_list");
if(mysql_num_rows($myrow)){
while($result = mysql_fetch_array($myrow)){
$contents = bklogin($login);
$info = get_bk_inf($contents);
if(is_array($info)){
$sql="UPDATE `newblacklist` SET
align ='".$info['align']."',
gamecity ='".$info['gamecity']."',
room_name='".$info['room_name']."',
gamecity_url='".$info['gamecity_url']."',
level='".$info['level']."',
klan='".$info['klan']."',
login_online='".$info['login_online']."'
WHERE `id`='".$result['id']."'";
$myrow2 = mysql_query($sql);
}else{echo'error';}
}
}else{return;}
}else{
$contents = bklogin($login);
$info = get_bk_inf($contents);
if(is_array($info)){
return $info;}else{
return 'Чтото не так';}
}
}
function liginviev($inf){
function align($align){if($align>0){return '<img src="http://img.combats.com/i/align'.$align.'.gif" border="0px">';}else{return ' ';}}
function klan($klan){if(strlen($klan)>0){
return "<a href='http://capitalcity.combats.com/clans_inf.pl?".$klan."' target='_blank'>
<img src='http://img.combats.com/i/klan/".$klan.".gif' title='".$klan."'></a>";}else{
return ' ';}}
function room($rooms){if(strlen($rooms)>0){return $rooms;}else{return' ';}}
function online($online){
if($online==1){return'<img src="/i/user_online.gif" />';}else{return'<img src="/i/user_offline.gif" />';}
return $on;}
}
function Logs($id){
$myrow = mysql_query("SELECT * FROM newblacklistlogs WHERE blackId='".$id."'");
$crow['loc'] = mysql_num_rows($myrow);
if($crow['loc']>0){
while($result = mysql_fetch_array($myrow)){
$crow['logs'] .='<a href="'.$result['file'].'" target="_blank"><img src="/i/fighttype6.gif" /></a>';
}
return $crow=array('col'=>$crow['loc'],'logs'=>$crow['logs']);
}else{return $crow=array('col'=>$crow['loc'],'logs'=>' ');}
}
?>
Один ЧС для клан сайта игры combats.ru
+169
if(this->connectionState)
{
db_Model->clear();
db_Model->setTable("lh_chat_archive");
db_Model->setRelation(6, QSqlRelation("lh_profiles", "id", "last_name"));
db_Model->setEditStrategy(QSqlRelationalTableModel::OnManualSubmit);
db_Model->removeColumn(0);
db_Model->removeColumn(0);
db_Model->removeColumn(0);
db_Model->removeColumn(0);
db_Model->removeColumn(0);
db_Model->removeColumn(2);
db_Model->removeColumn(2);
db_Model->removeColumn(2);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->removeColumn(3);
db_Model->select();
db_Model->setHeaderData(0, Qt::Horizontal, trUtf8("Клиент"));
db_Model->setHeaderData(1, Qt::Horizontal, trUtf8("Менеджер"));
mapper->setModel(db_Model);
mapper->setItemDelegate(new QSqlRelationalDelegate(this));
}
Сотрудник фирмы таким образом избавился от ненужных столбцов в выборке. На вопрос: "А как быть если столбцов много?", ответа не последовало...
+146
<?php
function curl($url='', $post='') {
$cl = curl_init();
curl_setopt($cl, CURLOPT_URL, $url);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cl, CURLOPT_HEADER, 1);
curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1) Gecko/20090624 Firefox/3.5');
curl_setopt($cl, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($cl, CURLOPT_COOKIEFILE, 'cookie.txt');
if(!empty($post)) {
curl_setopt($cl, CURLOPT_POST, 1);
curl_setopt($cl, CURLOPT_POSTFIELDS, $post);
} else curl_setopt($cl, CURLOPT_POST, 0);
$ex = curl_exec($cl);
curl_close($cl);
return $ex;
}
$wall_id = 'wallxxx_xxx';
$hash = 'a2069bb43c20769e9';
curl('http://vkontakte.ru/login.php?act=login&q=&[email protected]&pass=xxx&captcha_sid=&captcha_key=');
echo curl('http://vkontakte.ru/like.php', "act=a_do_like&object={$wall_id}&hash={$hash}&wall=1");
?>
Ребят, сервер отдаёт: HTTP/1.1 302 Found Server: nginx/0.7.59 Date: Thu, 29 Sep 2011 18:42:58 GMT Content-Type: text/html; charset=windows-1251 ..., но почему то "лайк" не ставит.
В чём может быть проблема?