- 1
https://t.me/GovnokodBot
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
https://t.me/GovnokodBot
Напомню, или может кто не знал.
P.S. Кстати, guest8 достаточно раскрученный, поэтому здесь может быть ваша реклама.
0
function check_license()
{
$m = 40141;
$p = 291;
$root_dir = dirname(__FILE__);
$fn = 'file_get_contents';
$lic = ($root_dir.'/license');
$d = split(' ', trim(file_get_contents($lic)));
$result = 1;
$max = count($d);
for ($j=0x0; $j<$max; $j++)
{
$b=base_convert($d[$j],36,10);
$result = 1;
for($i=0x0; $i<$p; $i++)
{
$result = ($result*$b) % $m;
}
$decoded .= chr($result);
}
$license = split('#', $decoded);
$hash = $license[1];
$data = $license[0];
$host = $host1 = $_SERVER['HTTP_HOST'];
$host2 = getenv('HTTP_HOST');
if(function_exists('apache_getenv'))
$host3 = apache_getenv('HTTP_HOST');
else
$host3 = $host1;
if(!($host1 == $host2 && $host1 == $host3))
return false;
$ip = getenv('REMOTE_ADDR');
if($_SERVER['REMOTE_ADDR'] == $ip && substr($ip,0,3)=='127' && strtoupper(substr(php_uname(), 0, 3)) === 'WIN' )
{
return true;
}
$l_array = split(';', $data);
$domain = $l_array[0];
if(isset($l_array[1]))
$start = $l_array[1];
else
return false;
if(isset($l_array[2]))
$end = $l_array[2];
else
return false;
if(isset($l_array[3]))
$comment = $l_array[3];
else
$comment = '';
$domns = split(',', $domain);
$ok = false;
foreach($domns as $d)
{
if(strtolower(trim($d)) == strtolower($host))
$ok = true;
}
if(!$ok)
return false;
if(strtotime($start)>time())
return false;
if(strtotime($end)<time())
return false;
return true;
}
Проверка лицензии в Simpla CMS первой версии
0
$output = '<div class="catalog catalog-category">';
$query = db_select('taxonomy_term_data','td');
$query->innerJoin('field_data_field_category', 'fc', "fc.field_category_tid = td.tid");
$query->innerJoin('taxonomy_term_hierarchy', 'tth', "tth.tid = td.tid");
$query->innerJoin('node', 'n', "n.nid = fc.entity_id");
$query->condition('td.vid', 4);
$query->condition('n.status', 1);
$query->condition('tth.parent', 0);
$query->fields('td', array('tid', 'name'));
$query->groupBy('td.tid');
$query->orderBy('td.weight', 'ASC');
$terms = $query->execute()->fetchAll();
foreach ($terms as $term) {
$prod_out = '';
$query = db_select('field_data_field_product', 'fp');
// Выбираем товары текущего типа
$query->innerJoin('node', 'n', "n.nid = fp.entity_id");
$query->innerJoin('field_data_field_category', 'fc', "fc.entity_id = n.nid");
$query->condition('n.status', 1);
$query->condition('fc.field_category_tid', $term->tid);
// Заголовок товара
$query->innerJoin('commerce_product', 'cp', "cp.product_id = fp.field_product_product_id");
$query->condition('cp.status', 1);
$query->fields('cp', array('title'));
// Цена без скидки
$query->innerJoin('field_data_commerce_price', 'dcp', "dcp.entity_id = fp.field_product_product_id");
$query->fields('dcp', array('commerce_price_amount'));
// Размер скидки
$query->leftJoin('field_data_field_discount', 'dcpd', "dcpd.entity_id = fp.field_product_product_id");
$query->fields('dcpd', array('field_discount_value'));
// Цена со скидкой
$query->leftJoin('field_data_field_price_new', 'dcpn', "dcpn.entity_id = fp.field_product_product_id");
$query->fields('dcpn', array('field_price_new_value'));
// Первое изображение
$query->innerJoin('field_data_field_image', 'dfi', "dfi.entity_id = fp.field_product_product_id");
$query->condition('dfi.delta', 0);
$query->fields('dfi', array('field_image_fid'));
$query->innerJoin('field_data_field_weight', 'fw', "fw.entity_id = fp.field_product_product_id");
$query->addExpression("(SELECT GROUP_CONCAT(td.name SEPARATOR ', ') FROM field_data_field_season AS dfs INNER JOIN taxonomy_term_data AS td ON td.tid=dfs.field_season_tid WHERE dfs.entity_id=n.nid)","name");
// Маркер
$query->leftJoin('field_data_field_marker', 'dfm', "dfm.entity_id = fp.field_product_product_id");
$query->fields('dfm', array('field_marker_value'));
// Товар
$query->fields('fp', array('field_product_product_id'));
// Связанная с товаром нода
$query->fields('n', array('nid'));
$query->range(0, 4);
$query->orderBy('fw.field_weight_value', 'ASC');
$products = $query->execute()->fetchAll();
// $output .= '<h2>' . l($term->name, 'taxonomy/term/'.$term->tid) . '</h2>';
$output .= '<div class="product_items">';
$output .= '<div class="catalog_item"><div style="width: 225px; height: 340px;"><h2>' . l($term->name, 'taxonomy/term/'.$term->tid) . '</h2></div></div>';
foreach ($products as $product) {
$fid = $product->field_image_fid;
if ($fid != 0 && is_numeric($fid)) {
$file_picture = file_load($fid);
$imageUrl = image_style_url('catalog', $file_picture->uri);
$title = $product->title;
$photo = "<img class='lazy-image' data-src='{$imageUrl}' alt='{$title}' title='{$title}'>";
}
else $photo = '';
$prod_out .= '<div class="catalog_item">';
$prod_out .= '<div class="title">' . l($product->title . '<br><span>' . $product->name . '</span><div>XS S M L XL</div>', 'node/'.$product->nid, array('html' => TRUE, 'query' => array('id' => $product->field_product_product_id))).'</div>';
$prod_out .= '<div class="image">' . $photo . '</div>';
if (!empty($product->field_discount_value)) {
$prod_out .= '<div class="views-field-field-discount"><div class="field-content">Sale ' . $product->field_discount_value . ' %</div></div>';
}
if (!empty($product->field_marker_value)) {
$prod_out .= '<div class="views-field-field-marker"><div class="field-content field-content field-content-' . $product->field_marker_value . '">' . ($product->field_marker_value == 'new'?'Новинка':'Бестселлер') . '</div></div>';
}
if (!empty($product->field_price_new_value)) {
$price = '<s>' . number_format($product->commerce_price_amount/100,0,'',' ') . '</s> ' . number_format($product->field_price_new_value,0,'',' ') . ' Р';
}
else {
$price = number_format($product->commerce_price_amount/100,0,'',' ') . ' Р';
}
$prod_out .= '<div class="views-field-field-price-new">' . $price . '</div>';
$prod_out .= '</div>';
}
}
$output .= $prod_out;
$output .= '<div class="catalog_item" style="position: absolute;">' . l('<img src="/sites/all/themes/base/img/strelka.png" style="width: 10px; height: 17px;">', 'taxonomy/term/'.$term->tid, array('html' => true)) . '</div>';
$output .= '</div>';
Уууъъъъъ пыхомразь
+1
from vk_bot.vk_config import GROUP_ID, TOKEN
import vk_api
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import random
from vk_bot.db_session import *
from vk_bot.__all_models import BugReport, Comment
import datetime
from vk_bot.vacancies import get_vacancies, ServerError
def main():
global_init("feedback/feedback.sqlite")
vk_session = vk_api.VkApi(
token=TOKEN)
vk = vk_session.get_api()
longpoll = VkBotLongPoll(vk_session, GROUP_ID)
bot_state = {}
def send_msg(msg):
vk.messages.send(user_id=event.obj.message['from_id'],
message=msg,
random_id=random.randint(0, 2 ** 64))
for event in longpoll.listen():
if event.type == VkBotEventType.MESSAGE_NEW:
if event.obj.message['from_id'] in bot_state and bot_state[event.obj.message['from_id']]:
state = bot_state[event.obj.message['from_id']]
if state == 1:
send_msg('Спасибо, ваше мнение для нас очень важно.')
Comment().new(event.obj.message['from_id'], datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
event.obj.message['text'])
bot_state[event.obj.message['from_id']] = 0
elif state == 2:
BugReport().new(event.obj.message['from_id'], datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
event.obj.message['text'])
send_msg('Спасибо за ваш отзыв, мы постараемся исправить проблему в ближайшем будущем.')
bot_state[event.obj.message['from_id']] = 0
elif state == 4:
parameters = [r.strip() for r in event.obj.message['text'].split(',')]
try:
vacancies = get_vacancies(parameters[0], parameters[1])
except ServerError:
send_msg('Не удалось получить ответ от сервера, попробуйте позже')
bot_state[event.obj.message['from_id']] = 0
except Exception:
send_msg('Данные введены некорректно, попробуйте заново.')
send_msg('Формат: <должность>, <мин. зарплата>')
else:
if len(vacancies) == 0:
send_msg('По данным критериям ничего не найдено')
else:
vacancy_list = [f"{i}) {v['title']}, {v['salary']}" for i, v in enumerate(vacancies)]
send_msg('\n'.join(vacancy_list))
if bot_state[event.obj.message['from_id']] == 0:
send_msg('1 - написать отзыв или предложение\n 2 - сообщить о неправильной работе сайта\n 3 - документация к api\n 4 - посмотреть список доступных вакансий\n иначе напишите сообщение и модератор вскоре на него ответит')
elif event.obj.message['from_id'] not in bot_state:
send_msg('1 - написать отзыв или предложение\n 2 - сообщить о неправильной работе сайта\n 3 - документация к api\n 4 - посмотреть список доступных вакансий\n иначе напишите сообщение и модератор вскоре на него ответит')
bot_state[event.obj.message['from_id']] = 0
else:
key = event.obj.message['text'][0]
if key == '1':
send_msg('Пожалуйста, поделитесь вашим мнением по поводу сайта.')
bot_state[event.obj.message['from_id']] = 1
elif key == '2':
send_msg('Пожалуйста, максимально подробно опишите вашу проблему.')
bot_state[event.obj.message['from_id']] = 2
elif key == '3':
send_msg('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
elif key == '4':
send_msg('Введите название должности и минимальную желаемую зарплату по образцу:<должность>, <мин. зарплата>')
bot_state[event.obj.message['from_id']] = 4
else:
send_msg('Модератор вам скоро ответит, пожалуйста подождите.')
if __name__ == '__main__':
main()
Код бота поддержки.
Один из товарищей по проекту ничего в нем не делал,
а потом чтобы его не выгоняли попросил дать ему хотя бы бота.
Вот результат.
Модели и вспомогательные файлы оставлять думаю не имеет смысла, все и так очевидно
+1
template <class... Args>
void log(Args&&... args)
{
auto dummy = { (std::clog << args, 0)... };
std::clog << std::endl;
}
новый printf на с++
0
public enum MemoryProtection
{
PAGE_EXECUTE = 16, // 0x00000010
PAGE_EXECUTE_READ = 32, // 0x00000020
PAGE_EXECUTE_READWRITE = 64, // 0x00000040
PAGE_EXECUTE_WRITECOPY = 128, // 0x00000080
PAGE_NOACCESS = 1,
PAGE_READONLY = 2,
PAGE_READWRITE = 4,
PAGE_WRITECOPY = 8,
PAGE_TARGETS_INVALID = 1073741824, // 0x40000000
PAGE_TARGETS_NO_UPDATE = PAGE_TARGETS_INVALID, // 0x40000000
PAGE_GUARD = 256, // 0x00000100
PAGE_NOCACHE = 512, // 0x00000200
PAGE_WRITECOMBINE = 1024, // 0x00000400
}
На всякий случай.
0
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int field1;
int field2;
} teststr;
typedef struct {
char data[sizeof(teststr)];
} teststr_holder __attribute__ (( aligned (__alignof__ (teststr)) ));
typedef union {
teststr n1;
teststr_holder n2;
} str_conv;
int field1_get(teststr_holder a)
{
str_conv cnv = {.n2 = a};
return cnv.n1.field1;
}
int field2_get(teststr_holder a)
{
str_conv cnv = {.n2 = a};
return cnv.n1.field2;
}
teststr_holder init_teststr(int field1, int field2)
{
str_conv cnv = {.n1 = {field1, field2}};
return cnv.n2;
}
int main(void)
{
teststr_holder a = init_teststr(1234, 5678);
printf("%d %d\n", field1_get(a), field2_get(a));
return EXIT_SUCCESS;
}
Какое сокрытие )))
0
def f(m, n):
if m == 0:
return n + 1
elif n == 0:
return f(m - 1, 1)
else:
return f(m - 1, f(m, n - 1))
0
#define DECLARE_TYPE(Name, Type) \
using TYPE = Type; \
ObjectInterface s_##Type##ObjectInterface (Name, []()->ObjectType* { return new Type;
#define DECLARE_METHODS \
}, {
#define DECLARE_PROPERTIES \
}, {
#define DECLARE_METHOD(Method) \
{ #Method, reinterpret_cast <_ObjectMethodProc> (&TYPE::Method) },
#define DECLARE_CUSTOM_NAME_METHOD(Name, Method) \
{ Name, reinterpret_cast <_ObjectMethodProc> (&TYPE::Method) },
#define DECLARE_METHOD_MAPPER(_1,_2,DECLARE_METHOD,...) DECLARE_METHOD
#define METHOD(...) DECLARE_METHOD_MAPPER(__VA_ARGS__, DECLARE_CUSTOM_NAME_METHOD, DECLARE_METHOD)(__VA_ARGS__)
#define PROPERTY(Name, Get, Set) \
{ Name, { reinterpret_cast <_PropertyGettingProc> (&TYPE::Get), reinterpret_cast <_PropertySettingProc> (&TYPE::Set) } },
#define END_DECLARE_TYPE \
});
???
0
#include <iostream>
#include <chrono>
#include <thread>
#include <fstream>
#include <string>
using namespace std;
float Cheking = 0;
void read_file()
{
string line;
ifstream file("text.bin");
if (file)
{
while (getline(file, line))
{
file >> Cheking;
}
file.close();
}
}
void write_file()
{
ofstream myfile("text.bin");
if (myfile.is_open())
{
myfile << "\n";
myfile << Cheking << "\n";
myfile.close();
}
else
{
cout << "Unable to open file";
myfile.close();
}
}
int main()
{
using namespace chrono;
using namespace this_thread;
setlocale(LC_ALL, "ukr");
read_file();
cout << "Число: " << Cheking << "\t\t";
cout << endl;
if (Cheking == 0)
{
cin >> Cheking;
}
write_file();
sleep_for(milliseconds(1000));
return 0;
}
Простой гавнокод для храненния переменных в файле.