Для создания виджета Product-Per-Page (выбор количества продуктов на странице) в WooCommerce нужно использовать вот такой сниппет
Добавлять в functions.php вашей темы
Добавлять в functions.php вашей темы
function php2js($a=false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. $a = str_replace(",", ".", strval($a)); } // All scalars are converted to strings to avoid indeterminism. // PHP's "1" and 1 are equal for all PHP operators, but // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend, // we should get the same result in the JS frontend (string). // Character replacements for JSON. static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) $result[] = php2js($v); return '[ ' . join(', ', $result) . ' ]'; } else { foreach ($a as $k => $v) $result[] = php2js($k).': '.php2js($v); return '{ ' . join(', ', $result) . ' }'; } }
php -r "echo md5('domains.txt');" aeae2f628c54f10054e5c70076e1237b
# echo -n "domains.txt" | md5sum aeae2f628c54f10054e5c70076e1237b
# echo "import md5;print md5.md5(\"domains.txt\").hexdigest()" | python aeae2f628c54f10054e5c70076e1237b
SELECT MD5('domains.txt'); aeae2f628c54f10054e5c70076e1237b
def main(): application = tornado.web.Application([ (r"/", MainHandler), ]) # this line will setup default logging no matter if you use command options tornado.options.parse_command_line()
logging.info("starting torando web server") http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) # hardcoded port tornado.ioloop.IOLoop.instance().start()
mneradkov@mneradkov-thinkpad:~/workspace/mysuperproject$ ./webapp.py [I 120315 16:33:28 mixins:28] [INFO] Directory [/home/mneradkov/workspace/mysuperproject] [I 120315 16:33:28 mixins:28] [INFO] Connected to MySQL [xx.xx.xx.xx:xxxx] [I 120315 16:33:28 mixins:28] [INFO] Connected to memcache [127.0.0.1:11211] [I 120315 16:33:28 mixins:28] [INFO][I 120315 16:33:28 mixins:28] [INFO] Server [My Super Server] version [X.Xalpha] binded to [127.0.0.1:11100] [I 120315 16:33:28 webapp:37] Starting I/O loop to serve requests...
class MyAsyncHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self, *args, **kwargs): try: # тут чего то берем с внешнего сервера self.auth_request({}) except Exception, ex: self.error('Async - %s'%ex) self.reply(None) def auth_request(self, params, callback=None): url = self.application.settings['external_service'] + '?' + urlencode(params) if not callback: callback = self._on_load http = httpclient.AsyncHTTPClient() http.fetch(url, callback, validate_cert=False) def _on_load(self, response): # обрабатываем полученные результат pass
class MyTestServer(AsyncHTTPTestCase): def get_host(self): return 'http://%s:%d'%(SERVER['host'], SERVER['port']) def get_app(self): myserver = MyServer() myserver.run(SERVER['host'], SERVER['port']) return myserver.app # приложение Tornado def get_response_obj(self, url, **kwargs): if len(kwargs) > 0: url += '?' + urllib.urlencode(kwargs) logging.info('Request [%s]'%url) self.http_client.fetch(url, self.stop) response = self.wait() print response if response.body: return response.body return None
Traceback (most recent call last): File "/home/xxxx/test_wait.py", line 9, in test_1 self.wait(timeout = 5) File "/xxxxx/site-packages/tornado/ testing.py", line 169, in timeout_func timeout) AssertionError: Async operation timed out after 5 secondsЛечится это добавлением в класс теста переопределенного метода get_new_ioloop
class MyTestServer(AsyncHTTPTestCase): .... def get_new_ioloop(self): return ioloop.IOLoop.instance()
$ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> isinstance('abcd', str) True >>> isinstance('abcd', basestring) True >>> isinstance(u'abcd', str) False >>> isinstance(u'abcd', basestring) True
#!/usr/bin/env python # -*- coding: utf-8 -*- import tornado.web import tornado.httpserver import tornado.ioloop PERIOD = 30 # в минутах class MyApplication(tornado.web.Application): def period_run(self): # чего-то тут делаем pass ... app = MyApplication(handlers=urls, **settings) http_server = tornado.httpserver.HTTPServer(app, xheaders=True) loop = tornado.ioloop.IOLoop.instance() period_cbk = tornado.ioloop.PeriodicCallback(app.period_run, 1000*60*PERIOD, loop) period_cbk.start() loop.start()
data : { 'id' : 1 }
data : { 'id' : [1] }
def bla-bla(self, args): data = { 'bla-bla' : bla_bla, 'name' : name, 'id' : temp_id, } return data
def bla-bla(self, args): data = { 'bla-bla' : bla_bla, 'name' : name, 'id' : temp_id } return data
tmp = [1,2,3,4,5] ','.join( tmp )
','.join( map( str, tmp ) ) '1,2,3,4,5'
X-Amavis-Alert: BAD HEADER SECTION, Non-encoded 8-bit data (char D3 hex): Subject: 323342345344356354353345355350345 356341 356[...] X-Spam-Flag: NO X-Spam-Score: 4.301 X-Spam-Level: **** X-Spam-Status: No, score=4.301 tagged_above=-10 required=5 tests=[BAYES_50=0.8, RCVD_IN_DNSWL_NONE=-0.0001, SUBJECT_NEEDS_ENCODING=0.049, SUBJ_ILLEGAL_CHARS=1.518, TO_NO_BRKTS_MSFT=1.934] autolearn=no
Subject: =?iso-8859-1?Q?=D3=E2=E5=E4=EE=EC=EB=E5=ED=E8=E5_=EE=E1_=EE=F2=E2?= =?iso-8859-1?Q?=E5=F2=E5_=E2_=F2=E5=EC=E5_-_=D7=F2=EE_=ED=E5_=ED=F0=E0=E2?= =?iso-8859-1?Q?=E8=F2=F1=FF_=ED=E0_=F1=E0=E9=F2=E5?=
MIME-Version: 1.0 Content-type: text/plain; charset=windows-1251 Content-transfer-encoding: 8bit
PHPBB_DIR/include/emailer.php
$this->subject = (($this->subject != '') ? $this->subject : 'No Subject');
$this->subject = '=?'.trim($lang['ENCODING']).'?B?'.base64_encode($this->subject).'?=';
X-Spam-Flag: NO X-Spam-Score: 0.034 X-Spam-Level: X-Spam-Status: No, score=0.034 tagged_above=-10 required=4 tests=[BAYES_00=-1.9, RCVD_IN_DNSWL_NONE=-0.0001, TO_NO_BRKTS_MSFT=1.934] autolearn=noПо материалам этой темы, спасибо коллеге BW4ever за баг-репорт
$addon_html = ' <script type="text/javascript" src="'.XOOPS_URL.'/class/xoopsform/yandex_speller/spell.js"></script> // YandexSpeller var speller = new Speller({ url:"/class/xoopsform/yandex_speller", lang:"ru", options:Speller.IGNORE_URLS }); // Настройка параметров проверки http://api.yandex.ru/speller/doc/dg/reference/speller-js.xml <button name="cmdSpell_message" onclick="speller.check([document.getElementById(\'message\')])" type="button">'._CORE_CHECK_ORPHO.'</button> '; $template->assign_vars(array( 'U_POST_SQR_TOPIC' => 'javascript:sqr_show_hide();', 'SQR_IMG' => $images['quickreply'], 'L_POST_SQR_TOPIC' => $lang['Show_hide_quick_reply_form'], 'L_EMPTY_MESSAGE' => $lang['Empty_message'], 'L_QUICK_REPLY' => $lang['Quick_Reply'], 'L_USERNAME' => $lang['Username'], 'L_NO_TEXT_SELECTED' => $lang['Qreply_no_text_selected'], 'L_SUBJECT' => $lang['Subject'], 'L_MESSAGE_BODY' => $lang['Message_body'], 'L_PREVIEW' => $lang['Preview'], 'L_SUBMIT' => $lang['Submit'], 'S_POST_ACTION' => append_sid("posting.php"), 'S_HIDDEN_FORM_FIELDS' => $hidden_form_fields, 'ADDON_HTML' => $addon_html, ) );
<?php var $file_cache = true; ?>
<?php $db->query($sql, false, false, ‘имя_файла’, время_кэширования) ?>
<?php var $compiling = true; ?>Данное «ядро» была введено мной в версии 1.6.1 - оно позволяет сэкономить примерно 6 SQL запросов на каждой странице, но несколько повысит нагрузку на PHP.
<?php define('RC_TREE_CACHE', 1); ?>это сильно поможет при работе с большими деревьями категорий - в таких модулях, как news, например
public function thumb_url($file = false) { $path = $this->path_by_file($file); $url = CMS_URL.'/'.$path.'/thumbs/'.$file; $key = md5($url) & 3; $static_url = 'http://st'.($key+1).'.xxx.ru/'.$path.'/thumbs/'.$file; return $static_url; }
error_reporting(E_ALL); ini_set("display_errors", 1);P.S. Причем сам постоянно забываю, как точно пишется эта конструкция - особенно после переключения с языка на язык. Ненавижу переключать контекст мозга ;-)
function log($msg) { file_put_contents(SUPER_CMS_ROOT_PATH.'/cache/php-debug.log',"\n".$msg, FILE_APPEND); }
from socket import socket, gethostbyname, AF_INET, SOCK_STREAM target = "localhost" targetIP = gethostbyname(target) port = 80 s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((targetIP, port)) if(result == 0) : print 'Port %d is open' % (port,) s.close()
from twisted.internet.task import LoopingCall #============================================================================== class MySuperServer(MyServer, twisted.web.server.Site): ''' мой собственный веб-сервер, с блекджеком и шлюхами ;-) ''' def __init__(self): lp = LoopingCall(self.checkStatus) lp.start(1.0) # период в секундах def checkStatus(self): #self._log('Looping call') pass
if ($is404) { $html = file_get_contents(YOUR_ROOT_PATH.'/404.htm'); header("HTTP/1.0 404 Not Found"); echo $html; exit(); }
import os import logging from twisted.python import log CURRENT_PATH = os.path.realpath(os.path.dirname(__file__)) # Все это "по уму" обычно запихивается в нормальный конфиг-файл LOG_DIR = os.path.join(CURRENT_PATH, 'logs') LOG_FILE = os.path.join(LOG_DIR, 'super-puper.log') LOG_LEVEL = logging.INFO # инициализируем FORMAT = ('%(asctime)-15s %(levelname)s %(message)s') if not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR) logging.basicConfig(format=FORMAT, filename=LOG_FILE, handler=logging.handlers.RotatingFileHandler) observer = log.PythonLoggingObserver(loggerName='twisted') observer.start() observer.logger.setLevel(LOG_LEVEL) # класс-примесь для логгирования - в принципе - необязательно, реализация может быть разная - хоть функциями class BasicLogClass(): def _log(self, msg): log.msg(msg, logLevel=logging.INFO) def _error(self, msg): log.msg(msg, logLevel=logging.ERROR) def _warning(self, msg): log.msg(msg, logLevel=logging.WARNING)
$ otool -L yourFile
$ otool -L /Developer/Applications/Qt/plugins/sqldrivers/libqsqlmysql.dylib /Developer/Applications/Qt/plugins/sqldrivers/libqsqlmysql.dylib: libqsqlmysql.dylib (compatibility version 0.0.0, current version 0.0.0) /opt/local/lib/mysql5/mysql/libmysqlclient_r.16.dylib (compatibility version 17.0.0, current version 17.0.0) QtSql.framework/Versions/4/QtSql (compatibility version 4.6.0, current version 4.6.2) QtCore.framework/Versions/4/QtCore (compatibility version 4.6.0, current version 4.6.2) /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 438.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.11)