- 1
- 2
- 3
- 4
- 5
- 6
- 7
<? $dir = $APPLICATION->GetCurDir();
$slashCount = substr_count($dir, "/");
//убираем со страницы отдельной новости
if($slashCount<6){ ?>
...
}?>
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
<? $dir = $APPLICATION->GetCurDir();
$slashCount = substr_count($dir, "/");
//убираем со страницы отдельной новости
if($slashCount<6){ ?>
...
}?>
Какая наикрасивейшая проверка на количество слешей в урл.
Супер решение
+1
...
if(empty($text)){
$response = chr(0xF0) . chr(0x9F) . chr(0x98) . chr(0x95);
}
else{
$textLines = explode("\n", $text);
if(preg_match('/^\d+$/', $textLines[0])){
$response = $this->doneTaskAction(
(int) $textLines[0]
);
}
else{
$response = chr(0xF0) . chr(0x9F) . chr(0x98) . chr(0x95);
}
}
...
class dCommand extends doneCommand{
protected $name = 'd';
protected $description = 'Псевдоним команды /done';
protected $usage = '/d <task_id>';
}
https://habrahabr.ru/post/305462/
https://github.com/Bashka/taskbot
+1
public void testGetInactiveSessionIds() throws Exception {
Session inactive1 = createTestSession();
Session inactive2 = createTestSession();
Thread.sleep(1001);
Date timestamp = new Date();
Thread.sleep(1001);
List<String> inactiveSessions = sessionDAO.getSessionsWithLastAccessTimeBefore(timestamp);
assertEquals(2, inactiveSessions.size());
assertTrue(inactive1.getId().equals(inactiveSessions.get(0)) || inactive1.getId().equals(inactiveSessions.get(1)));
assertTrue(inactive2.getId().equals(inactiveSessions.get(0)) || inactive2.getId().equals(inactiveSessions.get(1)));
}
Юнит тест поиск неактивных сессий перед их закрытием. Тут прекрасны задержки на секунду и проверка что сессия содержится в списке inactive
+1
if ($can_null || $can_unnull) {
...
}
Когда удачно назвал переменную.
+1
header.php
<?$APPLICATION->IncludeComponent(
"lenal:lenal.menu",
"mobile",
array(
"VIEW_MODE" => "LINE",
"SHOW_PARENT_NAME" => "Y",
"IBLOCK_TYPE" => "catalog",
"IBLOCK_ID" => "39",
"SECTION_ID" => $_REQUEST["SECTION_ID"],
"SECTION_CODE" => "",
"SECTION_URL" => "",
"COUNT_ELEMENTS" => "N",
"TOP_DEPTH" => "1",
"SECTION_FIELDS" => array(
0 => "",
1 => "",
),
"SECTION_USER_FIELDS" => array(
0 => "UF_MOST_POPULAR",
1 => "",
),
"ADD_SECTIONS_CHAIN" => "Y",
"CACHE_TYPE" => "A",
"CACHE_TIME" => "36000000",
"CACHE_GROUPS" => "Y",
"COMPONENT_TEMPLATE" => "ds_main_menu",
"MAX_COUNT" => "12",
"MAX_ACTIONS" => "4",
"MAX_POPULAR" => "5"
),
false
);?>
/**************************************************************/
component.php
if(!isset($arParams["CACHE_TIME"]))
$arParams["CACHE_TIME"] = 36000000;
if($this->StartResultCache(false, ($arParams["CACHE_GROUPS"]==="N"? false: $USER->GetGroups())))
{
if(!\Bitrix\Main\Loader::includeModule("iblock"))
{
$this->AbortResultCache();
ShowError(GetMessage("IBLOCK_MODULE_NOT_INSTALLED"));
return;
}
/**************************************************************/
В параметрах стоит "SECTION_ID" => $_REQUEST["SECTION_ID"] и единственным условием сброса кеша ("CACHE_TIME" => "36000000") является отсутствие одного из основных модулей.
Результат: по 99 460 файлов кеша на каждый сайт. И это - простое МЕНЮ.
Производство компания Lenal, платформа 1С-Битрикс
+1
while (cycle) {
#if DEBUG == 1
mvprintw(0, 0, "cn: %i", cn);
mvprintw(all_lines + 7, 0, "max_line: %i\nMaxX: %i\nMaxY: %i", max_line, maxX, maxY);
#endif
if (active_input == 1)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 1)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (dlgcfg.keys > 1) {
mvprintw(i + 3 + title_fix, left_border_x + 2, " %s ", dlgcfg.f_button.c_str()); // Первая кнопка
} else {
mvprintw(i + 3 + title_fix, maxX / 2 - (dlgcfg.f_button.length() / 2) - 1, " %s ", dlgcfg.f_button.c_str()); // Центровка первой кнопки (Если она одна)
}
if (active_input != 1)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 1)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
if (dlgcfg.keys == 2) {
if (active_input == 2)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 2)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
mvprintw(i + 3 + title_fix, maxX / 2 + (max_line / 2) - dlgcfg.s_button.length() - 3 - fix, " %s ", dlgcfg.s_button.c_str()); // Вторая кнопка
if (active_input != 2)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 2)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
}
if (dlgcfg.keys == 3) {
if (active_input == 2)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 2)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
mvprintw(i + 3 + title_fix, s_key_pos - dlgcfg.s_button.length() / 2, " %s ", dlgcfg.s_button.c_str()); // Вторая кнопка
if (active_input != 2)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 2)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input == 3)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 3)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
mvprintw(i + 3 + title_fix, maxX / 2 + (max_line / 2) - dlgcfg.t_button.length() - 3 - fix, " %s ", dlgcfg.t_button.c_str()); // Вторая кнопка
if (active_input != 3)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 3)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
}
cn = getch();
switch (cn) {
case CtrlF1: info_win();
break;
case KEY_LEFT: if (active_input != 1)
active_input--;
break;
case KEY_RIGHT: if (active_input != dlgcfg.keys)
active_input++;
break;
case TAB_KEY: if (active_input != dlgcfg.keys) {
active_input++;
} else {
active_input = 1;
}
break;
case 27: delete [] array;
return 0;
break;
case '\n': if (active_input != 0) {
delete [] array;
return active_input;
}
break;
}
И ещё ~400 строк такой же дичи)
Даже если интерфейс кажется вам милым и опрятным, не распространяйте свои догадки на реализацию...
+1
public void notificationSuccess(String operation) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation " + operation + " success");
FacesMessage msg = null;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Notification", "Success");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void notificationError(Exception e, String operation) {
Logger.getLogger(this.getClass().getName()).log(Level.ERROR, "Operation " + operation + " Error ", e);
FacesMessage msg = null;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Notification", "Error");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
А не созавать ли мне новый экземпляр логгера при каждом уведомлении...
+1
$string_of_query = "select * from gisgmp.f_gisgmp_bills" . $tableName . "8mod(null, 1, UnknownValidUntil);
if ($ValidUntil == null)
$string_of_query = str_replace("UnknownValidUntil", "null", $string_of_query);
else
$string_of_query = str_replace("UnknownValidUntil", "'$ValidUntil'", $string_of_query);
+1
std::deque<std::pair<int, int>> Pathing::findPath(int sx, int sy, int fx, int fy) const
{
std::list<Node> openNodes;
std::list<Node> closeNodes;
const Node startNode{nullptr, sx, sy, 0, 0, 0};
openNodes.push_back(startNode);
auto cells = gameMap->getCells();
auto findNode = [](auto&& list, int x, int y)
{
return std::find_if(std::begin(std::forward<decltype(list)>(list)),
std::end(std::forward<decltype(list)>(list)),
[x, y](auto n) {return n.x == x && n.y == y;});
};
auto isNodeInList = [findNode](auto&& list, int x, int y)
{
return findNode(std::forward<decltype(list)>(list), x, y) != list.cend();
};
auto processNode = [&](auto iterCurrentNode, int x, int y)
{
const auto nx = iterCurrentNode->x + x;
const auto ny = iterCurrentNode->y + y;
if (cells[nx][ny].passable && !isNodeInList(closeNodes, nx, ny))
{
const auto G = iterCurrentNode->G + (x && y ? 14 : 10);
const auto H = (std::abs(fx - nx) + std::abs(fy - ny)) * 10;
const auto F = G + H;
auto node = findNode(openNodes, nx, ny);
if (node == openNodes.cend())
{
openNodes.push_back({&(*iterCurrentNode), nx, ny, G, H, F});
if (nx == fx && ny == fy)
return true;
}
else
{
if (G < node->G)
{
node->parent = &(*iterCurrentNode);
node->G = G;
node->H = H;
node->F = F;
}
}
}
return false;
};
while (!openNodes.empty())
{
auto iterMinF = std::min_element(openNodes.cbegin(), openNodes.cend(),
[](auto n1, auto n2) {return n1.F < n2.F;});
closeNodes.push_back(*iterMinF);
auto iter = closeNodes.insert(closeNodes.cend(), *iterMinF);
openNodes.erase(iterMinF);
if (processNode(iter, 1, 0) ||
processNode(iter, 1, 1) ||
processNode(iter, 0, 1) ||
processNode(iter, -1, 1) ||
processNode(iter, -1, 0) ||
processNode(iter, -1, -1) ||
processNode(iter, 0, -1) ||
processNode(iter, 1, -1))
break;
}
auto finalNode = findNode(openNodes, fx, fy);
if (finalNode == openNodes.cend())
return {};
std::deque<std::pair<int, int>> route{{finalNode->x, finalNode->y}};
const Node* temp = finalNode->parent;
while (temp)
{
route.push_front({temp->x, temp->y});
temp = temp->parent;
}
return route;
}
+1
auto getMaxSize = [](const auto &vec) {
if (vec.size() == 0)
return 0;
const auto &max = *std::max_element(
vec.begin(),
vec.end(),
[](const auto &lhs, const auto &rhs){
return lhs.size() < rhs.size();
});
return max.size();
};
Раньше я не понимал актуальность шутки:
In C++14, you just write auto auto(auto auto) { auto; } The compiler infers the rest from context