text
stringlengths 2
100k
| meta
dict |
---|---|
namespace MvcSiteMapProvider.Caching
{
/// <summary>
/// The default mapper class that simply maps everything to the default <see cref="T:MvcSiteMapProvider.Builder.ISiteMapBulderSet"/>.
/// This class can be inherited to provide mapping logic that gets its data from a configuration file or database.
/// </summary>
public class SiteMapCacheKeyToBuilderSetMapper
: ISiteMapCacheKeyToBuilderSetMapper
{
public virtual string GetBuilderSetName(string cacheKey)
{
return "default";
}
}
}
| {
"pile_set_name": "Github"
} |
# Russian message translation file for pg_rewind
# Copyright (C) 2015-2016 PostgreSQL Global Development Group
# This file is distributed under the same license as the PostgreSQL package.
# Alexander Lakhin <[email protected]>, 2015-2017.
msgid ""
msgstr ""
"Project-Id-Version: pg_rewind (PostgreSQL current)\n"
"Report-Msgid-Bugs-To: [email protected]\n"
"POT-Creation-Date: 2018-01-31 07:53+0300\n"
"PO-Revision-Date: 2017-09-21 12:01+0300\n"
"Last-Translator: Alexander Lakhin <[email protected]>\n"
"Language-Team: Russian <[email protected]>\n"
"Language: ru\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
#: ../../common/fe_memutils.c:35 ../../common/fe_memutils.c:75
#: ../../common/fe_memutils.c:98 parsexlog.c:74 parsexlog.c:127 parsexlog.c:179
#, c-format
msgid "out of memory\n"
msgstr "нехватка памяти\n"
#: ../../common/fe_memutils.c:92
#, c-format
msgid "cannot duplicate null pointer (internal error)\n"
msgstr "попытка дублирования нулевого указателя (внутренняя ошибка)\n"
#: ../../common/restricted_token.c:68
#, c-format
msgid "%s: WARNING: cannot create restricted tokens on this platform\n"
msgstr "%s: ПРЕДУПРЕЖДЕНИЕ: в этой ОС нельзя создавать ограниченные маркеры\n"
#: ../../common/restricted_token.c:77
#, c-format
msgid "%s: could not open process token: error code %lu\n"
msgstr "%s: не удалось открыть маркер процесса (код ошибки: %lu)\n"
#: ../../common/restricted_token.c:90
#, c-format
msgid "%s: could not allocate SIDs: error code %lu\n"
msgstr "%s: не удалось подготовить структуры SID (код ошибки: %lu)\n"
#: ../../common/restricted_token.c:110
#, c-format
msgid "%s: could not create restricted token: error code %lu\n"
msgstr "%s: не удалось создать ограниченный маркер (код ошибки: %lu)\n"
#: ../../common/restricted_token.c:132
#, c-format
msgid "%s: could not start process for command \"%s\": error code %lu\n"
msgstr ""
"%s: не удалось запустить процесс для команды \"%s\" (код ошибки: %lu)\n"
#: ../../common/restricted_token.c:170
#, c-format
msgid "%s: could not re-execute with restricted token: error code %lu\n"
msgstr ""
"%s: не удалось перезапуститься с ограниченным маркером (код ошибки: %lu)\n"
#: ../../common/restricted_token.c:186
#, c-format
msgid "%s: could not get exit code from subprocess: error code %lu\n"
msgstr "%s: не удалось получить код выхода от подпроцесса (код ошибки: %lu)\n"
#: copy_fetch.c:62
#, c-format
msgid "could not open directory \"%s\": %s\n"
msgstr "не удалось открыть каталог \"%s\": %s\n"
#: copy_fetch.c:91 filemap.c:111 filemap.c:266
#, c-format
msgid "could not stat file \"%s\": %s\n"
msgstr "не удалось получить информацию о файле \"%s\": %s\n"
#: copy_fetch.c:120
#, c-format
msgid "could not read symbolic link \"%s\": %s\n"
msgstr "не удалось прочитать символическую ссылку \"%s\": %s\n"
#: copy_fetch.c:123
#, c-format
msgid "symbolic link \"%s\" target is too long\n"
msgstr "целевой путь символической ссылки \"%s\" слишком длинный\n"
#: copy_fetch.c:138
#, c-format
msgid ""
"\"%s\" is a symbolic link, but symbolic links are not supported on this "
"platform\n"
msgstr ""
"\"%s\" - символическая ссылка, но в этой ОС символические ссылки не "
"поддерживаются\n"
#: copy_fetch.c:145
#, c-format
msgid "could not read directory \"%s\": %s\n"
msgstr "не удалось прочитать каталог \"%s\": %s\n"
#: copy_fetch.c:149
#, c-format
msgid "could not close directory \"%s\": %s\n"
msgstr "не удалось закрыть каталог \"%s\": %s\n"
#: copy_fetch.c:169
#, c-format
msgid "could not open source file \"%s\": %s\n"
msgstr "не удалось открыть исходный файл \"%s\": %s\n"
#: copy_fetch.c:173
#, c-format
msgid "could not seek in source file: %s\n"
msgstr "не удалось переместиться в исходном файле: %s\n"
#: copy_fetch.c:190 file_ops.c:299
#, c-format
msgid "could not read file \"%s\": %s\n"
msgstr "не удалось прочитать файл \"%s\": %s\n"
#: copy_fetch.c:193
#, c-format
msgid "unexpected EOF while reading file \"%s\"\n"
msgstr "неожиданный конец при чтении файла \"%s\"\n"
#: copy_fetch.c:200
#, c-format
msgid "could not close file \"%s\": %s\n"
msgstr "не удалось закрыть файл \"%s\": %s\n"
#: datapagemap.c:124
#, c-format
msgid " block %u\n"
msgstr " блок %u\n"
#: file_ops.c:63
#, c-format
msgid "could not open target file \"%s\": %s\n"
msgstr "не удалось открыть целевой файл \"%s\": %s\n"
#: file_ops.c:77
#, c-format
msgid "could not close target file \"%s\": %s\n"
msgstr "не удалось закрыть целевой файл \"%s\": %s\n"
#: file_ops.c:97
#, c-format
msgid "could not seek in target file \"%s\": %s\n"
msgstr "не удалось переместиться в целевом файле \"%s\": %s\n"
#: file_ops.c:113
#, c-format
msgid "could not write file \"%s\": %s\n"
msgstr "не удалось записать файл \"%s\": %s\n"
#: file_ops.c:163
#, c-format
msgid "invalid action (CREATE) for regular file\n"
msgstr "неверное действие (CREATE) для обычного файла\n"
#: file_ops.c:178
#, c-format
msgid "could not remove file \"%s\": %s\n"
msgstr "не удалось стереть файл \"%s\": %s\n"
#: file_ops.c:195
#, c-format
msgid "could not open file \"%s\" for truncation: %s\n"
msgstr "не удалось открыть файл \"%s\" для усечения: %s\n"
#: file_ops.c:199
#, c-format
msgid "could not truncate file \"%s\" to %u: %s\n"
msgstr "не удалось усечь файл \"%s\" до нужного размера (%u): %s\n"
#: file_ops.c:215
#, c-format
msgid "could not create directory \"%s\": %s\n"
msgstr "создать каталог \"%s\" не удалось: %s\n"
#: file_ops.c:229
#, c-format
msgid "could not remove directory \"%s\": %s\n"
msgstr "ошибка при удалении каталога \"%s\": %s\n"
#: file_ops.c:243
#, c-format
msgid "could not create symbolic link at \"%s\": %s\n"
msgstr "не удалось создать символическую ссылку \"%s\": %s\n"
#: file_ops.c:257
#, c-format
msgid "could not remove symbolic link \"%s\": %s\n"
msgstr "ошибка при удалении символической ссылки \"%s\": %s\n"
#: file_ops.c:287 file_ops.c:291
#, c-format
msgid "could not open file \"%s\" for reading: %s\n"
msgstr "не удалось открыть файл \"%s\" для чтения: %s\n"
#: filemap.c:103
#, c-format
msgid "data file \"%s\" in source is not a regular file\n"
msgstr "файл данных \"%s\" в источнике не является обычным файлом\n"
#: filemap.c:125
#, c-format
msgid "\"%s\" is not a directory\n"
msgstr "\"%s\" не является каталогом\n"
#: filemap.c:148
#, c-format
msgid "\"%s\" is not a symbolic link\n"
msgstr "\"%s\" не является символической ссылкой\n"
#: filemap.c:160
#, c-format
msgid "\"%s\" is not a regular file\n"
msgstr "\"%s\" не является обычным файлом\n"
#: filemap.c:278
#, c-format
msgid "source file list is empty\n"
msgstr "список файлов в источнике пуст\n"
#: filemap.c:400
#, c-format
msgid "unexpected page modification for directory or symbolic link \"%s\"\n"
msgstr ""
"неожиданная модификация страницы для каталога или символической ссылки \"%s"
"\"\n"
#. translator: first %s is a file path, second is a keyword such as COPY
#: filemap.c:536
#, c-format
msgid "%s (%s)\n"
msgstr "%s (%s)\n"
#: libpq_fetch.c:55
#, c-format
msgid "could not connect to server: %s"
msgstr "не удалось подключиться к серверу: %s"
#: libpq_fetch.c:58
#, c-format
msgid "connected to server\n"
msgstr "подключение к серверу установлено\n"
#: libpq_fetch.c:68
#, c-format
msgid "source server must not be in recovery mode\n"
msgstr "исходный сервер должен быть в режиме восстановления\n"
#: libpq_fetch.c:78
#, c-format
msgid "full_page_writes must be enabled in the source server\n"
msgstr "на исходном сервере должен быть включён режим full_page_writes\n"
#: libpq_fetch.c:90
#, c-format
msgid "could not set up connection context: %s"
msgstr "не удалось настроить контекст подключения: %s"
#: libpq_fetch.c:108
#, c-format
msgid "error running query (%s) in source server: %s"
msgstr "ошибка выполнения запроса (%s) на исходном сервере: %s"
#: libpq_fetch.c:113
#, c-format
msgid "unexpected result set from query\n"
msgstr "неожиданный результат запроса\n"
#: libpq_fetch.c:136
#, c-format
msgid "unrecognized result \"%s\" for current WAL insert location\n"
msgstr ""
"нераспознанный результат \"%s\" вместо текущей позиции добавления в WAL\n"
#: libpq_fetch.c:186
#, c-format
msgid "could not fetch file list: %s"
msgstr "не удалось получить список файлов: %s"
#: libpq_fetch.c:191
#, c-format
msgid "unexpected result set while fetching file list\n"
msgstr "неожиданный результат при получении списка файлов\n"
#: libpq_fetch.c:261
#, c-format
msgid "could not send query: %s"
msgstr "не удалось отправить запрос: %s"
#: libpq_fetch.c:263
#, c-format
msgid "getting file chunks\n"
msgstr "получение сегментов файлов\n"
#: libpq_fetch.c:266
#, c-format
msgid "could not set libpq connection to single row mode\n"
msgstr "не удалось перевести подключение libpq в однострочный режим\n"
#: libpq_fetch.c:287
#, c-format
msgid "unexpected result while fetching remote files: %s"
msgstr "неожиданный результат при получении удалённых файлов: %s"
#: libpq_fetch.c:293
#, c-format
msgid "unexpected result set size while fetching remote files\n"
msgstr "неожиданный размер набора результатов при получении удалённых файлов\n"
#: libpq_fetch.c:299
#, c-format
msgid ""
"unexpected data types in result set while fetching remote files: %u %u %u\n"
msgstr ""
"неожиданные типы данных в наборе результатов при получении удалённых файлов: "
"%u %u %u\n"
#: libpq_fetch.c:307
#, c-format
msgid "unexpected result format while fetching remote files\n"
msgstr "неожиданный формат результата при получении удалённых файлов\n"
#: libpq_fetch.c:313
#, c-format
msgid "unexpected null values in result while fetching remote files\n"
msgstr ""
"неожиданные значения NULL в результате при получении удалённых файлов\n"
#: libpq_fetch.c:317
#, c-format
msgid "unexpected result length while fetching remote files\n"
msgstr "неожиданная длина результата при получении удалённых файлов\n"
#: libpq_fetch.c:339
#, c-format
msgid "received null value for chunk for file \"%s\", file has been deleted\n"
msgstr "для файла \"%s\" вместо сегмента получено NULL-значение, файл удалён\n"
#: libpq_fetch.c:351
#, c-format
msgid "received chunk for file \"%s\", offset %s, size %d\n"
msgstr "получен сегмент файла \"%s\": смещение %s, размер %d\n"
#: libpq_fetch.c:380
#, c-format
msgid "could not fetch remote file \"%s\": %s"
msgstr "не удалось получить удалённый файл \"%s\": %s"
#: libpq_fetch.c:385
#, c-format
msgid "unexpected result set while fetching remote file \"%s\"\n"
msgstr "неожиданный набор результатов при получении удалённого файла \"%s\"\n"
#: libpq_fetch.c:396
#, c-format
msgid "fetched file \"%s\", length %d\n"
msgstr "получен файл \"%s\", длина %d\n"
#: libpq_fetch.c:429
#, c-format
msgid "could not send COPY data: %s"
msgstr "не удалось отправить данные COPY: %s"
#: libpq_fetch.c:455
#, c-format
msgid "could not create temporary table: %s"
msgstr "не удалось создать временную таблицу: %s"
#: libpq_fetch.c:463
#, c-format
msgid "could not send file list: %s"
msgstr "не удалось отправить список файлов: %s"
#: libpq_fetch.c:505
#, c-format
msgid "could not send end-of-COPY: %s"
msgstr "не удалось отправить сообщение о завершении копирования: %s"
#: libpq_fetch.c:511
#, c-format
msgid "unexpected result while sending file list: %s"
msgstr "неожиданный результат при передаче списка: %s"
#: logging.c:57
msgid "Failure, exiting\n"
msgstr "Ошибка, выполняется выход\n"
#: logging.c:140
#, c-format
msgid "%*s/%s kB (%d%%) copied"
msgstr "%*s/%s КБ (%d%%) скопировано"
#: parsexlog.c:87 parsexlog.c:133
#, c-format
msgid "could not read WAL record at %X/%X: %s\n"
msgstr "не удалось прочитать запись WAL в позиции %X/%X: %s\n"
#: parsexlog.c:91 parsexlog.c:136
#, c-format
msgid "could not read WAL record at %X/%X\n"
msgstr "не удалось прочитать запись WAL в позиции %X/%X\n"
#: parsexlog.c:191
#, c-format
msgid "could not find previous WAL record at %X/%X: %s\n"
msgstr "не удалось найти предыдущую запись WAL в позиции %X/%X: %s\n"
#: parsexlog.c:195
#, c-format
msgid "could not find previous WAL record at %X/%X\n"
msgstr "не удалось найти предыдущую запись WAL в позиции %X/%X\n"
#: parsexlog.c:283
#, c-format
msgid "could not open file \"%s\": %s\n"
msgstr "не удалось открыть файл \"%s\": %s\n"
#: parsexlog.c:297
#, c-format
msgid "could not seek in file \"%s\": %s\n"
msgstr "не удалось переместиться в файле \"%s\": %s\n"
#: parsexlog.c:304
#, c-format
msgid "could not read from file \"%s\": %s\n"
msgstr "не удалось прочитать файл \"%s\": %s\n"
#: parsexlog.c:372
#, c-format
msgid ""
"WAL record modifies a relation, but record type is not recognized\n"
"lsn: %X/%X, rmgr: %s, info: %02X\n"
msgstr ""
"Запись WAL модифицирует отношение, но тип записи не распознан\n"
"lsn: %X/%X, rmgr: %s, info: %02X\n"
#: pg_rewind.c:64
#, c-format
msgid ""
"%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n"
"\n"
msgstr ""
"%s синхронизирует кластер PostgreSQL с другой копией кластера.\n"
"\n"
#: pg_rewind.c:65
#, c-format
msgid ""
"Usage:\n"
" %s [OPTION]...\n"
"\n"
msgstr ""
"Пример запуска:\n"
" %s [ПАРАМЕТР]...\n"
"\n"
#: pg_rewind.c:66
#, c-format
msgid "Options:\n"
msgstr "Параметры:\n"
#: pg_rewind.c:67
#, c-format
msgid " -D, --target-pgdata=DIRECTORY existing data directory to modify\n"
msgstr ""
" -D, --target-pgdata=КАТАЛОГ существующий каталог, куда будут записаны "
"данные\n"
#: pg_rewind.c:68
#, c-format
msgid ""
" --source-pgdata=DIRECTORY source data directory to synchronize with\n"
msgstr ""
" --source-pgdata=КАТАЛОГ исходный каталог, с которым будет проведена "
"синхронизация\n"
# well-spelled: ПОДКЛ
#: pg_rewind.c:69
#, c-format
msgid " --source-server=CONNSTR source server to synchronize with\n"
msgstr ""
" --source-server=СТР_ПОДКЛ сервер, с которым будет проведена "
"синхронизация\n"
#: pg_rewind.c:70
#, c-format
msgid " -n, --dry-run stop before modifying anything\n"
msgstr ""
" -n, --dry-run остановиться до внесения каких-либо "
"изменений\n"
#: pg_rewind.c:71
#, c-format
msgid " -P, --progress write progress messages\n"
msgstr " -P, --progress выводить сообщения о ходе процесса\n"
#: pg_rewind.c:72
#, c-format
msgid " --debug write a lot of debug messages\n"
msgstr ""
" --debug выдавать множество отладочных сообщений\n"
#: pg_rewind.c:73
#, c-format
msgid ""
" -V, --version output version information, then exit\n"
msgstr " -V, --version показать версию и выйти\n"
#: pg_rewind.c:74
#, c-format
msgid " -?, --help show this help, then exit\n"
msgstr " -?, --help показать эту справку и выйти\n"
#: pg_rewind.c:75
#, c-format
msgid ""
"\n"
"Report bugs to <[email protected]>.\n"
msgstr ""
"\n"
"Об ошибках сообщайте по адресу <[email protected]>.\n"
#: pg_rewind.c:130 pg_rewind.c:161 pg_rewind.c:168 pg_rewind.c:175
#: pg_rewind.c:183
#, c-format
msgid "Try \"%s --help\" for more information.\n"
msgstr "Для дополнительной информации попробуйте \"%s --help\".\n"
#: pg_rewind.c:160
#, c-format
msgid "%s: no source specified (--source-pgdata or --source-server)\n"
msgstr ""
"%s: источник не указан (требуется --source-pgdata или --source-server)\n"
#: pg_rewind.c:167
#, c-format
msgid "%s: only one of --source-pgdata or --source-server can be specified\n"
msgstr "%s: указать можно только --source-pgdata либо --source-server\n"
#: pg_rewind.c:174
#, c-format
msgid "%s: no target data directory specified (--target-pgdata)\n"
msgstr "%s: целевой каталог данных не указан (--target-pgdata)\n"
#: pg_rewind.c:181
#, c-format
msgid "%s: too many command-line arguments (first is \"%s\")\n"
msgstr "%s: слишком много аргументов командной строки (первый: \"%s\")\n"
#: pg_rewind.c:196
#, c-format
msgid "cannot be executed by \"root\"\n"
msgstr "программу не должен запускать root\n"
#: pg_rewind.c:197
#, c-format
msgid "You must run %s as the PostgreSQL superuser.\n"
msgstr "Запускать %s нужно от имени суперпользователя PostgreSQL.\n"
#: pg_rewind.c:228
#, c-format
msgid "source and target cluster are on the same timeline\n"
msgstr "исходный и целевой кластер уже на одной линии времени\n"
#: pg_rewind.c:234
#, c-format
msgid "servers diverged at WAL location %X/%X on timeline %u\n"
msgstr "серверы разошлись в позиции WAL %X/%X на линии времени %u\n"
#: pg_rewind.c:271
#, c-format
msgid "no rewind required\n"
msgstr "перемотка не требуется.\n"
#: pg_rewind.c:278
#, c-format
msgid "rewinding from last common checkpoint at %X/%X on timeline %u\n"
msgstr ""
"перемотка от последней общей контрольной точки в позиции %X/%X на линии "
"времени %u\n"
#: pg_rewind.c:286
#, c-format
msgid "reading source file list\n"
msgstr "чтение списка исходных файлов\n"
#: pg_rewind.c:288
#, c-format
msgid "reading target file list\n"
msgstr "чтение списка целевых файлов\n"
#: pg_rewind.c:298
#, c-format
msgid "reading WAL in target\n"
msgstr "чтение WAL в целевом кластере\n"
#: pg_rewind.c:315
#, c-format
msgid "need to copy %lu MB (total source directory size is %lu MB)\n"
msgstr ""
"требуется скопировать %lu МБ (общий размер исходного каталога: %lu МБ)\n"
#: pg_rewind.c:332
#, c-format
msgid ""
"\n"
"creating backup label and updating control file\n"
msgstr ""
"\n"
"создание метки копии и модификация управляющего файла\n"
#: pg_rewind.c:360
#, c-format
msgid "syncing target data directory\n"
msgstr "синхронизация целевого каталога данных\n"
#: pg_rewind.c:363
#, c-format
msgid "Done!\n"
msgstr "Готово!\n"
#: pg_rewind.c:375
#, c-format
msgid "source and target clusters are from different systems\n"
msgstr "исходный и целевой кластеры относятся к разным системам\n"
#: pg_rewind.c:383
#, c-format
msgid "clusters are not compatible with this version of pg_rewind\n"
msgstr "кластеры несовместимы с этой версией pg_rewind\n"
#: pg_rewind.c:393
#, c-format
msgid ""
"target server needs to use either data checksums or \"wal_log_hints = on\"\n"
msgstr ""
"на целевом сервере должны быть контрольные суммы данных или \"wal_log_hints "
"= on\"\n"
#: pg_rewind.c:404
#, c-format
msgid "target server must be shut down cleanly\n"
msgstr "целевой сервер должен быть выключен штатно\n"
#: pg_rewind.c:414
#, c-format
msgid "source data directory must be shut down cleanly\n"
msgstr "работа с исходным каталогом данных должна быть завершена штатно\n"
#: pg_rewind.c:469
#, c-format
msgid "invalid control file"
msgstr "неверный управляющий файл"
#: pg_rewind.c:480
#, c-format
msgid "Source timeline history:\n"
msgstr "История линии времени источника:\n"
#: pg_rewind.c:482
#, c-format
msgid "Target timeline history:\n"
msgstr "История линии времени получателя:\n"
#. translator: %d is a timeline number, others are LSN positions
#: pg_rewind.c:496
#, c-format
msgid "%d: %X/%X - %X/%X\n"
msgstr "%d: %X/%X - %X/%X\n"
#: pg_rewind.c:555
#, c-format
msgid ""
"could not find common ancestor of the source and target cluster's timelines\n"
msgstr ""
"не удалось найти общего предка линий времени исходного и целевого кластеров\n"
#: pg_rewind.c:596
#, c-format
msgid "backup label buffer too small\n"
msgstr "буфер для метки копии слишком мал\n"
#: pg_rewind.c:619
#, c-format
msgid "unexpected control file CRC\n"
msgstr "неверная контрольная сумма управляющего файла\n"
#: pg_rewind.c:629
#, c-format
msgid "unexpected control file size %d, expected %d\n"
msgstr "неверный размер управляющего файла (%d), ожидалось: %d\n"
#: pg_rewind.c:705
#, c-format
msgid ""
"The program \"initdb\" is needed by %s but was\n"
"not found in the same directory as \"%s\".\n"
"Check your installation.\n"
msgstr ""
"Для %s необходима программа \"initdb\", но она не найдена\n"
"в каталоге \"%s\".\n"
"Проверьте правильность установки СУБД.\n"
#: pg_rewind.c:709
#, c-format
msgid ""
"The program \"initdb\" was found by \"%s\"\n"
"but was not the same version as %s.\n"
"Check your installation.\n"
msgstr ""
"Программа \"initdb\" найдена в \"%s\",\n"
"но её версия отличается от версии %s.\n"
"Проверьте правильность установки СУБД.\n"
#: pg_rewind.c:727
#, c-format
msgid "sync of target directory failed\n"
msgstr "сбой синхронизации целевого каталога\n"
#: timeline.c:76 timeline.c:82
#, c-format
msgid "syntax error in history file: %s\n"
msgstr "синтаксическая ошибка в файле истории: %s\n"
#: timeline.c:77
#, c-format
msgid "Expected a numeric timeline ID.\n"
msgstr "Ожидается числовой идентификатор линии времени.\n"
#: timeline.c:83
#, c-format
msgid "Expected a write-ahead log switchpoint location.\n"
msgstr "Ожидается положение точки переключения журнала предзаписи.\n"
#: timeline.c:88
#, c-format
msgid "invalid data in history file: %s\n"
msgstr "неверные данные в файле истории: %s\n"
#: timeline.c:89
#, c-format
msgid "Timeline IDs must be in increasing sequence.\n"
msgstr "Идентификаторы линий времени должны возрастать.\n"
#: timeline.c:109
#, c-format
msgid "invalid data in history file\n"
msgstr "неверные данные в файле истории\n"
#: timeline.c:110
#, c-format
msgid "Timeline IDs must be less than child timeline's ID.\n"
msgstr ""
"Идентификаторы линий времени должны быть меньше идентификатора линии-"
"потомка.\n"
#: xlogreader.c:276
#, c-format
msgid "invalid record offset at %X/%X"
msgstr "неверное смещение записи: %X/%X"
#: xlogreader.c:284
#, c-format
msgid "contrecord is requested by %X/%X"
msgstr "по смещению %X/%X запрошено продолжение записи"
#: xlogreader.c:325 xlogreader.c:625
#, c-format
msgid "invalid record length at %X/%X: wanted %u, got %u"
msgstr "неверная длина записи по смещению %X/%X: ожидалось %u, получено %u"
#: xlogreader.c:340
#, c-format
msgid "record length %u at %X/%X too long"
msgstr "длина записи %u по смещению %X/%X слишком велика"
#: xlogreader.c:381
#, c-format
msgid "there is no contrecord flag at %X/%X"
msgstr "нет флага contrecord в позиции %X/%X"
#: xlogreader.c:394
#, c-format
msgid "invalid contrecord length %u at %X/%X"
msgstr "неверная длина contrecord (%u) в позиции %X/%X"
#: xlogreader.c:633
#, c-format
msgid "invalid resource manager ID %u at %X/%X"
msgstr "неверный ID менеджера ресурсов %u по смещению %X/%X"
#: xlogreader.c:647 xlogreader.c:664
#, c-format
msgid "record with incorrect prev-link %X/%X at %X/%X"
msgstr "запись с неверной ссылкой назад %X/%X по смещению %X/%X"
#: xlogreader.c:701
#, c-format
msgid "incorrect resource manager data checksum in record at %X/%X"
msgstr ""
"некорректная контрольная сумма данных менеджера ресурсов в записи по "
"смещению %X/%X"
#: xlogreader.c:734
#, c-format
msgid "invalid magic number %04X in log segment %s, offset %u"
msgstr "неверное магическое число %04X в сегменте журнала %s, смещение %u"
#: xlogreader.c:748 xlogreader.c:799
#, c-format
msgid "invalid info bits %04X in log segment %s, offset %u"
msgstr "неверные информационные биты %04X в сегменте журнала %s, смещение %u"
#: xlogreader.c:774
#, c-format
msgid ""
"WAL file is from different database system: WAL file database system "
"identifier is %s, pg_control database system identifier is %s"
msgstr ""
"файл WAL принадлежит другой СУБД: в нём указан идентификатор системы БД %s, "
"а идентификатор системы pg_control: %s"
#: xlogreader.c:781
#, c-format
msgid ""
"WAL file is from different database system: incorrect XLOG_SEG_SIZE in page "
"header"
msgstr ""
"файл WAL принадлежит другой СУБД: некорректный XLOG_SEG_SIZE в заголовке "
"страницы"
#: xlogreader.c:787
#, c-format
msgid ""
"WAL file is from different database system: incorrect XLOG_BLCKSZ in page "
"header"
msgstr ""
"файл WAL принадлежит другой СУБД: некорректный XLOG_BLCKSZ в заголовке "
"страницы"
#: xlogreader.c:813
#, c-format
msgid "unexpected pageaddr %X/%X in log segment %s, offset %u"
msgstr "неожиданный pageaddr %X/%X в сегменте журнала %s, смещение %u"
#: xlogreader.c:838
#, c-format
msgid "out-of-sequence timeline ID %u (after %u) in log segment %s, offset %u"
msgstr ""
"нарушение последовательности ID линии времени %u (после %u) в сегменте "
"журнала %s, смещение %u"
#: xlogreader.c:1083
#, c-format
msgid "out-of-order block_id %u at %X/%X"
msgstr "идентификатор блока %u идёт не по порядку в позиции %X/%X"
#: xlogreader.c:1106
#, c-format
msgid "BKPBLOCK_HAS_DATA set, but no data included at %X/%X"
msgstr "BKPBLOCK_HAS_DATA установлен, но данных в позиции %X/%X нет"
#: xlogreader.c:1113
#, c-format
msgid "BKPBLOCK_HAS_DATA not set, but data length is %u at %X/%X"
msgstr ""
"BKPBLOCK_HAS_DATA не установлен, но длина данных равна %u в позиции %X/%X"
#: xlogreader.c:1149
#, c-format
msgid ""
"BKPIMAGE_HAS_HOLE set, but hole offset %u length %u block image length %u at "
"%X/%X"
msgstr ""
"BKPIMAGE_HAS_HOLE установлен, но для пропуска заданы смещение %u и длина %u "
"при длине образа блока %u в позиции %X/%X"
#: xlogreader.c:1165
#, c-format
msgid "BKPIMAGE_HAS_HOLE not set, but hole offset %u length %u at %X/%X"
msgstr ""
"BKPIMAGE_HAS_HOLE не установлен, но для пропуска заданы смещение %u и длина "
"%u в позиции %X/%X"
#: xlogreader.c:1180
#, c-format
msgid "BKPIMAGE_IS_COMPRESSED set, but block image length %u at %X/%X"
msgstr ""
"BKPIMAGE_IS_COMPRESSED установлен, но длина образа блока равна %u в позиции "
"%X/%X"
#: xlogreader.c:1195
#, c-format
msgid ""
"neither BKPIMAGE_HAS_HOLE nor BKPIMAGE_IS_COMPRESSED set, but block image "
"length is %u at %X/%X"
msgstr ""
"ни BKPIMAGE_HAS_HOLE, ни BKPIMAGE_IS_COMPRESSED не установлены, но длина "
"образа блока равна %u в позиции %X/%X"
#: xlogreader.c:1211
#, c-format
msgid "BKPBLOCK_SAME_REL set but no previous rel at %X/%X"
msgstr ""
"BKPBLOCK_SAME_REL установлен, но предыдущее значение не задано в позиции %X/"
"%X"
#: xlogreader.c:1223
#, c-format
msgid "invalid block_id %u at %X/%X"
msgstr "неверный идентификатор блока %u в позиции %X/%X"
#: xlogreader.c:1306
#, c-format
msgid "record with invalid length at %X/%X"
msgstr "запись с неверной длиной в позиции %X/%X"
#: xlogreader.c:1395
#, c-format
msgid "invalid compressed image at %X/%X, block %d"
msgstr "неверный сжатый образ в позиции %X/%X, блок %d"
| {
"pile_set_name": "Github"
} |
---
title: Azure Site Recovery で Azure へのテスト フェールオーバー (ディザスター リカバリー訓練) を実行する
description: Azure Site Recovery サービスを使用して、オンプレミスから Azure へのテスト フェールオーバーの実行について説明します。
author: rayne-wiselman
manager: carmonm
ms.service: site-recovery
ms.topic: conceptual
ms.date: 11/14/2019
ms.author: raynew
ms.openlocfilehash: 4233df62de48dd7a7253c488b0cd69c38cd8d445
ms.sourcegitcommit: 11e2521679415f05d3d2c4c49858940677c57900
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 07/31/2020
ms.locfileid: "87503499"
---
# <a name="run-a-test-failover-disaster-recovery-drill-to-azure"></a>Azure へのテスト フェールオーバー (ディザスター リカバリー訓練) を実行する
この記事では、Site Recovery テスト フェールオーバーを使用して Azure に対してディザスター リカバリー ドリルを実行する方法について説明します。
テスト フェールオーバーを実行し、データの損失またはダウンタイムを発生させることなく、レプリケーションおよびディザスター リカバリー戦略を検証します。 テスト フェールオーバーは、実行中のレプリケーションや運用環境に影響ありません。 テスト フェールオーバーは、特定の仮想マシン (VM) または複数の VM を含む[復旧計画](site-recovery-create-recovery-plans.md)で実行できます。
## <a name="run-a-test-failover"></a>テスト フェールオーバーの実行
この手順では、復旧計画のテスト フェールオーバーを実行する方法について説明します。 1 つの VM のテスト フェールオーバーを実行する場合は、[ここ](tutorial-dr-drill-azure.md#run-a-test-failover-for-a-single-vm)で説明されている手順に従ってください
![Azure portal の [テスト フェールオーバー] ページのスクリーンショット。](./media/site-recovery-test-failover-to-azure/TestFailover.png)
1. Azure Portal の Site Recovery で、 **[Recovery Plans] (復旧計画)** > *[recoveryplan_name]* > **[Test Failover] (テスト フェールオーバー)** をクリックします。
2. フェールオーバーする **[Recovery Point] (復旧ポイント)** を選択します。 次のいずれかのオプションを使うことができます。
- **最後に処理があった時点**:Site Recovery によって処理された最新の復旧ポイントに、計画内のすべての VM をフェールオーバーします。 特定の VM の最新の復旧ポイントを参照するには、VM 設定の **[Latest Recovery Points] (最新の回復ポイント)** を確認します。 このオプションを使用すると、未処理のデータの処理に時間がかからないため、RTO (目標復旧時間) を低くできます。
- **最新のアプリ整合性**:Site Recovery によって処理されたアプリケーション整合性の最新の復旧ポイントに、計画内のすべての VM をフェールオーバーします。 特定の VM の最新の復旧ポイントを参照するには、VM 設定の **[Latest Recovery Points] (最新の回復ポイント)** を確認します。
- **Latest**:このオプションは、Site Recovery サービスに送信されたすべてのデータを最初に処理して、各 VM の復旧ポイントを作成してから、それにフェールオーバーします。 このオプションは、フェールオーバー後に作成された VM は、フェールオーバーがトリガーされた時点で Site Recovery にレプリケートされたすべてのデータを保持しているため、RPO (目標復旧時点) を最も低くすることができます。
- **最新のマルチ VM 処理**:このオプションは、マルチ VM 整合性が有効にされている 1 台または複数の VM を含む復旧計画で使用できます。 設定が有効にされている VM は、最新の共通マルチ VM 整合性復旧ポイントにフェールオーバーされます。 その他の VM は、最新の処理済み復旧ポイントにフェールオーバーされます。
- **最新のマルチ VM アプリ整合性**:このオプションは、マルチ VM 整合性が有効にされている 1 台または複数の VM を含む復旧計画で使用できます。 レプリケーション グループに含まれる VM は、最新の共通マルチ VM アプリケーション整合性復旧ポイントにフェールオーバーされます。 その他の VM は、最新のアプリケーション整合性復旧ポイントにフェールオーバーされます。
- **Custom**:特定の VM を特定の復旧ポイントにフェールオーバーする場合は、このオプションを使用します。
3. テスト VM を作成する Azure 仮想ネットワークを選択します。
- Site Recovery は、VM の **[コンピューティングとネットワーク]** の設定で提供されたものと同じ名前と同じ IP アドレスのサブネットに、テスト VM の作成を試みます。
- テスト フェールオーバーに使用される Azure 仮想ネットワークで同じ名前のサブネットを使用できない場合は、アルファベット順で最初のサブネットにテスト VM が作成されます。
- サブネットで同じ IP アドレスを使用できない場合、VM はサブネットで使用できる別の IP アドレスを受け取ります。 [詳細については、こちらを参照してください](#create-a-network-for-test-failover)。
4. Azure にフェールオーバーしていて、データ暗号化が有効になっている場合は、 **[暗号化キー]** で、プロバイダーのインストール中に暗号化を有効にしたときに発行された証明書を選びます。 暗号化が有効にされていない場合は、この手順を無視できます。
5. **[ジョブ]** タブで、フェールオーバーの進行状況を追跡します。テスト レプリカ マシンも Azure ポータルで確認できます。
6. Azure VM への RDP 接続を開始するには、フェールオーバーされる VM のネットワーク インターフェイスで、[パブリック IP アドレスを追加](https://aka.ms/addpublicip)する必要があります。
7. すべて問題なく動作している場合は、 **[Cleanup test failover] (テスト フェールオーバーのクリーンアップ)** をクリックします。 これで、テスト フェールオーバー中に作成された VM が削除されます。
8. **[メモ]** を使用して、テスト フェールオーバーに関連する観察結果をすべて記録し、保存します。
![[テスト フェールオーバー] の [ジョブ] タブのスクリーンショット。](./media/site-recovery-test-failover-to-azure/TestFailoverJob.png)
テスト フェールオーバーがトリガーされると次の操作が行われます。
1. **前提条件**:フェールオーバーを実行するために必要なすべての条件が満たされていることを確認する前提条件チェックが実行されます。
2. **フェールオーバー**:Azure VM を作成できるように、フェールオーバーによってデータが処理され、準備されます。
3. **Latest**:最新の復旧ポイントを選択した場合、サービスに送信済みのデータから復旧ポイントが作成されます。
4. **[開始]** : 前の手順で処理されたデータを使って Azure 仮想マシンが作成されます。
### <a name="failover-timing"></a>フェールオーバーのタイミング
以下のシナリオでは、フェールオーバーに、通常 8 ~ 10 分かかる特別な中間ステップが必要となります。
* 9\.8 よりも前のバージョンのモビリティ サービスを実行している VMware VM
* 物理サーバー
* VMware Linux VM
* 物理サーバーとして保護されている Hyper-V VM
* 次のドライバーがブート ドライバーでない VMware VM
* storvsc
* vmbus
* storflt
* intelide
* atapi
* DHCP が有効になっていない VMware VM (DHCP と静的 IP アドレスのどちらを使用しているかは関係しない)。
その他すべてのケースでは、中間ステップは不要であり、フェールオーバーに要する時間は大幅に短くなります。
## <a name="create-a-network-for-test-failover"></a>テスト フェールオーバー用のネットワークの作成
テスト フェールオーバー用に、各 VM の **[Compute and Network] \(コンピューティングとネットワーク)** 設定で、運用復旧サイト ネットワークから分離されたネットワークを選択することをお勧めします。 既定では、作成した Azure 仮想ネットワークは、他のネットワークから分離されます。 テスト ネットワークは、運用ネットワークを模倣したものにする必要があります。
- テスト ネットワークでは、運用ネットワークと同じ数のサブネットが必要です。 サブネットは、同じ名前を持つ必要があります。
- テスト ネットワークでは、同じ IP アドレス範囲を使用する必要があります。
- テスト ネットワークの DNS を、 **[Compute and Network] \(コンピューティングとネットワーク)** 設定で DNS VM に指定した IP アドレスで更新します。 詳細については、[Active Directory 用のテスト フェールオーバーの考慮事項](site-recovery-active-directory.md#test-failover-considerations)を参照してください。
## <a name="test-failover-to-a-production-network-in-the-recovery-site"></a>復旧サイトの運用ネットワークへのテスト フェールオーバー
運用ネットワークから分離されたテスト ネットワークを使用することをお勧めしますが、運用ネットワークへのディザスター リカバリー ドリルをテストする必要がある場合は、次のことに注意してください。
- テスト フェールオーバーを実行するときは、プライマリ VM がシャットダウンされていることを確認します。 そうしないと、同じ ID を持つ 2 つの仮想マシンが同じネットワークで同時に実行されることになります。 これは、予期しない結果につながる可能性があります。
- テスト フェールオーバー用に作成された VM の変更は、フェールオーバーをクリーンアップすると失われます。 これらの変更は、プライマリ VM にはレプリケートされません。
- 運用環境でのテストは、運用アプリケーションのダウンタイムにつながります。 テスト フェールオーバーの進行中に、ユーザーは、VM で実行中のアプリを使用しないでください。
## <a name="prepare-active-directory-and-dns"></a>Active Directory と DNS の準備
アプリケーションのテストのためにテスト フェールオーバーを実行するには、テスト環境内に Active Directory 運用環境のコピーが必要です。 詳細については、[Active Directory のテスト フェールオーバーの考慮事項](site-recovery-active-directory.md#test-failover-considerations)を参照してください。
## <a name="prepare-to-connect-to-azure-vms-after-failover"></a>フェールオーバー後に Azure VM に接続するための準備をする
フェールオーバー後に RDP/SSH を使用して Azure VM に接続する場合は、表にまとめられている要件に従います。
**[フェールオーバー]** | **場所** | **アクション**
--- | --- | ---
**Windows で実行中の Azure VM** | フェールオーバー前のオンプレミスのコンピューター | インターネット経由で Azure VM にアクセスするには、RDP を有効にし、TCP と UDP の規則が **[パブリック]** に追加されていることを確認し、 **[Windows ファイアウォール]** > **[許可されたアプリ]** のすべてのプロファイルで RDP が許可されていることを確認します。<br/><br/> サイト間接続で Azure VM にアクセスするには、コンピューターで RDP を有効にし、 **[Windows ファイアウォール]** -> **[許可されたアプリおよび機能]** の **[ドメイン] と [プライベート]** ネットワークで RDP が許可されていることを確認します。<br/><br/> オペレーティング システムの SAN ポリシーが **[OnlineAll]** に設定されていることを確認します。 [詳細については、こちらを参照してください](https://support.microsoft.com/kb/3031135)。<br/><br/> フェールオーバーを開始する際は、実行待ちの Windows Update が VM にないことを確認してください。 フェールオーバーの実行時に Windows Update が開始された場合、更新が完了するまで VM にログインできなくなります。
**Windows で実行中の Azure VM** | フェールオーバー後に Azure VM で | VM の[パブリック IP アドレスを追加](https://aka.ms/addpublicip)します。<br/><br/> フェールオーバーされる VM (およびその接続先となる Azure サブネット) は、そのネットワーク セキュリティ グループの規則で、RDP ポートへの受信接続を許可する必要があります。<br/><br/> **[ブート診断]** をオンにして、VM のスクリーンショットを確認します。<br/><br/> 接続できない場合は、VM が実行中であることを確認したうえで、[トラブルシューティングのヒント](https://social.technet.microsoft.com/wiki/contents/articles/31666.troubleshooting-remote-desktop-connection-after-failover-using-asr.aspx)を確認してください。
**Linux で実行中の Azure VM** | フェールオーバー前のオンプレミスのコンピューター | VM 上の Secure Shell サービスがシステム起動時に自動的に開始されるよう設定されていることを確認します。<br/><br/> ファイアウォール規則で SSH 接続が許可されていることを確認します。
**Linux で実行中の Azure VM** | フェールオーバー後に Azure VM で | フェールオーバーされた VM (および接続先の Azure サブネット) のネットワーク セキュリティ グループの規則で、SSH ポートへの着信接続を許可する必要があります。<br/><br/> VM の[パブリック IP アドレスを追加](https://aka.ms/addpublicip)します。<br/><br/> VM のスクリーンショットを得るために、 **[ブート診断]** をオンにします。<br/><br/>
フェールオーバー後の接続の問題をトラブルシューティングするには、[ここ](site-recovery-failover-to-azure-troubleshoot.md)で説明されている手順に従ってください。
## <a name="next-steps"></a>次のステップ
ディザスター リカバリー ドリルが完了したら、他の種類の[フェールオーバー](site-recovery-failover.md)について学習します。
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
use strict;
my @del_macos_files;
my @bad_cpp;
my @test_main;
my @makefiles;
my @autogen_cpp;
my $cleaned = 1;
my $dist_archives_exist = 0;
my @bad_h;
open EVERYTHING,'find . -type d \( -name docs \) -prune -o -type f |' or die "Can't open find for file listing";
my %exclude_from_memtest_checks = ('PollEmulator.cpp'=>1,'DebugMemLeakFinder.cpp'=>1,'MemLeakFinder.h'=>1,'MemLeakFindOn.h'=>1,'MemLeakFindOff.h'=>1,'Box.h'=>1);
while(<EVERYTHING>)
{
chomp;
next if -d;
if(m~/autogen_\w+\.(h|cpp)~)
{
push @autogen_cpp,$_
}
if(m~/\._[^/]+\Z~ || m~/\.DS_Store\Z~)
{
# mac OS files we don't want
push @del_macos_files,$_
}
elsif(m/\/(\w+\.cpp)/)
{
my $leafname = $1;
# check that Box.h is first include
open CPP,$_ or die "Can't open $_ for reading";
my $box_found = 0;
my $last_was_memteston = 0;
my $ok = 1;
while(my $l = <CPP>)
{
if($l =~ m/#include\s+["<](.+?)[">]/)
{
my $inc_name = $1;
if($inc_name eq 'Box.h')
{
$box_found = 1;
}
else
{
# Box.h must be first include file in every cpp file
$ok = 0 unless $box_found;
}
# is it the mem test on thing? (ignoring the wire packing .h files)
if($inc_name ne 'BeginStructPackForWire.h' && $inc_name ne 'EndStructPackForWire.h')
{
$last_was_memteston = ($inc_name eq 'MemLeakFindOn.h');
}
}
}
if(!exists $exclude_from_memtest_checks{$leafname})
{
$ok = 0 unless $last_was_memteston;
}
push @bad_cpp,$_ unless $ok;
close CPP;
}
elsif(m/\/(\w+\.h)/)
{
my $leafname = $1;
open H,$_ or die "Can't open $_ for reading";
my $ok = 1;
my $memteston = 0;
while(my $l = <H>)
{
if($l =~ m/#include\s+["<](.+?)[">]/)
{
if($1 eq 'MemLeakFindOn.h')
{
$memteston = 1;
}
elsif($1 eq 'MemLeakFindOff.h')
{
$memteston = 0;
}
else
{
# don't allow #include within mem test on
$ok = 0 unless !$memteston;
}
}
else
{
# strip comments
my $lsc = $l;
$lsc =~ s~//.+$~~;
if($lsc =~ m/\b(new|delete|malloc|free|realloc)\b/)
{
# only allow this if memory checking is ON
$ok = 0 unless $memteston;
}
}
}
# mem test must be off at the end of this .h file
$ok = 0 if $memteston;
if($_ !~ /testfiles/ && !exists $exclude_from_memtest_checks{$leafname})
{
push @bad_h,$_ unless $ok;
}
close H;
}
elsif(m~/Makefile\Z~)
{
push @makefiles,$_
}
if(m~/_(main\.cpp|t|t-gdb)\Z~)
{
push @test_main,$_
}
if(m~\./boxbackup~)
{
$dist_archives_exist = 1;
}
}
close EVERYTHING;
ask_about_delete(\@del_macos_files, "supurious MacOS X files");
ask_about_delete(\@makefiles, "automatically generated Makefiles");
ask_about_delete(\@test_main, "automatically generated test files");
ask_about_delete(\@autogen_cpp, "automatically generated source files");
if($#bad_cpp >= 0)
{
print "\n";
print $_,"\n" for @bad_cpp;
print "There are some .cpp file where Box.h is not the first included file or MemLeakFindOn.h is not the last .h file included\n";
$cleaned = 0;
}
if($#bad_h >= 0)
{
print "\n";
print $_,"\n" for @bad_h;
print "There are some .h files which use memory functions without memory leak finding on, or leave memory leak finding on at end\n";
$cleaned = 0;
}
if(-d 'debug') {print "debug directory exists\n"; $cleaned = 0;}
if(-d 'release') {print "release directory exists\n"; $cleaned = 0;}
if(-d 'parcels') {print "parcels directory exists\n"; $cleaned = 0;}
if($dist_archives_exist) {print "boxbackup* files/dirs exist\n"; $cleaned = 0;}
if(!$cleaned)
{
print <<__E;
========================================================
NOT CLEANED!
========================================================
__E
}
sub ask_about_delete
{
my ($del_r, $name) = @_;
return if $#$del_r < 0;
print "\n";
for(@$del_r)
{
print $_,"\n";
}
print "Delete these ",$#$del_r + 1, " $name? ";
my $in = <STDIN>;
chomp $in;
if($in eq 'yes')
{
print "Deleting...\n";
unlink $_ for @$del_r
}
else
{
$cleaned = 0;
}
}
| {
"pile_set_name": "Github"
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<configuration
xmlns="urn:activemq"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:activemq ../../main/resources/schema/artemis-server.xsd">
<core xmlns="urn:activemq:core">
<store>
<database-store>
<jdbc-connection-url>jdbc:derby:target/derby/database-store;create=true</jdbc-connection-url>
<jdbc-user>ENC(5493dd76567ee5ec269d11823973462f)</jdbc-user>
<jdbc-password>ENC(56a0db3b71043054269d11823973462f)</jdbc-password>
<bindings-table-name>BINDINGS_TABLE</bindings-table-name>
<message-table-name>MESSAGE_TABLE</message-table-name>
<large-message-table-name>LARGE_MESSAGE_TABLE</large-message-table-name>
<page-store-table-name>PAGE_STORE_TABLE</page-store-table-name>
<jdbc-driver-class-name>org.apache.derby.jdbc.EmbeddedDriver</jdbc-driver-class-name>
</database-store>
</store>
</core>
</configuration>
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSECORE_MODULE_H
#define EIGEN_SPARSECORE_MODULE_H
#include "Core"
#include "src/Core/util/DisableStupidWarnings.h"
#include <vector>
#include <map>
#include <cstdlib>
#include <cstring>
#include <algorithm>
/**
* \defgroup SparseCore_Module SparseCore module
*
* This module provides a sparse matrix representation, and basic associated matrix manipulations
* and operations.
*
* See the \ref TutorialSparse "Sparse tutorial"
*
* \code
* #include <Eigen/SparseCore>
* \endcode
*
* This module depends on: Core.
*/
#include "src/SparseCore/SparseUtil.h"
#include "src/SparseCore/SparseMatrixBase.h"
#include "src/SparseCore/SparseAssign.h"
#include "src/SparseCore/CompressedStorage.h"
#include "src/SparseCore/AmbiVector.h"
#include "src/SparseCore/SparseCompressedBase.h"
#include "src/SparseCore/SparseMatrix.h"
#include "src/SparseCore/SparseMap.h"
#include "src/SparseCore/MappedSparseMatrix.h"
#include "src/SparseCore/SparseVector.h"
#include "src/SparseCore/SparseRef.h"
#include "src/SparseCore/SparseCwiseUnaryOp.h"
#include "src/SparseCore/SparseCwiseBinaryOp.h"
#include "src/SparseCore/SparseTranspose.h"
#include "src/SparseCore/SparseBlock.h"
#include "src/SparseCore/SparseDot.h"
#include "src/SparseCore/SparseRedux.h"
#include "src/SparseCore/SparseView.h"
#include "src/SparseCore/SparseDiagonalProduct.h"
#include "src/SparseCore/ConservativeSparseSparseProduct.h"
#include "src/SparseCore/SparseSparseProductWithPruning.h"
#include "src/SparseCore/SparseProduct.h"
#include "src/SparseCore/SparseDenseProduct.h"
#include "src/SparseCore/SparseSelfAdjointView.h"
#include "src/SparseCore/SparseTriangularView.h"
#include "src/SparseCore/TriangularSolver.h"
#include "src/SparseCore/SparsePermutation.h"
#include "src/SparseCore/SparseFuzzy.h"
#include "src/SparseCore/SparseSolverBase.h"
#include "src/Core/util/ReenableStupidWarnings.h"
#endif // EIGEN_SPARSECORE_MODULE_H
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="sl_SI">
<context>
<name>Backend</name>
<message>
<location filename="../TarBackend.cpp" line="243"/>
<source>Could not read archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../TarBackend.cpp" line="245"/>
<source>Archive Loaded</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../TarBackend.cpp" line="278"/>
<source>Extraction Finished</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../TarBackend.cpp" line="280"/>
<source>Modification Finished</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainUI</name>
<message>
<location filename="../MainUI.ui" line="35"/>
<source>Archive:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="69"/>
<location filename="../MainUI.cpp" line="331"/>
<source>File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="125"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="134"/>
<source>&Edit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="145"/>
<source>&Burn to Disk</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="178"/>
<source>&Open Archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="181"/>
<source>Open archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="186"/>
<source>&New Archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="189"/>
<source>New archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="194"/>
<source>&Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="199"/>
<source>Add File(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="202"/>
<source>Add files to archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="207"/>
<source>Remove File(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="210"/>
<source>Remove selection from archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="215"/>
<source>Extract All</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="218"/>
<source>Extract archive into a directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="223"/>
<source>Add Directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="226"/>
<source>Add directory to archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="231"/>
<source>Extract Selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="234"/>
<source>Extract Selected Items</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="239"/>
<source>USB Image</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="242"/>
<source>Copy an IMG to a USB device (may require admin permission)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="28"/>
<source>Archive Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="29"/>
<source>Admin Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="55"/>
<source>CTRL+N</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="56"/>
<source>CTRL+O</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="57"/>
<source>CTRL+Q</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="58"/>
<source>CTRL+E</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="69"/>
<location filename="../MainUI.cpp" line="331"/>
<source>MimeType</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="69"/>
<location filename="../MainUI.cpp" line="331"/>
<source>Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="94"/>
<location filename="../MainUI.cpp" line="236"/>
<source>Opening Archive...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="180"/>
<source>All Types %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="181"/>
<location filename="../MainUI.cpp" line="199"/>
<source>Uncompressed Archive (*.tar)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="182"/>
<location filename="../MainUI.cpp" line="200"/>
<source>GZip Compressed Archive (*.tar.gz *.tgz)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="183"/>
<location filename="../MainUI.cpp" line="201"/>
<source>BZip Compressed Archive (*.tar.bz *.tbz)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="184"/>
<location filename="../MainUI.cpp" line="202"/>
<source>BZip2 Compressed Archive (*.tar.bz2 *.tbz2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="185"/>
<location filename="../MainUI.cpp" line="204"/>
<source>LMZA Compressed Archive (*.tar.lzma *.tlz)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="186"/>
<location filename="../MainUI.cpp" line="203"/>
<source>XZ Compressed Archive (*.tar.xz *.txz)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="187"/>
<location filename="../MainUI.cpp" line="205"/>
<source>CPIO Archive (*.cpio)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="188"/>
<location filename="../MainUI.cpp" line="206"/>
<source>PAX Archive (*.pax)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="189"/>
<location filename="../MainUI.cpp" line="207"/>
<source>AR Archive (*.ar)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="190"/>
<location filename="../MainUI.cpp" line="208"/>
<source>SHAR Archive (*.shar)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="191"/>
<location filename="../MainUI.cpp" line="209"/>
<source>Zip Archive (*.zip)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="192"/>
<location filename="../MainUI.cpp" line="210"/>
<source>7-Zip Archive (*.7z)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="198"/>
<source>All Known Types %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="211"/>
<source>READ-ONLY: ISO image (*.iso *.img)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="212"/>
<source>READ-ONLY: XAR archive (*.xar)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="213"/>
<source>READ-ONLY: Java archive (*.jar)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="214"/>
<source>READ-ONLY: RedHat Package (*.rpm)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="215"/>
<source>Show All Files (*)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="223"/>
<source>Create Archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="226"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="226"/>
<source>Could not overwrite file:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="234"/>
<source>Open Archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="242"/>
<location filename="../MainUI.cpp" line="249"/>
<source>Add to Archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="244"/>
<location filename="../MainUI.cpp" line="251"/>
<location filename="../MainUI.cpp" line="300"/>
<source>Adding Items...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="262"/>
<source>Removing Items...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="267"/>
<location filename="../MainUI.cpp" line="311"/>
<source>Extract Into Directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="269"/>
<location filename="../MainUI.cpp" line="287"/>
<location filename="../MainUI.cpp" line="294"/>
<location filename="../MainUI.cpp" line="313"/>
<location filename="../MainUI.cpp" line="325"/>
<source>Extracting...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="345"/>
<source>Link To: %1</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>XDGDesktopList</name>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/>
<source>Multimedia</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/>
<source>Development</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/>
<source>Education</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/>
<source>Games</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/>
<source>Graphics</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/>
<source>Office</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/>
<source>Science</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/>
<source>System</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
<source>Utility</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
<source>Wine</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
<source>Unsorted</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>imgDialog</name>
<message>
<location filename="../imgDialog.ui" line="14"/>
<source>Burn IMG to device</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="29"/>
<source>IMG File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="54"/>
<source>Block Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="84"/>
<source>USB Device</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="96"/>
<source>Refresh Device List</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="108"/>
<source>Wipe all extra space on device (conv = sync)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="132"/>
<source>Burning to USB:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="166"/>
<source>Time Elapsed:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="222"/>
<source>Cancel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.ui" line="229"/>
<source>Start</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="21"/>
<source>Burn IMG to Device</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="22"/>
<source>Admin Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="36"/>
<source>Kilobyte(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="37"/>
<source>Megabyte(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="38"/>
<source>Gigabyte(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="110"/>
<source>Cancel Image Burn?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="110"/>
<source>Do you wish to stop the current IMG burn process?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="110"/>
<source>Warning: This will leave the USB device in an inconsistent state</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="170"/>
<source>Administrator Permissions Needed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="170"/>
<source>This operation requires administrator priviledges.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="170"/>
<source>Would you like to enable these priviledges?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="175"/>
<source>ERROR</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="175"/>
<source>The process could not be completed:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="178"/>
<source>SUCCESS</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../imgDialog.cpp" line="178"/>
<source>The image was successfully burned to the USB device</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| {
"pile_set_name": "Github"
} |
/* Flot plugin for stacking data sets rather than overlyaing them.
Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin assumes the data is sorted on x (or y if stacking horizontally).
For line charts, it is assumed that if a line has an undefined gap (from a
null point), then the line above it should have the same gap - insert zeros
instead of "null" if you want another behaviour. This also holds for the start
and end of the chart. Note that stacking a mix of positive and negative values
in most instances doesn't make sense (so it looks weird).
Two or more series are stacked when their "stack" attribute is set to the same
key (which can be any number or string or just "true"). To specify the default
stack, you can set the stack option like this:
series: {
stack: null/false, true, or a key (number/string)
}
You can also specify it for a single series, like this:
$.plot( $("#placeholder"), [{
data: [ ... ],
stack: true
}])
The stacking order is determined by the order of the data series in the array
(later series end up on top of the previous).
Internally, the plugin modifies the datapoints in each series, adding an
offset to the y value. For line series, extra data points are inserted through
interpolation. If there's a second y value, it's also adjusted (e.g for bar
charts or filled areas).
*/
(function ($) {
var options = {
series: { stack: null } // or number/string
};
function init(plot) {
function findMatchingSeries(s, allseries) {
var res = null;
for (var i = 0; i < allseries.length; ++i) {
if (s == allseries[i])
break;
if (allseries[i].stack == s.stack)
res = allseries[i];
}
return res;
}
function stackData(plot, s, datapoints) {
if (s.stack == null || s.stack === false)
return;
var other = findMatchingSeries(s, plot.getData());
if (!other)
return;
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
horizontal = s.bars.horizontal,
withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y),
withsteps = withlines && s.lines.steps,
fromgap = true,
keyOffset = horizontal ? 1 : 0,
accumulateOffset = horizontal ? 0 : 1,
i = 0, j = 0, l, m;
while (true) {
if (i >= points.length)
break;
l = newpoints.length;
if (points[i] == null) {
// copy gaps
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
i += ps;
}
else if (j >= otherpoints.length) {
// for lines, we can't use the rest of the points
if (!withlines) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
}
i += ps;
}
else if (otherpoints[j] == null) {
// oops, got a gap
for (m = 0; m < ps; ++m)
newpoints.push(null);
fromgap = true;
j += otherps;
}
else {
// cases where we actually got two points
px = points[i + keyOffset];
py = points[i + accumulateOffset];
qx = otherpoints[j + keyOffset];
qy = otherpoints[j + accumulateOffset];
bottom = 0;
if (px == qx) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
newpoints[l + accumulateOffset] += qy;
bottom = qy;
i += ps;
j += otherps;
}
else if (px > qx) {
// we got past point below, might need to
// insert interpolated extra point
if (withlines && i > 0 && points[i - ps] != null) {
intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px);
newpoints.push(qx);
newpoints.push(intery + qy);
for (m = 2; m < ps; ++m)
newpoints.push(points[i + m]);
bottom = qy;
}
j += otherps;
}
else { // px < qx
if (fromgap && withlines) {
// if we come from a gap, we just skip this point
i += ps;
continue;
}
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
// we might be able to interpolate a point below,
// this can give us a better y
if (withlines && j > 0 && otherpoints[j - otherps] != null)
bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx);
newpoints[l + accumulateOffset] += bottom;
i += ps;
}
fromgap = false;
if (l != newpoints.length && withbottom)
newpoints[l + 2] += bottom;
}
// maintain the line steps invariant
if (withsteps && l != newpoints.length && l > 0
&& newpoints[l] != null
&& newpoints[l] != newpoints[l - ps]
&& newpoints[l + 1] != newpoints[l - ps + 1]) {
for (m = 0; m < ps; ++m)
newpoints[l + ps + m] = newpoints[l + m];
newpoints[l + 1] = newpoints[l - ps + 1];
}
}
datapoints.points = newpoints;
}
plot.hooks.processDatapoints.push(stackData);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'stack',
version: '1.2'
});
})(jQuery);
| {
"pile_set_name": "Github"
} |
.. Copyright (c) 2016, Ruslan Baratov
.. All rights reserved.
Executables
===========
.. admonition:: Examples on GitHub
* `Repository <https://github.com/cgold-examples/executable-examples>`__
* `Latest ZIP <https://github.com/cgold-examples/executable-examples/archive/master.zip>`__
.. admonition:: CMake documentation
* `add_executable <https://cmake.org/cmake/help/latest/command/add_executable.html>`__
Simple
------
Building executable from ``main.cpp``:
.. literalinclude:: /examples/executable-examples/simple/CMakeLists.txt
:language: cmake
:emphasize-lines: 4
.. code-block:: none
:emphasize-lines: 2, 20
[executable-examples]> rm -rf _builds
[executable-examples]> cmake -Hsimple -B_builds
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /.../executable-examples/_builds
[executable-examples]> cmake --build _builds
Scanning dependencies of target foo
[ 50%] Building CXX object CMakeFiles/foo.dir/main.cpp.o
[100%] Linking CXX executable foo
[100%] Built target foo
.. code-block:: none
:emphasize-lines: 2
[executable-examples]> ./_builds/foo
Hello from CGold!
.. _target duplicates:
Duplicates
----------
Targets are global, you can't declare two targets with the same name even
if they are declared in different ``CMakeLists.txt``:
.. literalinclude:: /examples/executable-examples/duplicates/CMakeLists.txt
:language: cmake
:emphasize-lines: 6-7
.. literalinclude:: /examples/executable-examples/duplicates/boo/CMakeLists.txt
:language: cmake
:emphasize-lines: 3
.. literalinclude:: /examples/executable-examples/duplicates/bar/CMakeLists.txt
:language: cmake
:emphasize-lines: 3
.. code-block:: none
:emphasize-lines: 2, 17-22
[examples]> rm -rf _builds
[examples]> cmake -Hexecutable-examples/duplicates -B_builds
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Error at bar/CMakeLists.txt:1 (add_executable):
add_executable cannot create target "foo" because another target with the
same name already exists. The existing target is an executable created in
source directory
"/.../executable-examples/duplicates/boo".
See documentation for policy CMP0002 for more details.
| {
"pile_set_name": "Github"
} |
import * as XP from 'xod-project';
import { getSwaggerClient, swaggerError } from './utils';
import { createLibUri, toString, toStringWithoutTag } from './lib-uri';
const packLibVersion = project => ({
libname: XP.getProjectName(project),
version: {
description: XP.getProjectDescription(project),
folder: { 'xodball.json': XP.toXodball(project) },
semver: `v${XP.getProjectVersion(project)}`,
},
});
export default function publish(swaggerUrl, grant, project) {
return getSwaggerClient(swaggerUrl).then(swagger => {
const { Library, Organization, User, Version } = swagger.apis;
// eslint-disable-next-line no-param-reassign
swagger.authorizations = {
bearer_token: `Bearer ${grant.accessToken}`,
};
const { username } = grant.user;
const orgname = username;
const { libname, version } = packLibVersion(project);
const libUri = createLibUri(orgname, libname, version.semver);
return Organization.getOrg({ orgname })
.catch(err => {
if (err.status !== 404) throw swaggerError(err);
return User.putUserOrg({ org: {}, orgname, username }).catch(err2 => {
if (err2.status === 403) {
throw new Error(`user "${username}" is not registered.`);
}
if (err2.status === 409) {
throw new Error(`orgname "${orgname}" is already taken.`);
}
throw swaggerError(err2);
});
})
.then(() =>
Library.getOrgLib({ libname, orgname }).catch(err => {
if (err.status !== 404) throw swaggerError(err);
return Library.putOrgLib({ lib: {}, libname, orgname }).catch(
err2 => {
if (err2.status === 403) {
throw new Error(
`user "${username}" can't access ${toStringWithoutTag(
libUri
)}.`
);
}
throw swaggerError(err2);
}
);
})
)
.then(() =>
Version.postLibVersion({ libname, orgname, version }).catch(err => {
if (err.status === 409) {
throw new Error(`version "${toString(libUri)}" already exists.`);
}
throw swaggerError(err);
})
);
});
}
| {
"pile_set_name": "Github"
} |
import React from 'react'
import connect from 'redux-connect-decorator'
import config from '@Config'
import styles from '@Styles'
import t from '@Localize'
import HeaderButton from '@Components/HeaderButton'
import Post from '@Components/Post'
import { fetchUserInfo, fetchTimeline, refreshTimeline, loadMoreTimeline, setModalVisibleStatus } from '@Store/Actions'
import {
View,
Text,
Animated,
Easing,
FlatList,
StyleSheet,
TouchableOpacity,
ActivityIndicator
} from 'react-native'
@connect(state => ({
timeline: state.home.timeline
}), {
setModalVisibleStatus,
fetchUserInfo,
fetchTimeline,
refreshTimeline,
loadMoreTimeline
})
export default class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state
const onPressRightButtonFunc = params.openPublisher || function() {}
return {
...config.defaultNavigation,
title: t('global.home'),
headerRight: (
<HeaderButton
icon='feedback'
onPressButton={ onPressRightButtonFunc }/>
)
}
}
constructor(props) {
super(props)
this.state = {
refreshing: false,
loading: false,
loadedEnd: false,
loadResultOpacity: new Animated.Value(0),
}
this.fadeInAnimated = Animated.timing(
this.state.loadResultOpacity,
{
toValue: 1,
duration: 800,
easing: Easing.linear,
}
)
this.fadeOutAnimated = Animated.timing(
this.state.loadResultOpacity,
{
toValue: 0,
duration: 800,
easing: Easing.linear,
}
)
}
componentDidMount () {
this.setState({
refreshing: true
})
this.props.navigation.setParams({ openPublisher: () => this.openPublisher() })
this.props.fetchUserInfo()
this.props.fetchTimeline().then(_ => {
this.setState({
refreshing: false
})
})
}
_renderItem({ item }) {
return (
<TouchableOpacity activeOpacity={0.7} onPress={_ => { this.navToPost(item) }}>
<Post post={item}/>
</TouchableOpacity>
)
}
_keyExtractor(item, index) {
return item.id
}
render() {
return (
<View style={viewStyles.container}>
<FlatList
contentContainerStyle={{ paddingBottom: 10 }}
keyExtractor={this._keyExtractor}
data={this.props.timeline}
renderItem={this._renderItem.bind(this)}
onRefresh={this._onRefresh.bind(this)}
onEndReached= {this._onEndReached.bind(this)}
refreshing={this.state.refreshing}
/>
<Animated.View style={ { opacity: this.state.loadResultOpacity } }>
<Text style={viewStyles.loadResultContainer}>{ t('home.noMorePost') }</Text>
</Animated.View>
</View>
)
}
openPublisher() {
this.props.setModalVisibleStatus({
name: 'publisher',
status: true
})
}
navToPost(item) {
this.props.navigation.navigate('Post', { mid: item.id })
}
_onRefresh() {
this.setState({
refreshing: true
})
if (this.props.timeline[0].id >= 48) {
this._showLoadResultContainer()
this.setState({
refreshing: false
})
} else {
this.props.refreshTimeline().then(_ => {
this.setState({
refreshing: false
})
})
}
}
_onEndReached() {
if (this.state.loading) return false
if (this.props.timeline[this.props.timeline.length - 1].id <= 24) {
this.setState({
loadedEnd: true
})
return false
} else {
this.setState({
loading: true
})
this.props.loadMoreTimeline().then(_ => {
this.setState({
loading: false
})
})
}
}
_showLoadResultContainer() {
this.fadeInAnimated.start(_ => setTimeout(_ => {
this.fadeOutAnimated.start()
}, 1500))
}
}
const viewStyles = StyleSheet.create({
container: {
...styles.container,
paddingTop: 5
},
loadResultContainer: {
width: '100%',
position: 'absolute',
bottom: 0,
backgroundColor: config.mainColor,
height: 30,
lineHeight: 30,
textAlign: 'center',
color: '#fff',
fontSize: 13
},
listFooter: {
height: 40,
justifyContent: 'center',
alignItems: 'center'
}
})
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2011-2012 Freescale Semiconductor, Inc.
*
* SPDX-License-Identifier: GPL-2.0+
*/
/*
* T4240 QDS board configuration file
*/
#ifndef __CONFIG_H
#define __CONFIG_H
#define CONFIG_FSL_SATA_V2
#define CONFIG_PCIE4
#define CONFIG_ICS307_REFCLK_HZ 25000000 /* ICS307 ref clk freq */
#ifdef CONFIG_RAMBOOT_PBL
#define CONFIG_SYS_FSL_PBL_PBI board/freescale/t4qds/t4_pbi.cfg
#if !defined(CONFIG_NAND) && !defined(CONFIG_SDCARD)
#define CONFIG_RAMBOOT_TEXT_BASE CONFIG_SYS_TEXT_BASE
#define CONFIG_RESET_VECTOR_ADDRESS 0xfffffffc
#else
#define CONFIG_SPL_FLUSH_IMAGE
#define CONFIG_SPL_TARGET "u-boot-with-spl.bin"
#define CONFIG_SYS_TEXT_BASE 0x00201000
#define CONFIG_SPL_TEXT_BASE 0xFFFD8000
#define CONFIG_SPL_PAD_TO 0x40000
#define CONFIG_SPL_MAX_SIZE 0x28000
#define RESET_VECTOR_OFFSET 0x27FFC
#define BOOT_PAGE_OFFSET 0x27000
#ifdef CONFIG_NAND
#define CONFIG_SYS_NAND_U_BOOT_SIZE (768 << 10)
#define CONFIG_SYS_NAND_U_BOOT_DST 0x00200000
#define CONFIG_SYS_NAND_U_BOOT_START 0x00200000
#define CONFIG_SYS_NAND_U_BOOT_OFFS (256 << 10)
#define CONFIG_SYS_LDSCRIPT "arch/powerpc/cpu/mpc85xx/u-boot-nand.lds"
#define CONFIG_SYS_FSL_PBL_RCW board/freescale/t4qds/t4_nand_rcw.cfg
#define CONFIG_SPL_NAND_BOOT
#endif
#ifdef CONFIG_SDCARD
#define CONFIG_RESET_VECTOR_ADDRESS 0x200FFC
#define CONFIG_SPL_MMC_MINIMAL
#define CONFIG_SYS_MMC_U_BOOT_SIZE (768 << 10)
#define CONFIG_SYS_MMC_U_BOOT_DST 0x00200000
#define CONFIG_SYS_MMC_U_BOOT_START 0x00200000
#define CONFIG_SYS_MMC_U_BOOT_OFFS (260 << 10)
#ifndef CONFIG_SPL_BUILD
#define CONFIG_SYS_MPC85XX_NO_RESETVEC
#endif
#define CONFIG_SYS_LDSCRIPT "arch/powerpc/cpu/mpc85xx/u-boot.lds"
#define CONFIG_SYS_FSL_PBL_RCW board/freescale/t4qds/t4_sd_rcw.cfg
#define CONFIG_SPL_MMC_BOOT
#endif
#ifdef CONFIG_SPL_BUILD
#define CONFIG_SPL_SKIP_RELOCATE
#define CONFIG_SPL_COMMON_INIT_DDR
#define CONFIG_SYS_CCSR_DO_NOT_RELOCATE
#endif
#endif
#endif /* CONFIG_RAMBOOT_PBL */
#ifdef CONFIG_SRIO_PCIE_BOOT_SLAVE
/* Set 1M boot space */
#define CONFIG_SYS_SRIO_PCIE_BOOT_SLAVE_ADDR (CONFIG_SYS_TEXT_BASE & 0xfff00000)
#define CONFIG_SYS_SRIO_PCIE_BOOT_SLAVE_ADDR_PHYS \
(0x300000000ull | CONFIG_SYS_SRIO_PCIE_BOOT_SLAVE_ADDR)
#define CONFIG_RESET_VECTOR_ADDRESS 0xfffffffc
#endif
#define CONFIG_SRIO_PCIE_BOOT_MASTER
#define CONFIG_DDR_ECC
#include "t4qds.h"
#ifndef CONFIG_MTD_NOR_FLASH
#if !defined(CONFIG_SRIO_PCIE_BOOT_SLAVE) && !defined(CONFIG_RAMBOOT_PBL)
#define CONFIG_ENV_IS_NOWHERE
#endif
#else
#define CONFIG_FLASH_CFI_DRIVER
#define CONFIG_SYS_FLASH_CFI
#define CONFIG_SYS_FLASH_USE_BUFFER_WRITE
#endif
#if defined(CONFIG_SPIFLASH)
#define CONFIG_SYS_EXTRA_ENV_RELOC
#define CONFIG_ENV_IS_IN_SPI_FLASH
#define CONFIG_ENV_SPI_BUS 0
#define CONFIG_ENV_SPI_CS 0
#define CONFIG_ENV_SPI_MAX_HZ 10000000
#define CONFIG_ENV_SPI_MODE 0
#define CONFIG_ENV_SIZE 0x2000 /* 8KB */
#define CONFIG_ENV_OFFSET 0x100000 /* 1MB */
#define CONFIG_ENV_SECT_SIZE 0x10000
#elif defined(CONFIG_SDCARD)
#define CONFIG_SYS_EXTRA_ENV_RELOC
#define CONFIG_ENV_IS_IN_MMC
#define CONFIG_SYS_MMC_ENV_DEV 0
#define CONFIG_ENV_SIZE 0x2000
#define CONFIG_ENV_OFFSET (512 * 0x800)
#elif defined(CONFIG_NAND)
#define CONFIG_SYS_EXTRA_ENV_RELOC
#define CONFIG_ENV_IS_IN_NAND
#define CONFIG_ENV_SIZE 0x2000
#define CONFIG_ENV_OFFSET (10 * CONFIG_SYS_NAND_BLOCK_SIZE)
#elif defined(CONFIG_SRIO_PCIE_BOOT_SLAVE)
#define CONFIG_ENV_IS_IN_REMOTE
#define CONFIG_ENV_ADDR 0xffe20000
#define CONFIG_ENV_SIZE 0x2000
#elif defined(CONFIG_ENV_IS_NOWHERE)
#define CONFIG_ENV_SIZE 0x2000
#else
#define CONFIG_ENV_IS_IN_FLASH
#define CONFIG_ENV_ADDR (CONFIG_SYS_MONITOR_BASE - CONFIG_ENV_SECT_SIZE)
#define CONFIG_ENV_SIZE 0x2000
#define CONFIG_ENV_SECT_SIZE 0x20000 /* 128K (one sector) */
#endif
#define CONFIG_SYS_CLK_FREQ get_board_sys_clk()
#define CONFIG_DDR_CLK_FREQ get_board_ddr_clk()
#ifndef __ASSEMBLY__
unsigned long get_board_sys_clk(void);
unsigned long get_board_ddr_clk(void);
#endif
/* EEPROM */
#define CONFIG_ID_EEPROM
#define CONFIG_SYS_I2C_EEPROM_NXID
#define CONFIG_SYS_EEPROM_BUS_NUM 0
#define CONFIG_SYS_I2C_EEPROM_ADDR 0x57
#define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 1
/*
* DDR Setup
*/
#define CONFIG_SYS_SPD_BUS_NUM 0
#define SPD_EEPROM_ADDRESS1 0x51
#define SPD_EEPROM_ADDRESS2 0x52
#define SPD_EEPROM_ADDRESS3 0x53
#define SPD_EEPROM_ADDRESS4 0x54
#define SPD_EEPROM_ADDRESS5 0x55
#define SPD_EEPROM_ADDRESS6 0x56
#define SPD_EEPROM_ADDRESS SPD_EEPROM_ADDRESS1 /* for p3041/p5010 */
#define CONFIG_SYS_SDRAM_SIZE 4096 /* for fixed parameter use */
/*
* IFC Definitions
*/
#define CONFIG_SYS_NOR0_CSPR_EXT (0xf)
#define CONFIG_SYS_NOR0_CSPR (CSPR_PHYS_ADDR(CONFIG_SYS_FLASH_BASE_PHYS \
+ 0x8000000) | \
CSPR_PORT_SIZE_16 | \
CSPR_MSEL_NOR | \
CSPR_V)
#define CONFIG_SYS_NOR1_CSPR_EXT (0xf)
#define CONFIG_SYS_NOR1_CSPR (CSPR_PHYS_ADDR(CONFIG_SYS_FLASH_BASE_PHYS) | \
CSPR_PORT_SIZE_16 | \
CSPR_MSEL_NOR | \
CSPR_V)
#define CONFIG_SYS_NOR_AMASK IFC_AMASK(128*1024*1024)
/* NOR Flash Timing Params */
#define CONFIG_SYS_NOR_CSOR CSOR_NAND_TRHZ_80
#define CONFIG_SYS_NOR_FTIM0 (FTIM0_NOR_TACSE(0x4) | \
FTIM0_NOR_TEADC(0x5) | \
FTIM0_NOR_TEAHC(0x5))
#define CONFIG_SYS_NOR_FTIM1 (FTIM1_NOR_TACO(0x35) | \
FTIM1_NOR_TRAD_NOR(0x1A) |\
FTIM1_NOR_TSEQRAD_NOR(0x13))
#define CONFIG_SYS_NOR_FTIM2 (FTIM2_NOR_TCS(0x4) | \
FTIM2_NOR_TCH(0x4) | \
FTIM2_NOR_TWPH(0x0E) | \
FTIM2_NOR_TWP(0x1c))
#define CONFIG_SYS_NOR_FTIM3 0x0
#define CONFIG_SYS_FLASH_QUIET_TEST
#define CONFIG_FLASH_SHOW_PROGRESS 45 /* count down from 45/5: 9..1 */
#define CONFIG_SYS_MAX_FLASH_BANKS 2 /* number of banks */
#define CONFIG_SYS_MAX_FLASH_SECT 1024 /* sectors per device */
#define CONFIG_SYS_FLASH_ERASE_TOUT 60000 /* Flash Erase Timeout (ms) */
#define CONFIG_SYS_FLASH_WRITE_TOUT 500 /* Flash Write Timeout (ms) */
#define CONFIG_SYS_FLASH_EMPTY_INFO
#define CONFIG_SYS_FLASH_BANKS_LIST {CONFIG_SYS_FLASH_BASE_PHYS \
+ 0x8000000, CONFIG_SYS_FLASH_BASE_PHYS}
#define CONFIG_FSL_QIXIS /* use common QIXIS code */
#define QIXIS_BASE 0xffdf0000
#define QIXIS_LBMAP_SWITCH 6
#define QIXIS_LBMAP_MASK 0x0f
#define QIXIS_LBMAP_SHIFT 0
#define QIXIS_LBMAP_DFLTBANK 0x00
#define QIXIS_LBMAP_ALTBANK 0x04
#define QIXIS_RST_CTL_RESET 0x83
#define QIXIS_RST_FORCE_MEM 0x1
#define QIXIS_RCFG_CTL_RECONFIG_IDLE 0x20
#define QIXIS_RCFG_CTL_RECONFIG_START 0x21
#define QIXIS_RCFG_CTL_WATCHDOG_ENBLE 0x08
#define QIXIS_BRDCFG5 0x55
#define QIXIS_MUX_SDHC 2
#define QIXIS_MUX_SDHC_WIDTH8 1
#define QIXIS_BASE_PHYS (0xf00000000ull | QIXIS_BASE)
#define CONFIG_SYS_CSPR3_EXT (0xf)
#define CONFIG_SYS_CSPR3 (CSPR_PHYS_ADDR(QIXIS_BASE_PHYS) \
| CSPR_PORT_SIZE_8 \
| CSPR_MSEL_GPCM \
| CSPR_V)
#define CONFIG_SYS_AMASK3 IFC_AMASK(4*1024)
#define CONFIG_SYS_CSOR3 0x0
/* QIXIS Timing parameters for IFC CS3 */
#define CONFIG_SYS_CS3_FTIM0 (FTIM0_GPCM_TACSE(0x0e) | \
FTIM0_GPCM_TEADC(0x0e) | \
FTIM0_GPCM_TEAHC(0x0e))
#define CONFIG_SYS_CS3_FTIM1 (FTIM1_GPCM_TACO(0xff) | \
FTIM1_GPCM_TRAD(0x3f))
#define CONFIG_SYS_CS3_FTIM2 (FTIM2_GPCM_TCS(0x0e) | \
FTIM2_GPCM_TCH(0x8) | \
FTIM2_GPCM_TWP(0x1f))
#define CONFIG_SYS_CS3_FTIM3 0x0
/* NAND Flash on IFC */
#define CONFIG_NAND_FSL_IFC
#define CONFIG_SYS_NAND_BASE 0xff800000
#define CONFIG_SYS_NAND_BASE_PHYS (0xf00000000ull | CONFIG_SYS_NAND_BASE)
#define CONFIG_SYS_NAND_CSPR_EXT (0xf)
#define CONFIG_SYS_NAND_CSPR (CSPR_PHYS_ADDR(CONFIG_SYS_NAND_BASE_PHYS) \
| CSPR_PORT_SIZE_8 /* Port Size = 8 bit */ \
| CSPR_MSEL_NAND /* MSEL = NAND */ \
| CSPR_V)
#define CONFIG_SYS_NAND_AMASK IFC_AMASK(64*1024)
#define CONFIG_SYS_NAND_CSOR (CSOR_NAND_ECC_ENC_EN /* ECC on encode */ \
| CSOR_NAND_ECC_DEC_EN /* ECC on decode */ \
| CSOR_NAND_ECC_MODE_4 /* 4-bit ECC */ \
| CSOR_NAND_RAL_3 /* RAL = 2Byes */ \
| CSOR_NAND_PGS_2K /* Page Size = 2K */ \
| CSOR_NAND_SPRZ_64/* Spare size = 64 */ \
| CSOR_NAND_PB(64)) /*Pages Per Block = 64*/
#define CONFIG_SYS_NAND_ONFI_DETECTION
/* ONFI NAND Flash mode0 Timing Params */
#define CONFIG_SYS_NAND_FTIM0 (FTIM0_NAND_TCCST(0x07) | \
FTIM0_NAND_TWP(0x18) | \
FTIM0_NAND_TWCHT(0x07) | \
FTIM0_NAND_TWH(0x0a))
#define CONFIG_SYS_NAND_FTIM1 (FTIM1_NAND_TADLE(0x32) | \
FTIM1_NAND_TWBE(0x39) | \
FTIM1_NAND_TRR(0x0e) | \
FTIM1_NAND_TRP(0x18))
#define CONFIG_SYS_NAND_FTIM2 (FTIM2_NAND_TRAD(0x0f) | \
FTIM2_NAND_TREH(0x0a) | \
FTIM2_NAND_TWHRE(0x1e))
#define CONFIG_SYS_NAND_FTIM3 0x0
#define CONFIG_SYS_NAND_DDR_LAW 11
#define CONFIG_SYS_NAND_BASE_LIST { CONFIG_SYS_NAND_BASE }
#define CONFIG_SYS_MAX_NAND_DEVICE 1
#define CONFIG_CMD_NAND
#define CONFIG_SYS_NAND_BLOCK_SIZE (128 * 1024)
#define CONFIG_SYS_NAND_MAX_OOBFREE 2
#define CONFIG_SYS_NAND_MAX_ECCPOS 256
#if defined(CONFIG_NAND)
#define CONFIG_SYS_CSPR0_EXT CONFIG_SYS_NAND_CSPR_EXT
#define CONFIG_SYS_CSPR0 CONFIG_SYS_NAND_CSPR
#define CONFIG_SYS_AMASK0 CONFIG_SYS_NAND_AMASK
#define CONFIG_SYS_CSOR0 CONFIG_SYS_NAND_CSOR
#define CONFIG_SYS_CS0_FTIM0 CONFIG_SYS_NAND_FTIM0
#define CONFIG_SYS_CS0_FTIM1 CONFIG_SYS_NAND_FTIM1
#define CONFIG_SYS_CS0_FTIM2 CONFIG_SYS_NAND_FTIM2
#define CONFIG_SYS_CS0_FTIM3 CONFIG_SYS_NAND_FTIM3
#define CONFIG_SYS_CSPR1_EXT CONFIG_SYS_NOR0_CSPR_EXT
#define CONFIG_SYS_CSPR1 CONFIG_SYS_NOR0_CSPR
#define CONFIG_SYS_AMASK1 CONFIG_SYS_NOR_AMASK
#define CONFIG_SYS_CSOR1 CONFIG_SYS_NOR_CSOR
#define CONFIG_SYS_CS1_FTIM0 CONFIG_SYS_NOR_FTIM0
#define CONFIG_SYS_CS1_FTIM1 CONFIG_SYS_NOR_FTIM1
#define CONFIG_SYS_CS1_FTIM2 CONFIG_SYS_NOR_FTIM2
#define CONFIG_SYS_CS1_FTIM3 CONFIG_SYS_NOR_FTIM3
#define CONFIG_SYS_CSPR2_EXT CONFIG_SYS_NOR1_CSPR_EXT
#define CONFIG_SYS_CSPR2 CONFIG_SYS_NOR1_CSPR
#define CONFIG_SYS_AMASK2 CONFIG_SYS_NOR_AMASK
#define CONFIG_SYS_CSOR2 CONFIG_SYS_NOR_CSOR
#define CONFIG_SYS_CS2_FTIM0 CONFIG_SYS_NOR_FTIM0
#define CONFIG_SYS_CS2_FTIM1 CONFIG_SYS_NOR_FTIM1
#define CONFIG_SYS_CS2_FTIM2 CONFIG_SYS_NOR_FTIM2
#define CONFIG_SYS_CS2_FTIM3 CONFIG_SYS_NOR_FTIM3
#else
#define CONFIG_SYS_CSPR0_EXT CONFIG_SYS_NOR0_CSPR_EXT
#define CONFIG_SYS_CSPR0 CONFIG_SYS_NOR0_CSPR
#define CONFIG_SYS_AMASK0 CONFIG_SYS_NOR_AMASK
#define CONFIG_SYS_CSOR0 CONFIG_SYS_NOR_CSOR
#define CONFIG_SYS_CS0_FTIM0 CONFIG_SYS_NOR_FTIM0
#define CONFIG_SYS_CS0_FTIM1 CONFIG_SYS_NOR_FTIM1
#define CONFIG_SYS_CS0_FTIM2 CONFIG_SYS_NOR_FTIM2
#define CONFIG_SYS_CS0_FTIM3 CONFIG_SYS_NOR_FTIM3
#define CONFIG_SYS_CSPR1_EXT CONFIG_SYS_NOR1_CSPR_EXT
#define CONFIG_SYS_CSPR1 CONFIG_SYS_NOR1_CSPR
#define CONFIG_SYS_AMASK1 CONFIG_SYS_NOR_AMASK
#define CONFIG_SYS_CSOR1 CONFIG_SYS_NOR_CSOR
#define CONFIG_SYS_CS1_FTIM0 CONFIG_SYS_NOR_FTIM0
#define CONFIG_SYS_CS1_FTIM1 CONFIG_SYS_NOR_FTIM1
#define CONFIG_SYS_CS1_FTIM2 CONFIG_SYS_NOR_FTIM2
#define CONFIG_SYS_CS1_FTIM3 CONFIG_SYS_NOR_FTIM3
#define CONFIG_SYS_CSPR2_EXT CONFIG_SYS_NAND_CSPR_EXT
#define CONFIG_SYS_CSPR2 CONFIG_SYS_NAND_CSPR
#define CONFIG_SYS_AMASK2 CONFIG_SYS_NAND_AMASK
#define CONFIG_SYS_CSOR2 CONFIG_SYS_NAND_CSOR
#define CONFIG_SYS_CS2_FTIM0 CONFIG_SYS_NAND_FTIM0
#define CONFIG_SYS_CS2_FTIM1 CONFIG_SYS_NAND_FTIM1
#define CONFIG_SYS_CS2_FTIM2 CONFIG_SYS_NAND_FTIM2
#define CONFIG_SYS_CS2_FTIM3 CONFIG_SYS_NAND_FTIM3
#endif
#if defined(CONFIG_RAMBOOT_PBL)
#define CONFIG_SYS_RAMBOOT
#endif
/* I2C */
#define CONFIG_SYS_FSL_I2C_SPEED 100000 /* I2C speed */
#define CONFIG_SYS_FSL_I2C2_SPEED 100000 /* I2C2 speed */
#define I2C_MUX_PCA_ADDR_PRI 0x77 /* I2C bus multiplexer,primary */
#define I2C_MUX_PCA_ADDR_SEC 0x76 /* I2C bus multiplexer,secondary */
#define I2C_MUX_CH_DEFAULT 0x8
#define I2C_MUX_CH_VOL_MONITOR 0xa
#define I2C_MUX_CH_VSC3316_FS 0xc
#define I2C_MUX_CH_VSC3316_BS 0xd
/* Voltage monitor on channel 2*/
#define I2C_VOL_MONITOR_ADDR 0x40
#define I2C_VOL_MONITOR_BUS_V_OFFSET 0x2
#define I2C_VOL_MONITOR_BUS_V_OVF 0x1
#define I2C_VOL_MONITOR_BUS_V_SHIFT 3
/* VSC Crossbar switches */
#define CONFIG_VSC_CROSSBAR
#define VSC3316_FSM_TX_ADDR 0x70
#define VSC3316_FSM_RX_ADDR 0x71
/*
* RapidIO
*/
/*
* for slave u-boot IMAGE instored in master memory space,
* PHYS must be aligned based on the SIZE
*/
#define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_PHYS 0xfef200000ull
#define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_BUS1 0xfff00000ull
#define CONFIG_SRIO_PCIE_BOOT_IMAGE_SIZE 0x100000 /* 1M */
#define CONFIG_SRIO_PCIE_BOOT_IMAGE_MEM_BUS2 0x3fff00000ull
/*
* for slave UCODE and ENV instored in master memory space,
* PHYS must be aligned based on the SIZE
*/
#define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_MEM_PHYS 0xfef100000ull
#define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_MEM_BUS 0x3ffe00000ull
#define CONFIG_SRIO_PCIE_BOOT_UCODE_ENV_SIZE 0x40000 /* 256K */
/* slave core release by master*/
#define CONFIG_SRIO_PCIE_BOOT_BRR_OFFSET 0xe00e4
#define CONFIG_SRIO_PCIE_BOOT_RELEASE_MASK 0x00000001 /* release core 0 */
/*
* SRIO_PCIE_BOOT - SLAVE
*/
#ifdef CONFIG_SRIO_PCIE_BOOT_SLAVE
#define CONFIG_SYS_SRIO_PCIE_BOOT_UCODE_ENV_ADDR 0xFFE00000
#define CONFIG_SYS_SRIO_PCIE_BOOT_UCODE_ENV_ADDR_PHYS \
(0x300000000ull | CONFIG_SYS_SRIO_PCIE_BOOT_UCODE_ENV_ADDR)
#endif
/*
* eSPI - Enhanced SPI
*/
#define CONFIG_SF_DEFAULT_SPEED 10000000
#define CONFIG_SF_DEFAULT_MODE 0
/* Qman/Bman */
#ifndef CONFIG_NOBQFMAN
#define CONFIG_SYS_DPAA_QBMAN /* Support Q/Bman */
#define CONFIG_SYS_BMAN_NUM_PORTALS 50
#define CONFIG_SYS_BMAN_MEM_BASE 0xf4000000
#define CONFIG_SYS_BMAN_MEM_PHYS 0xff4000000ull
#define CONFIG_SYS_BMAN_MEM_SIZE 0x02000000
#define CONFIG_SYS_BMAN_SP_CENA_SIZE 0x4000
#define CONFIG_SYS_BMAN_SP_CINH_SIZE 0x1000
#define CONFIG_SYS_BMAN_CENA_BASE CONFIG_SYS_BMAN_MEM_BASE
#define CONFIG_SYS_BMAN_CENA_SIZE (CONFIG_SYS_BMAN_MEM_SIZE >> 1)
#define CONFIG_SYS_BMAN_CINH_BASE (CONFIG_SYS_BMAN_MEM_BASE + \
CONFIG_SYS_BMAN_CENA_SIZE)
#define CONFIG_SYS_BMAN_CINH_SIZE (CONFIG_SYS_BMAN_MEM_SIZE >> 1)
#define CONFIG_SYS_BMAN_SWP_ISDR_REG 0xE08
#define CONFIG_SYS_QMAN_NUM_PORTALS 50
#define CONFIG_SYS_QMAN_MEM_BASE 0xf6000000
#define CONFIG_SYS_QMAN_MEM_PHYS 0xff6000000ull
#define CONFIG_SYS_QMAN_MEM_SIZE 0x02000000
#define CONFIG_SYS_QMAN_SP_CENA_SIZE 0x4000
#define CONFIG_SYS_QMAN_SP_CINH_SIZE 0x1000
#define CONFIG_SYS_QMAN_CENA_BASE CONFIG_SYS_QMAN_MEM_BASE
#define CONFIG_SYS_QMAN_CENA_SIZE (CONFIG_SYS_QMAN_MEM_SIZE >> 1)
#define CONFIG_SYS_QMAN_CINH_BASE (CONFIG_SYS_QMAN_MEM_BASE + \
CONFIG_SYS_QMAN_CENA_SIZE)
#define CONFIG_SYS_QMAN_CINH_SIZE (CONFIG_SYS_QMAN_MEM_SIZE >> 1)
#define CONFIG_SYS_QMAN_SWP_ISDR_REG 0xE08
#define CONFIG_SYS_DPAA_FMAN
#define CONFIG_SYS_DPAA_PME
#define CONFIG_SYS_PMAN
#define CONFIG_SYS_DPAA_DCE
#define CONFIG_SYS_DPAA_RMAN
#define CONFIG_SYS_INTERLAKEN
/* Default address of microcode for the Linux Fman driver */
#if defined(CONFIG_SPIFLASH)
/*
* env is stored at 0x100000, sector size is 0x10000, ucode is stored after
* env, so we got 0x110000.
*/
#define CONFIG_SYS_QE_FW_IN_SPIFLASH
#define CONFIG_SYS_FMAN_FW_ADDR 0x110000
#elif defined(CONFIG_SDCARD)
/*
* PBL SD boot image should stored at 0x1000(8 blocks), the size of the image is
* about 1MB (2048 blocks), Env is stored after the image, and the env size is
* 0x2000 (16 blocks), 8 + 2048 + 16 = 2072, enlarge it to 2080.
*/
#define CONFIG_SYS_QE_FMAN_FW_IN_MMC
#define CONFIG_SYS_FMAN_FW_ADDR (512 * 0x820)
#elif defined(CONFIG_NAND)
#define CONFIG_SYS_QE_FMAN_FW_IN_NAND
#define CONFIG_SYS_FMAN_FW_ADDR (11 * CONFIG_SYS_NAND_BLOCK_SIZE)
#elif defined(CONFIG_SRIO_PCIE_BOOT_SLAVE)
/*
* Slave has no ucode locally, it can fetch this from remote. When implementing
* in two corenet boards, slave's ucode could be stored in master's memory
* space, the address can be mapped from slave TLB->slave LAW->
* slave SRIO or PCIE outbound window->master inbound window->
* master LAW->the ucode address in master's memory space.
*/
#define CONFIG_SYS_QE_FMAN_FW_IN_REMOTE
#define CONFIG_SYS_FMAN_FW_ADDR 0xFFE00000
#else
#define CONFIG_SYS_QE_FMAN_FW_IN_NOR
#define CONFIG_SYS_FMAN_FW_ADDR 0xEFF00000
#endif
#define CONFIG_SYS_QE_FMAN_FW_LENGTH 0x10000
#define CONFIG_SYS_FDT_PAD (0x3000 + CONFIG_SYS_QE_FMAN_FW_LENGTH)
#endif /* CONFIG_NOBQFMAN */
#ifdef CONFIG_SYS_DPAA_FMAN
#define CONFIG_FMAN_ENET
#define CONFIG_PHYLIB_10G
#define CONFIG_PHY_VITESSE
#define CONFIG_PHY_TERANETICS
#define SGMII_CARD_PORT1_PHY_ADDR 0x1C
#define SGMII_CARD_PORT2_PHY_ADDR 0x1D
#define SGMII_CARD_PORT3_PHY_ADDR 0x1E
#define SGMII_CARD_PORT4_PHY_ADDR 0x1F
#define FM1_10GEC1_PHY_ADDR 0x0
#define FM1_10GEC2_PHY_ADDR 0x1
#define FM2_10GEC1_PHY_ADDR 0x2
#define FM2_10GEC2_PHY_ADDR 0x3
#endif
/* SATA */
#ifdef CONFIG_FSL_SATA_V2
#define CONFIG_LIBATA
#define CONFIG_FSL_SATA
#define CONFIG_SYS_SATA_MAX_DEVICE 2
#define CONFIG_SATA1
#define CONFIG_SYS_SATA1 CONFIG_SYS_MPC85xx_SATA1_ADDR
#define CONFIG_SYS_SATA1_FLAGS FLAGS_DMA
#define CONFIG_SATA2
#define CONFIG_SYS_SATA2 CONFIG_SYS_MPC85xx_SATA2_ADDR
#define CONFIG_SYS_SATA2_FLAGS FLAGS_DMA
#define CONFIG_LBA48
#define CONFIG_CMD_SATA
#endif
#ifdef CONFIG_FMAN_ENET
#define CONFIG_MII /* MII PHY management */
#define CONFIG_ETHPRIME "FM1@DTSEC1"
#define CONFIG_PHY_GIGE /* Include GbE speed/duplex detection */
#endif
/*
* USB
*/
#define CONFIG_USB_EHCI_FSL
#define CONFIG_EHCI_HCD_INIT_AFTER_RESET
#define CONFIG_HAS_FSL_DR_USB
#ifdef CONFIG_MMC
#define CONFIG_FSL_ESDHC
#define CONFIG_SYS_FSL_ESDHC_ADDR CONFIG_SYS_MPC85xx_ESDHC_ADDR
#define CONFIG_SYS_FSL_ESDHC_BROKEN_TIMEOUT
#define CONFIG_SYS_FSL_MMC_HAS_CAPBLT_VS33
#define CONFIG_ESDHC_DETECT_QUIRK \
(!(readb(QIXIS_BASE + QIXIS_BRDCFG5) & QIXIS_MUX_SDHC) || \
IS_SVR_REV(get_svr(), 1, 0))
#define CONFIG_ESDHC_DETECT_8_BIT_QUIRK \
(!(readb(QIXIS_BASE + QIXIS_BRDCFG5) & QIXIS_MUX_SDHC_WIDTH8))
#endif
#define __USB_PHY_TYPE utmi
/*
* T4240 has 3 DDR controllers. Default to 3-way interleaving. It can be
* 3way_1KB, 3way_4KB, 3way_8KB. T4160 has 2 DDR controllers. Default to 2-way
* interleaving. It can be cacheline, page, bank, superbank.
* See doc/README.fsl-ddr for details.
*/
#ifdef CONFIG_ARCH_T4240
#define CTRL_INTLV_PREFERED 3way_4KB
#else
#define CTRL_INTLV_PREFERED cacheline
#endif
#define CONFIG_EXTRA_ENV_SETTINGS \
"hwconfig=fsl_ddr:" \
"ctlr_intlv=" __stringify(CTRL_INTLV_PREFERED) "," \
"bank_intlv=auto;" \
"usb1:dr_mode=host,phy_type=" __stringify(__USB_PHY_TYPE) "\0"\
"netdev=eth0\0" \
"uboot=" __stringify(CONFIG_UBOOTPATH) "\0" \
"ubootaddr=" __stringify(CONFIG_SYS_TEXT_BASE) "\0" \
"tftpflash=tftpboot $loadaddr $uboot && " \
"protect off $ubootaddr +$filesize && " \
"erase $ubootaddr +$filesize && " \
"cp.b $loadaddr $ubootaddr $filesize && " \
"protect on $ubootaddr +$filesize && " \
"cmp.b $loadaddr $ubootaddr $filesize\0" \
"consoledev=ttyS0\0" \
"ramdiskaddr=2000000\0" \
"ramdiskfile=t4240qds/ramdisk.uboot\0" \
"fdtaddr=1e00000\0" \
"fdtfile=t4240qds/t4240qds.dtb\0" \
"bdev=sda3\0"
#define CONFIG_HVBOOT \
"setenv bootargs config-addr=0x60000000; " \
"bootm 0x01000000 - 0x00f00000"
#define CONFIG_ALU \
"setenv bootargs root=/dev/$bdev rw " \
"console=$consoledev,$baudrate $othbootargs;" \
"cpu 1 release 0x01000000 - - -;" \
"cpu 2 release 0x01000000 - - -;" \
"cpu 3 release 0x01000000 - - -;" \
"cpu 4 release 0x01000000 - - -;" \
"cpu 5 release 0x01000000 - - -;" \
"cpu 6 release 0x01000000 - - -;" \
"cpu 7 release 0x01000000 - - -;" \
"go 0x01000000"
#define CONFIG_LINUX \
"setenv bootargs root=/dev/ram rw " \
"console=$consoledev,$baudrate $othbootargs;" \
"setenv ramdiskaddr 0x02000000;" \
"setenv fdtaddr 0x00c00000;" \
"setenv loadaddr 0x1000000;" \
"bootm $loadaddr $ramdiskaddr $fdtaddr"
#define CONFIG_HDBOOT \
"setenv bootargs root=/dev/$bdev rw " \
"console=$consoledev,$baudrate $othbootargs;" \
"tftp $loadaddr $bootfile;" \
"tftp $fdtaddr $fdtfile;" \
"bootm $loadaddr - $fdtaddr"
#define CONFIG_NFSBOOTCOMMAND \
"setenv bootargs root=/dev/nfs rw " \
"nfsroot=$serverip:$rootpath " \
"ip=$ipaddr:$serverip:$gatewayip:$netmask:$hostname:$netdev:off " \
"console=$consoledev,$baudrate $othbootargs;" \
"tftp $loadaddr $bootfile;" \
"tftp $fdtaddr $fdtfile;" \
"bootm $loadaddr - $fdtaddr"
#define CONFIG_RAMBOOTCOMMAND \
"setenv bootargs root=/dev/ram rw " \
"console=$consoledev,$baudrate $othbootargs;" \
"tftp $ramdiskaddr $ramdiskfile;" \
"tftp $loadaddr $bootfile;" \
"tftp $fdtaddr $fdtfile;" \
"bootm $loadaddr $ramdiskaddr $fdtaddr"
#define CONFIG_BOOTCOMMAND CONFIG_LINUX
#include <asm/fsl_secure_boot.h>
#endif /* __CONFIG_H */
| {
"pile_set_name": "Github"
} |
module TemplateMethod where
import Adapter (Minute (..), WallTime (..), addMinutesToWallTime, marshalMW, unmarshalWM)
addMinutesTemplate :: (Int -> WallTime -> WallTime) -> Int -> Minute -> Minute
addMinutesTemplate f x =
unmarshalWM .
f x .
marshalMW
-- implements linear addition even for values > 1440
linearTimeAdd :: Int -> Minute -> Minute
linearTimeAdd = addMinutesTemplate addMinutesToWallTime
-- implements cyclic addition, respecting a 24 hour (1440 Min) cycle
cyclicTimeAdd :: Int -> Minute -> Minute
cyclicTimeAdd = addMinutesTemplate addMinutesToWallTime'
-- a 24 hour (1440 min) cyclic version of addition: 1400 + 100 = 60
addMinutesToWallTime' :: Int -> WallTime -> WallTime
addMinutesToWallTime' x (WallTime (h, m)) =
let (hAdd, mAdd) = x `quotRem` 60
hNew = h + hAdd
mNew = m + mAdd
in if mNew >= 60
then WallTime ((hNew + 1) `rem` 24, mNew-60)
else WallTime (hNew, mNew)
addWallTimes :: WallTime -> WallTime -> WallTime
addWallTimes a@(WallTime (h,m)) b =
let aMin = h*60 + m
in addMinutesToWallTime aMin b
instance Semigroup WallTime where
(<>) = addWallTimes
instance Monoid WallTime where
mempty = WallTime (0,0)
templateMethodDemo = do
putStrLn "TemplateMethod -> higher order function -> typeclass default implementations"
putStrLn $ "linear time: " ++ (show $ linearTimeAdd 100 (Minute 1400))
putStrLn $ "cyclic time: " ++ (show $ cyclicTimeAdd 100 (Minute 1400))
putStrLn ""
let a = WallTime (3,20)
print $ mappend a a
print $ mconcat [a,a,a,a,a,a,a,a,a]
putStrLn ""
| {
"pile_set_name": "Github"
} |
<div class="ico_btn">
<a href="../../routes"><img src="$rootContextPath.getURI("images/ico_back.png")" width="12" height="12" /><span class="ico_font">$i18n.get("back")</span></a>
<span class="ico_line">|</span>
<a href="../$route.id/routeselect"><img src="$rootContextPath.getURI("images/ico_show.png")" width="12" height="12" /><span class="ico_font">$i18n.get("proview")</span></a>
#if($currentUser.role != "G")
<span class="ico_line">|</span>
<a href="../$route.id"><img src="$rootContextPath.getURI("images/ico_show.png")" width="12" height="12" /><span class="ico_font">$i18n.get("show")</span></a>
<span class="ico_line">|</span>
<a href="../$route.id/edit?actionflag=copy"><img src="$rootContextPath.getURI("images/ico_register.png")" width="12" height="12" /><span class="ico_font">$i18n.get("copy")</span></a>
<span class="ico_line">|</span>
#if($route.enabled)
<a href="#" onclick="showConfirm('$i18n.get("confirm.disable")', '$route.name', '../$route.id/disable'); return false;">
<img src="$rootContextPath.getURI("images/ico_disable.png")" width="13" height="13" />
<span class="ico_font">$i18n.get("disable")</span></a>
#else
<a href="#" onclick="showConfirm('$i18n.get("confirm.enable")', '$route.name', '../$route.id/enable'); return false;">
<img src="$rootContextPath.getURI("images/ico_enable.png")" width="13" height="13" />
<span class="ico_font">$i18n.get("enable")</span></a>
#end
<span class="ico_line">|</span>
<a href="#" onclick="showConfirm('$i18n.get("confirm.delete")', '$route.name', '../$route.id/delete'); return false;">
<img src="$rootContextPath.getURI("images/ico_delete.png")" width="12" height="12" />
<span class="ico_font">$i18n.get("delete")</span></a>
#end
</div>
<br/>
<form id="df" #if($actionflag=="copy") action="../../routes" #else action="../$route.id" #end onSubmit="return check();" method="POST">
<table cellpadding="0" cellspacing="0" class="info">
<tr>
<th width="100">$i18n.get("route.name"): <font color='red'>*</font></th>
<td colspan="2">
#if($actionflag=="copy")
<input type="text" id="name" name="name" maxlength="200" value=""/>
#else
<input type="text" id="name" name="name" maxlength="200" value="$route.name"/>
#end
</td>
<td><font color='blue'>$i18n.get("RouteNameTip")</font> </td>
</tr>
<tr>
<th>$i18n.get("Priority"):</th>
<td colspan="2">
<input type="text" id="priority" name="priority" value="#if($route)$route.priority#{else}0#end" onkeydown="return checkNumber();"/>
</td>
<td>
<font color='blue'>$i18n.get("RoutePriorityTip")</font>
</td>
</tr>
<tr>
<th>$i18n.get("service"): <font color='red'>*</font></th>
<td colspan="2">
<input type="hidden" id="service" name="service" value="$service" />$service
</td>
<td></td>
</tr>
<tr>
<th>$i18n.get("methodName"):</th>
<td colspan="2">
<input type="text" id="method" name="method" value="$!method" style="ime-mode:disabled"/>
#if ($methods)
<select onchange="if (this.value != '') { if (byId('method').value == '') { byId('method').value = this.value; } else { byId('method').value = byId('method').value + ',' + this.value; } this.value = ''; }">
<option value="">$i18n.get("Choose")</option>
#foreach ($m in $methods)
<option value="$m">$m</option>
#end
</select>
#end
</td>
<td>
<font color='blue'>$i18n.get("RouteMethodTip")<font>
</td>
</tr>
<tr>
<th>$i18n.get("MatchRule")</th>
<th>$i18n.get("Match")</th>
<th>$i18n.get("Mismatch")</th>
<td><font color='blue'>$i18n.get("RouteMatchTip")</font></td>
</tr>
<tr>
<th>$i18n.get("ConsumerHost"): </th>
<td><input type="text" id="consumerHost" name="consumerHost" value="$!consumerHost" style="ime-mode:disabled"/></td>
<td><input type="text" id="unconsumerHost" name="unconsumerHost" value="$!unconsumerHost" style="ime-mode:disabled"/></td>
<td><font color="blue">$i18n.get("RouteHostTip")</font></td>
</tr>
<tr>
<th>$i18n.get("ConsumerApplication"): </th>
<td><input type="text" id="consumerApplication" name="consumerApplication" value="$!consumerApplication" style="ime-mode:disabled"/></td>
<td><input type="text" id="unconsumerApplication" name="unconsumerApplication" value="$!unconsumerApplication" style="ime-mode:disabled"/></td>
<td><font color="blue">$i18n.get("RouteApplicationTip")</font></td>
</tr>
<tr>
<th>$i18n.get("ConsumerCluster"): </th>
<td>
<input type="text" id="consumerCluster" name="consumerCluster" value="$!consumerCluster" style="ime-mode:disabled" />
#if ($clusterNames && $clusterNames.size() > 0)
<select onchange="if (this.value != '') { if (byId('consumerCluster').value == '') { byId('consumerCluster').value = this.value; } else { byId('consumerCluster').value = byId('consumerCluster').value + ',' + this.value; } this.value = ''; }">
<option value="">$i18n.get("Choose")</option>
#foreach ($c in $clusterNames)
<option value="$c">$c</option>
#end
</select>
#end
</td>
<td>
<input type="text" id="unconsumerCluster" name="unconsumerCluster" value="$!unconsumerCluster" style="ime-mode:disabled" />
#if ($clusterNames && $clusterNames.size() > 0)
<select onchange="if (this.value != '') { if (byId('unconsumerCluster').value == '') { byId('unconsumerCluster').value = this.value; } else { byId('unconsumerCluster').value = byId('unconsumerCluster').value + ',' + this.value; } this.value = ''; }">
<option value="">$i18n.get("Choose")</option>
#foreach ($c in $clusterNames)
<option value="$c">$c</option>
#end
</select>
#end
</td>
<td><font color="blue">$i18n.get("RouteClusterTip")</font></td>
</tr>
<tr>
<th>$i18n.get("FilterRule")</th>
<th>$i18n.get("Match")</th>
<th>$i18n.get("Mismatch")</th>
<td><font color='blue'>$i18n.get("RouteFilterTip")</font></td>
</tr>
<tr id="host">
<th>$i18n.get("ProviderHost"): </th>
<td><input type="text" id="providerHost" value="$!providerHost"
name="providerHost" style="ime-mode:disabled"/></td>
<td><input type="text" id="unproviderHost" value="$!unproviderHost"
name="unproviderHost" style="ime-mode:disabled"/></td>
<td><font color="blue">$i18n.get("RouteHostTip")</font></td>
</tr>
<tr id="cluster">
<th>$i18n.get("ProviderCluster"): </th>
<td>
<input type="text" id="providerCluster" value="$!providerCluster" name="providerCluster" style="ime-mode:disabled"/>
#if ($clusterNames && $clusterNames.size() > 0)
<select onchange="if (this.value != '') { if (byId('providerCluster').value == '') { byId('providerCluster').value = this.value; } else { byId('providerCluster').value = byId('providerCluster').value + ',' + this.value; } this.value = ''; }">
<option value="">$i18n.get("Choose")</option>
#foreach ($c in $clusterNames)
<option value="$c">$c</option>
#end
</select>
#end
</td>
<td>
<input type="text" id="unproviderCluster" value="$!unproviderCluster" name="unproviderCluster" style="ime-mode:disabled"/>
#if ($clusterNames && $clusterNames.size() > 0)
<select onchange="if (this.value != '') { if (byId('unproviderCluster').value == '') { byId('unproviderCluster').value = this.value; } else { byId('unproviderCluster').value = byId('unproviderCluster').value + ',' + this.value; } this.value = ''; }">
<option value="">$i18n.get("Choose")</option>
#foreach ($c in $clusterNames)
<option value="$c">$c</option>
#end
</select>
#end
</td>
<td><font color="blue">$i18n.get("RouteClusterTip")</font></td>
</tr>
<tr id="protocol">
<th>$i18n.get("ProviderProtocol"): </th>
<td><input type="text" id="providerProtocol" value="$!providerProtocol"
name="providerProtocol" style="ime-mode:disabled"/></td>
<td><input type="text" id="unproviderProtocol" value="$!unproviderProtocol"
name="unproviderProtocol" style="ime-mode:disabled"/></td>
<td></td>
</tr>
<tr id="port">
<th>$i18n.get("ProviderPort"): </th>
<td><input type="text" id="providerPort" name="providerPort" value="$!providerPort" style="ime-mode:disabled"/>
</td>
<td><input type="text" id="unproviderPort" name="unproviderPort" value="$!unproviderPort" style="ime-mode:disabled"/></td>
</tr>
<tr>
<td colspan="4"><div class="btn"><a href="#" onclick="if(check()){document.getElementById('df').submit();}">$i18n.get("save")</a></div></td>
</tr>
</table>
</form>
<script type="text/javascript">
function check() {
if(byId('name').value.trim()==''){
showAlert("$i18n.get("PleaseInput", $i18n.get("route.name"))", 'name');
return false;
}
if(byId('service').value.trim()==''){
showAlert("$i18n.get("PleaseInput", $i18n.get("service"))", 'service');
return false;
}
if(byId('service').value.indexOf('*') != -1 || byId('service').value.indexOf(',') != -1 ){
showAlert("Service name can not contain '*' or ','.", 'service');
return false;
}
var exp=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.\*$/;
var exp2=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
var paddress = byId('providerHost').value;
if(paddress.trim()!=''){
var padds = paddress.split(",");
for(var i = 0; i < padds.length; i++){
if(!padds[i].match(exp2) && !padds[i].match(exp)){
showAlert("Match provider host : " + padds[i] + " is illegal", 'ProviderHost');
return false;
}
}
}
var punaddress = byId('unproviderHost').value;
if(punaddress.trim()!=''){
var punadds = punaddress.split(",");
for(var i = 0; i < punadds.length; i++){
if(!punadds[i].match(exp2) && !punadds[i].match(exp)){
showAlert("Mismatch provider host : " + punadds[i] + " is illegal", 'ProviderHost');
return false;
}
}
}
return true;
}
function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
showAlert("content maxlength is " + mlength + "!", 'docContent');
return false;
}
function imposeMaxLength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
return (obj.value.length <mlength);
}
</script> | {
"pile_set_name": "Github"
} |
{
"id": 235,
"created_at": "2016-12-01",
"updated_at": "2016-12-16",
"title": "Downloads Resources over HTTP",
"author": {
"name": "Adam Baldwin",
"website": null,
"username": null
},
"module_name": "mongodb-instance",
"publish_date": "2016-12-16",
"cves": [],
"vulnerable_versions": "<0.0.3",
"patched_versions": ">=0.0.3",
"overview": "mongodb-instance installs mongodb locally.\n\nmongodb-instance downloads binary resources over HTTP, which leaves it vulnerable to MITM attacks. It may be possible to cause remote code execution (RCE) by swapping out the requested binary with an attacker controlled binary if the attacker is on the network or positioned in between the user and the remote server.",
"recommendation": "Update to version 0.0.3 or later.",
"references": null,
"cvss_vector": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:H/I:H/A:H",
"cvss_score": 7.1,
"coordinating_vendor": "^Lift Security"
}
| {
"pile_set_name": "Github"
} |
Fix CVE-2014-8157 - dec->numtiles off-by-one check in jpc_dec_process_sot()
From https://bugzilla.redhat.com/show_bug.cgi?id=1179282
Signed-off-by: Gustavo Zacarias <[email protected]>
diff -up jasper-1.900.1/src/libjasper/jpc/jpc_dec.c.CVE-2014-8157 jasper-1.900.1/src/libjasper/jpc/jpc_dec.c
--- jasper-1.900.1/src/libjasper/jpc/jpc_dec.c.CVE-2014-8157 2015-01-19 16:59:36.000000000 +0100
+++ jasper-1.900.1/src/libjasper/jpc/jpc_dec.c 2015-01-19 17:07:41.609863268 +0100
@@ -489,7 +489,7 @@ static int jpc_dec_process_sot(jpc_dec_t
dec->curtileendoff = 0;
}
- if (JAS_CAST(int, sot->tileno) > dec->numtiles) {
+ if (JAS_CAST(int, sot->tileno) >= dec->numtiles) {
jas_eprintf("invalid tile number in SOT marker segment\n");
return -1;
}
| {
"pile_set_name": "Github"
} |
- [English](README.md)
- [日本語](README.ja.md)
- [한국어](README.ko.md)
- [Bahasa Indonesia](README.in.md)
- [Español](README.es.md)
- [简体中文](README.zh.md)
- [français](README.fr.md)
- [العربية](README.ar.md)
# مشروع هيا بنا لنعتقل
:في اليابان تم اعتقال تلميذة من طرف الشرطة لوضعها رابطا نحو موقع الكتروني يحتوي على حلقة لانهائية من التحذيرات بالجافسكربت كالتالي
```js
while (1) {
alert("!");
}
```
:مقالات صحفية ذات صلة
- (اليابانية) [https://www.sanspo.com/geino/news/20190304/tro19030418410013-n1.html](https://www.sanspo.com/geino/news/20190304/tro19030418410013-n1.html)
- (الإنجليزية) [https://www.zdnet.com/article/japanese-police-charge-13-year-old-for-sharing-unclosable-popup-prank-online/](https://www.zdnet.com/article/japanese-police-charge-13-year-old-for-sharing-unclosable-popup-prank-online/)
اذن يعتبر هذا جريمة في اليابان. اذن لنكن مجرمين و هيا بنا نعتقل
استمتع بالحياة الاجرامية
## كيف يتم القبض عليك
هذا سهل. احصل على النسخة الخاصة بك من المشروع ثم قم بتفريعها انظر اسفله . تم كل شيء. سيكون من الافضل لو قمت بنشر الرابط اسفله في موقع اجتماعي
Branch: "pages-gh"
URL: "https://youraccount.github.io/lets-get-arrested"
## لم يتم القبض عليك؟
يمكنك تسليم نفسك للشرطة
| {
"pile_set_name": "Github"
} |
!--------------------------------------------------------------------------------------------------!
! CP2K: A general program to perform molecular dynamics simulations !
! Copyright 2000-2020 CP2K developers group <https://cp2k.org> !
! !
! SPDX-License-Identifier: GPL-2.0-or-later !
!--------------------------------------------------------------------------------------------------!
! **************************************************************************************************
!> \brief Program to Map on grid the hills spawned during a metadynamics run
!> \author Teodoro Laino [tlaino] - 06.2009
!> \par History
!> 03.2006 created [tlaino]
!> teodoro.laino .at. gmail.com
!> 11.2007 - tlaino (University of Zurich): Periodic COLVAR - cleaning.
!> 12.2010 - [email protected]: addition of the MEP for FES
!>
!> \par Note
!> Please report any bug to the author
! **************************************************************************************************
MODULE graph_methods
USE cp_files, ONLY: close_file,&
open_file
USE graph_utils, ONLY: derivative,&
get_val_res,&
mep_input_data_type,&
pbc,&
point_no_pbc,&
point_pbc
USE kinds, ONLY: dp
USE memory_utilities, ONLY: reallocate
USE periodic_table, ONLY: init_periodic_table,&
nelem,&
ptable
USE physcon, ONLY: bohr
USE string_utilities, ONLY: uppercase
#include "../base/base_uses.f90"
IMPLICIT NONE
PRIVATE
PUBLIC :: fes_compute_low, &
fes_write, &
fes_only_write, &
fes_min, &
fes_path, &
fes_cube_write
CONTAINS
! **************************************************************************************************
!> \brief Efficiently map the gaussians on the grid
!> \param idim ...
!> \param nn ...
!> \param fes ...
!> \param gauss ...
!> \param ind ...
!> \param ind0 ...
!> \param nfes ...
!> \param ndim ...
!> \param ngauss ...
!> \param ngrid ...
!> \param iperd ...
!> \par History
!> 03.2006 created [tlaino]
!> teodoro.laino .at. gmail.com
!> \author Teodoro Laino
! **************************************************************************************************
RECURSIVE SUBROUTINE fes_compute_low(idim, nn, fes, gauss, ind, ind0, nfes, ndim, &
ngauss, ngrid, iperd)
INTEGER, INTENT(in) :: idim
INTEGER, DIMENSION(:) :: nn
REAL(KIND=dp), DIMENSION(:), POINTER :: fes
REAL(KIND=dp), DIMENSION(:, :), POINTER :: gauss
INTEGER, DIMENSION(:) :: ind, ind0
INTEGER, INTENT(in) :: nfes, ndim, ngauss
INTEGER, DIMENSION(:), POINTER :: ngrid
INTEGER, DIMENSION(:) :: iperd
INTEGER :: i, j, k, pnt
INTEGER, DIMENSION(:), POINTER :: ll, pos
REAL(KIND=dp) :: prod
ALLOCATE (pos(ndim), ll(ndim))
pos = ind
k = nn(idim)
DO i = -k, k
pos(idim) = ind(idim) + i
IF (iperd(idim) == 0) THEN
IF (pos(idim) .GT. ngrid(idim)) CYCLE
IF (pos(idim) .LT. 1) CYCLE
END IF
IF (idim /= 1) THEN
CALL fes_compute_low(idim - 1, nn, fes, gauss, pos, ind0, nfes, ndim, ngauss, ngrid, iperd)
ELSE
pnt = point_pbc(pos, iperd, ngrid, ndim)
prod = 1.0_dp
DO j = 1, ndim
ll(j) = pos(j) - ind0(j)
prod = prod*gauss(ll(j), j)
END DO
fes(pnt) = fes(pnt) + prod
END IF
END DO
DEALLOCATE (pos, ll)
END SUBROUTINE fes_compute_low
! **************************************************************************************************
!> \brief Writes the FES on the file
!> \param unit_nr ...
!> \param idim ...
!> \param fes ...
!> \param pos ...
!> \param ndim ...
!> \param ngrid ...
!> \param dp_grid ...
!> \param x0 ...
!> \param ndw ...
!> \param l_fes_int ...
!> \param array ...
!> \par History
!> 03.2006 created [tlaino]
!> teodoro.laino .at. gmail.com
!> \author Teodoro Laino
! **************************************************************************************************
RECURSIVE SUBROUTINE fes_write(unit_nr, idim, fes, pos, ndim, ngrid, &
dp_grid, x0, ndw, l_fes_int, array)
INTEGER, INTENT(IN) :: unit_nr, idim
REAL(KIND=dp), DIMENSION(:), POINTER :: fes
INTEGER, DIMENSION(:), POINTER :: pos
INTEGER, INTENT(IN) :: ndim
INTEGER, DIMENSION(:), POINTER :: ngrid
REAL(KIND=dp), DIMENSION(:), POINTER :: dp_grid, x0
INTEGER, INTENT(IN) :: ndw
LOGICAL, INTENT(IN) :: l_fes_int
REAL(KIND=dp), DIMENSION(:), OPTIONAL :: array
INTEGER :: dimval, i, id, ind, is, it, itt, np, pnt
REAL(KIND=dp) :: dvol, sum_fes
REAL(KIND=dp), DIMENSION(:), POINTER :: xx
ALLOCATE (xx(ndim))
xx = x0
DO i = 1, ngrid(idim)
pos(idim) = i
IF (idim /= ndim - ndw + 1) THEN
IF (PRESENT(array)) THEN
CALL fes_write(unit_nr, idim - 1, fes, pos, ndim, ngrid, dp_grid, &
x0, ndw, l_fes_int, array)
ELSE
CALL fes_write(unit_nr, idim - 1, fes, pos, ndim, ngrid, dp_grid, &
x0, ndw, l_fes_int)
END IF
ELSE
IF (PRESENT(array)) THEN
ind = 1
np = ngrid(ndim)*ngrid(ndim - 1)*ngrid(ndim - 2)
DO is = 1, ndw
itt = 1
DO it = 1, is - 1
itt = itt*ngrid(ndim - it)
END DO
ind = ind + (pos(ndim - is + 1) - 1)*itt
END DO
IF (ind > np) CPABORT("something wrong in indexing ..")
END IF
pnt = point_no_pbc(pos, ngrid, ndim)
xx = x0 + dp_grid*(pos - 1)
dimval = PRODUCT(ngrid(1:ndim - ndw))
IF (.NOT. l_fes_int) THEN
IF (PRESENT(array)) THEN
array(ind) = MINVAL(-fes(pnt:pnt + dimval - 1))
ELSE
WRITE (unit_nr, '(10f20.10)') (xx(id), id=ndim, ndim - ndw + 1, -1), MINVAL(-fes(pnt:pnt + dimval - 1))
END IF
ELSE
sum_fes = 0.0_dp
dvol = 1.0_dp
dvol = PRODUCT(dp_grid(1:ndim - ndw))
DO is = pnt, pnt + dimval - 1
sum_fes = sum_fes + fes(is)*dvol
END DO
IF (PRESENT(array)) THEN
array(ind) = -sum_fes
ELSE
WRITE (unit_nr, '(10f20.10)') (xx(id), id=ndim, ndim - ndw + 1, -1), -sum_fes
END IF
END IF
END IF
END DO
DEALLOCATE (xx)
END SUBROUTINE fes_write
! **************************************************************************************************
!> \brief Writes the FES on the file when stride is requested
!> \param idim ...
!> \param fes ...
!> \param pos ...
!> \param ndim ...
!> \param ngrid ...
!> \param dp_grid ...
!> \param ndw ...
!> \param l_fes_int ...
!> \param unit_nr ...
!> \par History
!> 03.2006 created [tlaino]
!> teodoro.laino .at. gmail.com
!> \author Teodoro Laino
! **************************************************************************************************
RECURSIVE SUBROUTINE fes_only_write(idim, fes, pos, ndim, ngrid, dp_grid, ndw, l_fes_int, unit_nr)
INTEGER, INTENT(IN) :: idim
REAL(KIND=dp), DIMENSION(:), POINTER :: fes
INTEGER, DIMENSION(:), POINTER :: pos
INTEGER, INTENT(IN) :: ndim
INTEGER, DIMENSION(:), POINTER :: ngrid
REAL(KIND=dp), DIMENSION(:), POINTER :: dp_grid
INTEGER, INTENT(IN) :: ndw
LOGICAL, INTENT(IN) :: l_fes_int
INTEGER :: unit_nr
INTEGER :: dimval, i, is, pnt
REAL(KIND=dp) :: dvol, sum_fes
DO i = 1, ngrid(idim)
pos(idim) = i
IF (idim /= ndim - ndw + 1) THEN
CALL fes_only_write(idim - 1, fes, pos, ndim, ngrid, dp_grid, ndw, l_fes_int, unit_nr)
ELSE
pnt = point_no_pbc(pos, ngrid, ndim)
dimval = PRODUCT(ngrid(1:ndim - ndw))
IF (l_fes_int) THEN
WRITE (unit_nr, '(1f12.5)') MINVAL(-fes(pnt:pnt + dimval - 1))
ELSE
sum_fes = 0.0_dp
dvol = PRODUCT(dp_grid(1:ndim - ndw))
DO is = pnt, pnt + dimval - 1
sum_fes = sum_fes + fes(is)*dvol
END DO
WRITE (unit_nr, '(1f12.5)') - sum_fes
END IF
END IF
END DO
END SUBROUTINE fes_only_write
! **************************************************************************************************
!> \brief Finds minima of the FES
!> \param fes ...
!> \param ndim ...
!> \param iperd ...
!> \param ngrid ...
!> \param dp_grid ...
!> \param x0 ...
!> \param ndw ...
!> \par History
!> 06.2009 created [tlaino]
!> teodoro.laino .at. gmail.com
!> \author Teodoro Laino
! **************************************************************************************************
SUBROUTINE fes_min(fes, ndim, iperd, ngrid, dp_grid, x0, ndw)
REAL(KIND=dp), DIMENSION(:), POINTER :: fes
INTEGER, INTENT(IN) :: ndim
INTEGER, DIMENSION(:), POINTER :: iperd, ngrid
REAL(KIND=dp), DIMENSION(:), POINTER :: dp_grid, x0
INTEGER, INTENT(IN) :: ndw
INTEGER :: i, id, iter, j, k, max_ntrust, nacc, &
ntrials, pnt
INTEGER, ALLOCATABLE, DIMENSION(:, :) :: history
INTEGER, DIMENSION(:), POINTER :: pos, pos0
INTEGER, DIMENSION(ndim) :: Dpos, ntrust
LOGICAL :: do_save
REAL(KIND=dp) :: fes_now, fes_old, norm_dx, resto
REAL(KIND=dp), DIMENSION(:), POINTER :: dx, rnd, xx
IF (ndw /= ndim) CPABORT("Not implemented for projected FES!")
ntrust = ngrid/10
ntrials = PRODUCT(ngrid)
WRITE (*, '(A,10I6)', ADVANCE="no") "FES| Trust hyper-radius ", ntrust
WRITE (*, '(A,10F12.6)') " which is equivalent to: ", ntrust*dp_grid
ALLOCATE (xx(ndim), dx(ndim), pos0(ndim), rnd(ndim), pos(ndim))
ALLOCATE (history(ndim, ntrials))
history = 0
nacc = 0
Trials: DO j = 1, ntrials
! Loop over all points
pnt = j
DO k = ndim, 2, -1
pos0(k) = pnt/PRODUCT(ngrid(1:k - 1))
resto = MOD(pnt, PRODUCT(ngrid(1:k - 1)))
IF (resto /= 0) THEN
pnt = pnt - pos0(k)*PRODUCT(ngrid(1:k - 1))
pos0(k) = pos0(k) + 1
ELSE
pnt = PRODUCT(ngrid(1:k - 1))
END IF
END DO
pos0(1) = pnt
! Loop over the frame points unless it is periodic
DO k = 1, ndim
IF ((iperd(k) == 0) .AND. (pos0(k) < ntrust(k))) CYCLE Trials
IF ((iperd(k) == 0) .AND. (pos0(k) > ngrid(k) - ntrust(k))) CYCLE Trials
END DO
! Evaluate position and derivative
pos = pos0
xx = x0 + dp_grid*(pos - 1)
dx = derivative(fes, pos, iperd, ndim, ngrid, dp_grid)
! Integrate till derivative is small enough..
pnt = point_no_pbc(pos, ngrid, ndim)
fes_now = -fes(pnt)
fes_old = HUGE(0.0_dp)
i = 1
DO WHILE ((i <= 100) .OR. (fes_now < fes_old))
fes_old = fes_now
!WRITE(10+j,'(10f20.10)')(xx(id),id=ndim,1,-1),-fes(pnt)
norm_dx = SQRT(DOT_PRODUCT(dx, dx))
IF (norm_dx == 0.0_dp) EXIT ! It is in a really flat region
xx = xx - MIN(0.1_dp, norm_dx)*dx/norm_dx
! Re-evaluating pos
pos = CEILING((xx - x0)/dp_grid) + 1
CALL pbc(pos, iperd, ngrid, ndim)
! Incremental pos
dx = derivative(fes, pos, iperd, ndim, ngrid, dp_grid)
pnt = point_no_pbc(pos, ngrid, ndim)
fes_now = -fes(pnt)
i = i + 1
END DO
iter = i
! Compare with the available minima and if they are the same skip
! saving this position..
do_save = fes(pnt) >= 1.0E-3_dp
IF (do_save) THEN
DO i = 1, nacc
Dpos = pos - history(:, i)
norm_dx = DOT_PRODUCT(Dpos, Dpos)
max_ntrust = MAXVAL(ntrust)
! (SQRT(REAL(norm_dx, KIND=dp)) <= MAXVAL(ntrust)) ...
IF ((norm_dx <= REAL(max_ntrust*max_ntrust, KIND=dp)) .OR. (fes(pnt) < 1.0E-3_dp)) THEN
do_save = .FALSE.
EXIT
END IF
END DO
END IF
IF (do_save) THEN
pnt = point_no_pbc(pos, ngrid, ndim)
xx = x0 + dp_grid*(pos - 1)
WRITE (*, '(A,5F12.6)', ADVANCE="NO") "FES| Minimum found (", (xx(id), id=ndim, ndim - ndw + 1, -1)
WRITE (*, '(A,F12.6,A,I6)') " ). FES value = ", -fes(pnt), " Hartree. Number of Iter: ", iter
nacc = nacc + 1
history(:, nacc) = pos
END IF
END DO Trials
WRITE (*, '(A,I6,A)') "FES| Number of Minimum found: ", nacc, "."
DEALLOCATE (xx, dx, pos0, rnd, pos)
DEALLOCATE (history)
END SUBROUTINE fes_min
! **************************************************************************************************
!> \brief Finds path between two points (a) and (b)
!> \param fes ...
!> \param ndim ...
!> \param ngrid ...
!> \param dp_grid ...
!> \param iperd ...
!> \param x0 ...
!> \param ndw ...
!> \param mep_input_data ...
!> \param l_int ...
!> \par History
!> 12.2010 created [tlaino]
!> teodoro.laino .at. gmail.com
!> \author Teodoro Laino
! **************************************************************************************************
SUBROUTINE fes_path(fes, ndim, ngrid, dp_grid, iperd, x0, ndw, mep_input_data, l_int)
REAL(KIND=dp), DIMENSION(:), POINTER :: fes
INTEGER, INTENT(IN) :: ndim
INTEGER, DIMENSION(:), POINTER :: ngrid
REAL(KIND=dp), DIMENSION(:), POINTER :: dp_grid
INTEGER, DIMENSION(:), POINTER :: iperd
REAL(KIND=dp), DIMENSION(:), POINTER :: x0
INTEGER, INTENT(IN) :: ndw
TYPE(mep_input_data_type), INTENT(IN) :: mep_input_data
LOGICAL :: l_int
INTEGER :: i, id, irep, iter, nf, nreplica, ns, &
pnt, unit_nr
INTEGER, DIMENSION(:), POINTER :: ipos
LOGICAL :: converged
REAL(KIND=dp) :: avg1, avg2, diff, ene, norm_dx, xx0, yy0
REAL(KIND=dp), DIMENSION(:), POINTER :: davg1, davg2, dxx, dyy, fes_rep, tang, &
xx, yy
REAL(KIND=dp), DIMENSION(:, :), POINTER :: dx, pos, pos_old
IF (ndw /= ndim) CPABORT("Not implemented for projected FES!")
nreplica = mep_input_data%nreplica
ALLOCATE (xx(ndim), dx(ndim, nreplica), pos_old(ndim, nreplica), pos(ndim, nreplica), &
ipos(ndim), fes_rep(nreplica), dxx(ndim), dyy(ndim), yy(ndim), davg1(ndim), &
tang(ndim), davg2(ndim))
IF (l_int) THEN
id = 0
DO i = ndim, ndim - ndw + 1, -1
id = id + 1
pos(i, 1) = mep_input_data%minima(id, 1)
pos(i, nreplica) = mep_input_data%minima(id, 2)
END DO
! Interpolate nreplica-2 points
xx = (pos(:, nreplica) - pos(:, 1))/REAL(nreplica - 1, KIND=dp)
DO irep = 2, nreplica - 1
pos(:, irep) = pos(:, 1) + xx(:)*REAL(irep - 1, KIND=dp)
END DO
ELSE
pos = mep_input_data%minima
ENDIF
! Compute value and derivative in all replicas
DO irep = 1, nreplica
ipos = FLOOR((pos(:, irep) - x0)/dp_grid) + 1
pnt = point_no_pbc(ipos, ngrid, ndim)
dx(:, irep) = derivative(fes, ipos, iperd, ndim, ngrid, dp_grid)
fes_rep(irep) = -fes(pnt)
END DO
! Implement a simple elastic band method (Hamiltonian): definitely not the best
! method, but for such a simple task it should be more than enough
converged = .FALSE.
pos_old = pos
iter = 0
DO WHILE ((.NOT. converged) .AND. (iter <= mep_input_data%max_iter))
iter = iter + 1
avg1 = 0.0_dp
! compute average length (distance 1)
DO irep = 2, nreplica
xx = pos(:, irep) - pos(:, irep - 1)
avg1 = avg1 + SQRT(DOT_PRODUCT(xx, xx))
END DO
avg1 = avg1/REAL(nreplica - 1, KIND=dp)
avg2 = 0.0_dp
! compute average length (distance 2)
DO irep = 3, nreplica
xx = pos(:, irep) - pos(:, irep - 2)
avg2 = avg2 + SQRT(DOT_PRODUCT(xx, xx))
END DO
avg2 = avg2/REAL(nreplica - 2, KIND=dp)
! compute energy and derivatives
dx = 0.0_dp
ene = 0.0_dp
ns = 1
nf = nreplica
DO irep = 1, nreplica
! compute energy and map point replica irep
ipos = FLOOR((pos(:, irep) - x0)/dp_grid) + 1
pnt = point_no_pbc(ipos, ngrid, ndim)
fes_rep(irep) = -fes(pnt)
IF ((irep == 1) .OR. (irep == nreplica)) CYCLE
! -------------------------------------------------------------
! compute non-linear elastic terms : including only 2-d springs
! -------------------------------------------------------------
davg2 = 0.0_dp
IF (irep < nf - 1) THEN
xx = pos(:, irep) - pos(:, irep + 2)
xx0 = SQRT(DOT_PRODUCT(xx, xx))
dxx = 1.0_dp/xx0*xx
ene = ene + 0.25_dp*mep_input_data%kb*(xx0 - avg2)**2
davg2 = davg2 + dxx
END IF
IF (irep > ns + 1) THEN
xx = pos(:, irep) - pos(:, irep - 2)
yy0 = SQRT(DOT_PRODUCT(xx, xx))
dyy = 1.0_dp/yy0*xx
davg2 = davg2 + dyy
END IF
davg2 = davg2/REAL(nreplica - 2, KIND=dp)
IF (irep < nf - 1) THEN
dx(:, irep) = dx(:, irep) + 0.5_dp*mep_input_data%kb*(xx0 - avg2)*(dxx - davg2)
END IF
IF (irep > ns + 1) THEN
dx(:, irep) = dx(:, irep) + 0.5_dp*mep_input_data%kb*(yy0 - avg2)*(dyy - davg2)
END IF
! -------------------------------------------------------------
! Evaluation of the elastic term
! -------------------------------------------------------------
xx = pos(:, irep) - pos(:, irep + 1)
yy0 = SQRT(DOT_PRODUCT(xx, xx))
dyy = 1.0_dp/yy0*xx
xx = pos(:, irep) - pos(:, irep - 1)
xx0 = SQRT(DOT_PRODUCT(xx, xx))
dxx = 1.0_dp/xx0*xx
davg1 = (dxx + dyy)/REAL(nreplica - 1, KIND=dp)
ene = ene + 0.5_dp*mep_input_data%kb*(xx0 - avg1)**2
dx(:, irep) = dx(:, irep) + mep_input_data%kb*(xx0 - avg1)*(dxx - davg1) + &
mep_input_data%kb*(yy0 - avg1)*(dyy - davg1)
! Evaluate the tangent
xx = pos(:, irep + 1) - pos(:, irep)
xx = xx/SQRT(DOT_PRODUCT(xx, xx))
yy = pos(:, irep) - pos(:, irep - 1)
yy = yy/SQRT(DOT_PRODUCT(yy, yy))
tang = xx + yy
tang = tang/SQRT(DOT_PRODUCT(tang, tang))
xx = derivative(fes, ipos, iperd, ndim, ngrid, dp_grid)
dx(:, irep) = DOT_PRODUCT(dx(:, irep), tang)*tang + &
xx - DOT_PRODUCT(xx, tang)*tang
END DO
dx(:, 1) = 0.0_dp
dx(:, nreplica) = 0.0_dp
! propagate the band with a SD step
diff = 0.0_dp
DO irep = 1, nreplica
ene = ene + fes_rep(irep)
IF ((irep == 1) .OR. (irep == nreplica)) CYCLE
norm_dx = SQRT(DOT_PRODUCT(dx(:, irep), dx(:, irep)))
IF (norm_dx /= 0.0_dp) THEN
pos(:, irep) = pos(:, irep) - MIN(0.1_dp, norm_dx)*dx(:, irep)/norm_dx
END IF
xx = pos(:, irep) - pos_old(:, irep)
diff = diff + DOT_PRODUCT(xx, xx)
END DO
! SQRT(diff) <= 0.001_dp
IF (diff <= 1.0e-6_dp) THEN
converged = .TRUE.
END IF
pos_old = pos
WRITE (*, *) "Iteration nr.", iter, SQRT(diff)
END DO
WRITE (*, *) "MEP saved on <mep.data> file."
CALL open_file(unit_number=unit_nr, file_name="mep.data", file_action="WRITE", file_status="UNKNOWN", file_form="FORMATTED")
DO irep = 1, nreplica
! compute energy and derivative for each single point of the replica
ipos = FLOOR((pos(:, irep) - x0)/dp_grid) + 1
pnt = point_no_pbc(ipos, ngrid, ndim)
fes_rep(irep) = -fes(pnt)
WRITE (unit_nr, *) irep, pos(:, nreplica - irep + 1), fes_rep(nreplica - irep + 1)
END DO
CALL close_file(unit_nr)
DEALLOCATE (xx, dx, pos, fes_rep, ipos, pos_old, yy, dyy, dxx, davg1, tang, davg2)
END SUBROUTINE fes_path
! **************************************************************************************************
!> \brief Dump FES with a GAUSSIAN cube format - Useful for multidimensional FES
!> \param idim ...
!> \param fes ...
!> \param pos ...
!> \param ndim ...
!> \param ngrid ...
!> \param dp_grid ...
!> \param x0 ...
!> \param ndw ...
!> \param l_fes_int ...
!> \param file ...
!> \par History
!> 12.2013 created [tlaino]
!> teodoro.laino .at. gmail.com
!> \author Teodoro Laino
! **************************************************************************************************
SUBROUTINE fes_cube_write(idim, fes, pos, ndim, ngrid, dp_grid, x0, ndw, l_fes_int, file)
INTEGER, INTENT(IN) :: idim
REAL(KIND=dp), DIMENSION(:), POINTER :: fes
INTEGER, DIMENSION(:), POINTER :: pos
INTEGER, INTENT(IN) :: ndim
INTEGER, DIMENSION(:), POINTER :: ngrid
REAL(KIND=dp), DIMENSION(:), POINTER :: dp_grid, x0
INTEGER, INTENT(IN) :: ndw
LOGICAL, INTENT(IN) :: l_fes_int
CHARACTER(LEN=80) :: file
CHARACTER(LEN=120) :: line
CHARACTER(LEN=5) :: label, labelp
INTEGER :: i, id(3), ii, iix, iiy, iiz, ix, iy, iz, &
natoms, np
INTEGER, DIMENSION(:), POINTER :: izat
REAL(KIND=dp) :: cell(3, 3), delta(3), dr(3), residual, &
rt(3)
REAL(KIND=dp), ALLOCATABLE, DIMENSION(:) :: rho, rhot
REAL(KIND=dp), DIMENSION(:, :), POINTER :: xat
CALL init_periodic_table()
IF (ndw .GT. 3) THEN
WRITE (*, *)
WRITE (*, *) 'ERROR: GAUSSIAN format can only handle FES on 3 CV !'
CPABORT("")
END IF
OPEN (10, file=file, status='old')
CALL get_val_res(unit=10, section="&SUBSYS", subsection="&CELL")
READ (10, *) label, cell(1, 1), cell(2, 1), cell(3, 1)
READ (10, *) label, cell(1, 2), cell(2, 2), cell(3, 2)
READ (10, *) label, cell(1, 3), cell(2, 3), cell(3, 3)
rt(1) = -(cell(1, 1)/2._dp)
rt(2) = -(cell(2, 2)/2._dp)
rt(3) = -(cell(3, 3)/2._dp)
WRITE (*, *) 'Dumping GAUSSIAN CUBE format'
WRITE (*, *) 'Cell vectors'
WRITE (*, *)
residual = 0.0d0
DO ix = 1, 3
DO iy = ix + 1, 3
residual = residual + cell(ix, iy)**2
END DO
END DO
IF (residual .GT. 1.0d-6) THEN
WRITE (*, *)
WRITE (*, *) 'ERROR: this program can only handle orthogonal cells'
WRITE (*, *) ' with vectors pointing in the X, Y and Z directions'
CPABORT("")
END IF
WRITE (*, *)
WRITE (*, *) 'Cube grid mesh: ', ngrid(1), 'x', ngrid(2), 'x', ngrid(3)
WRITE (*, *) 'Origin in:', rt
WRITE (*, *)
DO ix = 1, 3
dr(ix) = cell(ix, ix)/REAL(ngrid(ix), KIND=dp)
END DO
np = ngrid(1)*ngrid(2)*ngrid(3)
ALLOCATE (rho(np), rhot(np))
CALL fes_write(123, idim, fes, pos, ndim, ngrid, dp_grid, x0, ndw, l_fes_int, rho)
WRITE (*, *) 'Internal FES transfer completed!'
! translate cell
DO ix = 1, 3
delta(ix) = rt(ix)/dr(ix)
id(ix) = INT(delta(ix))
delta(ix) = rt(ix) - id(ix)*dr(ix)
END DO
DO iz = 1, ngrid(3)
DO iy = 1, ngrid(2)
DO ix = 1, ngrid(1)
iix = ix + id(1)
iiy = iy + id(2)
iiz = iz + id(3)
IF (iix .LT. 1) iix = iix + ngrid(1)
IF (iiy .LT. 1) iiy = iiy + ngrid(2)
IF (iiz .LT. 1) iiz = iiz + ngrid(3)
IF (iix .GT. ngrid(1)) iix = iix - ngrid(1)
IF (iiy .GT. ngrid(2)) iiy = iiy - ngrid(2)
IF (iiz .GT. ngrid(3)) iiz = iiz - ngrid(3)
IF (iix .LT. 1) CPABORT("ix < 0")
IF (iiy .LT. 1) CPABORT("iy < 0")
IF (iiz .LT. 1) CPABORT("iz < 0")
IF (iix .GT. ngrid(1)) CPABORT("ix > cell")
IF (iiy .GT. ngrid(2)) CPABORT("iy > cell")
IF (iiz .GT. ngrid(3)) CPABORT("iz > cell")
i = ix + (iy - 1)*ngrid(1) + (iz - 1)*ngrid(1)*ngrid(2)
ii = iix + (iiy - 1)*ngrid(1) + (iiz - 1)*ngrid(1)*ngrid(2)
rhot(ii) = rho(i)
END DO
END DO
END DO
REWIND (10)
CALL get_val_res(unit=10, section="&SUBSYS", subsection="&COORD")
natoms = 0
ALLOCATE (xat(1000, 3))
ALLOCATE (izat(1000))
DO WHILE (.TRUE.)
READ (10, '(A)') line
IF (INDEX(line, '&END') /= 0) EXIT
natoms = natoms + 1
READ (line, *) label, (xat(natoms, ix), ix=1, 3)
IF (natoms == SIZE(xat, 1)) THEN
CALL reallocate(xat, 1, SIZE(xat, 1)*2, 1, 3)
CALL reallocate(izat, 1, SIZE(izat)*2)
END IF
CALL uppercase(label)
DO i = 1, nelem
labelp = ptable(i)%symbol
CALL uppercase(labelp)
IF (TRIM(label) == TRIM(labelp)) EXIT
END DO
IF (i == nelem + 1) THEN
WRITE (*, *) TRIM(label), "In line: ", line
CPABORT("Element not recognized!")
END IF
izat(natoms) = i
END DO
CALL reallocate(xat, 1, natoms, 1, 3)
CALL reallocate(izat, 1, natoms)
DO i = 1, natoms
DO ix = 1, 3
xat(i, ix) = xat(i, ix) + rt(ix) - delta(ix)
IF (xat(i, ix) .LT. rt(ix)) xat(i, ix) = xat(i, ix) + cell(ix, ix)
IF (xat(i, ix) .GT. -rt(ix)) xat(i, ix) = xat(i, ix) - cell(ix, ix)
END DO
END DO
WRITE (123, *) "FES on CUBE"
WRITE (123, *) "created by fes in CP2K"
WRITE (123, '(i5,3f12.6)') natoms, rt(1:3)*bohr
DO ix = 1, 3
ii = ngrid(ix)
WRITE (123, '(i5,4f12.6)') ii, (cell(ix, iy)/ii*bohr, iy=1, 3)
END DO
DO i = 1, natoms
WRITE (123, '(i5,4f12.6)') izat(i), 0.0, (xat(i, ix)*bohr, ix=1, 3)
END DO
DO ix = 1, ngrid(1)
DO iy = 1, ngrid(2)
WRITE (123, '(6e13.5)') (rhot(ix + (iy - 1)*ngrid(1) + (iz - 1)*ngrid(1)&
&*ngrid(2)), iz=1, ngrid(3))
END DO
END DO
DEALLOCATE (xat, rho, rhot)
END SUBROUTINE fes_cube_write
END MODULE graph_methods
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel;
/**
* Contains all events thrown in the HttpKernel component.
*
* @author Bernhard Schussek <[email protected]>
*/
final class KernelEvents
{
/**
* The REQUEST event occurs at the very beginning of request
* dispatching.
*
* This event allows you to create a response for a request before any
* other code in the framework is executed.
*
* @Event("Symfony\Component\HttpKernel\Event\RequestEvent")
*/
const REQUEST = 'kernel.request';
/**
* The EXCEPTION event occurs when an uncaught exception appears.
*
* This event allows you to create a response for a thrown exception or
* to modify the thrown exception.
*
* @Event("Symfony\Component\HttpKernel\Event\ExceptionEvent")
*/
const EXCEPTION = 'kernel.exception';
/**
* The VIEW event occurs when the return value of a controller
* is not a Response instance.
*
* This event allows you to create a response for the return value of the
* controller.
*
* @Event("Symfony\Component\HttpKernel\Event\ViewEvent")
*/
const VIEW = 'kernel.view';
/**
* The CONTROLLER event occurs once a controller was found for
* handling a request.
*
* This event allows you to change the controller that will handle the
* request.
*
* @Event("Symfony\Component\HttpKernel\Event\ControllerEvent")
*/
const CONTROLLER = 'kernel.controller';
/**
* The CONTROLLER_ARGUMENTS event occurs once controller arguments have been resolved.
*
* This event allows you to change the arguments that will be passed to
* the controller.
*
* @Event("Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent")
*/
const CONTROLLER_ARGUMENTS = 'kernel.controller_arguments';
/**
* The RESPONSE event occurs once a response was created for
* replying to a request.
*
* This event allows you to modify or replace the response that will be
* replied.
*
* @Event("Symfony\Component\HttpKernel\Event\ResponseEvent")
*/
const RESPONSE = 'kernel.response';
/**
* The TERMINATE event occurs once a response was sent.
*
* This event allows you to run expensive post-response jobs.
*
* @Event("Symfony\Component\HttpKernel\Event\TerminateEvent")
*/
const TERMINATE = 'kernel.terminate';
/**
* The FINISH_REQUEST event occurs when a response was generated for a request.
*
* This event allows you to reset the global and environmental state of
* the application, when it was changed during the request.
*
* @Event("Symfony\Component\HttpKernel\Event\FinishRequestEvent")
*/
const FINISH_REQUEST = 'kernel.finish_request';
}
| {
"pile_set_name": "Github"
} |
/*
** $Id: lstrlib.c,v 1.132.1.5 2010/05/14 15:34:19 roberto Exp $
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lstrlib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/* macro to `unsign' a character */
#define uchar(c) ((unsigned char)(c))
static int str_len (lua_State *L) {
size_t l;
luaL_checklstring(L, 1, &l);
lua_pushinteger(L, l);
return 1;
}
static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
/* relative string position: negative means back from end */
if (pos < 0) pos += (ptrdiff_t)len + 1;
return (pos >= 0) ? pos : 0;
}
static int str_sub (lua_State *L) {
size_t l;
const char *s = luaL_checklstring(L, 1, &l);
ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
if (start < 1) start = 1;
if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
if (start <= end)
lua_pushlstring(L, s+start-1, end-start+1);
else lua_pushliteral(L, "");
return 1;
}
static int str_reverse (lua_State *L) {
size_t l;
luaL_Buffer b;
const char *s = luaL_checklstring(L, 1, &l);
luaL_buffinit(L, &b);
while (l--) luaL_addchar(&b, s[l]);
luaL_pushresult(&b);
return 1;
}
static int str_lower (lua_State *L) {
size_t l;
size_t i;
luaL_Buffer b;
const char *s = luaL_checklstring(L, 1, &l);
luaL_buffinit(L, &b);
for (i=0; i<l; i++)
luaL_addchar(&b, tolower(uchar(s[i])));
luaL_pushresult(&b);
return 1;
}
static int str_upper (lua_State *L) {
size_t l;
size_t i;
luaL_Buffer b;
const char *s = luaL_checklstring(L, 1, &l);
luaL_buffinit(L, &b);
for (i=0; i<l; i++)
luaL_addchar(&b, toupper(uchar(s[i])));
luaL_pushresult(&b);
return 1;
}
static int str_rep (lua_State *L) {
size_t l;
luaL_Buffer b;
const char *s = luaL_checklstring(L, 1, &l);
int n = luaL_checkint(L, 2);
luaL_buffinit(L, &b);
while (n-- > 0)
luaL_addlstring(&b, s, l);
luaL_pushresult(&b);
return 1;
}
static int str_byte (lua_State *L) {
size_t l;
const char *s = luaL_checklstring(L, 1, &l);
ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
int n, i;
if (posi <= 0) posi = 1;
if ((size_t)pose > l) pose = l;
if (posi > pose) return 0; /* empty interval; return no values */
n = (int)(pose - posi + 1);
if (posi + n <= pose) /* overflow? */
luaL_error(L, "string slice too long");
luaL_checkstack(L, n, "string slice too long");
for (i=0; i<n; i++)
lua_pushinteger(L, uchar(s[posi+i-1]));
return n;
}
static int str_char (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
int i;
luaL_Buffer b;
luaL_buffinit(L, &b);
for (i=1; i<=n; i++) {
int c = luaL_checkint(L, i);
luaL_argcheck(L, uchar(c) == c, i, "invalid value");
luaL_addchar(&b, uchar(c));
}
luaL_pushresult(&b);
return 1;
}
static int writer (lua_State *L, const void* b, size_t size, void* B) {
(void)L;
luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
return 0;
}
static int str_dump (lua_State *L) {
luaL_Buffer b;
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, 1);
luaL_buffinit(L,&b);
if (lua_dump(L, writer, &b) != 0)
luaL_error(L, "unable to dump given function");
luaL_pushresult(&b);
return 1;
}
/*
** {======================================================
** PATTERN MATCHING
** =======================================================
*/
#define CAP_UNFINISHED (-1)
#define CAP_POSITION (-2)
typedef struct MatchState {
const char *src_init; /* init of source string */
const char *src_end; /* end (`\0') of source string */
lua_State *L;
int level; /* total number of captures (finished or unfinished) */
struct {
const char *init;
ptrdiff_t len;
} capture[LUA_MAXCAPTURES];
} MatchState;
#define L_ESC '%'
#define SPECIALS "^$*+?.([%-"
static int check_capture (MatchState *ms, int l) {
l -= '1';
if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
return luaL_error(ms->L, "invalid capture index");
return l;
}
static int capture_to_close (MatchState *ms) {
int level = ms->level;
for (level--; level>=0; level--)
if (ms->capture[level].len == CAP_UNFINISHED) return level;
return luaL_error(ms->L, "invalid pattern capture");
}
static const char *classend (MatchState *ms, const char *p) {
switch (*p++) {
case L_ESC: {
if (*p == '\0')
luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
return p+1;
}
case '[': {
if (*p == '^') p++;
do { /* look for a `]' */
if (*p == '\0')
luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
if (*(p++) == L_ESC && *p != '\0')
p++; /* skip escapes (e.g. `%]') */
} while (*p != ']');
return p+1;
}
default: {
return p;
}
}
}
static int match_class (int c, int cl) {
int res;
switch (tolower(cl)) {
case 'a' : res = isalpha(c); break;
case 'c' : res = iscntrl(c); break;
case 'd' : res = isdigit(c); break;
case 'l' : res = islower(c); break;
case 'p' : res = ispunct(c); break;
case 's' : res = isspace(c); break;
case 'u' : res = isupper(c); break;
case 'w' : res = isalnum(c); break;
case 'x' : res = isxdigit(c); break;
case 'z' : res = (c == 0); break;
default: return (cl == c);
}
return (islower(cl) ? res : !res);
}
static int matchbracketclass (int c, const char *p, const char *ec) {
int sig = 1;
if (*(p+1) == '^') {
sig = 0;
p++; /* skip the `^' */
}
while (++p < ec) {
if (*p == L_ESC) {
p++;
if (match_class(c, uchar(*p)))
return sig;
}
else if ((*(p+1) == '-') && (p+2 < ec)) {
p+=2;
if (uchar(*(p-2)) <= c && c <= uchar(*p))
return sig;
}
else if (uchar(*p) == c) return sig;
}
return !sig;
}
static int singlematch (int c, const char *p, const char *ep) {
switch (*p) {
case '.': return 1; /* matches any char */
case L_ESC: return match_class(c, uchar(*(p+1)));
case '[': return matchbracketclass(c, p, ep-1);
default: return (uchar(*p) == c);
}
}
static const char *match (MatchState *ms, const char *s, const char *p);
static const char *matchbalance (MatchState *ms, const char *s,
const char *p) {
if (*p == 0 || *(p+1) == 0)
luaL_error(ms->L, "unbalanced pattern");
if (*s != *p) return NULL;
else {
int b = *p;
int e = *(p+1);
int cont = 1;
while (++s < ms->src_end) {
if (*s == e) {
if (--cont == 0) return s+1;
}
else if (*s == b) cont++;
}
}
return NULL; /* string ends out of balance */
}
static const char *max_expand (MatchState *ms, const char *s,
const char *p, const char *ep) {
ptrdiff_t i = 0; /* counts maximum expand for item */
while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
i++;
/* keeps trying to match with the maximum repetitions */
while (i>=0) {
const char *res = match(ms, (s+i), ep+1);
if (res) return res;
i--; /* else didn't match; reduce 1 repetition to try again */
}
return NULL;
}
static const char *min_expand (MatchState *ms, const char *s,
const char *p, const char *ep) {
for (;;) {
const char *res = match(ms, s, ep+1);
if (res != NULL)
return res;
else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
s++; /* try with one more repetition */
else return NULL;
}
}
static const char *start_capture (MatchState *ms, const char *s,
const char *p, int what) {
const char *res;
int level = ms->level;
if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
ms->capture[level].init = s;
ms->capture[level].len = what;
ms->level = level+1;
if ((res=match(ms, s, p)) == NULL) /* match failed? */
ms->level--; /* undo capture */
return res;
}
static const char *end_capture (MatchState *ms, const char *s,
const char *p) {
int l = capture_to_close(ms);
const char *res;
ms->capture[l].len = s - ms->capture[l].init; /* close capture */
if ((res = match(ms, s, p)) == NULL) /* match failed? */
ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
return res;
}
static const char *match_capture (MatchState *ms, const char *s, int l) {
size_t len;
l = check_capture(ms, l);
len = ms->capture[l].len;
if ((size_t)(ms->src_end-s) >= len &&
memcmp(ms->capture[l].init, s, len) == 0)
return s+len;
else return NULL;
}
static const char *match (MatchState *ms, const char *s, const char *p) {
init: /* using goto's to optimize tail recursion */
switch (*p) {
case '(': { /* start capture */
if (*(p+1) == ')') /* position capture? */
return start_capture(ms, s, p+2, CAP_POSITION);
else
return start_capture(ms, s, p+1, CAP_UNFINISHED);
}
case ')': { /* end capture */
return end_capture(ms, s, p+1);
}
case L_ESC: {
switch (*(p+1)) {
case 'b': { /* balanced string? */
s = matchbalance(ms, s, p+2);
if (s == NULL) return NULL;
p+=4; goto init; /* else return match(ms, s, p+4); */
}
case 'f': { /* frontier? */
const char *ep; char previous;
p += 2;
if (*p != '[')
luaL_error(ms->L, "missing " LUA_QL("[") " after "
LUA_QL("%%f") " in pattern");
ep = classend(ms, p); /* points to what is next */
previous = (s == ms->src_init) ? '\0' : *(s-1);
if (matchbracketclass(uchar(previous), p, ep-1) ||
!matchbracketclass(uchar(*s), p, ep-1)) return NULL;
p=ep; goto init; /* else return match(ms, s, ep); */
}
default: {
if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
s = match_capture(ms, s, uchar(*(p+1)));
if (s == NULL) return NULL;
p+=2; goto init; /* else return match(ms, s, p+2) */
}
goto dflt; /* case default */
}
}
}
case '\0': { /* end of pattern */
return s; /* match succeeded */
}
case '$': {
if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
return (s == ms->src_end) ? s : NULL; /* check end of string */
else goto dflt;
}
default: dflt: { /* it is a pattern item */
const char *ep = classend(ms, p); /* points to what is next */
int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
switch (*ep) {
case '?': { /* optional */
const char *res;
if (m && ((res=match(ms, s+1, ep+1)) != NULL))
return res;
p=ep+1; goto init; /* else return match(ms, s, ep+1); */
}
case '*': { /* 0 or more repetitions */
return max_expand(ms, s, p, ep);
}
case '+': { /* 1 or more repetitions */
return (m ? max_expand(ms, s+1, p, ep) : NULL);
}
case '-': { /* 0 or more repetitions (minimum) */
return min_expand(ms, s, p, ep);
}
default: {
if (!m) return NULL;
s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
}
}
}
}
}
static const char *lmemfind (const char *s1, size_t l1,
const char *s2, size_t l2) {
if (l2 == 0) return s1; /* empty strings are everywhere */
else if (l2 > l1) return NULL; /* avoids a negative `l1' */
else {
const char *init; /* to search for a `*s2' inside `s1' */
l2--; /* 1st char will be checked by `memchr' */
l1 = l1-l2; /* `s2' cannot be found after that */
while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
init++; /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct `l1' and `s1' to try again */
l1 -= init-s1;
s1 = init;
}
}
return NULL; /* not found */
}
}
static void push_onecapture (MatchState *ms, int i, const char *s,
const char *e) {
if (i >= ms->level) {
if (i == 0) /* ms->level == 0, too */
lua_pushlstring(ms->L, s, e - s); /* add whole match */
else
luaL_error(ms->L, "invalid capture index");
}
else {
ptrdiff_t l = ms->capture[i].len;
if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
if (l == CAP_POSITION)
lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
else
lua_pushlstring(ms->L, ms->capture[i].init, l);
}
}
static int push_captures (MatchState *ms, const char *s, const char *e) {
int i;
int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
luaL_checkstack(ms->L, nlevels, "too many captures");
for (i = 0; i < nlevels; i++)
push_onecapture(ms, i, s, e);
return nlevels; /* number of strings pushed */
}
static int str_find_aux (lua_State *L, int find) {
size_t l1, l2;
const char *s = luaL_checklstring(L, 1, &l1);
const char *p = luaL_checklstring(L, 2, &l2);
ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
if (init < 0) init = 0;
else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
if (find && (lua_toboolean(L, 4) || /* explicit request? */
strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
/* do a plain search */
const char *s2 = lmemfind(s+init, l1-init, p, l2);
if (s2) {
lua_pushinteger(L, s2-s+1);
lua_pushinteger(L, s2-s+l2);
return 2;
}
}
else {
MatchState ms;
int anchor = (*p == '^') ? (p++, 1) : 0;
const char *s1=s+init;
ms.L = L;
ms.src_init = s;
ms.src_end = s+l1;
do {
const char *res;
ms.level = 0;
if ((res=match(&ms, s1, p)) != NULL) {
if (find) {
lua_pushinteger(L, s1-s+1); /* start */
lua_pushinteger(L, res-s); /* end */
return push_captures(&ms, NULL, 0) + 2;
}
else
return push_captures(&ms, s1, res);
}
} while (s1++ < ms.src_end && !anchor);
}
lua_pushnil(L); /* not found */
return 1;
}
static int str_find (lua_State *L) {
return str_find_aux(L, 1);
}
static int str_match (lua_State *L) {
return str_find_aux(L, 0);
}
static int gmatch_aux (lua_State *L) {
MatchState ms;
size_t ls;
const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
const char *p = lua_tostring(L, lua_upvalueindex(2));
const char *src;
ms.L = L;
ms.src_init = s;
ms.src_end = s+ls;
for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
src <= ms.src_end;
src++) {
const char *e;
ms.level = 0;
if ((e = match(&ms, src, p)) != NULL) {
lua_Integer newstart = e-s;
if (e == src) newstart++; /* empty match? go at least one position */
lua_pushinteger(L, newstart);
lua_replace(L, lua_upvalueindex(3));
return push_captures(&ms, src, e);
}
}
return 0; /* not found */
}
static int gmatch (lua_State *L) {
luaL_checkstring(L, 1);
luaL_checkstring(L, 2);
lua_settop(L, 2);
lua_pushinteger(L, 0);
lua_pushcclosure(L, gmatch_aux, 3);
return 1;
}
static int gfind_nodef (lua_State *L) {
return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
LUA_QL("string.gmatch"));
}
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
const char *e) {
size_t l, i;
const char *news = lua_tolstring(ms->L, 3, &l);
for (i = 0; i < l; i++) {
if (news[i] != L_ESC)
luaL_addchar(b, news[i]);
else {
i++; /* skip ESC */
if (!isdigit(uchar(news[i])))
luaL_addchar(b, news[i]);
else if (news[i] == '0')
luaL_addlstring(b, s, e - s);
else {
push_onecapture(ms, news[i] - '1', s, e);
luaL_addvalue(b); /* add capture to accumulated result */
}
}
}
}
static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
const char *e) {
lua_State *L = ms->L;
switch (lua_type(L, 3)) {
case LUA_TNUMBER:
case LUA_TSTRING: {
add_s(ms, b, s, e);
return;
}
case LUA_TFUNCTION: {
int n;
lua_pushvalue(L, 3);
n = push_captures(ms, s, e);
lua_call(L, n, 1);
break;
}
case LUA_TTABLE: {
push_onecapture(ms, 0, s, e);
lua_gettable(L, 3);
break;
}
}
if (!lua_toboolean(L, -1)) { /* nil or false? */
lua_pop(L, 1);
lua_pushlstring(L, s, e - s); /* keep original text */
}
else if (!lua_isstring(L, -1))
luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
luaL_addvalue(b); /* add result to accumulator */
}
static int str_gsub (lua_State *L) {
size_t srcl;
const char *src = luaL_checklstring(L, 1, &srcl);
const char *p = luaL_checkstring(L, 2);
int tr = lua_type(L, 3);
int max_s = luaL_optint(L, 4, srcl+1);
int anchor = (*p == '^') ? (p++, 1) : 0;
int n = 0;
MatchState ms;
luaL_Buffer b;
luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
"string/function/table expected");
luaL_buffinit(L, &b);
ms.L = L;
ms.src_init = src;
ms.src_end = src+srcl;
while (n < max_s) {
const char *e;
ms.level = 0;
e = match(&ms, src, p);
if (e) {
n++;
add_value(&ms, &b, src, e);
}
if (e && e>src) /* non empty match? */
src = e; /* skip it */
else if (src < ms.src_end)
luaL_addchar(&b, *src++);
else break;
if (anchor) break;
}
luaL_addlstring(&b, src, ms.src_end-src);
luaL_pushresult(&b);
lua_pushinteger(L, n); /* number of substitutions */
return 2;
}
/* }====================================================== */
/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
#define MAX_ITEM 512
/* valid flags in a format specification */
#define FLAGS "-+ #0"
/*
** maximum size of each format specification (such as '%-099.99d')
** (+10 accounts for %99.99x plus margin of error)
*/
#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
size_t l;
const char *s = luaL_checklstring(L, arg, &l);
luaL_addchar(b, '"');
while (l--) {
switch (*s) {
case '"': case '\\': case '\n': {
luaL_addchar(b, '\\');
luaL_addchar(b, *s);
break;
}
case '\r': {
luaL_addlstring(b, "\\r", 2);
break;
}
case '\0': {
luaL_addlstring(b, "\\000", 4);
break;
}
default: {
luaL_addchar(b, *s);
break;
}
}
s++;
}
luaL_addchar(b, '"');
}
static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
const char *p = strfrmt;
while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
luaL_error(L, "invalid format (repeated flags)");
if (isdigit(uchar(*p))) p++; /* skip width */
if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
if (*p == '.') {
p++;
if (isdigit(uchar(*p))) p++; /* skip precision */
if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
}
if (isdigit(uchar(*p)))
luaL_error(L, "invalid format (width or precision too long)");
*(form++) = '%';
strncpy(form, strfrmt, p - strfrmt + 1);
form += p - strfrmt + 1;
*form = '\0';
return p;
}
static void addintlen (char *form) {
size_t l = strlen(form);
char spec = form[l - 1];
strcpy(form + l - 1, LUA_INTFRMLEN);
form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
}
static int str_format (lua_State *L) {
int top = lua_gettop(L);
int arg = 1;
size_t sfl;
const char *strfrmt = luaL_checklstring(L, arg, &sfl);
const char *strfrmt_end = strfrmt+sfl;
luaL_Buffer b;
luaL_buffinit(L, &b);
while (strfrmt < strfrmt_end) {
if (*strfrmt != L_ESC)
luaL_addchar(&b, *strfrmt++);
else if (*++strfrmt == L_ESC)
luaL_addchar(&b, *strfrmt++); /* %% */
else { /* format item */
char form[MAX_FORMAT]; /* to store the format (`%...') */
char buff[MAX_ITEM]; /* to store the formatted item */
if (++arg > top)
luaL_argerror(L, arg, "no value");
strfrmt = scanformat(L, strfrmt, form);
switch (*strfrmt++) {
case 'c': {
sprintf(buff, form, (int)luaL_checknumber(L, arg));
break;
}
case 'd': case 'i': {
addintlen(form);
sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
break;
}
case 'o': case 'u': case 'x': case 'X': {
addintlen(form);
sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
break;
}
case 'e': case 'E': case 'f':
case 'g': case 'G': {
sprintf(buff, form, (double)luaL_checknumber(L, arg));
break;
}
case 'q': {
addquoted(L, &b, arg);
continue; /* skip the 'addsize' at the end */
}
case 's': {
size_t l;
const char *s = luaL_checklstring(L, arg, &l);
if (!strchr(form, '.') && l >= 100) {
/* no precision and string is too long to be formatted;
keep original string */
lua_pushvalue(L, arg);
luaL_addvalue(&b);
continue; /* skip the `addsize' at the end */
}
else {
sprintf(buff, form, s);
break;
}
}
default: { /* also treat cases `pnLlh' */
return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
LUA_QL("format"), *(strfrmt - 1));
}
}
luaL_addlstring(&b, buff, strlen(buff));
}
}
luaL_pushresult(&b);
return 1;
}
static const luaL_Reg strlib[] = {
{"byte", str_byte},
{"char", str_char},
{"dump", str_dump},
{"find", str_find},
{"format", str_format},
{"gfind", gfind_nodef},
{"gmatch", gmatch},
{"gsub", str_gsub},
{"len", str_len},
{"lower", str_lower},
{"match", str_match},
{"rep", str_rep},
{"reverse", str_reverse},
{"sub", str_sub},
{"upper", str_upper},
{NULL, NULL}
};
static void createmetatable (lua_State *L) {
lua_createtable(L, 0, 1); /* create metatable for strings */
lua_pushliteral(L, ""); /* dummy string */
lua_pushvalue(L, -2);
lua_setmetatable(L, -2); /* set string metatable */
lua_pop(L, 1); /* pop dummy string */
lua_pushvalue(L, -2); /* string library... */
lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
lua_pop(L, 1); /* pop metatable */
}
/*
** Open string library
*/
LUALIB_API int luaopen_string (lua_State *L) {
luaL_register(L, LUA_STRLIBNAME, strlib);
#if defined(LUA_COMPAT_GFIND)
lua_getfield(L, -1, "gmatch");
lua_setfield(L, -2, "gfind");
#endif
createmetatable(L);
return 1;
}
| {
"pile_set_name": "Github"
} |
use nom::{be_u16, be_u24, be_u32, be_u8, ErrorKind};
use std::fmt;
mod sni;
use self::sni::{parse_tls_extension, TlsExtension};
use bytes::Bytes;
/// Tls connection that can be recognized to some extent
#[derive(Clone, Debug)]
pub struct TlsWithSni {
/// only possibly useful fields are included here
pub version: TlsVersion,
pub sni: Bytes,
}
pub fn parse_tls_sni(bs: &[u8]) -> Option<TlsWithSni> {
let x = parse_tls_plaintext(bs).ok().map(|y| y.1)?;
let v = x.version;
let n = x.get_sni()?;
Some(TlsWithSni { version: v, sni: n })
}
/// Content type, as defined in IANA TLS ContentType registry
const TLS_RECORD_TYPE_HANDSHAKE: u8 = 0x16;
/// Handshake type
///
/// Handshake types are defined in [RFC5246](https://tools.ietf.org/html/rfc5246) and
/// the [IANA HandshakeType
/// Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-7)
const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01;
/// TLS version
///
/// Only the TLS version defined in the TLS message header is meaningful, the
/// version defined in the record should be ignored or set to TLS 1.0
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct TlsVersion(pub u16);
#[allow(non_upper_case_globals)]
impl TlsVersion {
pub const Ssl30: TlsVersion = TlsVersion(0x0300);
pub const Tls10: TlsVersion = TlsVersion(0x0301);
pub const Tls11: TlsVersion = TlsVersion(0x0302);
pub const Tls12: TlsVersion = TlsVersion(0x0303);
pub const Tls13: TlsVersion = TlsVersion(0x0304);
pub const Tls13Draft18: TlsVersion = TlsVersion(0x7f12);
pub const Tls13Draft19: TlsVersion = TlsVersion(0x7f13);
pub const Tls13Draft20: TlsVersion = TlsVersion(0x7f14);
pub const Tls13Draft21: TlsVersion = TlsVersion(0x7f15);
pub const Tls13Draft22: TlsVersion = TlsVersion(0x7f16);
pub const Tls13Draft23: TlsVersion = TlsVersion(0x7f17);
}
impl From<TlsVersion> for u16 {
fn from(v: TlsVersion) -> u16 {
v.0
}
}
impl fmt::Debug for TlsVersion {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
TlsVersion::Ssl30 => fmt.write_str("TlsVersion::Ssl30"),
TlsVersion::Tls10 => fmt.write_str("TlsVersion::Tls10"),
TlsVersion::Tls11 => fmt.write_str("TlsVersion::Tls11"),
TlsVersion::Tls12 => fmt.write_str("TlsVersion::Tls12"),
TlsVersion::Tls13 => fmt.write_str("TlsVersion::Tls13"),
TlsVersion::Tls13Draft18 => fmt.write_str("TlsVersion::Tls13Draft18"),
TlsVersion::Tls13Draft19 => fmt.write_str("TlsVersion::Tls13Draft19"),
TlsVersion::Tls13Draft20 => fmt.write_str("TlsVersion::Tls13Draft20"),
TlsVersion::Tls13Draft21 => fmt.write_str("TlsVersion::Tls13Draft21"),
TlsVersion::Tls13Draft22 => fmt.write_str("TlsVersion::Tls13Draft22"),
TlsVersion::Tls13Draft23 => fmt.write_str("TlsVersion::Tls13Draft23"),
_ => write!(fmt, "{:x}", self.0),
}
}
}
impl fmt::LowerHex for TlsVersion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:x}", self.0)
}
}
/// TLS Client Hello (from TLS 1.0 to TLS 1.2)
///
/// Some fields are unparsed (for performance reasons), for ex to parse `ext`,
/// call the `parse_tls_extensions` function.
#[derive(Clone, Debug, PartialEq)]
pub struct TlsClientHello<'a> {
/// TLS version of message
pub version: TlsVersion,
pub rand_time: u32,
pub rand_data: &'a [u8],
pub session_id: Option<&'a [u8]>,
/// A list of ciphers supported by client
pub ciphers: &'a [u8],
/// A list of compression methods supported by client
pub comp: &'a [u8],
pub ext: Vec<TlsExtension<'a>>,
}
impl<'a> TlsClientHello<'a> {
pub fn new(
v: u16,
rt: u32,
rd: &'a [u8],
sid: Option<&'a [u8]>,
c: &'a [u8],
co: &'a [u8],
e: Vec<TlsExtension<'a>>,
) -> Self {
TlsClientHello {
version: TlsVersion(v),
rand_time: rt,
rand_data: rd,
session_id: sid,
ciphers: c,
comp: co,
ext: e,
}
}
#[allow(dead_code)]
pub fn get_sni(self) -> Option<Bytes> {
for e in self.ext {
match e {
TlsExtension::SNI(names) => {
for (nt, nb) in names {
if nt == 0 {
return Some(nb);
}
}
}
_ => {}
}
}
None
}
}
/// Helper macro for nom parsers: raise error if the condition is false
macro_rules! error_if (
($i:expr, $cond:expr, $err:expr) => (
{
if $cond {
Err(::nom::Err::Error(error_position!($i, $err)))
} else {
Ok(($i, ()))
}
}
);
);
named!(
parse_tls_handshake_msg_client_hello<TlsClientHello>,
do_parse!(
v: be_u16 >>
rand_time: be_u32 >>
rand_data: take!(28) >> // 28 as 32 (aligned) - 4 (time)
sidlen: be_u8 >> // check <= 32, can be 0
error_if!(sidlen > 32, ErrorKind::Custom(128)) >>
sid: cond!(sidlen > 0, take!(sidlen as usize)) >>
ciphers: length_bytes!(be_u16) >>
comp_len: take!(1) >>
comp: take!(comp_len[0] as usize) >>
// maybe extensions are optional but they are needed in the use case
exts_len: be_u16 >>
exts: flat_map!(take!(exts_len), many0!(complete!(parse_tls_extension ))) >>
(TlsClientHello::new(v,rand_time,rand_data,sid,ciphers,comp, exts))
)
);
/// Parse one packet only, as plaintext
/// A single record can contain multiple messages, they must share the same record type
#[allow(dead_code)]
named!(
parse_tls_plaintext<TlsClientHello>,
do_parse!(
tag!( &[ TLS_RECORD_TYPE_HANDSHAKE ][..] ) >>
_rec_ver: be_u16 >>
_rec_len: be_u16 >>
// just try to parse one message
tag!( &[ TLS_HANDSHAKE_TYPE_CLIENT_HELLO ][..] ) >>
msg_len: be_u24 >>
m: flat_map!(take!(msg_len), call!(parse_tls_handshake_msg_client_hello)) >>
( m )
)
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tls_record_clienthello() {
let empty = &b""[..];
let bytes = [
0x16, // handshake
0x03, 0x01, 0x01, 0x3e, // length: 318 bytes
0x01, // client hello
0x00, 0x01, 0x3a, // len: 314
0x03, 0x03, // tls 1.2
// random
0x97, 0x7e, 0xaa, 0x9c, 0x0f, 0xa9, 0xc4, 0x9f, 0x79, 0x5d, 0xe9, 0x48, 0xa8, 0x26,
0xf0, 0x4a, 0x93, 0x58, 0x1c, 0x31, 0x00, 0x00, 0x00, 0x00, 0xa2, 0xb7, 0x11, 0xba,
0x37, 0x05, 0x36, 0x90, 0x00, // Session ID Length
0x00, 0xaa, // Cipher Suites Length: 170
// cipher
0xca, 0xa0, 0x12, 0x0c, 0xfc, 0x5c, 0x8f, 0xd6, 0x62, 0x92, 0xd2, 0x2f, 0xa0, 0x1e,
0xeb, 0x59, 0xeb, 0x6e, 0x55, 0x1c, 0x66, 0x93, 0xde, 0xab, 0x2f, 0x63, 0x75, 0x8a,
0x32, 0x72, 0x08, 0xb1, 0xf8, 0x6c, 0x92, 0xa7, 0x72, 0x81, 0x9c, 0x33, 0xd4, 0xf5,
0xbc, 0x06, 0x15, 0xdb, 0xcf, 0x06, 0x28, 0x7c, 0xce, 0xe8, 0xa6, 0x9f, 0x68, 0x44,
0x1e, 0x95, 0xdf, 0x21, 0xf5, 0x4a, 0x63, 0x9b, 0xd4, 0x3d, 0xf9, 0x02, 0xfb, 0x4d,
0x7a, 0x58, 0xf7, 0xf2, 0x20, 0x31, 0x96, 0xc8, 0xf8, 0x1a, 0xaa, 0x61, 0x06, 0x5f,
0xa7, 0x02, 0xab, 0x86, 0xb8, 0x75, 0x7c, 0xc0, 0x83, 0x4c, 0x75, 0x2e, 0xa2, 0x48,
0x16, 0x7c, 0x3a, 0x21, 0x13, 0x0a, 0xd9, 0xf2, 0xf7, 0x38, 0xd2, 0xbf, 0x0e, 0xec,
0xec, 0xab, 0xdb, 0xd4, 0xdd, 0x14, 0x6b, 0x7c, 0xeb, 0x8d, 0x2d, 0x60, 0xb9, 0x96,
0xf5, 0x13, 0x5b, 0xf8, 0xb8, 0x43, 0xa8, 0x44, 0x6a, 0x9d, 0xb2, 0xdd, 0xfe, 0x01,
0x63, 0x15, 0x1d, 0x07, 0xf7, 0x54, 0x85, 0x7f, 0x77, 0x90, 0x07, 0x03, 0xc4, 0x24,
0x42, 0x8a, 0xc4, 0xd1, 0x26, 0xed, 0x03, 0x56, 0x83, 0xd9, 0x9e, 0x9e, 0x1c, 0x7a,
0x9e, 0x78, 0x01, 0x00, // compression
0x00, 0x67, // ext len: 103
0x00, 0x00, // Extension Type: Server Name (check extension type)
0x00, 0x0e, // Length (use for bounds checking)
0x00, 0x0c, // Server Name Indication Length
0x00, // Server Name Type: host_name (check server name type)
0x00, 0x09, // Length (length of your data)
// "localhost" (data your after)
0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x00,
0x0b, // ec_point_formats
0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00,
0x0a, // supported_groups (renamed from "elliptic_curves")
0x00, 0x1c, // len: 28
0x2e, 0x79, 0x60, 0x6c, 0x1e, 0x66, 0xe7, 0x96, 0x7a, 0xa9, 0x8c, 0xdf, 0x5f, 0xd8,
0x75, 0x91, 0x66, 0x6a, 0xcb, 0x73, 0x2d, 0x92, 0xea, 0xf8, 0xd8, 0x1d, 0xf7, 0xf5,
0x00, 0x23, // session_ticket (renamed from "SessionTicket TLS")
0x00, 0x00, 0x00, 0x0d, // Signature Algorithms
0x00, 0x20, 0xa8, 0x26, 0xf0, 0x4a, 0x93, 0x58, 0x1c, 0x31, 0xf8, 0x6c, 0x92, 0xa7,
0x72, 0x81, 0x9c, 0x33, 0x83, 0x4c, 0x75, 0x2e, 0xa2, 0x48, 0x16, 0x7c, 0xc4, 0x24,
0x42, 0x8a, 0xc4, 0xd1, 0x26, 0xed, 0x00, 0x0f, // heartbeat
0x00, 0x01, 0x01,
];
let rand_data = &bytes[15..43];
let ciphers = &bytes[46..(46 + 170)];
let expected = TlsClientHello {
version: TlsVersion::Tls12,
rand_time: 0x977e_aa9c,
rand_data: &rand_data,
session_id: None,
ciphers,
comp: &[0],
ext: vec![
TlsExtension::SNI(vec![(0, "localhost".into())]),
TlsExtension::Unknown(11, &[3, 0, 1, 2]),
TlsExtension::Unknown(
10,
&[
0x2e, 0x79, 0x60, 0x6c, 0x1e, 0x66, 0xe7, 0x96, 0x7a, 0xa9, 0x8c, 0xdf,
0x5f, 0xd8, 0x75, 0x91, 0x66, 0x6a, 0xcb, 0x73, 0x2d, 0x92, 0xea, 0xf8,
0xd8, 0x1d, 0xf7, 0xf5,
],
),
TlsExtension::Unknown(35, &[]),
TlsExtension::Unknown(
13,
&[
0xa8, 0x26, 0xf0, 0x4a, 0x93, 0x58, 0x1c, 0x31, 0xf8, 0x6c, 0x92, 0xa7,
0x72, 0x81, 0x9c, 0x33, 0x83, 0x4c, 0x75, 0x2e, 0xa2, 0x48, 0x16, 0x7c,
0xc4, 0x24, 0x42, 0x8a, 0xc4, 0xd1, 0x26, 0xed,
],
),
TlsExtension::Unknown(15, &[1]),
],
};
let res = parse_tls_plaintext(&bytes);
assert_eq!(res, Ok((empty, expected)));
}
}
| {
"pile_set_name": "Github"
} |
--- services/device/hid/hid_connection_freebsd.cc.orig 2019-12-16 13:33:58 UTC
+++ services/device/hid/hid_connection_freebsd.cc
@@ -0,0 +1,240 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "services/device/hid/hid_connection_freebsd.h"
+
+#include <dev/usb/usbhid.h>
+#include <dev/usb/usb_ioctl.h>
+
+#include "base/bind.h"
+#include "base/files/file_descriptor_watcher_posix.h"
+#include "base/location.h"
+#include "base/numerics/safe_math.h"
+#include "base/posix/eintr_wrapper.h"
+#include "base/single_thread_task_runner.h"
+#include "base/strings/stringprintf.h"
+#include "base/task/post_task.h"
+#include "base/threading/scoped_blocking_call.h"
+#include "base/threading/thread_restrictions.h"
+#include "base/threading/thread_task_runner_handle.h"
+#include "components/device_event_log/device_event_log.h"
+#include "services/device/hid/hid_service.h"
+
+namespace device {
+
+class HidConnectionFreeBSD::BlockingTaskHelper {
+ public:
+ BlockingTaskHelper(base::ScopedFD fd,
+ scoped_refptr<HidDeviceInfo> device_info,
+ base::WeakPtr<HidConnectionFreeBSD> connection)
+ : fd_(std::move(fd)),
+ connection_(connection),
+ origin_task_runner_(base::ThreadTaskRunnerHandle::Get()) {
+ DETACH_FROM_SEQUENCE(sequence_checker_);
+ // Report buffers must always have room for the report ID.
+ report_buffer_size_ = device_info->max_input_report_size() + 1;
+ has_report_id_ = device_info->has_report_id();
+ }
+
+ ~BlockingTaskHelper() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); }
+
+ // Starts the FileDescriptorWatcher that reads input events from the device.
+ // Must be called on a thread that has a base::MessageLoopForIO.
+ void Start() {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ base::internal::AssertBlockingAllowed();
+
+ file_watcher_ = base::FileDescriptorWatcher::WatchReadable(
+ fd_.get(), base::Bind(&BlockingTaskHelper::OnFileCanReadWithoutBlocking,
+ base::Unretained(this)));
+ }
+
+ void Write(scoped_refptr<base::RefCountedBytes> buffer,
+ WriteCallback callback) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ base::ScopedBlockingCall scoped_blocking_call(
+ FROM_HERE, base::BlockingType::MAY_BLOCK);
+
+ auto data = buffer->front();
+ size_t size = buffer->size();
+ // if report id is 0, it shouldn't be included
+ if (data[0] == 0) {
+ data++;
+ size--;
+ }
+
+ ssize_t result = HANDLE_EINTR(write(fd_.get(), data, size));
+ if (result < 0) {
+ HID_PLOG(EVENT) << "Write failed";
+ origin_task_runner_->PostTask(FROM_HERE, base::BindOnce(std::move(callback), false));
+ } else {
+ if (static_cast<size_t>(result) != size)
+ HID_LOG(EVENT) << "Incomplete HID write: " << result << " != " << size;
+ origin_task_runner_->PostTask(FROM_HERE, base::BindOnce(std::move(callback), true));
+ }
+ }
+
+ void GetFeatureReport(uint8_t report_id,
+ scoped_refptr<base::RefCountedBytes> buffer,
+ ReadCallback callback) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ base::ScopedBlockingCall scoped_blocking_call(
+ FROM_HERE, base::BlockingType::MAY_BLOCK);
+ struct usb_gen_descriptor ugd;
+ ugd.ugd_report_type = UHID_FEATURE_REPORT;
+ ugd.ugd_data = buffer->front();
+ ugd.ugd_maxlen = buffer->size();
+ int result = HANDLE_EINTR(
+ ioctl(fd_.get(), USB_GET_REPORT, &ugd));
+ if (result < 0) {
+ HID_PLOG(EVENT) << "Failed to get feature report";
+ origin_task_runner_->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), false, nullptr, 0));
+ } else if (result == 0) {
+ HID_LOG(EVENT) << "Get feature result too short.";
+ origin_task_runner_->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), false, nullptr, 0));
+ } else {
+ origin_task_runner_->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), true, buffer, result));
+ }
+ }
+
+ void SendFeatureReport(scoped_refptr<base::RefCountedBytes> buffer,
+ WriteCallback callback) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ struct usb_gen_descriptor ugd;
+ ugd.ugd_report_type = UHID_FEATURE_REPORT;
+ ugd.ugd_data = buffer->front();
+ ugd.ugd_maxlen = buffer->size();
+ // FreeBSD does not require report id if it's not used
+ if (buffer->front()[0] == 0) {
+ ugd.ugd_data = buffer->front() + 1;
+ ugd.ugd_maxlen = buffer->size() - 1;
+ } else {
+ ugd.ugd_data = buffer->front();
+ ugd.ugd_maxlen = buffer->size();
+ }
+ int result = HANDLE_EINTR(
+ ioctl(fd_.get(), USB_SET_REPORT, &ugd));
+ if (result < 0) {
+ HID_PLOG(EVENT) << "Failed to send feature report";
+ origin_task_runner_->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), false));
+ } else {
+ origin_task_runner_->PostTask(FROM_HERE,
+ base::BindOnce(std::move(callback), true));
+ }
+ }
+
+ private:
+ void OnFileCanReadWithoutBlocking() {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+
+ scoped_refptr<base::RefCountedBytes> buffer(new base::RefCountedBytes(report_buffer_size_));
+ unsigned char* data = buffer->front();
+ size_t length = report_buffer_size_;
+ if (!has_report_id_) {
+ // FreeBSD will not prefix the buffer with a report ID if report IDs are not
+ // used by the device. Prefix the buffer with 0.
+ *data++ = 0;
+ length--;
+ }
+
+ ssize_t bytes_read = HANDLE_EINTR(read(fd_.get(), data, length));
+ if (bytes_read < 0) {
+ if (errno != EAGAIN) {
+ HID_PLOG(EVENT) << "Read failed";
+ // This assumes that the error is unrecoverable and disables reading
+ // from the device until it has been re-opened.
+ // TODO(reillyg): Investigate starting and stopping the file descriptor
+ // watcher in response to pending read requests so that per-request
+ // errors can be returned to the client.
+ file_watcher_.reset();
+ }
+ return;
+ }
+ if (!has_report_id_) {
+ // Behave as if the byte prefixed above as the the report ID was read.
+ bytes_read++;
+ }
+
+ origin_task_runner_->PostTask(
+ FROM_HERE, base::BindOnce(&HidConnectionFreeBSD::ProcessInputReport,
+ connection_, buffer, bytes_read));
+ }
+
+ SEQUENCE_CHECKER(sequence_checker_);
+ base::ScopedFD fd_;
+ size_t report_buffer_size_;
+ bool has_report_id_;
+ base::WeakPtr<HidConnectionFreeBSD> connection_;
+ const scoped_refptr<base::SequencedTaskRunner> origin_task_runner_;
+ std::unique_ptr<base::FileDescriptorWatcher::Controller> file_watcher_;
+
+ DISALLOW_COPY_AND_ASSIGN(BlockingTaskHelper);
+};
+
+HidConnectionFreeBSD::HidConnectionFreeBSD(
+ scoped_refptr<HidDeviceInfo> device_info,
+ base::ScopedFD fd,
+ scoped_refptr<base::SequencedTaskRunner> blocking_task_runner)
+ : HidConnection(device_info),
+ blocking_task_runner_(std::move(blocking_task_runner)),
+ weak_factory_(this) {
+ helper_ = std::make_unique<BlockingTaskHelper>(std::move(fd), device_info,
+ weak_factory_.GetWeakPtr());
+ blocking_task_runner_->PostTask(
+ FROM_HERE, base::BindOnce(&BlockingTaskHelper::Start,
+ base::Unretained(helper_.get())));
+}
+
+HidConnectionFreeBSD::~HidConnectionFreeBSD() {}
+
+void HidConnectionFreeBSD::PlatformClose() {
+ // By closing the device on the blocking task runner 1) the requirement that
+ // base::ScopedFD is destroyed on a thread where I/O is allowed is satisfied
+ // and 2) any tasks posted to this task runner that refer to this file will
+ // complete before it is closed.
+ blocking_task_runner_->DeleteSoon(FROM_HERE, helper_.release());
+}
+
+void HidConnectionFreeBSD::PlatformWrite(scoped_refptr<base::RefCountedBytes> buffer,
+ WriteCallback callback) {
+
+ blocking_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&BlockingTaskHelper::Write, base::Unretained(helper_.get()),
+ buffer, std::move(callback)));
+}
+
+void HidConnectionFreeBSD::PlatformGetFeatureReport(uint8_t report_id,
+ ReadCallback callback) {
+ // The first byte of the destination buffer is the report ID being requested
+ // and is overwritten by the feature report.
+ DCHECK_GT(device_info()->max_feature_report_size(), 0u);
+ scoped_refptr<base::RefCountedBytes> buffer(
+ new base::RefCountedBytes(device_info()->max_feature_report_size() + 1));
+ if (report_id != 0)
+ buffer->data()[0] = report_id;
+
+ blocking_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&BlockingTaskHelper::GetFeatureReport,
+ base::Unretained(helper_.get()), report_id,
+ buffer, std::move(callback)));
+}
+
+void HidConnectionFreeBSD::PlatformSendFeatureReport(
+ scoped_refptr<base::RefCountedBytes> buffer,
+ WriteCallback callback) {
+ base::ScopedBlockingCall scoped_blocking_call(
+ FROM_HERE, base::BlockingType::MAY_BLOCK);
+ blocking_task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&BlockingTaskHelper::SendFeatureReport,
+ base::Unretained(helper_.get()), buffer, std::move(callback)));
+}
+
+} // namespace device
| {
"pile_set_name": "Github"
} |
/**
* This file is part of Skript.
*
* Skript is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Skript is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Skript. If not, see <http://www.gnu.org/licenses/>.
*
*
* Copyright 2011-2017 Peter Güttinger and contributors
*/
package ch.njol.skript.effects;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.Nullable;
import ch.njol.skript.Skript;
import ch.njol.skript.classes.ClassInfo;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Examples;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.skript.lang.function.FunctionEvent;
import ch.njol.skript.lang.function.Functions;
import ch.njol.skript.lang.function.ScriptFunction;
import ch.njol.skript.log.RetainingLogHandler;
import ch.njol.skript.log.SkriptLogger;
import ch.njol.util.Kleenean;
/**
* @author Peter Güttinger
*/
@Name("Return")
@Description("Makes a function return a value")
@Examples({"function double(i: number) :: number:",
" return 2 * {_i}"})
@Since("2.2")
public class EffReturn extends Effect {
static {
Skript.registerEffect(EffReturn.class, "return %objects%");
}
@SuppressWarnings("null")
private ScriptFunction<?> function;
@SuppressWarnings("null")
private Expression<?> value;
@SuppressWarnings("unchecked")
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
final ScriptFunction<?> f = Functions.currentFunction;
if (f == null) {
Skript.error("The return statement can only be used in a function");
return false;
}
if (!isDelayed.isFalse()) {
Skript.error("A return statement after a delay is useless, as the calling trigger will resume when the delay starts (and won't get any returned value)");
return false;
}
function = f;
final ClassInfo<?> rt = function.getReturnType();
if (rt == null) {
Skript.error("This function doesn't return any value. Please use 'stop' or 'exit' if you want to stop the function.");
return false;
}
final RetainingLogHandler log = SkriptLogger.startRetainingLog();
final Expression<?> v;
try {
v = exprs[0].getConvertedExpression(rt.getC());
if (v == null) {
log.printErrors("This function is declared to return " + rt.getName().withIndefiniteArticle() + ", but " + exprs[0].toString(null, false) + " is not of that type.");
return false;
}
log.printLog();
} finally {
log.stop();
}
if (f.isSingle() && !v.isSingle()) {
Skript.error("This function is defined to only return a single " + rt.toString() + ", but this return statement can return multiple values.");
return false;
}
value = v;
return true;
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
@Nullable
protected TriggerItem walk(final Event e) {
debug(e, false);
if (e instanceof FunctionEvent)
((ScriptFunction) function).setReturnValue((FunctionEvent) e, value.getArray(e));
else
assert false : e;
return null;
}
@Override
protected void execute(final Event e) {
assert false;
}
@Override
public String toString(@Nullable final Event e, final boolean debug) {
return "return " + value.toString(e, debug);
}
}
| {
"pile_set_name": "Github"
} |
.jp-card-logo.jp-card-mastercard {
// display: none;
$red: #FF0000;
$yellow: #FFAB00;
$offset: 0;
color: white;
font-weight: bold;
text-align: center;
font-size: 9px;
line-height: $logo-height;
z-index: 1;
text-shadow: 1px 1px rgba(0, 0, 0, .6);
&:before, &:after {
content: " ";
display: block;
width: $logo-height;
top: 0;
position: absolute;
height: $logo-height;
border-radius: $logo-height / 2;
}
&:before {
left: $offset;
background: $red;
z-index: -1;
}
&:after {
right: $offset;
background: $yellow;
z-index: -2;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.cert;
import java.security.PublicKey;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import java.security.SignatureException;
/**
* <p>Abstract class for managing a variety of identity certificates.
* An identity certificate is a guarantee by a principal that
* a public key is that of another principal. (A principal represents
* an entity such as an individual user, a group, or a corporation.)
*<p>
* This class is an abstraction for certificates that have different
* formats but important common uses. For example, different types of
* certificates, such as X.509 and PGP, share general certificate
* functionality (like encoding and verifying) and
* some types of information (like a public key).
* <p>
* X.509, PGP, and SDSI certificates can all be implemented by
* subclassing the Certificate class, even though they contain different
* sets of information, and they store and retrieve the information in
* different ways.
*
* <p><em>Note: The classes in the package {@code javax.security.cert}
* exist for compatibility with earlier versions of the
* Java Secure Sockets Extension (JSSE). New applications should instead
* use the standard Java SE certificate classes located in
* {@code java.security.cert}.</em></p>
*
* @since 1.4
* @see X509Certificate
* @deprecated Use the classes in {@code java.security.cert} instead.
*
* @author Hemma Prafullchandra
*/
@Deprecated(since="9")
public abstract class Certificate {
/**
* Compares this certificate for equality with the specified
* object. If the {@code other} object is an
* {@code instanceof} {@code Certificate}, then
* its encoded form is retrieved and compared with the
* encoded form of this certificate.
*
* @param other the object to test for equality with this certificate.
* @return true if the encoded forms of the two certificates
* match, false otherwise.
*/
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof Certificate))
return false;
try {
byte[] thisCert = this.getEncoded();
byte[] otherCert = ((Certificate)other).getEncoded();
if (thisCert.length != otherCert.length)
return false;
for (int i = 0; i < thisCert.length; i++)
if (thisCert[i] != otherCert[i])
return false;
return true;
} catch (CertificateException e) {
return false;
}
}
/**
* Returns a hashcode value for this certificate from its
* encoded form.
*
* @return the hashcode value.
*/
public int hashCode() {
int retval = 0;
try {
byte[] certData = this.getEncoded();
for (int i = 1; i < certData.length; i++) {
retval += certData[i] * i;
}
return (retval);
} catch (CertificateException e) {
return (retval);
}
}
/**
* Returns the encoded form of this certificate. It is
* assumed that each certificate type would have only a single
* form of encoding; for example, X.509 certificates would
* be encoded as ASN.1 DER.
*
* @return encoded form of this certificate
* @exception CertificateEncodingException on internal certificate
* encoding failure
*/
public abstract byte[] getEncoded() throws CertificateEncodingException;
/**
* Verifies that this certificate was signed using the
* private key that corresponds to the specified public key.
*
* @param key the PublicKey used to carry out the verification.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public abstract void verify(PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException;
/**
* Verifies that this certificate was signed using the
* private key that corresponds to the specified public key.
* This method uses the signature verification engine
* supplied by the specified provider.
*
* @param key the PublicKey used to carry out the verification.
* @param sigProvider the name of the signature provider.
* @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public abstract void verify(PublicKey key, String sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException;
/**
* Returns a string representation of this certificate.
*
* @return a string representation of this certificate.
*/
public abstract String toString();
/**
* Gets the public key from this certificate.
*
* @return the public key.
*/
public abstract PublicKey getPublicKey();
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2011, 2013 Ericsson and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Ericsson - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.dsf.gdb.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.debug.core.CDebugUtils;
import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.DsfExecutor;
import org.eclipse.cdt.dsf.concurrent.IDsfStatusConstants;
import org.eclipse.cdt.dsf.concurrent.ImmediateDataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
import org.eclipse.cdt.dsf.datamodel.IDMContext;
import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
import org.eclipse.cdt.dsf.gdb.internal.GdbPlugin;
import org.eclipse.cdt.dsf.gdb.service.command.IGDBControl;
import org.eclipse.cdt.dsf.mi.service.command.CommandFactory;
import org.eclipse.cdt.dsf.mi.service.command.output.MIAddInferiorInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.MIInfo;
import org.eclipse.cdt.dsf.service.DsfServicesTracker;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* With GDB 7.2, to create a new process, we need to use the -add-inferior command first.
* This allows to create multiple processes, unlike previous versions of GDB.
* Note that GDB 7.1 does support multi-process but didn't have the MI commands (e.g., -add-inferior)
* so we only support multi-process starting with 7.2
*
* @since 4.0
*/
public class DebugNewProcessSequence_7_2 extends DebugNewProcessSequence {
private IGDBControl fGdbControl;
private IGDBProcesses fProcService;
private IGDBBackend fBackend;
private CommandFactory fCommandFactory;
private String fSessionId;
private final boolean fInitialProcess;
private final Map<String, Object> fAttributes;
public DebugNewProcessSequence_7_2(DsfExecutor executor, boolean isInitial, IDMContext dmc, String file,
Map<String, Object> attributes, DataRequestMonitor<IDMContext> rm) {
super(executor, isInitial, dmc, file, attributes, rm);
fSessionId = dmc.getSessionId();
fInitialProcess = isInitial;
fAttributes = attributes;
}
@Override
protected String[] getExecutionOrder(String group) {
if (GROUP_TOP_LEVEL.equals(group)) {
// Initialize the list with the base class' steps
// We need to create a list that we can modify, which is why we create our own ArrayList.
List<String> orderList = new ArrayList<>(Arrays.asList(super.getExecutionOrder(GROUP_TOP_LEVEL)));
// Now insert our steps right after the initialization of the base class.
orderList.add(orderList.indexOf("stepInitializeBaseSequence") + 1, "stepInitializeSequence_7_2"); //$NON-NLS-1$ //$NON-NLS-2$
orderList.add(orderList.indexOf("stepInitializeSequence_7_2") + 1, "stepAddInferior"); //$NON-NLS-1$ //$NON-NLS-2$
orderList.add(orderList.indexOf("stepSetExecutable") + 1, "stepSetRemoteExecutable"); //$NON-NLS-1$ //$NON-NLS-2$
return orderList.toArray(new String[orderList.size()]);
}
return null;
}
/**
* Initialize the members of the DebugNewProcessSequence_7_2 class.
* This step is mandatory for the rest of the sequence to complete.
*/
@Execute
public void stepInitializeSequence_7_2(RequestMonitor rm) {
DsfServicesTracker tracker = new DsfServicesTracker(GdbPlugin.getBundleContext(), fSessionId);
fGdbControl = tracker.getService(IGDBControl.class);
fProcService = tracker.getService(IGDBProcesses.class);
fBackend = tracker.getService(IGDBBackend.class);
tracker.dispose();
if (fGdbControl == null || fProcService == null || fBackend == null) {
rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR,
"Cannot obtain service", null)); //$NON-NLS-1$
rm.done();
return;
}
fCommandFactory = fGdbControl.getCommandFactory();
rm.done();
}
/**
* Add a new inferior.
*/
@Execute
public void stepAddInferior(final RequestMonitor rm) {
if (fInitialProcess) {
// The first process is automatically created by GDB. We actually want to use that first created process
// instead of ignoring it and creating a new one for a couple of reasons:
// 1- post-mortem and non-attach remote sessions don't support creating a new process
// 2- commands that were part of the .gdbinit file will affect the initial process, which is what the user expects,
// but would not affect a new process we created instead.
setContainerContext(fProcService.createContainerContextFromGroupId(fGdbControl.getContext(),
GDBProcesses_7_2.INITIAL_THREAD_GROUP_ID));
rm.done();
return;
}
fGdbControl.queueCommand(fGdbControl.getCommandFactory().createMIAddInferior(fGdbControl.getContext()),
new ImmediateDataRequestMonitor<MIAddInferiorInfo>(rm) {
@Override
protected void handleSuccess() {
final String groupId = getData().getGroupId();
if (groupId == null || groupId.trim().length() == 0) {
rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID,
IDsfStatusConstants.REQUEST_FAILED, "Invalid gdb group id.", null)); //$NON-NLS-1$
rm.done();
return;
}
setContainerContext(
fProcService.createContainerContextFromGroupId(fGdbControl.getContext(), groupId));
rm.done();
}
});
}
/**
* Set remote executable.
* @since 4.2
*/
@Execute
public void stepSetRemoteExecutable(final RequestMonitor rm) {
if (fBackend.getSessionType() == SessionType.REMOTE && fBackend.getIsAttachSession()) {
String remoteBinary = CDebugUtils.getAttribute(fAttributes,
IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_REMOTE_BINARY, ""); //$NON-NLS-1$
if (remoteBinary.length() == 0) {
rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, "Binary on host is not specified")); //$NON-NLS-1$
rm.done();
return;
}
fGdbControl.queueCommand(fCommandFactory.createMIGDBSet(getContainerContext(), new String[] { "remote", //$NON-NLS-1$
"exec-file", //$NON-NLS-1$
remoteBinary, }), new ImmediateDataRequestMonitor<MIInfo>(rm));
} else {
rm.done();
}
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>AnyNodeDescriptionProps Protocol Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Protocol/AnyNodeDescriptionProps" class="dashAnchor"></a>
<a title="AnyNodeDescriptionProps Protocol Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html">Katana Docs</a> (100% documented)</p>
<p class="header-right"><a href="https://github.com/BendingSpoons/katana-swift"><img src="../img/gh.png"/>View on GitHub</a></p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html">Katana Reference</a>
<img id="carat" src="../img/carat.png" />
AnyNodeDescriptionProps Protocol Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes/EmptySideEffectDependencyContainer.html">EmptySideEffectDependencyContainer</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Node.html">Node</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PlasticNode.html">PlasticNode</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PlasticView.html">PlasticView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Renderer.html">Renderer</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Store.html">Store</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ViewsContainer.html">ViewsContainer</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Enums.html">Enums</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Enums/AnimationType.html">AnimationType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/AsyncActionState.html">AsyncActionState</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:O6Katana9EmptyKeys">EmptyKeys</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Extensions/Array.html">Array</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGSize.html">CGSize</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIView.html">UIView</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/Action.html">Action</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ActionWithSideEffect.html">ActionWithSideEffect</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyAsyncAction.html">AnyAsyncAction</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyConnectedNodeDescription.html">AnyConnectedNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNode.html">AnyNode</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNodeDescription.html">AnyNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNodeDescriptionProps.html">AnyNodeDescriptionProps</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNodeDescriptionWithChildren.html">AnyNodeDescriptionWithChildren</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyPlasticNodeDescription.html">AnyPlasticNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyStore.html">AnyStore</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AsyncAction.html">AsyncAction</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/Childrenable.html">Childrenable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ConnectedNodeDescription.html">ConnectedNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/LinkeableAction.html">LinkeableAction</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescription.html">NodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescriptionProps.html">NodeDescriptionProps</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescriptionState.html">NodeDescriptionState</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescriptionWithChildren.html">NodeDescriptionWithChildren</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PlasticNodeDescription.html">PlasticNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PlasticReferenceSizeable.html">PlasticReferenceSizeable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PlatformNativeView.html">PlatformNativeView</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SideEffectDependencyContainer.html">SideEffectDependencyContainer</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/State.html">State</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Structs.html">Structs</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Structs/ActionLinker.html">ActionLinker</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ActionLinks.html">ActionLinks</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Anchor.html">Anchor</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Anchor/Kind.html">– Kind</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Animation.html">Animation</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnimationContainer.html">AnimationContainer</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnimationOptions.html">AnimationOptions</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnimationProps.html">AnimationProps</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ChildrenAnimations.html">ChildrenAnimations</a>
</li>
<li class="nav-group-task">
<a href="../Structs/EdgeInsets.html">EdgeInsets</a>
</li>
<li class="nav-group-task">
<a href="../Structs/EmptyProps.html">EmptyProps</a>
</li>
<li class="nav-group-task">
<a href="../Structs/EmptyState.html">EmptyState</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Size.html">Size</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Value.html">Value</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Typealiases.html">Typealiases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Typealiases.html#/s:6Katana25AnimationPropsTransformer">AnimationPropsTransformer</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:6Katana20NodeUpdateCompletion">NodeUpdateCompletion</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Associated Types.html">Associated Types</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Associated Types.html#/s:P6Katana27NodeDescriptionWithChildren9PropsType">PropsType</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>AnyNodeDescriptionProps</h1>
<div class="declaration">
<div class="language">
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">protocol</span> <span class="kt">AnyNodeDescriptionProps</span></code></pre>
</div>
</div>
<p>Type Erasure for <code><a href="../Protocols/NodeDescriptionProps.html">NodeDescriptionProps</a></code></p>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:vP6Katana23AnyNodeDescriptionProps5frameVSC6CGRect"></a>
<a name="//apple_ref/swift/Property/frame" class="dashAnchor"></a>
<a class="token" href="#/s:vP6Katana23AnyNodeDescriptionProps5frameVSC6CGRect">frame</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The frame of the <code><a href="../Protocols/NodeDescription.html">NodeDescription</a></code></p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">var</span> <span class="nv">frame</span><span class="p">:</span> <span class="kt">CGRect</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.0/Katana/Core/NodeDescription/NodeDescription.swift#L42">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vP6Katana23AnyNodeDescriptionProps5alphaV12CoreGraphics7CGFloat"></a>
<a name="//apple_ref/swift/Property/alpha" class="dashAnchor"></a>
<a class="token" href="#/s:vP6Katana23AnyNodeDescriptionProps5alphaV12CoreGraphics7CGFloat">alpha</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The alpha of the <code><a href="../Protocols/NodeDescription.html">NodeDescription</a></code></p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">var</span> <span class="nv">alpha</span><span class="p">:</span> <span class="kt">CGFloat</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.0/Katana/Core/NodeDescription/NodeDescription.swift#L45">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vP6Katana23AnyNodeDescriptionProps3keyGSqSS_"></a>
<a name="//apple_ref/swift/Property/key" class="dashAnchor"></a>
<a class="token" href="#/s:vP6Katana23AnyNodeDescriptionProps3keyGSqSS_">key</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The key is used for many purposes. It is used for instance to calculate a more precise <code>replaceKey</code>,
from Plastic to implement the layout system or in the animation management to reference children</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">var</span> <span class="nv">key</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.0/Katana/Core/NodeDescription/NodeDescription.swift#L51">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FP6Katana23AnyNodeDescriptionProps6setKeyurFqd__T_"></a>
<a name="//apple_ref/swift/Method/setKey(_:)" class="dashAnchor"></a>
<a class="token" href="#/s:FP6Katana23AnyNodeDescriptionProps6setKeyurFqd__T_">setKey(_:)</a>
</code>
<span class="declaration-note">
Default implementation
</span>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Helper method to translate any Swift value to a key, which is a String</p>
</div>
<h4>Default Implementation</h4>
<div class="default_impl abstract">
<p>The default implementation uses the Swift string interpolation to create the key</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">mutating</span> <span class="kd">func</span> <span class="n">setKey</span><span class="o"><</span><span class="kt">K</span><span class="o">></span><span class="p">(</span><span class="n">_</span> <span class="nv">key</span><span class="p">:</span> <span class="kt">K</span><span class="p">)</span></code></pre>
</div>
</div>
<div>
<h4>Parameters</h4>
<table class="graybox">
<tbody>
<tr>
<td>
<code>
<em>key</em>
</code>
</td>
<td>
<div>
<p>the key</p>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.0/Katana/Core/NodeDescription/NodeDescription.swift#L58">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2017 <a class="link" href="http://bendingspoons.com" target="_blank" rel="external">Bending Spoons Team</a>. All rights reserved. (Last updated: 2017-02-07)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.7.3</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Mime
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Zend_Exception
*/
//require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Mime
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Mime_Exception extends Zend_Exception
{
}
| {
"pile_set_name": "Github"
} |
#layout {
#align {
.btn-group {
height: 120px;
width: 180px;
position: relative;
.btn {
position: absolute;
display: inline-block;
&.top { top: 0px; left: 50%; margin-left: -30px; }
&.bottom { bottom: 0px; left: 50%; margin-left: -30px; }
&.left { left: 0px; top: 50%; margin-top: -30px; }
&.right { right: 0px; top: 50%; margin-top: -30px; }
}
}
}
} | {
"pile_set_name": "Github"
} |
# This module contains abstractions for the input stream. You don't have to
# looks further, there are no pretty code.
#
# We define two classes here.
#
# Mark(source, line, column)
# It's just a record and its only use is producing nice error messages.
# Parser does not use it for any other purposes.
#
# Reader(source, data)
# Reader determines the encoding of `data` and converts it to unicode.
# Reader provides the following methods and attributes:
# reader.peek(length=1) - return the next `length` characters
# reader.forward(length=1) - move the current position to `length` characters.
# reader.index - the number of the current character.
# reader.line, stream.column - the line and the column of the current character.
__all__ = ['Reader', 'ReaderError']
from .error import YAMLError, Mark
import codecs, re
class ReaderError(YAMLError):
def __init__(self, name, position, character, encoding, reason):
self.name = name
self.character = character
self.position = position
self.encoding = encoding
self.reason = reason
def __str__(self):
if isinstance(self.character, bytes):
return "'%s' codec can't decode byte #x%02x: %s\n" \
" in \"%s\", position %d" \
% (self.encoding, ord(self.character), self.reason,
self.name, self.position)
else:
return "unacceptable character #x%04x: %s\n" \
" in \"%s\", position %d" \
% (self.character, self.reason,
self.name, self.position)
class Reader(object):
# Reader:
# - determines the data encoding and converts it to a unicode string,
# - checks if characters are in allowed range,
# - adds '\0' to the end.
# Reader accepts
# - a `bytes` object,
# - a `str` object,
# - a file-like object with its `read` method returning `str`,
# - a file-like object with its `read` method returning `unicode`.
# Yeah, it's ugly and slow.
def __init__(self, stream):
self.name = None
self.stream = None
self.stream_pointer = 0
self.eof = True
self.buffer = ''
self.pointer = 0
self.raw_buffer = None
self.raw_decode = None
self.encoding = None
self.index = 0
self.line = 0
self.column = 0
if isinstance(stream, str):
self.name = "<unicode string>"
self.check_printable(stream)
self.buffer = stream+'\0'
elif isinstance(stream, bytes):
self.name = "<byte string>"
self.raw_buffer = stream
self.determine_encoding()
else:
self.stream = stream
self.name = getattr(stream, 'name', "<file>")
self.eof = False
self.raw_buffer = None
self.determine_encoding()
def peek(self, index=0):
try:
return self.buffer[self.pointer+index]
except IndexError:
self.update(index+1)
return self.buffer[self.pointer+index]
def prefix(self, length=1):
if self.pointer+length >= len(self.buffer):
self.update(length)
return self.buffer[self.pointer:self.pointer+length]
def forward(self, length=1):
if self.pointer+length+1 >= len(self.buffer):
self.update(length+1)
while length:
ch = self.buffer[self.pointer]
self.pointer += 1
self.index += 1
if ch in '\n\x85\u2028\u2029' \
or (ch == '\r' and self.buffer[self.pointer] != '\n'):
self.line += 1
self.column = 0
elif ch != '\uFEFF':
self.column += 1
length -= 1
def get_mark(self):
if self.stream is None:
return Mark(self.name, self.index, self.line, self.column,
self.buffer, self.pointer)
else:
return Mark(self.name, self.index, self.line, self.column,
None, None)
def determine_encoding(self):
while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2):
self.update_raw()
if isinstance(self.raw_buffer, bytes):
if self.raw_buffer.startswith(codecs.BOM_UTF16_LE):
self.raw_decode = codecs.utf_16_le_decode
self.encoding = 'utf-16-le'
elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE):
self.raw_decode = codecs.utf_16_be_decode
self.encoding = 'utf-16-be'
else:
self.raw_decode = codecs.utf_8_decode
self.encoding = 'utf-8'
self.update(1)
NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]')
def check_printable(self, data):
match = self.NON_PRINTABLE.search(data)
if match:
character = match.group()
position = self.index+(len(self.buffer)-self.pointer)+match.start()
raise ReaderError(self.name, position, ord(character),
'unicode', "special characters are not allowed")
def update(self, length):
if self.raw_buffer is None:
return
self.buffer = self.buffer[self.pointer:]
self.pointer = 0
while len(self.buffer) < length:
if not self.eof:
self.update_raw()
if self.raw_decode is not None:
try:
data, converted = self.raw_decode(self.raw_buffer,
'strict', self.eof)
except UnicodeDecodeError as exc:
character = self.raw_buffer[exc.start]
if self.stream is not None:
position = self.stream_pointer-len(self.raw_buffer)+exc.start
else:
position = exc.start
raise ReaderError(self.name, position, character,
exc.encoding, exc.reason)
else:
data = self.raw_buffer
converted = len(data)
self.check_printable(data)
self.buffer += data
self.raw_buffer = self.raw_buffer[converted:]
if self.eof:
self.buffer += '\0'
self.raw_buffer = None
break
def update_raw(self, size=4096):
data = self.stream.read(size)
if self.raw_buffer is None:
self.raw_buffer = data
else:
self.raw_buffer += data
self.stream_pointer += len(data)
if not data:
self.eof = True
| {
"pile_set_name": "Github"
} |
#ifndef CAFFE_BASE_CONVOLUTION_LAYER_HPP_
#define CAFFE_BASE_CONVOLUTION_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/im2col.hpp"
namespace caffe {
/**
* @brief Abstract base class that factors out the BLAS code common to
* ConvolutionLayer and DeconvolutionLayer.
*/
template <typename Dtype>
class BaseConvolutionLayer : public Layer<Dtype> {
public:
explicit BaseConvolutionLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline int MinBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline bool EqualNumBottomTopBlobs() const { return true; }
protected:
// Helper functions that abstract away the column buffer and gemm arguments.
// The last argument in forward_cpu_gemm is so that we can skip the im2col if
// we just called weight_cpu_gemm with the same input.
void forward_cpu_gemm(const Dtype* input, const Dtype* weights,
Dtype* output, bool skip_im2col = false);
void forward_cpu_bias(Dtype* output, const Dtype* bias);
void backward_cpu_gemm(const Dtype* input, const Dtype* weights,
Dtype* output);
void weight_cpu_gemm(const Dtype* input, const Dtype* output, Dtype*
weights);
void backward_cpu_bias(Dtype* bias, const Dtype* input);
#ifndef CPU_ONLY
void forward_gpu_gemm(const Dtype* col_input, const Dtype* weights,
Dtype* output, bool skip_im2col = false);
void forward_gpu_bias(Dtype* output, const Dtype* bias);
void backward_gpu_gemm(const Dtype* input, const Dtype* weights,
Dtype* col_output);
void weight_gpu_gemm(const Dtype* col_input, const Dtype* output, Dtype*
weights);
void backward_gpu_bias(Dtype* bias, const Dtype* input);
#endif
/// @brief The spatial dimensions of the input.
inline int input_shape(int i) {
return (*bottom_shape_)[channel_axis_ + i];
}
// reverse_dimensions should return true iff we are implementing deconv, so
// that conv helpers know which dimensions are which.
virtual bool reverse_dimensions() = 0;
// Compute height_out_ and width_out_ from other parameters.
virtual void compute_output_shape() = 0;
/// @brief The spatial dimensions of a filter kernel.
Blob<int> kernel_shape_;
/// @brief The spatial dimensions of the stride.
Blob<int> stride_;
/// @brief The spatial dimensions of the padding.
Blob<int> pad_;
/// @brief The spatial dimensions of the dilation.
Blob<int> dilation_;
/// @brief The spatial dimensions of the convolution input.
Blob<int> conv_input_shape_;
/// @brief The spatial dimensions of the col_buffer.
vector<int> col_buffer_shape_;
/// @brief The spatial dimensions of the output.
vector<int> output_shape_;
const vector<int>* bottom_shape_;
int num_spatial_axes_;
int bottom_dim_;
int top_dim_;
int channel_axis_;
int num_;
int channels_;
int group_;
int out_spatial_dim_;
int weight_offset_;
int num_output_;
bool bias_term_;
bool is_1x1_;
bool force_nd_im2col_;
private:
// wrap im2col/col2im so we don't have to remember the (long) argument lists
inline void conv_im2col_cpu(const Dtype* data, Dtype* col_buff) {
if (!force_nd_im2col_ && num_spatial_axes_ == 2) {
im2col_cpu(data, conv_in_channels_,
conv_input_shape_.cpu_data()[1], conv_input_shape_.cpu_data()[2],
kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1],
pad_.cpu_data()[0], pad_.cpu_data()[1],
stride_.cpu_data()[0], stride_.cpu_data()[1],
dilation_.cpu_data()[0], dilation_.cpu_data()[1], col_buff);
} else {
im2col_nd_cpu(data, num_spatial_axes_, conv_input_shape_.cpu_data(),
col_buffer_shape_.data(), kernel_shape_.cpu_data(),
pad_.cpu_data(), stride_.cpu_data(), dilation_.cpu_data(), col_buff);
}
}
inline void conv_col2im_cpu(const Dtype* col_buff, Dtype* data) {
if (!force_nd_im2col_ && num_spatial_axes_ == 2) {
col2im_cpu(col_buff, conv_in_channels_,
conv_input_shape_.cpu_data()[1], conv_input_shape_.cpu_data()[2],
kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1],
pad_.cpu_data()[0], pad_.cpu_data()[1],
stride_.cpu_data()[0], stride_.cpu_data()[1],
dilation_.cpu_data()[0], dilation_.cpu_data()[1], data);
} else {
col2im_nd_cpu(col_buff, num_spatial_axes_, conv_input_shape_.cpu_data(),
col_buffer_shape_.data(), kernel_shape_.cpu_data(),
pad_.cpu_data(), stride_.cpu_data(), dilation_.cpu_data(), data);
}
}
#ifndef CPU_ONLY
inline void conv_im2col_gpu(const Dtype* data, Dtype* col_buff) {
if (!force_nd_im2col_ && num_spatial_axes_ == 2) {
im2col_gpu(data, conv_in_channels_,
conv_input_shape_.cpu_data()[1], conv_input_shape_.cpu_data()[2],
kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1],
pad_.cpu_data()[0], pad_.cpu_data()[1],
stride_.cpu_data()[0], stride_.cpu_data()[1],
dilation_.cpu_data()[0], dilation_.cpu_data()[1], col_buff);
} else {
im2col_nd_gpu(data, num_spatial_axes_, num_kernels_im2col_,
conv_input_shape_.gpu_data(), col_buffer_.gpu_shape(),
kernel_shape_.gpu_data(), pad_.gpu_data(),
stride_.gpu_data(), dilation_.gpu_data(), col_buff);
}
}
inline void conv_col2im_gpu(const Dtype* col_buff, Dtype* data) {
if (!force_nd_im2col_ && num_spatial_axes_ == 2) {
col2im_gpu(col_buff, conv_in_channels_,
conv_input_shape_.cpu_data()[1], conv_input_shape_.cpu_data()[2],
kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1],
pad_.cpu_data()[0], pad_.cpu_data()[1],
stride_.cpu_data()[0], stride_.cpu_data()[1],
dilation_.cpu_data()[0], dilation_.cpu_data()[1], data);
} else {
col2im_nd_gpu(col_buff, num_spatial_axes_, num_kernels_col2im_,
conv_input_shape_.gpu_data(), col_buffer_.gpu_shape(),
kernel_shape_.gpu_data(), pad_.gpu_data(), stride_.gpu_data(),
dilation_.gpu_data(), data);
}
}
#endif
int num_kernels_im2col_;
int num_kernels_col2im_;
int conv_out_channels_;
int conv_in_channels_;
int conv_out_spatial_dim_;
int kernel_dim_;
int col_offset_;
int output_offset_;
Blob<Dtype> col_buffer_;
Blob<Dtype> bias_multiplier_;
};
} // namespace caffe
#endif // CAFFE_BASE_CONVOLUTION_LAYER_HPP_
| {
"pile_set_name": "Github"
} |
import { VirtualJoystick, JoystickAxis } from "../../Misc/virtualJoystick";
import { Nullable } from "../../types";
import { ICameraInput, CameraInputTypes } from "../../Cameras/cameraInputsManager";
import { FreeCamera } from "../../Cameras/freeCamera";
import { Matrix, Vector3 } from "../../Maths/math.vector";
import { FreeCameraInputsManager } from "../../Cameras/freeCameraInputsManager";
// Module augmentation to abstract virtual joystick from camera.
declare module "../../Cameras/freeCameraInputsManager" {
export interface FreeCameraInputsManager {
/**
* Add virtual joystick input support to the input manager.
* @returns the current input manager
*/
addVirtualJoystick(): FreeCameraInputsManager;
}
}
/**
* Add virtual joystick input support to the input manager.
* @returns the current input manager
*/
FreeCameraInputsManager.prototype.addVirtualJoystick = function(): FreeCameraInputsManager {
this.add(new FreeCameraVirtualJoystickInput());
return this;
};
/**
* Manage the Virtual Joystick inputs to control the movement of a free camera.
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
*/
export class FreeCameraVirtualJoystickInput implements ICameraInput<FreeCamera> {
/**
* Defines the camera the input is attached to.
*/
public camera: FreeCamera;
private _leftjoystick: VirtualJoystick;
private _rightjoystick: VirtualJoystick;
/**
* Gets the left stick of the virtual joystick.
* @returns The virtual Joystick
*/
public getLeftJoystick(): VirtualJoystick {
return this._leftjoystick;
}
/**
* Gets the right stick of the virtual joystick.
* @returns The virtual Joystick
*/
public getRightJoystick(): VirtualJoystick {
return this._rightjoystick;
}
/**
* Update the current camera state depending on the inputs that have been used this frame.
* This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
*/
public checkInputs() {
if (this._leftjoystick) {
var camera = this.camera;
var speed = camera._computeLocalCameraSpeed() * 50;
var cameraTransform = Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
var deltaTransform = Vector3.TransformCoordinates(new Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
if (!this._leftjoystick.pressed) {
this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
}
if (!this._rightjoystick.pressed) {
this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
}
}
}
/**
* Attach the input controls to a specific dom element to get the input from.
* @param element Defines the element the controls should be listened from
* @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
*/
public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
this._leftjoystick = new VirtualJoystick(true);
this._leftjoystick.setAxisForUpDown(JoystickAxis.Z);
this._leftjoystick.setAxisForLeftRight(JoystickAxis.X);
this._leftjoystick.setJoystickSensibility(0.15);
this._rightjoystick = new VirtualJoystick(false);
this._rightjoystick.setAxisForUpDown(JoystickAxis.X);
this._rightjoystick.setAxisForLeftRight(JoystickAxis.Y);
this._rightjoystick.reverseUpDown = true;
this._rightjoystick.setJoystickSensibility(0.05);
this._rightjoystick.setJoystickColor("yellow");
}
/**
* Detach the current controls from the specified dom element.
* @param element Defines the element to stop listening the inputs from
*/
public detachControl(element: Nullable<HTMLElement>): void {
this._leftjoystick.releaseCanvas();
this._rightjoystick.releaseCanvas();
}
/**
* Gets the class name of the current intput.
* @returns the class name
*/
public getClassName(): string {
return "FreeCameraVirtualJoystickInput";
}
/**
* Get the friendly name associated with the input class.
* @returns the input friendly name
*/
public getSimpleName(): string {
return "virtualJoystick";
}
}
(<any>CameraInputTypes)["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
| {
"pile_set_name": "Github"
} |
package de.vogella.rcp.help.application;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
/**
* This class controls all aspects of the application's execution
*/
public class Application implements IApplication {
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
public Object start(IApplicationContext context) {
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop() {
if (!PlatformUI.isWorkbenchRunning())
return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed())
workbench.close();
}
});
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Schema object for: StandardTermsQueryRq
*
* @author "Keith Palmer Jr." <[email protected]>
* @license LICENSE.txt
*
* @package QuickBooks
* @subpackage QBXML
*/
/**
*
*/
require_once 'QuickBooks.php';
/**
*
*/
require_once 'QuickBooks/QBXML/Schema/Object.php';
/**
*
*/
class QuickBooks_QBXML_Schema_Object_StandardTermsQueryRq extends QuickBooks_QBXML_Schema_Object
{
protected function &_qbxmlWrapper()
{
static $wrapper = '';
return $wrapper;
}
protected function &_dataTypePaths()
{
static $paths = array (
'ListID' => 'IDTYPE',
'FullName' => 'STRTYPE',
'MaxReturned' => 'INTTYPE',
'ActiveStatus' => 'ENUMTYPE',
'FromModifiedDate' => 'DATETIMETYPE',
'ToModifiedDate' => 'DATETIMETYPE',
'NameFilter MatchCriterion' => 'ENUMTYPE',
'NameFilter Name' => 'STRTYPE',
'NameRangeFilter FromName' => 'STRTYPE',
'NameRangeFilter ToName' => 'STRTYPE',
'IncludeRetElement' => 'STRTYPE',
);
return $paths;
}
protected function &_maxLengthPaths()
{
static $paths = array (
'ListID' => 0,
'FullName' => 0,
'MaxReturned' => 0,
'ActiveStatus' => 0,
'FromModifiedDate' => 0,
'ToModifiedDate' => 0,
'NameFilter MatchCriterion' => 0,
'NameFilter Name' => 0,
'NameRangeFilter FromName' => 0,
'NameRangeFilter ToName' => 0,
'IncludeRetElement' => 50,
);
return $paths;
}
protected function &_isOptionalPaths()
{
static $paths = array (
'ListID' => false,
'FullName' => false,
'MaxReturned' => true,
'ActiveStatus' => true,
'FromModifiedDate' => true,
'ToModifiedDate' => true,
'NameFilter MatchCriterion' => false,
'NameFilter Name' => false,
'NameRangeFilter FromName' => true,
'NameRangeFilter ToName' => true,
'IncludeRetElement' => true,
);
}
protected function &_sinceVersionPaths()
{
static $paths = array (
'ListID' => 999.99,
'FullName' => 999.99,
'MaxReturned' => 0,
'ActiveStatus' => 999.99,
'FromModifiedDate' => 999.99,
'ToModifiedDate' => 999.99,
'NameFilter MatchCriterion' => 999.99,
'NameFilter Name' => 999.99,
'NameRangeFilter FromName' => 999.99,
'NameRangeFilter ToName' => 999.99,
'IncludeRetElement' => 4,
);
return $paths;
}
protected function &_isRepeatablePaths()
{
static $paths = array (
'ListID' => true,
'FullName' => true,
'MaxReturned' => false,
'ActiveStatus' => false,
'FromModifiedDate' => false,
'ToModifiedDate' => false,
'NameFilter MatchCriterion' => false,
'NameFilter Name' => false,
'NameRangeFilter FromName' => false,
'NameRangeFilter ToName' => false,
'IncludeRetElement' => true,
);
return $paths;
}
/*
abstract protected function &_inLocalePaths()
{
static $paths = array(
'FirstName' => array( 'QBD', 'QBCA', 'QBUK', 'QBAU' ),
'LastName' => array( 'QBD', 'QBCA', 'QBUK', 'QBAU' ),
);
return $paths;
}
*/
protected function &_reorderPathsPaths()
{
static $paths = array (
0 => 'ListID',
1 => 'FullName',
2 => 'MaxReturned',
3 => 'ActiveStatus',
4 => 'FromModifiedDate',
5 => 'ToModifiedDate',
6 => 'NameFilter MatchCriterion',
7 => 'NameFilter Name',
8 => 'NameRangeFilter FromName',
9 => 'NameRangeFilter ToName',
10 => 'IncludeRetElement',
);
return $paths;
}
}
?> | {
"pile_set_name": "Github"
} |
---
title: Cursor text
categories:
- Typography
tags:
- text
- type
- cursor
---
| {
"pile_set_name": "Github"
} |
# SCCS Id: @(#)yendor.des 3.4 1996/10/20
# Copyright (c) 1989 by Jean-Christophe Collet
# Copyright (c) 1992 by M. Stephenson and Izchak Miller
# NetHack may be freely redistributed. See license for details.
#
# The top (real) wizard level.
# Keeping the Moat for old-time's sake
MAZE:"wizard1",random
FLAGS:noteleport,hardfloor
GEOMETRY:center,center
MAP
----------------------------.
|.......|..|.........|.....|.
|.......S..|.}}}}}}}.|.....|.
|..--S--|..|.}}---}}.|---S-|.
|..|....|..|.}--.--}.|..|..|.
|..|....|..|.}|...|}.|..|..|.
|..--------|.}--.--}.|..|..|.
|..|.......|.}}---}}.|..|..|.
|..S.......|.}}}}}}}.|..|..|.
|..|.......|.........|..|..|.
|..|.......|-----------S-S-|.
|..|.......S...............|.
----------------------------.
ENDMAP
STAIR:levregion(01,00,79,20),(0,0,28,12),up
STAIR:levregion(01,00,79,20),(0,0,28,12),down
BRANCH:levregion(01,00,79,20),(0,0,28,12)
TELEPORT_REGION:levregion(01,00,79,20),(0,0,27,12)
# Make it a morgue for rm id in mkmaze.c
# for the purpose of random sdoor placement
REGION:(12,01,20,09),unlit,"morgue",unfilled
MAZEWALK:(28,05),east
LADDER:(06,05),down
# Non diggable walls
# Walls inside the moat stay diggable
NON_DIGGABLE:(00,00,11,12)
NON_DIGGABLE:(11,00,21,00)
NON_DIGGABLE:(11,10,27,12)
NON_DIGGABLE:(21,00,27,10)
# Non passable walls
NON_PASSWALL:(00,00,11,12)
NON_PASSWALL:(11,00,21,00)
NON_PASSWALL:(11,10,27,12)
NON_PASSWALL:(21,00,27,10)
# The wizard and his guards
MONSTER:'@',"Wizard of Yendor",(16,05),asleep
MONSTER:'d',"hell hound",(15,05)
MONSTER:'V',"vampire lord",(17,05)
# The local treasure
OBJECT:'+',"Book of the Dead",(16,05)
# Surrounding terror
MONSTER:';',"kraken",(14,02)
MONSTER:';',"giant eel",(17,02)
MONSTER:';',"kraken",(13,04)
MONSTER:';',"giant eel",(13,06)
MONSTER:';',"kraken",(19,04)
MONSTER:';',"giant eel",(19,06)
MONSTER:';',"kraken",(15,08)
MONSTER:';',"giant eel",(17,08)
MONSTER:';',"piranha",(15,02)
MONSTER:';',"piranha",(19,08)
# Random monsters
MONSTER:'D',random,random
MONSTER:'H',random,random
MONSTER:'&',random,random
MONSTER:'&',random,random
MONSTER:'&',random,random
MONSTER:'&',random,random
# And to make things a little harder.
TRAP:"board",(16,04)
TRAP:"board",(16,06)
TRAP:"board",(15,05)
TRAP:"board",(17,05)
# Random traps.
TRAP:"spiked pit",random
TRAP:"sleep gas",random
TRAP:"anti magic",random
TRAP:"magic",random
# Some random loot.
OBJECT:'*',"ruby",random
OBJECT:'!',random,random
OBJECT:'!',random,random
OBJECT:'?',random,random
OBJECT:'?',random,random
OBJECT:'+',random,random
OBJECT:'+',random,random
OBJECT:'+',random,random
# The middle wizard level.
MAZE:"wizard2",random
FLAGS:noteleport,hardfloor
GEOMETRY:center,center
MAP
----------------------------.
|.....|.S....|.............|.
|.....|.-------S--------S--|.
|.....|.|.........|........|.
|..-S--S|.........|........|.
|..|....|.........|------S-|.
|..|....|.........|.....|..|.
|-S-----|.........|.....|..|.
|.......|.........|S--S--..|.
|.......|.........|.|......|.
|-----S----S-------.|......|.
|............|....S.|......|.
----------------------------.
ENDMAP
STAIR:levregion(01,00,79,20),(0,0,28,12),up
STAIR:levregion(01,00,79,20),(0,0,28,12),down
BRANCH:levregion(01,00,79,20),(0,0,28,12)
TELEPORT_REGION:levregion(01,00,79,20),(0,0,27,12)
REGION:(09,03,17,09),unlit,"zoo"
DOOR:closed,(15,02)
DOOR:closed,(11,10)
MAZEWALK:(28,05),east
LADDER:(12,01),up
LADDER:(14,11),down
# Non diggable walls everywhere
NON_DIGGABLE:(00,00,27,12)
#
NON_PASSWALL:(00,00,06,12)
NON_PASSWALL:(06,00,27,02)
NON_PASSWALL:(16,02,27,12)
NON_PASSWALL:(06,12,16,12)
# Random traps.
TRAP:"spiked pit",random
TRAP:"sleep gas",random
TRAP:"anti magic",random
TRAP:"magic",random
# Some random loot.
OBJECT:'!',random,random
OBJECT:'!',random,random
OBJECT:'?',random,random
OBJECT:'?',random,random
OBJECT:'+',random,random
# treasures
OBJECT:'"',random,(04,06)
# The bottom wizard level.
# Memorialize the fakewiz setup.
MAZE:"wizard3",random
FLAGS:noteleport,hardfloor
GEOMETRY:center,center
MAP
----------------------------.
|..|............S..........|.
|..|..------------------S--|.
|..|..|.........|..........|.
|..S..|.}}}}}}}.|..........|.
|..|..|.}}---}}.|-S--------|.
|..|..|.}--.--}.|..|.......|.
|..|..|.}|...|}.|..|.......|.
|..---|.}--.--}.|..|.......|.
|.....|.}}---}}.|..|.......|.
|.....S.}}}}}}}.|..|.......|.
|.....|.........|..S.......|.
----------------------------.
ENDMAP
STAIR:levregion(01,00,79,20),(0,0,28,12),up
STAIR:levregion(01,00,79,20),(0,0,28,12),down
BRANCH:levregion(01,00,79,20),(0,0,28,12)
TELEPORT_REGION:levregion(01,00,79,20),(0,0,27,12)
PORTAL:(25,11,25,11),(0,0,0,0),"fakewiz1"
MAZEWALK:(28,09),east
REGION:(07,03,15,11),unlit,"morgue",unfilled
REGION:(17,06,18,11),unlit,"beehive"
# make the entry chamber a real room; it affects monster arrival;
# `unfilled' is a kludge to force an ordinary room to remain a room
REGION:(20,06,26,11),unlit,"ordinary",unfilled
DOOR:closed,(18,05)
DOOR:closed,(19,11)
LADDER:(11,07),up
# Non diggable walls
# Walls inside the moat stay diggable
NON_DIGGABLE:(00,00,06,12)
NON_DIGGABLE:(06,00,27,02)
NON_DIGGABLE:(16,02,27,12)
NON_DIGGABLE:(06,12,16,12)
#
NON_PASSWALL:(00,00,06,12)
NON_PASSWALL:(06,00,27,02)
NON_PASSWALL:(16,02,27,12)
NON_PASSWALL:(06,12,16,12)
#
MONSTER:'L',random,(10,07)
MONSTER:'V',"vampire lord",(12,07)
# Some surrounding horrors
MONSTER:';',"kraken",(08,05)
MONSTER:';',"giant eel",(08,08)
MONSTER:';',"kraken",(14,05)
MONSTER:';',"giant eel",(14,08)
# Other monsters
MONSTER:'L',random,random
MONSTER:'D',random,random
MONSTER:'D',random,(26,09)
MONSTER:'&',random,random
MONSTER:'&',random,random
MONSTER:'&',random,random
# And to make things a little harder.
TRAP:"board",(10,07)
TRAP:"board",(12,07)
TRAP:"board",(11,06)
TRAP:"board",(11,08)
# Some loot
OBJECT:')',random,random
OBJECT:'!',random,random
OBJECT:'?',random,random
OBJECT:'?',random,random
OBJECT:'(',random,random
# treasures
OBJECT:'"',random,(11,07)
# The former decoy wizard levels.
# There are two of these, and we need to
# distinguish between them for the portal.
MAZE:"fakewiz1",random
GEOMETRY:center,center
MAP
.........
.}}}}}}}.
.}}---}}.
.}--.--}.
.}|...|}.
.}--.--}.
.}}---}}.
.}}}}}}}.
ENDMAP
STAIR:levregion(01,00,79,20),(0,0,8,7),up
STAIR:levregion(01,00,79,20),(0,0,8,7),down
BRANCH:levregion(01,00,79,20),(0,0,8,7)
TELEPORT_REGION:levregion(01,00,79,20),(2,2,6,6)
PORTAL:(4,4,4,4),(0,0,0,0),"wizard3"
MAZEWALK:(08,05),east
REGION:(04,03,06,06),unlit,"ordinary",unfilled,true
MONSTER:'L',random,(04,04)
MONSTER:'V',"vampire lord",(03,04)
MONSTER:';',"kraken",(06,06)
# And to make things a little harder.
TRAP:"board",(04,03)
TRAP:"board",(04,05)
TRAP:"board",(03,04)
TRAP:"board",(05,04)
MAZE:"fakewiz2",random
GEOMETRY:center,center
MAP
.........
.}}}}}}}.
.}}---}}.
.}--.--}.
.}|...|}.
.}--.--}.
.}}---}}.
.}}}}}}}.
ENDMAP
STAIR:levregion(01,00,79,20),(0,0,8,7),up
STAIR:levregion(01,00,79,20),(0,0,8,7),down
BRANCH:levregion(01,00,79,20),(0,0,8,7)
TELEPORT_REGION:levregion(01,00,79,20),(2,2,6,6)
MAZEWALK:(08,05),east
REGION:(04,03,06,06),unlit,"ordinary",unfilled,true
MONSTER:'L',random,(04,04)
MONSTER:'V',"vampire lord",(03,04)
MONSTER:';',"kraken",(06,06)
# And to make things a little harder.
TRAP:"board",(04,03)
TRAP:"board",(04,05)
TRAP:"board",(03,04)
TRAP:"board",(05,04)
# treasures
OBJECT:'"',random,(04,04)
| {
"pile_set_name": "Github"
} |
@import "reset-to-defaults.css";
label {
font-size: 40px;
font-style: italic;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
RegExp.prototype.exec behavior depends on global property.
If global is true next exec calling start to match from lastIndex position
es5id: 15.10.6.2_A4_T5
description: >
Call first exec, then set re.lastIndex = x and again call exec,
where x is undefined variable
---*/
__re = /(?:ab|cd)\d?/g;
__executed = __re.exec("aacd2233ab12nm444ab42");
__expected = ["cd2"];
__expected.index = 2;
__expected.input = "aacd2233ab12nm444ab42";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __re = /(?:ab|cd)\\d?/g; __executed = __re.exec("aacd2233ab12nm444ab42"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __re = /(?:ab|cd)\\d?/g; __executed = __re.exec("aacd2233ab12nm444ab42"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __re = /(?:ab|cd)\\d?/g; __executed = __re.exec("aacd2233ab12nm444ab42"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __re = /(?:ab|cd)\\d?/g; __executed = __re.exec("aacd2233ab12nm444ab42"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
__re.lastIndex = x;
__executed = __re.exec("aacd2233ab12nm444ab42");
__expected = ["cd2"];
__expected.index = 2;
__expected.input = "aacd2233ab12nm444ab42";
//CHECK#5
if (__executed.length !== __expected.length) {
$ERROR('#5: __re = /(?:ab|cd)\\d?/g; __re.lastIndex = x; __executed = __re.exec("aacd2233ab12nm444ab42"); var x; __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#6
if (__executed.index !== __expected.index) {
$ERROR('#6: __re = /(?:ab|cd)\\d?/g; __re.lastIndex = x; __executed = __re.exec("aacd2233ab12nm444ab42"); var x; __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#7
if (__executed.input !== __expected.input) {
$ERROR('#7: __re = /(?:ab|cd)\\d?/g; __re.lastIndex = x; __executed = __re.exec("aacd2233ab12nm444ab42"); var x; __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#8
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#8: __re = /(?:ab|cd)\\d?/g; __re.lastIndex = x; __executed = __re.exec("aacd2233ab12nm444ab42"); var x; __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
var x;
| {
"pile_set_name": "Github"
} |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) && objectToString(e) === '[object Error]';
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return arg instanceof Buffer;
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
| {
"pile_set_name": "Github"
} |
{{ extends "/default.html" }}
{{ define "body"}}
<div class="mdl-grid mdl-grid--no-spacing">
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-phone">
<div class="mdl-grid">
{{ range .Posts }}
<div id="dingo-post-{{ .Id }}" class="mdl-cell mdl-cell--6-col mdl-cell--4-col-tablet">
<div class="mdl-card dingo-card dingo-card-short dingo-card-post mdl-shadow--0dp">
<div class="p-15 mdl-card--expand p-b-5">
<h3 class="no-margin w600">{{ .Title }}</h3>
</div>
<div class="mdl-card__supporting-text p-t-5">
{{ .Excerpt }}
<div class="tags m-t-20">
<p class="timestamp"><i class="material-icons md-18 f-left">access_time</i>{{DateFormat .CreatedAt "%Y-%m-%d"}}</p>
{{ if .IsPublished }}
{{ else }}
<p class="status mdl-color-text--amber"><i class="material-icons md-18 f-left">description</i>draft</p>
{{ end }}
<div class="f-right">
{{ if .IsPublished }}
<a href="{{ .Url }}" class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
<i class="material-icons f18">pageview</i>
</a>
{{ else }}
<button href="{{ .Url }}" class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect" disabled>
<i class="material-icons f18">pageview</i>
</button>
{{ end }}
<a href="/admin/editor/{{ .Id }}/" class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect" data-upgraded=",MaterialButton,MaterialRipple">
<i class="material-icons f18">edit</i>
</a>
<a rel="{{ .Id }}" class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect trash delete-post">
<i class="material-icons f18 mdl-color-text--red-400">delete</i>
</a>
</div>
<div class="p-t-5">
{{ range .Tags }}
<span class="mdl-color--grey-200 radius3 inline p-5 f11 m-r-5">
{{ .Name }}
</span>
{{ end }}
</div>
</div>
</div>
</div>
</div>
{{ end }}
</div>
</div>
</div>
<a href="/admin/editor/post" class="mdl-button mdl-button--fab mdl-button--primary mdl-js-button mdl-js-ripple-effect dingo-button--new">
<i class="material-icons">add</i>
<span class="mdl-button__ripple-container"><span class="mdl-ripple is-animating"></span></span>
</a>
{{end}}
| {
"pile_set_name": "Github"
} |
<Dataset
name="test_one_var.nc"
dapVersion="4.0"
dmrVersion="1.0"
xmlns="http://xml.opendap.org/ns/DAP/4.0#"
xmlns:dap="http://xml.opendap.org/ns/DAP/4.0#">
<Variables>
<Int32 name="t"/>
</Variables>
<Attribute name="_DAP4_Little_Endian" type="UInt8">
<Value value="1"/>
</Attribute>
</Dataset>
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0+
/*
* bdc_cmd.c - BRCM BDC USB3.0 device controller
*
* Copyright (C) 2014 Broadcom Corporation
*
* Author: Ashwini Pahuja
*/
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include "bdc.h"
#include "bdc_cmd.h"
#include "bdc_dbg.h"
/* Issues a cmd to cmd processor and waits for cmd completion */
static int bdc_issue_cmd(struct bdc *bdc, u32 cmd_sc, u32 param0,
u32 param1, u32 param2)
{
u32 timeout = BDC_CMD_TIMEOUT;
u32 cmd_status;
u32 temp;
bdc_writel(bdc->regs, BDC_CMDPAR0, param0);
bdc_writel(bdc->regs, BDC_CMDPAR1, param1);
bdc_writel(bdc->regs, BDC_CMDPAR2, param2);
/* Issue the cmd */
/* Make sure the cmd params are written before asking HW to exec cmd */
wmb();
bdc_writel(bdc->regs, BDC_CMDSC, cmd_sc | BDC_CMD_CWS | BDC_CMD_SRD);
do {
temp = bdc_readl(bdc->regs, BDC_CMDSC);
dev_dbg_ratelimited(bdc->dev, "cmdsc=%x", temp);
cmd_status = BDC_CMD_CST(temp);
if (cmd_status != BDC_CMDS_BUSY) {
dev_dbg(bdc->dev,
"command completed cmd_sts:%x\n", cmd_status);
return cmd_status;
}
udelay(1);
} while (timeout--);
dev_err(bdc->dev,
"command operation timedout cmd_status=%d\n", cmd_status);
return cmd_status;
}
/* Submits cmd and analyze the return value of bdc_issue_cmd */
static int bdc_submit_cmd(struct bdc *bdc, u32 cmd_sc,
u32 param0, u32 param1, u32 param2)
{
u32 temp, cmd_status;
int ret;
temp = bdc_readl(bdc->regs, BDC_CMDSC);
dev_dbg(bdc->dev,
"%s:CMDSC:%08x cmdsc:%08x param0=%08x param1=%08x param2=%08x\n",
__func__, temp, cmd_sc, param0, param1, param2);
cmd_status = BDC_CMD_CST(temp);
if (cmd_status == BDC_CMDS_BUSY) {
dev_err(bdc->dev, "command processor busy: %x\n", cmd_status);
return -EBUSY;
}
ret = bdc_issue_cmd(bdc, cmd_sc, param0, param1, param2);
switch (ret) {
case BDC_CMDS_SUCC:
dev_dbg(bdc->dev, "command completed successfully\n");
ret = 0;
break;
case BDC_CMDS_PARA:
dev_err(bdc->dev, "command parameter error\n");
ret = -EINVAL;
break;
case BDC_CMDS_STAT:
dev_err(bdc->dev, "Invalid device/ep state\n");
ret = -EINVAL;
break;
case BDC_CMDS_FAIL:
dev_err(bdc->dev, "Command failed?\n");
ret = -EAGAIN;
break;
case BDC_CMDS_INTL:
dev_err(bdc->dev, "BDC Internal error\n");
ret = -ECONNRESET;
break;
case BDC_CMDS_BUSY:
dev_err(bdc->dev,
"command timedout waited for %dusec\n",
BDC_CMD_TIMEOUT);
ret = -ECONNRESET;
break;
default:
dev_dbg(bdc->dev, "Unknown command completion code:%x\n", ret);
}
return ret;
}
/* Deconfigure the endpoint from HW */
int bdc_dconfig_ep(struct bdc *bdc, struct bdc_ep *ep)
{
u32 cmd_sc;
cmd_sc = BDC_SUB_CMD_DRP_EP|BDC_CMD_EPN(ep->ep_num)|BDC_CMD_EPC;
dev_dbg(bdc->dev, "%s ep->ep_num =%d cmd_sc=%x\n", __func__,
ep->ep_num, cmd_sc);
return bdc_submit_cmd(bdc, cmd_sc, 0, 0, 0);
}
/* Reinitalize the bdlist after config ep command */
static void ep_bd_list_reinit(struct bdc_ep *ep)
{
struct bdc *bdc = ep->bdc;
struct bdc_bd *bd;
ep->bd_list.eqp_bdi = 0;
ep->bd_list.hwd_bdi = 0;
bd = ep->bd_list.bd_table_array[0]->start_bd;
dev_dbg(bdc->dev, "%s ep:%p bd:%p\n", __func__, ep, bd);
memset(bd, 0, sizeof(struct bdc_bd));
bd->offset[3] |= cpu_to_le32(BD_SBF);
}
/* Configure an endpoint */
int bdc_config_ep(struct bdc *bdc, struct bdc_ep *ep)
{
const struct usb_ss_ep_comp_descriptor *comp_desc;
const struct usb_endpoint_descriptor *desc;
u32 param0, param1, param2, cmd_sc;
u32 mps, mbs, mul, si;
int ret;
desc = ep->desc;
comp_desc = ep->comp_desc;
cmd_sc = mul = mbs = param2 = 0;
param0 = lower_32_bits(ep->bd_list.bd_table_array[0]->dma);
param1 = upper_32_bits(ep->bd_list.bd_table_array[0]->dma);
cpu_to_le32s(¶m0);
cpu_to_le32s(¶m1);
dev_dbg(bdc->dev, "%s: param0=%08x param1=%08x",
__func__, param0, param1);
si = desc->bInterval;
si = clamp_val(si, 1, 16) - 1;
mps = usb_endpoint_maxp(desc);
mps &= 0x7ff;
param2 |= mps << MP_SHIFT;
param2 |= usb_endpoint_type(desc) << EPT_SHIFT;
switch (bdc->gadget.speed) {
case USB_SPEED_SUPER:
if (usb_endpoint_xfer_int(desc) ||
usb_endpoint_xfer_isoc(desc)) {
param2 |= si;
if (usb_endpoint_xfer_isoc(desc) && comp_desc)
mul = comp_desc->bmAttributes;
}
param2 |= mul << EPM_SHIFT;
if (comp_desc)
mbs = comp_desc->bMaxBurst;
param2 |= mbs << MB_SHIFT;
break;
case USB_SPEED_HIGH:
if (usb_endpoint_xfer_isoc(desc) ||
usb_endpoint_xfer_int(desc)) {
param2 |= si;
mbs = usb_endpoint_maxp_mult(desc);
param2 |= mbs << MB_SHIFT;
}
break;
case USB_SPEED_FULL:
case USB_SPEED_LOW:
/* the hardware accepts SI in 125usec range */
if (usb_endpoint_xfer_isoc(desc))
si += 3;
/*
* FS Int endpoints can have si of 1-255ms but the controller
* accepts 2^bInterval*125usec, so convert ms to nearest power
* of 2
*/
if (usb_endpoint_xfer_int(desc))
si = fls(desc->bInterval * 8) - 1;
param2 |= si;
break;
default:
dev_err(bdc->dev, "UNKNOWN speed ERR\n");
return -EINVAL;
}
cmd_sc |= BDC_CMD_EPC|BDC_CMD_EPN(ep->ep_num)|BDC_SUB_CMD_ADD_EP;
dev_dbg(bdc->dev, "cmd_sc=%x param2=%08x\n", cmd_sc, param2);
ret = bdc_submit_cmd(bdc, cmd_sc, param0, param1, param2);
if (ret) {
dev_err(bdc->dev, "command failed :%x\n", ret);
return ret;
}
ep_bd_list_reinit(ep);
return ret;
}
/*
* Change the HW deq pointer, if this command is successful, HW will start
* fetching the next bd from address dma_addr.
*/
int bdc_ep_bla(struct bdc *bdc, struct bdc_ep *ep, dma_addr_t dma_addr)
{
u32 param0, param1;
u32 cmd_sc = 0;
dev_dbg(bdc->dev, "%s: add=%08llx\n", __func__,
(unsigned long long)(dma_addr));
param0 = lower_32_bits(dma_addr);
param1 = upper_32_bits(dma_addr);
cpu_to_le32s(¶m0);
cpu_to_le32s(¶m1);
cmd_sc |= BDC_CMD_EPN(ep->ep_num)|BDC_CMD_BLA;
dev_dbg(bdc->dev, "cmd_sc=%x\n", cmd_sc);
return bdc_submit_cmd(bdc, cmd_sc, param0, param1, 0);
}
/* Set the address sent bu Host in SET_ADD request */
int bdc_address_device(struct bdc *bdc, u32 add)
{
u32 cmd_sc = 0;
u32 param2;
dev_dbg(bdc->dev, "%s: add=%d\n", __func__, add);
cmd_sc |= BDC_SUB_CMD_ADD|BDC_CMD_DVC;
param2 = add & 0x7f;
return bdc_submit_cmd(bdc, cmd_sc, 0, 0, param2);
}
/* Send a Function Wake notification packet using FH command */
int bdc_function_wake_fh(struct bdc *bdc, u8 intf)
{
u32 param0, param1;
u32 cmd_sc = 0;
param0 = param1 = 0;
dev_dbg(bdc->dev, "%s intf=%d\n", __func__, intf);
cmd_sc |= BDC_CMD_FH;
param0 |= TRA_PACKET;
param0 |= (bdc->dev_addr << 25);
param1 |= DEV_NOTF_TYPE;
param1 |= (FWK_SUBTYPE<<4);
dev_dbg(bdc->dev, "param0=%08x param1=%08x\n", param0, param1);
return bdc_submit_cmd(bdc, cmd_sc, param0, param1, 0);
}
/* Send a Function Wake notification packet using DNC command */
int bdc_function_wake(struct bdc *bdc, u8 intf)
{
u32 cmd_sc = 0;
u32 param2 = 0;
dev_dbg(bdc->dev, "%s intf=%d", __func__, intf);
param2 |= intf;
cmd_sc |= BDC_SUB_CMD_FWK|BDC_CMD_DNC;
return bdc_submit_cmd(bdc, cmd_sc, 0, 0, param2);
}
/* Stall the endpoint */
int bdc_ep_set_stall(struct bdc *bdc, int epnum)
{
u32 cmd_sc = 0;
dev_dbg(bdc->dev, "%s epnum=%d\n", __func__, epnum);
/* issue a stall endpoint command */
cmd_sc |= BDC_SUB_CMD_EP_STL | BDC_CMD_EPN(epnum) | BDC_CMD_EPO;
return bdc_submit_cmd(bdc, cmd_sc, 0, 0, 0);
}
/* resets the endpoint, called when host sends CLEAR_FEATURE(HALT) */
int bdc_ep_clear_stall(struct bdc *bdc, int epnum)
{
struct bdc_ep *ep;
u32 cmd_sc = 0;
int ret;
dev_dbg(bdc->dev, "%s: epnum=%d\n", __func__, epnum);
ep = bdc->bdc_ep_array[epnum];
/*
* If we are not in stalled then stall Endpoint and issue clear stall,
* his will reset the seq number for non EP0.
*/
if (epnum != 1) {
/* if the endpoint it not stallled */
if (!(ep->flags & BDC_EP_STALL)) {
ret = bdc_ep_set_stall(bdc, epnum);
if (ret)
return ret;
}
}
/* Preserve the seq number for ep0 only */
if (epnum != 1)
cmd_sc |= BDC_CMD_EPO_RST_SN;
/* issue a reset endpoint command */
cmd_sc |= BDC_SUB_CMD_EP_RST | BDC_CMD_EPN(epnum) | BDC_CMD_EPO;
ret = bdc_submit_cmd(bdc, cmd_sc, 0, 0, 0);
if (ret) {
dev_err(bdc->dev, "command failed:%x\n", ret);
return ret;
}
bdc_notify_xfr(bdc, epnum);
return ret;
}
/* Stop the endpoint, called when software wants to dequeue some request */
int bdc_stop_ep(struct bdc *bdc, int epnum)
{
struct bdc_ep *ep;
u32 cmd_sc = 0;
int ret;
ep = bdc->bdc_ep_array[epnum];
dev_dbg(bdc->dev, "%s: ep:%s ep->flags:%08x\n", __func__,
ep->name, ep->flags);
/* Endpoint has to be in running state to execute stop ep command */
if (!(ep->flags & BDC_EP_ENABLED)) {
dev_err(bdc->dev, "stop endpoint called for disabled ep\n");
return -EINVAL;
}
if ((ep->flags & BDC_EP_STALL) || (ep->flags & BDC_EP_STOP))
return 0;
/* issue a stop endpoint command */
cmd_sc |= BDC_CMD_EP0_XSD | BDC_SUB_CMD_EP_STP
| BDC_CMD_EPN(epnum) | BDC_CMD_EPO;
ret = bdc_submit_cmd(bdc, cmd_sc, 0, 0, 0);
if (ret) {
dev_err(bdc->dev,
"stop endpoint command didn't complete:%d ep:%s\n",
ret, ep->name);
return ret;
}
ep->flags |= BDC_EP_STOP;
bdc_dump_epsts(bdc);
return ret;
}
| {
"pile_set_name": "Github"
} |
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
"go_test",
"cgo_library",
)
go_library(
name = "go_default_library",
srcs = ["runtime.go"],
tags = ["automanaged"],
deps = ["//vendor:github.com/golang/glog"],
)
go_test(
name = "go_default_test",
srcs = ["runtime_test.go"],
library = "go_default_library",
tags = ["automanaged"],
deps = [],
)
| {
"pile_set_name": "Github"
} |
from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import Integer, String
from demo.base import Base
class TestModel(Base):
__tablename__ = "test_model"
id = Column(Integer, primary_key=True)
name = Column(String)
class TestUser(Base):
__tablename__ = "test_user"
id = Column(Integer, primary_key=True)
username = Column(String)
password = Column(
String
) # do not store plain password in the database, hash it, see porridge for example
| {
"pile_set_name": "Github"
} |
import Lean
open Lean
def oh_no : Nat := 0
def snakeLinter : Linter :=
fun env n stx =>
-- TODO(Sebastian): return actual message with position from syntax tree
if n.toString.contains '_' then throw $ IO.userError "SNAKES!!"
else pure MessageLog.empty
@[init]
def registerSnakeLinter : IO Unit :=
addLinter snakeLinter
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE index
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp Index Version 1.0//EN"
"http://java.sun.com/products/javahelp/index_2_0.dtd">
<index version="2.0">
<!-- index entries are merged (sorted) into core index -->
<indexitem text="httpsinfo" target="httpsinfo" />
</index>
| {
"pile_set_name": "Github"
} |
"""Utilities for working with master"""
import contextlib
import logging
import json
from functools import lru_cache
import pytest
import requests
import retrying
from datetime import timedelta
from precisely import equal_to
from . import master_ip, master_url, network
from .agent import kill_process_from_pid_file_on_host
from .command import run_command, run_command_on_master
from .zookeeper import get_zk_node_children, get_zk_node_data
from ..clients.authentication import dcos_acs_token, DCOSAcsAuth
from ..clients.rpcclient import verify_ssl
from ..errors import DCOSException
from ..matcher import assert_that, eventually
DISABLE_MASTER_INCOMING = "-I INPUT -p tcp --dport 5050 -j REJECT"
DISABLE_MASTER_OUTGOING = "-I OUTPUT -p tcp --sport 5050 -j REJECT"
logger = logging.getLogger(__name__)
def partition_master(incoming=True, outgoing=True):
""" Partition master's port alone. To keep DC/OS cluster running.
:param incoming: Partition incoming traffic to master process. Default True.
:param outgoing: Partition outgoing traffic from master process. Default True.
"""
logger.info('Partitioning master. Incoming:%s | Outgoing:%s', incoming, outgoing)
network.save_iptables(master_ip())
network.flush_all_rules(master_ip())
network.allow_all_traffic(master_ip())
if incoming and outgoing:
network.run_iptables(master_ip(), DISABLE_MASTER_INCOMING)
network.run_iptables(master_ip(), DISABLE_MASTER_OUTGOING)
elif incoming:
network.run_iptables(master_ip(), DISABLE_MASTER_INCOMING)
elif outgoing:
network.run_iptables(master_ip(), DISABLE_MASTER_OUTGOING)
else:
pass
def reconnect_master():
""" Reconnect a previously partitioned master to the network
"""
network.restore_iptables(master_ip())
def restart_master_node():
""" Restarts the master node
"""
run_command_on_master("sudo /sbin/shutdown -r now")
def systemctl_master(command='restart'):
""" Used to start, stop or restart the master process
"""
run_command_on_master('sudo systemctl {} dcos-mesos-master'.format(command))
def mesos_available_predicate():
url = master_url()
auth = DCOSAcsAuth(dcos_acs_token())
try:
response = requests.get(url(), auth=auth, verify=verify_ssl())
return response.status_code == 200
except Exception:
return False
def wait_for_mesos_endpoint(timeout_sec=timedelta(minutes=5).total_seconds()):
"""Checks the service url if available it returns true, on expiration
it returns false"""
assert_that(lambda: mesos_available_predicate(), eventually(equal_to(True)))
def _mesos_zk_nodes():
""" Returns all the children nodes under /mesos in zk
"""
return get_zk_node_children('/mesos')
def _master_zk_nodes_keys():
""" The masters can be registered in zk with arbitrary ids which start with
`json.info_`. This provides a list of all master keys.
"""
master_zk = []
for node in _mesos_zk_nodes():
if 'json.info' in node['title']:
master_zk.append(node['key'])
return master_zk
def get_all_masters():
""" Returns the json object that represents each of the masters.
"""
masters = []
for master in _master_zk_nodes_keys():
master_zk_str = get_zk_node_data(master)['str']
masters.append(json.loads(master_zk_str))
return masters
def get_all_master_ips():
""" Returns a list of IPs for the masters
"""
ips = []
for master in get_all_masters():
ips.append(master['hostname'])
return ips
def is_multi_master():
master_count = len(get_all_masters())
return master_count > 1
def required_masters(count):
""" Returns True if the number of private agents is equal to or greater than
the count. This is useful in using pytest skipif such as:
`pytest.mark.skipif('required_masters(3)')` which will skip the test if
the number of masters is only 1.
:param count: the number of required masters.
"""
master_count = len(get_all_masters())
# reverse logic (skip if less than count)
# returns True if less than count
return master_count < count
def masters(count=1):
return pytest.mark.skipif('required_masters({})'.format(count))
def start_master_http_service(port=7777, pid_file='python_http.pid'):
""" Starts a http service on the master leader. The main purpose is to serve
up artifacts for launched test applications. This is commonly used in combination
with copying tests or artifacts to the leader than configuring the messos task
to fetch from http://master.mesos:7777/artifact.tar (becareful in a multi-master env)
:param port: port to use for the http service
:return: pid_file
"""
run_command_on_master(
'nohup /opt/mesosphere/bin/python -m http.server {} > http.log 2>&1 & '
'echo $! > {}'.format(port, pid_file))
return pid_file
@contextlib.contextmanager
def master_http_service(port=7777):
pid_file = start_master_http_service(port)
yield
kill_process_from_pid_file_on_host(master_ip(), pid_file)
@contextlib.contextmanager
def disconnected_master(incoming=True, outgoing=True):
partition_master(incoming, outgoing)
try:
yield
finally:
# return config to previous state
reconnect_master()
@lru_cache()
def dcos_masters_public_ips():
"""
retrieves public ips of all masters
:return: public ips of all masters
"""
@retrying.retry(
wait_fixed=1000,
stop_max_attempt_number=240, # waiting 20 minutes for exhibitor start-up
retry_on_exception=lambda exc: isinstance(exc, DCOSException))
def all_master_ips():
return get_all_master_ips()
master_public_ips = [run_command(private_ip, '/opt/mesosphere/bin/detect_ip_public')[1]
for private_ip in all_master_ips()]
return master_public_ips
| {
"pile_set_name": "Github"
} |
require File.dirname(__FILE__) + "/../../spec_helper"
describe Admin::UsersController do
it "should be paginated" do
Admin::UsersController.paginated.should be_true
controller.paginated?.should be_true
end
## I need to redo these with mock classes
#
# describe "with pagination settings from paginate_models" do
# it "should override defaults" do
# Radiant.config['admin.pagination.per_page'] = ""
# Admin::UsersController.send :paginate_models, {:per_page => 5, :inner_window => 12}
# controller.pagination_parameters.should == {:page => 1, :per_page => 5}
# controller.will_paginate_options.should == {:inner_window => 12, :param_name => :p}
# end
# end
#
# describe "with configured pagination settings" do
# it "should override defaults" do
# Radiant.config['admin.pagination.per_page'] = 23
# controller.pagination_parameters.should == {:page => 1, :per_page => 23}
# end
# end
#
describe "without configuration" do
it "should have pagination defaults" do
Radiant.config['admin.pagination.per_page'] = nil
controller.pagination_parameters.should == {:page => 1, :per_page => 50}
controller.will_paginate_options.should == {:param_name => :p}
end
end
end | {
"pile_set_name": "Github"
} |
/*
* /MathJax/jax/output/SVG/fonts/TeX/Main/Bold/LatinExtendedA.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax.SVG.FONTDATA.FONTS["MathJax_Main-bold"],{305:[452,8,394,24,367,"24 296Q24 305 34 328T63 380T115 430T187 452Q205 452 223 448T262 435T295 406T308 360Q308 345 287 290T240 170T207 87Q202 67 202 57Q202 42 215 42Q235 42 257 64Q288 92 302 140Q307 156 310 159T330 162H336H347Q367 162 367 148Q367 140 357 117T329 65T276 14T201 -8Q158 -8 121 15T83 84Q83 104 133 229T184 358Q189 376 189 388Q189 402 177 402Q156 402 134 380Q103 352 89 304Q84 288 81 285T61 282H55H44Q24 282 24 296"]});MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/Main/Bold/LatinExtendedA.js");
| {
"pile_set_name": "Github"
} |
StartChar: uni0679.init_BaaBaaMemInit
Encoding: 1116255 -1 2427
Width: 162
Flags: HW
AnchorPoint: "TashkilAbove" 72 845 basechar 0
AnchorPoint: "TashkilBelow" 86 -327 basechar 0
LayerCount: 2
Fore
Refer: 212 -1 N 1 0 0 1 91 527 2
Refer: 152 -1 N 1 0 0 1 0 0 3
EndChar
| {
"pile_set_name": "Github"
} |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by TranslationDll.rc
//
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| {
"pile_set_name": "Github"
} |
MIIB1AoBAKCCAc0wggHJBgkrBgEFBQcwAQEEggG6MIIBtjCBn6IWBBStvZh6NLQm
9/rEJlTvA73gJMtUGhgPMjAxMjEwMDkxNjAxNTNaMHQwcjBKMAkGBSsOAwIaBQAE
FHyxZlScq9tE7mImFq30ZXv3etWUBBStvZh6NLQm9/rEJlTvA73gJMtUGgIRAKcN
bJWejX5BTb8DmevkCauAABgPMjAxMjEwMDkxNjAxNTNaoBEYDzIwMTIxMDEzMTYw
MTUzWjANBgkqhkiG9w0BAQUFAAOCAQEAFnJAzuT8P4KKyTI6sdj5HkQ352qEu5CN
K9M2kU/eg9kPfwLv8z3yArobwgx+/IDRajbVAKrk8UPCGUqkDc0OiU5c0+jpn+nT
20VVCtWsBSWDfzKqYln/NGrblhv+/iuFZJpyfud5nWguW5nogPC8IAfgt9FMDMl6
wlQWLSWEkgAJWvhNR3nzgvyMnuDuMIVQgB9/+vAIxA7nlpEEh6KTswyGqE9+u1yC
kvrz4PwKZQMT6r1eRCLs6NaagOZT84QHhZ6TAA+QHjfK406KL8F9mFgbGKbW+st2
QHm+giUhrgZMv+1Yaxe34BjDS439LCPjdZ29On8FeZr3F55T+s3VzA==
| {
"pile_set_name": "Github"
} |
/*
* Alchemy Semi Pb1500 Referrence Board
*
* Copyright 2001, 2008 MontaVista Software Inc.
* Author: MontaVista Software, Inc. <[email protected]>
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*
*
*/
#ifndef __ASM_PB1500_H
#define __ASM_PB1500_H
#define IDENT_BOARD_REG 0xAE000000
#define BOARD_STATUS_REG 0xAE000004
#define PCI_BOARD_REG 0xAE000010
#define PCMCIA_BOARD_REG 0xAE000010
# define PC_DEASSERT_RST 0x80
# define PC_DRV_EN 0x10
#define PB1500_G_CONTROL 0xAE000014
#define PB1500_RST_VDDI 0xAE00001C
#define PB1500_LEDS 0xAE000018
#define PB1500_HEX_LED 0xAF000004
#define PB1500_HEX_LED_BLANK 0xAF000008
/* PCMCIA Pb1500 specific defines */
#define PCMCIA_MAX_SOCK 0
#define PCMCIA_NUM_SOCKS (PCMCIA_MAX_SOCK + 1)
/* VPP/VCC */
#define SET_VCC_VPP(VCC, VPP) (((VCC) << 2) | ((VPP) << 0))
#endif /* __ASM_PB1500_H */
| {
"pile_set_name": "Github"
} |
{
"name": "method-override",
"description": "Override HTTP verbs",
"version": "2.3.5",
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "[email protected]"
},
{
"name": "Jonathan Ong",
"email": "[email protected]",
"url": "http://jongleberry.com"
}
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/expressjs/method-override"
},
"dependencies": {
"debug": "~2.2.0",
"methods": "~1.1.1",
"parseurl": "~1.3.0",
"vary": "~1.0.1"
},
"devDependencies": {
"istanbul": "0.3.17",
"mocha": "2.2.5",
"supertest": "1.0.1"
},
"files": [
"LICENSE",
"HISTORY.md",
"index.js"
],
"engines": {
"node": ">= 0.8.0"
},
"scripts": {
"test": "mocha --check-leaks --reporter spec --bail test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/"
},
"gitHead": "367129dbe18743bcaae8a9300b90621e51825e70",
"bugs": {
"url": "https://github.com/expressjs/method-override/issues"
},
"homepage": "https://github.com/expressjs/method-override",
"_id": "[email protected]",
"_shasum": "2cd5cdbff00c3673d7ae345119a812a5d95b8c8e",
"_from": "method-override@",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "[email protected]"
},
"maintainers": [
{
"name": "jongleberry",
"email": "[email protected]"
},
{
"name": "dougwilson",
"email": "[email protected]"
},
{
"name": "tjholowaychuk",
"email": "[email protected]"
},
{
"name": "mscdex",
"email": "[email protected]"
},
{
"name": "fishrock123",
"email": "[email protected]"
},
{
"name": "defunctzombie",
"email": "[email protected]"
}
],
"dist": {
"shasum": "2cd5cdbff00c3673d7ae345119a812a5d95b8c8e",
"tarball": "http://registry.npmjs.org/method-override/-/method-override-2.3.5.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/method-override/-/method-override-2.3.5.tgz",
"readme": "ERROR: No README data found!"
}
| {
"pile_set_name": "Github"
} |
import FWCore.ParameterSet.Config as cms
siStripBadStripFakeESSource = cms.ESSource("SiStripBadStripFakeESSource",
appendToDataLabel = cms.string('')
)
| {
"pile_set_name": "Github"
} |
---
title: IHostManualEvent (Interfaz)
ms.date: 03/30/2017
api_name:
- IHostManualEvent
api_location:
- mscoree.dll
api_type:
- COM
f1_keywords:
- IHostManualEvent
helpviewer_keywords:
- IHostManualEvent interface [.NET Framework hosting]
ms.assetid: 300c2661-b7d1-4c39-b080-9ebdef0fd523
topic_type:
- apiref
ms.openlocfilehash: 7c46f00063cdf9281a5f1080594e8d6dbc6c101e
ms.sourcegitcommit: d223616e7e6fe2139079052e6fcbe25413fb9900
ms.translationtype: MT
ms.contentlocale: es-ES
ms.lasthandoff: 05/22/2020
ms.locfileid: "83804589"
---
# <a name="ihostmanualevent-interface"></a>IHostManualEvent (Interfaz)
Proporciona la implementación del host de una representación de un evento de restablecimiento manual.
## <a name="methods"></a>Métodos
|Método|Descripción|
|------------|-----------------|
|[Reset (Método)](ihostmanualevent-reset-method.md)|Restablece la instancia actual `IHostManualEvent` a un estado no señalado.|
|[Método Set](ihostmanualevent-set-method.md)|Establece la `IHostManualEvent` instancia actual en un estado señalado.|
|[Wait (Método)](ihostmanualevent-wait-method.md)|Hace que la `IHostManualEvent` instancia actual espere hasta que sea propiedad o transcurra un período de tiempo especificado.|
## <a name="requirements"></a>Requisitos
**Plataformas:** Vea [Requisitos de sistema](../../get-started/system-requirements.md).
**Encabezado:** MSCorEE. h
**Biblioteca:** Se incluye como recurso en MSCorEE. dll
**.NET Framework versiones:**[!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)]
## <a name="see-also"></a>Consulte también
- [ICLRSyncManager (Interfaz)](iclrsyncmanager-interface.md)
- [IHostAutoEvent (Interfaz)](ihostautoevent-interface.md)
- [IHostSemaphore (Interfaz)](ihostsemaphore-interface.md)
- [IHostSyncManager (Interfaz)](ihostsyncmanager-interface.md)
- [Interfaces de hospedaje](hosting-interfaces.md)
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016-2020 Adrian Cotfas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.apps.adrcotfas.goodtime.Util;
import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TimePicker;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Workaround for this bug: https://code.google.com/p/android/issues/detail?id=222208
* In Android 7.0 Nougat, spinner mode for the TimePicker in TimePickerDialog is
* incorrectly displayed as clock, even when the theme specifies otherwise, such as:
*
* <resources>
* <style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
* <item name="android:timePickerStyle">@style/Widget.MyApp.TimePicker</item>
* </style>
*
* <style name="Widget.MyApp.TimePicker" parent="android:Widget.Material.TimePicker">
* <item name="android:timePickerMode">spinner</item>
* </style>
* </resources>
*
* May also pass TimePickerDialog.THEME_HOLO_LIGHT as an argument to the constructor,
* as this theme has the TimePickerMode set to spinner.
*/
public class TimePickerDialogFixedNougatSpinner extends TimePickerDialog {
/**
* Creates a new time picker dialog.
*
* @param context the parent context
* @param listener the listener to call when the time is set
* @param hourOfDay the initial hour
* @param minute the initial minute
* @param is24HourView whether this is a 24 hour view or AM/PM
*/
public TimePickerDialogFixedNougatSpinner(Context context, OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) {
super(context, listener, hourOfDay, minute, is24HourView);
fixSpinner(context, hourOfDay, minute, is24HourView);
}
/**
* Creates a new time picker dialog with the specified theme.
*
* @param context the parent context
* @param themeResId the resource ID of the theme to apply to this dialog
* @param listener the listener to call when the time is set
* @param hourOfDay the initial hour
* @param minute the initial minute
* @param is24HourView Whether this is a 24 hour view, or AM/PM.
*/
public TimePickerDialogFixedNougatSpinner(Context context, int themeResId, OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) {
super(context, themeResId, listener, hourOfDay, minute, is24HourView);
fixSpinner(context, hourOfDay, minute, is24HourView);
}
private void fixSpinner(Context context, int hourOfDay, int minute, boolean is24HourView) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) { // fixes the bug in API 24
try {
// Get the theme's android:timePickerMode
final int MODE_SPINNER = 1;
@SuppressLint("PrivateApi") Class<?> styleableClass = Class.forName("com.android.internal.R$styleable");
Field timePickerStyleableField = styleableClass.getField("TimePicker");
int[] timePickerStyleable = (int[]) timePickerStyleableField.get(null);
final TypedArray a = context.obtainStyledAttributes(null, timePickerStyleable, android.R.attr.timePickerStyle, 0);
Field timePickerModeStyleableField = styleableClass.getField("TimePicker_timePickerMode");
int timePickerModeStyleable = timePickerModeStyleableField.getInt(null);
final int mode = a.getInt(timePickerModeStyleable, MODE_SPINNER);
a.recycle();
if (mode == MODE_SPINNER) {
TimePicker timePicker = (TimePicker) findField(TimePickerDialog.class, TimePicker.class, "mTimePicker").get(this);
Class<?> delegateClass = Class.forName("android.widget.TimePicker$TimePickerDelegate");
Field delegateField = findField(TimePicker.class, delegateClass, "mDelegate");
Object delegate = delegateField.get(timePicker);
Class<?> spinnerDelegateClass;
spinnerDelegateClass = Class.forName("android.widget.TimePickerSpinnerDelegate");
// In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
if (delegate.getClass() != spinnerDelegateClass) {
delegateField.set(timePicker, null); // throw out the TimePickerClockDelegate!
timePicker.removeAllViews(); // remove the TimePickerClockDelegate views
Constructor spinnerDelegateConstructor = spinnerDelegateClass.getConstructor(TimePicker.class, Context.class, AttributeSet.class, int.class, int.class);
spinnerDelegateConstructor.setAccessible(true);
// Instantiate a TimePickerSpinnerDelegate
delegate = spinnerDelegateConstructor.newInstance(timePicker, context, null, android.R.attr.timePickerStyle, 0);
delegateField.set(timePicker, delegate); // set the TimePicker.mDelegate to the spinner delegate
// Set up the TimePicker again, with the TimePickerSpinnerDelegate
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(hourOfDay);
timePicker.setCurrentMinute(minute);
timePicker.setOnTimeChangedListener(this);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static Field findField(Class objectClass, Class fieldClass, String expectedName) {
try {
Field field = objectClass.getDeclaredField(expectedName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {} // ignore
// search for it if it wasn't found under the expected ivar name
for (Field searchField : objectClass.getDeclaredFields()) {
if (searchField.getType() == fieldClass) {
searchField.setAccessible(true);
return searchField;
}
}
return null;
}
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Created by PhpStorm.
* User: zhangjincheng
* Date: 16-9-2
* Time: 下午1:44
*/
namespace Server\Asyn\Mysql;
use Server\CoreBase\Child;
use Server\Memory\Pool;
/**
* A dead simple PHP class for building SQL statements. No manual string
* concatenation necessary.
*/
class Miner extends Child
{
/**
* INNER JOIN type.
*/
const INNER_JOIN = "INNER JOIN";
/**
* LEFT JOIN type.
*/
const LEFT_JOIN = "LEFT JOIN";
/**
* RIGHT JOIN type.
*/
const RIGHT_JOIN = "RIGHT JOIN";
/**
* AND logical operator.
*/
const LOGICAL_AND = "AND";
/**
* OR logical operator.
*/
const LOGICAL_OR = "OR";
/**
* Equals comparison operator.
*/
const EQUALS = "=";
/**
* Not equals comparison operator.
*/
const NOT_EQUALS = "!=";
/**
* Less than comparison operator.
*/
const LESS_THAN = "<";
/**
* Less than or equal to comparison operator.
*/
const LESS_THAN_OR_EQUAL = "<=";
/**
* Greater than comparison operator.
*/
const GREATER_THAN = ">";
/**
* Greater than or equal to comparison operator.
*/
const GREATER_THAN_OR_EQUAL = ">=";
/**
* IN comparison operator.
*/
const IN = "IN";
/**
* NOT IN comparison operator.
*/
const NOT_IN = "NOT IN";
/**
* LIKE comparison operator.
*/
const LIKE = "LIKE";
/**
* NOT LIKE comparison operator.
*/
const NOT_LIKE = "NOT LIKE";
/**
* ILIKE comparison operator.
*/
const ILIKE = "ILIKE";
/**
* REGEXP comparison operator.
*/
const REGEX = "REGEXP";
/**
* NOT REGEXP comparison operator.
*/
const NOT_REGEX = "NOT REGEXP";
/**
* BETWEEN comparison operator.
*/
const BETWEEN = "BETWEEN";
/**
* NOT BETWEEN comparison operator.
*/
const NOT_BETWEEN = "NOT BETWEEN";
/**
* IS comparison operator.
*/
const IS = "IS";
/**
* IS NOT comparison operator.
*/
const IS_NOT = "IS NOT";
/**
* Ascending ORDER BY direction.
*/
const ORDER_BY_ASC = "ASC";
/**
* Descending ORDER BY direction.
*/
const ORDER_BY_DESC = "DESC";
/**
* Open bracket for grouping criteria.
*/
const BRACKET_OPEN = "(";
/**
* Closing bracket for grouping criteria.
*/
const BRACKET_CLOSE = ")";
/**
* RAW
*/
const LOGICAL_RAW = "RAW";
/**
* @var MysqlAsynPool
*/
public $mysql_pool;
/**
* @var array
*/
protected $activeConfig;
/**
* PDO database connection to use in executing the statement.
*
* @var \PDO|null
*/
private $PdoConnection;
/**
* Whether to automatically escape values.
*
* @var bool|null
*/
private $autoQuote;
/**
* Execution options like DISTINCT and SQL_CALC_FOUND_ROWS.
*
* @var array
*/
private $option;
/**
* Columns, tables, and expressions to SELECT from.
*
* @var array
*/
private $select;
/**
* Table to INSERT into.
*
* @var string
*/
private $insert;
/**
* Table to REPLACE into.
*
* @var string
*/
private $replace;
/**
* Table to UPDATE.
*
* @var string
*/
private $update;
/**
* Tables to DELETE from, or true if deleting from the FROM table.
*
* @var array|true
*/
private $delete;
/**
* Column values to INSERT, UPDATE, or REPLACE.
*
* @var array
*/
private $set;
/**
* Table to select FROM.
*
* @var array
*/
private $from;
/**
* JOIN tables and ON criteria.
*
* @var array
*/
private $join;
/**
* WHERE criteria.
*
* @var array
*/
private $where;
/**
* Columns to GROUP BY.
*
* @var array
*/
private $groupBy;
/**
* HAVING criteria.
*
* @var array
*/
private $having;
/**
* Columns to ORDER BY.
*
* @var array
*/
private $orderBy;
/**
* Number of rows to return from offset.
*
* @var array
*/
private $limit;
/**
* SET placeholder values.
*
* @var array
*/
private $setPlaceholderValues;
/**
* WHERE placeholder values.
*
* @var array
*/
private $wherePlaceholderValues;
/**
* HAVING placeholder values.
*
* @var array
*/
private $havingPlaceholderValues;
/**
* InTo
* @var bool
*/
private $isInto = false;
/**
* into colums
* @var array
*/
private $intoColums;
/**
* into values
* @var array
*/
private $intoValues;
/**
* Miner constructor.
* @param $mysql_pool
*/
public function __construct($mysql_pool = null)
{
parent::__construct();
$this->option = array();
$this->select = array();
$this->delete = array();
$this->set = array();
$this->from = array();
$this->join = array();
$this->where = array();
$this->groupBy = array();
$this->having = array();
$this->orderBy = array();
$this->limit = array();
$this->intoColums = array();
$this->intoValues = array();
$this->setPlaceholderValues = array();
$this->wherePlaceholderValues = array();
$this->havingPlaceholderValues = array();
$this->mysql_pool = $mysql_pool;
$this->setAutoQuote(true);
}
/**
* @param $mysql_pool
* @return $this
*/
public function setPool(MysqlAsynPool $mysql_pool)
{
$this->core_name = $mysql_pool->getAsynName();
$this->mysql_pool = $mysql_pool;
$this->clear();
return $this;
}
/**
* Add SQL_CALC_FOUND_ROWS execution option.
*
* @return Miner
*/
public function calcFoundRows()
{
return $this->option('SQL_CALC_FOUND_ROWS');
}
/**
* Add an execution option like DISTINCT or SQL_CALC_FOUND_ROWS.
*
* @param string $option execution option to add
* @return Miner
*/
public function option($option)
{
$this->option[] = $option;
return $this;
}
/**
* Add DISTINCT execution option.
*
* @return Miner
*/
public function distinct()
{
return $this->option('DISTINCT');
}
/**
* Add an array of columns => values to INSERT, UPDATE, or REPLACE.
*
* @param array $values columns => values
* @return Miner
*/
public function values(array $values)
{
return $this->set($values);
}
/**
* Add one or more column values to INSERT, UPDATE, or REPLACE.
*
* @param string|array $column column name or array of columns => values
* @param mixed|null $value optional value for single column
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function set($column, $value = null, $quote = null)
{
if (is_array($column)) {
foreach ($column as $columnName => $columnValue) {
$this->set($columnName, $columnValue, $quote);
}
} else {
$this->set[] = array('column' => $column,
'value' => $value,
'quote' => $quote);
}
return $this;
}
/**
* 配合into使用
* @param array $columns
* @return $this
*/
public function intoColumns(array $columns)
{
$this->intoColums = $columns;
return $this;
}
/**
* 配合into使用
* @param array $values
* @return $this
*/
public function intoValues(array $values)
{
if (is_array($values[0])) {
$this->intoValues = $values;
} else {
$this->intoValues[] = $values;
}
return $this;
}
/**
* Add an INNER JOIN table with optional ON criteria.
*
* @param string $table table name
* @param string|array $criteria optional ON criteria
* @param string $alias optional alias
* @return Miner
*/
public function innerJoin($table, $criteria = null, $alias = null)
{
return $this->join($table, $criteria, self::INNER_JOIN, $alias);
}
/**
* Add a JOIN table with optional ON criteria.
*
* @param string $table table name
* @param string|array $criteria optional ON criteria
* @param string $type optional type of join, default INNER JOIN
* @param string $alias optional alias
* @return Miner
*/
public function join($table, $criteria = null, $type = self::INNER_JOIN, $alias = null)
{
if (!$this->isJoinUnique($table, $alias)) {
return $this;
}
if (is_string($criteria)) {
$criteria = array($criteria);
}
$this->join[] = array('table' => $table,
'criteria' => $criteria,
'type' => $type,
'alias' => $alias);
return $this;
}
/**
* Whether the join table and alias is unique (hasn't already been joined).
*
* @param string $table table name
* @param string $alias table alias
* @return bool whether the join table and alias is unique
*/
private function isJoinUnique($table, $alias)
{
foreach ($this->join as $join) {
if ($join['table'] == $table && $join['alias'] == $alias) {
return false;
}
}
return true;
}
/**
* Add a LEFT JOIN table with optional ON criteria.
*
* @param string $table table name
* @param string|array $criteria optional ON criteria
* @param string $alias optional alias
* @return Miner
*/
public function leftJoin($table, $criteria = null, $alias = null)
{
return $this->join($table, $criteria, self::LEFT_JOIN, $alias);
}
/**
* Add a RIGHT JOIN table with optional ON criteria.
*
* @param string $table table name
* @param string|array $criteria optional ON criteria
* @param string $alias optional alias
* @return Miner
*/
public function rightJoin($table, $criteria = null, $alias = null)
{
return $this->join($table, $criteria, self::RIGHT_JOIN, $alias);
}
/**
* Add an AND WHERE condition.
*
* @param string $column colum name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function andWhere($column, $value, $operator = self::EQUALS, $quote = null)
{
return $this->criteria($this->where, $column, $value, $operator, self::LOGICAL_AND, $quote);
}
/**
* Add a condition to the specified WHERE or HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $column column name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
private function criteria(array &$criteria, $column, $value, $operator = self::EQUALS,
$connector = self::LOGICAL_AND, $quote = null)
{
$criteria[] = array('column' => $column,
'value' => $value,
'operator' => $operator,
'connector' => $connector,
'quote' => $quote);
return $this;
}
/**
* Add an OR WHERE condition.
*
* @param string $column colum name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function orWhere($column, $value, $operator = self::EQUALS, $quote = null)
{
return $this->orCriteria($this->where, $column, $value, $operator, $quote);
}
/**
* Add an OR condition to the specified WHERE or HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $column column name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
private function orCriteria(array &$criteria, $column, $value, $operator = self::EQUALS, $quote = null)
{
return $this->criteria($criteria, $column, $value, $operator, self::LOGICAL_OR, $quote);
}
/**
* Add an IN WHERE condition.
*
* @param string $column column name
* @param array $values values
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function whereIn($column, array $values, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaIn($this->where, $column, $values, $connector, $quote);
}
/**
* Add an IN condition to the specified WHERE or HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $column column name
* @param array $values values
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
private function criteriaIn(array &$criteria, $column, array $values, $connector = self::LOGICAL_AND,
$quote = null)
{
return $this->criteria($criteria, $column, $values, self::IN, $connector, $quote);
}
/**
* Add a NOT IN WHERE condition.
*
* @param string $column column name
* @param array $values values
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function whereNotIn($column, array $values, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaNotIn($this->where, $column, $values, $connector, $quote);
}
/**
* Add a NOT IN condition to the specified WHERE or HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $column column name
* @param array $values values
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
private function criteriaNotIn(array &$criteria, $column, array $values, $connector = self::LOGICAL_AND,
$quote = null)
{
return $this->criteria($criteria, $column, $values, self::NOT_IN, $connector, $quote);
}
/**
* Add a BETWEEN WHERE condition.
*
* @param string $column column name
* @param mixed $min minimum value
* @param mixed $max maximum value
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function whereBetween($column, $min, $max, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaBetween($this->where, $column, $min, $max, $connector, $quote);
}
/**
* Add a BETWEEN condition to the specified WHERE or HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $column column name
* @param mixed $min minimum value
* @param mixed $max maximum value
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
private function criteriaBetween(array &$criteria, $column, $min, $max, $connector = self::LOGICAL_AND,
$quote = null)
{
return $this->criteria($criteria, $column, array($min, $max), self::BETWEEN, $connector, $quote);
}
/**
* Add a NOT BETWEEN WHERE condition.
*
* @param string $column column name
* @param mixed $min minimum value
* @param mixed $max maximum value
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function whereNotBetween($column, $min, $max, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaNotBetween($this->where, $column, $min, $max, $connector, $quote);
}
/**
* Add a NOT BETWEEN condition to the specified WHERE or HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $column column name
* @param mixed $min minimum value
* @param mixed $max maximum value
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
private function criteriaNotBetween(array &$criteria, $column, $min, $max, $connector = self::LOGICAL_AND,
$quote = null)
{
return $this->criteria($criteria, $column, array($min, $max), self::NOT_BETWEEN, $connector, $quote);
}
/**
* Add an AND HAVING condition.
*
* @param string $column colum name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function andHaving($column, $value, $operator = self::EQUALS, $quote = null)
{
return $this->criteria($this->having, $column, $value, $operator, self::LOGICAL_AND, $quote);
}
/**
* Add an OR HAVING condition.
*
* @param string $column colum name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function orHaving($column, $value, $operator = self::EQUALS, $quote = null)
{
return $this->orCriteria($this->having, $column, $value, $operator, $quote);
}
/**
* Add an IN WHERE condition.
*
* @param string $column column name
* @param array $values values
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function havingIn($column, array $values, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaIn($this->having, $column, $values, $connector, $quote);
}
/**
* Add a NOT IN HAVING condition.
*
* @param string $column column name
* @param array $values values
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function havingNotIn($column, array $values, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaNotIn($this->having, $column, $values, $connector, $quote);
}
/**
* Add a BETWEEN HAVING condition.
*
* @param string $column column name
* @param mixed $min minimum value
* @param mixed $max maximum value
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function havingBetween($column, $min, $max, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaBetween($this->having, $column, $min, $max, $connector, $quote);
}
/**
* Add a NOT BETWEEN HAVING condition.
*
* @param string $column column name
* @param mixed $min minimum value
* @param mixed $max maximum value
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function havingNotBetween($column, $min, $max, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteriaNotBetween($this->having, $column, $min, $max, $connector, $quote);
}
/**
* ISet the INSERT INTO table.
* @param $table
* @return Miner
*/
public function insertInto($table)
{
$this->isInto = true;
return $this->insert($table);
}
/**
* Set the INSERT table.
*
* @param string $table INSERT table
* @return Miner
*/
public function insert($table)
{
$this->insert = $table;
return $this;
}
/**
* ISet the REPLACE INTO table.
* @param $table
* @return Miner
*/
public function replaceInto($table)
{
$this->isInto = true;
return $this->replace($table);
}
/**
* Set the REPLACE table.
*
* @param string $table REPLACE table
* @return Miner
*/
public function replace($table)
{
$this->replace = $table;
return $this;
}
/**
* ISet the UPDATE INTO table.
* @param $table
* @return Miner
*/
public function updateInto($table)
{
$this->isInto = true;
return $this->update($table);
}
/**
* Set the UPDATE table.
*
* @param string $table UPDATE table
* @return Miner
*/
public function update($table)
{
$this->update = $table;
return $this;
}
/**
* Get the full SQL statement without value placeholders.
*
* @return string full SQL statement
*/
public function __toString()
{
return $this->getStatement(false);
}
/**
* Get the full SQL statement.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @return string full SQL statement
*/
public function getStatement($usePlaceholders = true)
{
$statement = "";
if ($this->isSelect()) {
$statement = $this->getSelectStatement($usePlaceholders);
} elseif ($this->isInsert()) {
$statement = $this->getInsertStatement($usePlaceholders);
} elseif ($this->isReplace()) {
$statement = $this->getReplaceStatement($usePlaceholders);
} elseif ($this->isUpdate()) {
$statement = $this->getUpdateStatement($usePlaceholders);
} elseif ($this->isDelete()) {
$statement = $this->getDeleteStatement($usePlaceholders);
}
return $statement;
}
/**
* Whether this is a SELECT statement.
*
* @return bool whether this is a SELECT statement
*/
public function isSelect()
{
return !empty($this->select);
}
/**
* Get the full SELECT statement.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @return string full SELECT statement
*/
private function getSelectStatement($usePlaceholders = true)
{
$statement = "";
if (!$this->isSelect()) {
return $statement;
}
$statement .= $this->getSelectString();
if ($this->from) {
$statement .= " " . $this->getFromString();
}
if ($this->where) {
$statement .= " " . $this->getWhereString($usePlaceholders);
}
if ($this->groupBy) {
$statement .= " " . $this->getGroupByString();
}
if ($this->having) {
$statement .= " " . $this->getHavingString($usePlaceholders);
}
if ($this->orderBy) {
$statement .= " " . $this->getOrderByString();
}
if ($this->limit) {
$statement .= " " . $this->getLimitString();
}
return $statement;
}
/**
* Get the SELECT portion of the statement as a string.
*
* @param bool $includeText optional include 'SELECT' text, default true
* @return string SELECT portion of the statement
*/
public function getSelectString($includeText = true)
{
$statement = "";
if (!$this->select) {
return $statement;
}
$statement .= $this->getOptionsString(true);
foreach ($this->select as $column => $alias) {
$statement .= $column;
if ($alias) {
$statement .= " AS " . $alias;
}
$statement .= ", ";
}
$statement = substr($statement, 0, -2);
if ($includeText && $statement) {
$statement = "SELECT " . $statement;
}
return $statement;
}
/**
* Get the execution options portion of the statement as a string.
*
* @param bool $includeTrailingSpace optional include space after options
* @return string execution options portion of the statement
*/
public function getOptionsString($includeTrailingSpace = false)
{
$statement = "";
if (!$this->option) {
return $statement;
}
$statement .= implode(' ', $this->option);
if ($includeTrailingSpace) {
$statement .= " ";
}
return $statement;
}
/**
* Get the FROM portion of the statement, including all JOINs, as a string.
*
* @param bool $includeText optional include 'FROM' text, default true
* @return string FROM portion of the statement
*/
public function getFromString($includeText = true)
{
$statement = "";
if (!$this->from) {
return $statement;
}
$statement .= $this->getFrom();
if ($this->getFromAlias()) {
$statement .= " AS " . $this->getFromAlias();
}
// Add any JOINs.
$statement .= " " . $this->getJoinString();
$statement = rtrim($statement);
if ($includeText && $statement) {
$statement = "FROM " . $statement;
}
return $statement;
}
/**
* Get the FROM table.
*
* @return string FROM table
*/
public function getFrom()
{
return $this->from['table'];
}
/**
* Get the FROM table alias.
*
* @return string FROM table alias
*/
public function getFromAlias()
{
return $this->from['alias'];
}
/**
* Get the JOIN portion of the statement as a string.
*
* @return string JOIN portion of the statement
*/
public function getJoinString()
{
$statement = "";
foreach ($this->join as $i => $join) {
$statement .= " " . $join['type'] . " " . $join['table'];
if ($join['alias']) {
$statement .= " AS " . $join['alias'];
}
// Add ON criteria if specified.
if ($join['criteria']) {
$statement .= " ON ";
foreach ($join['criteria'] as $x => $criterion) {
// Logically join each criterion with AND.
if ($x != 0) {
$statement .= " " . self::LOGICAL_AND . " ";
}
// If the criterion does not include an equals sign, assume a
// column name and join against the same column from the previous
// table.
if (strpos($criterion, '=') === false) {
$statement .= $this->getJoinCriteriaUsingPreviousTable($i, $join['alias'] ?? $join['table'], $criterion);
} else {
$statement .= $criterion;
}
}
}
}
$statement = trim($statement);
return $statement;
}
/**
* Get an ON criteria string joining the specified table and column to the
* same column of the previous JOIN or FROM table.
*
* @param int $joinIndex index of current join
* @param string $table current table name
* @param string $column current column name
* @return string ON join criteria
*/
private function getJoinCriteriaUsingPreviousTable($joinIndex, $table, $column)
{
$joinCriteria = "";
$previousJoinIndex = $joinIndex - 1;
// If the previous table is from a JOIN, use that. Otherwise, use the
// FROM table.
if (array_key_exists($previousJoinIndex, $this->join)) {
$previousTable = $this->join[$previousJoinIndex]['alias'] ?? $this->join[$previousJoinIndex]['table'];
} elseif ($this->isSelect()) {
$previousTable = $this->getFromAlias() ?? $this->getFrom();
} elseif ($this->isUpdate()) {
$previousTable = $this->getUpdate();
} else {
$previousTable = false;
}
// In the off chance there is no previous table.
if ($previousTable) {
$joinCriteria .= $previousTable . ".";
}
$joinCriteria .= $column . " " . self::EQUALS . " " . $table . "." . $column;
return $joinCriteria;
}
/**
* Whether this is an UPDATE statement.
*
* @return bool whether this is an UPDATE statement
*/
public function isUpdate()
{
return !empty($this->update);
}
/**
* Get the UPDATE table.
*
* @return string UPDATE table
*/
public function getUpdate()
{
return $this->update;
}
/**
* Get the WHERE portion of the statement as a string.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @param bool $includeText optional include 'WHERE' text, default true
* @return string WHERE portion of the statement
*/
public function getWhereString($usePlaceholders = true, $includeText = true)
{
$statement = $this->getCriteriaString($this->where, $usePlaceholders, $this->wherePlaceholderValues);
if ($includeText && $statement) {
$statement = "WHERE " . $statement;
}
return $statement;
}
/**
* Get the WHERE or HAVING portion of the statement as a string.
*
* @param array $criteria WHERE or HAVING criteria
* @param bool $usePlaceholders optional use ? placeholders, default true
* @param array $placeholderValues optional placeholder values array
* @return string WHERE or HAVING portion of the statement
*/
private function getCriteriaString(array &$criteria, $usePlaceholders = true,
array &$placeholderValues = array())
{
$statement = "";
$placeholderValues = array();
$useConnector = false;
foreach ($criteria as $i => $criterion) {
if (array_key_exists('bracket', $criterion)) {
// If an open bracket, include the logical connector.
if (strcmp($criterion['bracket'], self::BRACKET_OPEN) == 0) {
if ($useConnector) {
$statement .= " " . $criterion['connector'] . " ";
}
$useConnector = false;
} else {
$useConnector = true;
}
$statement .= $criterion['bracket'];
} else {
if ($useConnector) {
$statement .= " " . $criterion['connector'] . " ";
}
$useConnector = true;
$autoQuote = $this->getAutoQuote($criterion['quote']);
switch ($criterion['operator']) {
case self::BETWEEN:
case self::NOT_BETWEEN:
if ($usePlaceholders && $autoQuote) {
$value = "? " . self::LOGICAL_AND . " ?";
$placeholderValues[] = $criterion['value'][0];
$placeholderValues[] = $criterion['value'][1];
} else {
$value = $this->autoQuote($criterion['value'][0], $autoQuote) . " " . self::LOGICAL_AND . " " .
$this->autoQuote($criterion['value'][1], $autoQuote);
}
break;
case self::IN:
case self::NOT_IN:
if ($usePlaceholders && $autoQuote) {
$value = self::BRACKET_OPEN . substr(str_repeat('?, ', count($criterion['value'])), 0, -2) .
self::BRACKET_CLOSE;
$placeholderValues = array_merge($placeholderValues, $criterion['value']);
} else {
$value = self::BRACKET_OPEN;
foreach ($criterion['value'] as $criterionValue) {
$value .= $this->autoQuote($criterionValue, $autoQuote) . ", ";
}
$value = substr($value, 0, -2);
$value .= self::BRACKET_CLOSE;
}
break;
case self::LOGICAL_RAW:
case self::IS:
case self::IS_NOT:
$value = $criterion['value'];
break;
default:
if ($usePlaceholders && $autoQuote) {
$value = "?";
$placeholderValues[] = $criterion['value'];
} else {
$value = $this->autoQuote($criterion['value'], $autoQuote);
}
break;
}
if ($criterion['operator'] == self::LOGICAL_RAW) {
$statement .= " " . $value . " ";
} else {
$statement .= $criterion['column'] . " " . $criterion['operator'] . " " . $value;
}
}
}
return $statement;
}
/**
* Get whether values will be automatically escaped.
*
* The $override parameter is for convenience in checking if a specific
* value should be quoted differently than the rest. 'null' defers to the
* global setting.
*
* @param bool|null $override value-specific override for convenience
* @return bool
*/
public function getAutoQuote($override = null)
{
return $override === null ? $this->autoQuote : $override;
}
/**
* Set whether to automatically escape values.
*
* @param bool|null $autoQuote whether to automatically escape values
* @return Miner
*/
public function setAutoQuote($autoQuote)
{
$this->autoQuote = $autoQuote;
return $this;
}
/**
* Safely escape a value if auto-quoting is enabled, or do nothing if
* disabled.
*
* The $override parameter is for convenience in checking if a specific
* value should be quoted differently than the rest. 'null' defers to the
* global setting.
*
* @param mixed $value value to escape (or not)
* @param bool|null $override value-specific override for convenience
* @return mixed|false value (escaped or original) or false if failed
*/
public function autoQuote($value, $override = null)
{
return $this->getAutoQuote($override) ? $this->quote($value) : $value;
}
/**
* Safely escape a value for use in a statement.
*
* @param mixed $value value to escape
* @return mixed|false escaped value or false if failed
*/
public function quote($value)
{
$PdoConnection = $this->getPdoConnection();
if ($value === true) {
return 1;
}
if ($value === false) {
return 0;
}
// If a PDO database connection is set, use it to quote the value using
// the underlying database. Otherwise, quote it manually.
if ($PdoConnection) {
return $PdoConnection->quote($value);
} elseif (is_null($value)) {
return "NULL";
} else {
return "'" . addslashes($value) . "'";
}
}
/**
* Get the PDO database connection to use in executing this statement.
*
* @return \PDO|null
*/
public function getPdoConnection()
{
return $this->PdoConnection;
}
/**
* Set the PDO database connection to use in executing this statement.
*
* @param \PDO|null $PdoConnection optional PDO database connection
* @return Miner
*/
public function setPdoConnection(\PDO $PdoConnection = null)
{
$this->PdoConnection = $PdoConnection;
return $this;
}
/**
* Get the GROUP BY portion of the statement as a string.
*
* @param bool $includeText optional include 'GROUP BY' text, default true
* @return string GROUP BY portion of the statement
*/
public function getGroupByString($includeText = true)
{
$statement = "";
foreach ($this->groupBy as $groupBy) {
$statement .= $groupBy['column'];
if ($groupBy['order']) {
$statement .= " " . $groupBy['order'];
}
$statement .= ", ";
}
$statement = substr($statement, 0, -2);
if ($includeText && $statement) {
$statement = "GROUP BY " . $statement;
}
return $statement;
}
/**
* Get the HAVING portion of the statement as a string.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @param bool $includeText optional include 'HAVING' text, default true
* @return string HAVING portion of the statement
*/
public function getHavingString($usePlaceholders = true, $includeText = true)
{
$statement = $this->getCriteriaString($this->having, $usePlaceholders, $this->havingPlaceholderValues);
if ($includeText && $statement) {
$statement = "HAVING " . $statement;
}
return $statement;
}
/**
* Get the ORDER BY portion of the statement as a string.
*
* @param bool $includeText optional include 'ORDER BY' text, default true
* @return string ORDER BY portion of the statement
*/
public function getOrderByString($includeText = true)
{
$statement = "";
foreach ($this->orderBy as $orderBy) {
$statement .= $orderBy['column'] . " " . $orderBy['order'] . ", ";
}
$statement = substr($statement, 0, -2);
if ($includeText && $statement) {
$statement = "ORDER BY " . $statement;
}
return $statement;
}
/**
* Get the LIMIT portion of the statement as a string.
*
* @param bool $includeText optional include 'LIMIT' text, default true
* @return string LIMIT portion of the statement
*/
public function getLimitString($includeText = true)
{
$statement = "";
if (!$this->limit) {
return $statement;
}
$statement .= $this->limit['limit'];
if ($this->limit['offset'] !== 0) {
$statement .= " OFFSET " . $this->limit['offset'];
}
if ($includeText && $statement) {
$statement = "LIMIT " . $statement;
}
return $statement;
}
/**
* Whether this is an INSERT statement.
*
* @return bool whether this is an INSERT statement
*/
public function isInsert()
{
return !empty($this->insert);
}
/**
* Get the full INSERT statement.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @return string full INSERT statement
*/
private function getInsertStatement($usePlaceholders = true)
{
$statement = "";
if (!$this->isInsert()) {
return $statement;
}
$statement .= $this->getInsertString();
if ($this->isInto) {
$statement .= " " . $this->getIntoString($usePlaceholders);
} else {
if ($this->set) {
$statement .= " " . $this->getSetString($usePlaceholders);
}
}
return $statement;
}
/**
* Get the INSERT portion of the statement as a string.
*
* @param bool $includeText optional include 'INSERT' text, default true
* @return string INSERT portion of the statement
*/
public function getInsertString($includeText = true)
{
$statement = "";
if (!$this->insert) {
return $statement;
}
if ($this->isInto) {
$statement .= $this->getOptionsString(true) . 'INTO ';
} else {
$statement .= $this->getOptionsString(true);
}
$statement .= $this->getInsert();
if ($includeText && $statement) {
$statement = "INSERT " . $statement;
}
return $statement;
}
/**
* Get the INSERT table.
*
* @return string INSERT table
*/
public function getInsert()
{
return $this->insert;
}
/**
* Get the INTO portion of the statement as a string.
* @param bool $usePlaceholders
* @return string
*/
public function getIntoString($usePlaceholders = true)
{
$statement = '(';
$this->setPlaceholderValues = array();
foreach ($this->intoColums as $colum) {
if (strpos($colum, '.') !== false) {
$colum = explode(".", $colum);
foreach ($colum as $key => $value) {
$colum[$key] = "`$value`";
}
$statement .= implode(".", $colum);
} else {
$statement .= "`$colum`" . ", ";
}
}
$statement = substr($statement, 0, -2);
$statement .= ') VALUES ';
foreach ($this->intoValues as $values) {
$value_statement = '(';
foreach ($values as $value) {
if ($usePlaceholders) {
$value_statement .= "?, ";
$this->setPlaceholderValues[] = $value;
} else {
$value_statement .= $this->autoQuote($value) . ", ";
}
}
$value_statement = substr($value_statement, 0, -2);
$value_statement .= '), ';
$statement .= $value_statement;
}
$statement = substr($statement, 0, -2);
return $statement;
}
/**
* Get the SET portion of the statement as a string.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @param bool $includeText optional include 'SET' text, default true
* @return string SET portion of the statement
*/
public function getSetString($usePlaceholders = true, $includeText = true)
{
$statement = "";
$this->setPlaceholderValues = array();
foreach ($this->set as $set) {
$autoQuote = $this->getAutoQuote($set['quote']);
if ($usePlaceholders && $autoQuote) {
if (strpos($set['column'], '.') !== false) {
$colum = explode(".", $set['column']);
foreach ($colum as $key => $value) {
$colum[$key] = "`$value`";
}
$statement .= implode(".", $colum) . " " . self::EQUALS . " ?, ";
} else {
$statement .= "`" . $set['column'] . "` " . self::EQUALS . " ?, ";
}
if ($set['value'] === false) {
$this->setPlaceholderValues[] = 0;
} elseif ($set['value'] === true) {
$this->setPlaceholderValues[] = 1;
} else {
$this->setPlaceholderValues[] = $set['value'];
}
} else {
if (strpos($set['column'], '.') !== false) {
$colum = explode(".", $set['column']);
foreach ($colum as $key => $value) {
$colum[$key] = "`$value`";
}
$statement .= implode(".", $colum) . " " . self::EQUALS . " " . $this->autoQuote($set['value'], $autoQuote) . ", ";
} else {
$statement .= "`" . $set['column'] . "` " . self::EQUALS . " " . $this->autoQuote($set['value'], $autoQuote) . ", ";
}
}
}
$statement = substr($statement, 0, -2);
if ($includeText && $statement) {
$statement = "SET " . $statement;
}
return $statement;
}
/**
* Whether this is a REPLACE statement.
*
* @return bool whether this is a REPLACE statement
*/
public function isReplace()
{
return !empty($this->replace);
}
/**
* Get the full REPLACE statement.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @return string full REPLACE statement
*/
private function getReplaceStatement($usePlaceholders = true)
{
$statement = "";
if (!$this->isReplace()) {
return $statement;
}
$statement .= $this->getReplaceString();
if ($this->isInto) {
$statement .= " " . $this->getIntoString($usePlaceholders);
} else {
if ($this->set) {
$statement .= " " . $this->getSetString($usePlaceholders);
}
}
return $statement;
}
/**
* Get the REPLACE portion of the statement as a string.
*
* @param bool $includeText optional include 'REPLACE' text, default true
* @return string REPLACE portion of the statement
*/
public function getReplaceString($includeText = true)
{
$statement = "";
if (!$this->replace) {
return $statement;
}
if ($this->isInto) {
$statement .= $this->getOptionsString(true) . 'INTO ';
} else {
$statement .= $this->getOptionsString(true);
}
$statement .= $this->getReplace();
if ($includeText && $statement) {
$statement = "REPLACE " . $statement;
}
return $statement;
}
/**
* Get the REPLACE table.
*
* @return string REPLACE table
*/
public function getReplace()
{
return $this->replace;
}
/**
* Get the full UPDATE statement.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @return string full UPDATE statement
*/
private function getUpdateStatement($usePlaceholders = true)
{
$statement = "";
if (!$this->isUpdate()) {
return $statement;
}
$statement .= $this->getUpdateString();
if ($this->isInto) {
$statement .= " " . $this->getIntoString($usePlaceholders);
} else {
if ($this->set) {
$statement .= " " . $this->getSetString($usePlaceholders);
}
}
if ($this->where) {
$statement .= " " . $this->getWhereString($usePlaceholders);
}
// ORDER BY and LIMIT are only applicable when updating a single table.
if (!$this->join) {
if ($this->orderBy) {
$statement .= " " . $this->getOrderByString();
}
if ($this->limit) {
$statement .= " " . $this->getLimitString();
}
}
return $statement;
}
/**
* Get the UPDATE portion of the statement as a string.
*
* @param bool $includeText optional include 'UPDATE' text, default true
* @return string UPDATE portion of the statement
*/
public function getUpdateString($includeText = true)
{
$statement = "";
if (!$this->update) {
return $statement;
}
if ($this->isInto) {
$statement .= $this->getOptionsString(true) . 'INTO ';
} else {
$statement .= $this->getOptionsString(true);
}
$statement .= $this->getUpdate();
// Add any JOINs.
$statement .= " " . $this->getJoinString();
$statement = rtrim($statement);
if ($includeText && $statement) {
$statement = "UPDATE " . $statement;
}
return $statement;
}
/**
* Whether this is a DELETE statement.
*
* @return bool whether this is a DELETE statement
*/
public function isDelete()
{
return !empty($this->delete);
}
/**
* Get the full DELETE statement.
*
* @param bool $usePlaceholders optional use ? placeholders, default true
* @return string full DELETE statement
*/
private function getDeleteStatement($usePlaceholders = true)
{
$statement = "";
if (!$this->isDelete()) {
return $statement;
}
$statement .= $this->getDeleteString();
if ($this->from) {
$statement .= " " . $this->getFromString();
}
if ($this->where) {
$statement .= " " . $this->getWhereString($usePlaceholders);
}
// ORDER BY and LIMIT are only applicable when deleting from a single
// table.
if ($this->isDeleteTableFrom()) {
if ($this->orderBy) {
$statement .= " " . $this->getOrderByString();
}
if ($this->limit) {
$statement .= " " . $this->getLimitString();
}
}
return $statement;
}
/**
* Get the DELETE portion of the statement as a string.
*
* @param bool $includeText optional include 'DELETE' text, default true
* @return string DELETE portion of the statement
*/
public function getDeleteString($includeText = true)
{
$statement = "";
if (!$this->delete && !$this->isDeleteTableFrom()) {
return $statement;
}
$statement .= $this->getOptionsString(true);
if (is_array($this->delete)) {
$statement .= implode(', ', $this->delete);
}
if ($includeText && ($statement || $this->isDeleteTableFrom())) {
$statement = "DELETE " . $statement;
// Trim in case the table is specified in FROM.
$statement = trim($statement);
}
return $statement;
}
/**
* Whether the FROM table is the single table to delete from.
*
* @return bool whether the delete table is FROM
*/
private function isDeleteTableFrom()
{
return $this->delete === true;
}
/**
* Merge this Miner into the given Miner.
*
* @param Miner $Miner to merge into
* @param bool $overrideLimit optional override limit, default true
* @return Miner
*/
public function mergeInto(Miner $Miner, $overrideLimit = true)
{
if ($this->isSelect()) {
$this->mergeSelectInto($Miner);
$this->mergeFromInto($Miner);
$this->mergeJoinInto($Miner);
$this->mergeWhereInto($Miner);
$this->mergeGroupByInto($Miner);
$this->mergeHavingInto($Miner);
$this->mergeOrderByInto($Miner);
if ($overrideLimit) {
$this->mergeLimitInto($Miner);
}
} elseif ($this->isInsert()) {
$this->mergeInsertInto($Miner);
$this->mergeSetInto($Miner);
$this->mergeIntoColumns($Miner);
$this->mergeIntoValues($Miner);
} elseif ($this->isReplace()) {
$this->mergeReplaceInto($Miner);
$this->mergeSetInto($Miner);
$this->mergeIntoColumns($Miner);
$this->mergeIntoValues($Miner);
} elseif ($this->isUpdate()) {
$this->mergeUpdateInto($Miner);
$this->mergeJoinInto($Miner);
$this->mergeSetInto($Miner);
$this->mergeWhereInto($Miner);
// ORDER BY and LIMIT are only applicable when updating a single table.
if (!$this->join) {
$this->mergeOrderByInto($Miner);
if ($overrideLimit) {
$this->mergeLimitInto($Miner);
}
}
} elseif ($this->isDelete()) {
$this->mergeDeleteInto($Miner);
$this->mergeFromInto($Miner);
$this->mergeJoinInto($Miner);
$this->mergeWhereInto($Miner);
// ORDER BY and LIMIT are only applicable when deleting from a single
// table.
if ($this->isDeleteTableFrom()) {
$this->mergeOrderByInto($Miner);
if ($overrideLimit) {
$this->mergeLimitInto($Miner);
}
}
}
return $Miner;
}
/**
* Merge this Miner's SELECT into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeSelectInto(Miner $Miner)
{
$this->mergeOptionsInto($Miner);
foreach ($this->select as $column => $alias) {
$Miner->select($column, $alias);
}
return $Miner;
}
/**
* Merge this Miner's execution options into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeOptionsInto(Miner $Miner)
{
foreach ($this->option as $option) {
$Miner->option($option);
}
return $Miner;
}
/**
* Add a SELECT column, table, or expression with optional alias.
*
* @param string $column column name, table name, or expression
* @param string $alias optional alias
* @return Miner
*/
public function select($column, $alias = null)
{
$this->select[$column] = $alias;
return $this;
}
/**
* Merge this Miner's FROM into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeFromInto(Miner $Miner)
{
if ($this->from) {
$Miner->from($this->getFrom(), $this->getFromAlias());
}
return $Miner;
}
/**
* Set the FROM table with optional alias.
*
* @param string $table table name
* @param string $alias optional alias
* @return Miner
*/
public function from($table, $alias = null)
{
$this->from['table'] = $table;
$this->from['alias'] = $alias;
return $this;
}
/**
* Merge this Miner's JOINs into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeJoinInto(Miner $Miner)
{
foreach ($this->join as $join) {
$Miner->join($join['table'], $join['criteria'], $join['type'], $join['alias']);
}
return $Miner;
}
/**
* Merge this Miner's WHERE into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeWhereInto(Miner $Miner)
{
foreach ($this->where as $where) {
// Handle open/close brackets differently than other criteria.
if (array_key_exists('bracket', $where)) {
if (strcmp($where['bracket'], self::BRACKET_OPEN) == 0) {
$Miner->openWhere($where['connector']);
} else {
$Miner->closeWhere();
}
} else {
$Miner->where($where['column'], $where['value'], $where['operator'], $where['connector'], $where['quote']);
}
}
return $Miner;
}
/**
* Add an open bracket for nesting WHERE conditions.
*
* @param string $connector optional logical connector, default AND
* @return Miner
*/
public function openWhere($connector = self::LOGICAL_AND)
{
return $this->openCriteria($this->where, $connector);
}
/**
* Add an open bracket for nesting conditions to the specified WHERE or
* HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @param string $connector optional logical connector, default AND
* @return Miner
*/
private function openCriteria(array &$criteria, $connector = self::LOGICAL_AND)
{
$criteria[] = array('bracket' => self::BRACKET_OPEN,
'connector' => $connector);
return $this;
}
/**
* Add a closing bracket for nesting WHERE conditions.
*
* @return Miner
*/
public function closeWhere()
{
return $this->closeCriteria($this->where);
}
/**
* Add a closing bracket for nesting conditions to the specified WHERE or
* HAVING criteria.
*
* @param array $criteria WHERE or HAVING criteria
* @return Miner
*/
private function closeCriteria(array &$criteria)
{
$criteria[] = array('bracket' => self::BRACKET_CLOSE,
'connector' => null);
return $this;
}
/**
* Add a WHERE condition.
*
* @param string $column column name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function where($column, $value, $operator = self::EQUALS, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteria($this->where, $column, $value, $operator, $connector, $quote);
}
/**
* Merge this Miner's GROUP BY into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeGroupByInto(Miner $Miner)
{
foreach ($this->groupBy as $groupBy) {
$Miner->groupBy($groupBy['column'], $groupBy['order']);
}
return $Miner;
}
/**
* Add a GROUP BY column.
*
* @param string $column column name
* @param string|null $order optional order direction, default none
* @return Miner
*/
public function groupBy($column, $order = null)
{
$this->groupBy[] = array('column' => $column,
'order' => $order);
return $this;
}
/**
* Merge this Miner's HAVING into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeHavingInto(Miner $Miner)
{
foreach ($this->having as $having) {
// Handle open/close brackets differently than other criteria.
if (array_key_exists('bracket', $having)) {
if (strcmp($having['bracket'], self::BRACKET_OPEN) == 0) {
$Miner->openHaving($having['connector']);
} else {
$Miner->closeHaving();
}
} else {
$Miner->having($having['column'], $having['value'], $having['operator'],
$having['connector'], $having['quote']);
}
}
return $Miner;
}
/**
* Add an open bracket for nesting HAVING conditions.
*
* @param string $connector optional logical connector, default AND
* @return Miner
*/
public function openHaving($connector = self::LOGICAL_AND)
{
return $this->openCriteria($this->having, $connector);
}
/**
* Add a closing bracket for nesting HAVING conditions.
*
* @return Miner
*/
public function closeHaving()
{
return $this->closeCriteria($this->having);
}
/**
* Add a HAVING condition.
*
* @param string $column colum name
* @param mixed $value value
* @param string $operator optional comparison operator, default =
* @param string $connector optional logical connector, default AND
* @param bool|null $quote optional auto-escape value, default to global
* @return Miner
*/
public function having($column, $value, $operator = self::EQUALS, $connector = self::LOGICAL_AND, $quote = null)
{
return $this->criteria($this->having, $column, $value, $operator, $connector, $quote);
}
/**
* Merge this Miner's ORDER BY into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeOrderByInto(Miner $Miner)
{
foreach ($this->orderBy as $orderBy) {
$Miner->orderBy($orderBy['column'], $orderBy['order']);
}
return $Miner;
}
/**
* Add a column to ORDER BY.
*
* @param string $column column name
* @param string $order optional order direction, default ASC
* @return Miner
*/
public function orderBy($column, $order = self::ORDER_BY_ASC)
{
$this->orderBy[] = array('column' => $column,
'order' => $order);
return $this;
}
/**
* Merge this Miner's LIMIT into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeLimitInto(Miner $Miner)
{
if ($this->limit) {
$Miner->limit($this->getLimit(), $this->getLimitOffset());
}
return $Miner;
}
/**
* Set the LIMIT on number of rows to return with optional offset.
*
* @param int|string $limit number of rows to return
* @param int|string $offset optional row number to start at, default 0
* @return Miner
*/
public function limit($limit, $offset = 0)
{
$this->limit['limit'] = $limit;
$this->limit['offset'] = $offset;
return $this;
}
/**
* Get the LIMIT on number of rows to return.
*
* @return int|string LIMIT on number of rows to return
*/
public function getLimit()
{
return $this->limit['limit'];
}
/**
* Get the LIMIT row number to start at.
*
* @return int|string LIMIT row number to start at
*/
public function getLimitOffset()
{
return $this->limit['offset'];
}
/**
* Merge this Miner's INTOCOLUMS into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeIntoColumns(Miner $Miner)
{
if ($this->intoColums) {
$Miner->intoColumns($this->intoColums);
}
return $Miner;
}
/**
* Merge this Miner's INTOVALUES into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeIntoValues(Miner $Miner)
{
if ($this->intoValues) {
$Miner->intoValues($this->intoValues);
}
return $Miner;
}
/**
* Merge this Miner's INSERT into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeInsertInto(Miner $Miner)
{
$this->mergeOptionsInto($Miner);
if ($this->insert) {
if ($this->isInto) {
$Miner->insertInto($this->getInsert());
} else {
$Miner->insert($this->getInsert());
}
}
return $Miner;
}
/**
* Merge this Miner's SET into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeSetInto(Miner $Miner)
{
foreach ($this->set as $set) {
$Miner->set($set['column'], $set['value'], $set['quote']);
}
return $Miner;
}
/**
* Merge this Miner's REPLACE into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeReplaceInto(Miner $Miner)
{
$this->mergeOptionsInto($Miner);
if ($this->replace) {
if ($this->isInto) {
$Miner->replaceInto($this->getReplace());
} else {
$Miner->replace($this->getReplace());
}
}
return $Miner;
}
/**
* Merge this Miner's UPDATE into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeUpdateInto(Miner $Miner)
{
$this->mergeOptionsInto($Miner);
if ($this->update) {
$Miner->update($this->getUpdate());
}
return $Miner;
}
/**
* Merge this Miner's DELETE into the given Miner.
*
* @param Miner $Miner to merge into
* @return Miner
*/
public function mergeDeleteInto(Miner $Miner)
{
$this->mergeOptionsInto($Miner);
if ($this->isDeleteTableFrom()) {
$Miner->delete();
} else {
foreach ($this->delete as $delete) {
$Miner->delete($delete);
}
}
return $Miner;
}
/**
* Add a table to DELETE from, or false if deleting from the FROM table.
*
* @param string|false $table optional table name, default false
* @return Miner
*/
public function delete($table = false)
{
if ($table === false) {
$this->delete = true;
} else {
// Reset the array in case the class variable was previously set to a
// boolean value.
if (!is_array($this->delete)) {
$this->delete = array();
}
$this->delete[] = $table;
}
return $this;
}
/**
* @var
*/
protected $client;
/**
* 事务用的client
* @param $client
*/
public function setClient($client)
{
$this->client = $client;
}
/**
* 开始事务
* @param callable $fuc
* @param callable|null $errorFuc
* @return null
* @throws \Server\CoreBase\SwooleException
*/
public function begin($fuc, $errorFuc = null)
{
if (get_instance()->isTaskWorker()) {//如果是task进程自动转换为同步模式
$result = null;
$this->mysql_pool->getSync()->pdoBeginTrans();
try {
$result = $fuc(null);
$this->mysql_pool->getSync()->pdoCommitTrans();
} catch (\Throwable $e) {
$this->mysql_pool->getSync()->pdoRollBackTrans();
if ($errorFuc != null) {
$result = $errorFuc(null, $e);
}
}
return $result;
} else {
return $this->mysql_pool->begin($this, $fuc, $errorFuc);
}
}
/**
* @param null $sql
* @param callable|null $set
* @return MysqlSyncHelp
* @throws \Server\CoreBase\SwooleException
* @throws \Throwable
*/
public function prepareQuery($sql = null, callable $set = null)
{
return $this->getProxy()->_prepareQuery($sql, $set);
}
/**
* @param callable|null $set
* @return MysqlSyncHelp
* @throws \Throwable
*/
public function _prepareQuery(callable $set = null)
{
$mySqlCoroutine = Pool::getInstance()->get(MySqlCoroutine::class);
if (get_instance()->isTaskWorker()) {//如果是task进程自动转换为同步模式
$this->mergeInto($this->mysql_pool->getSync());
$this->clear();
$data = $this->mysql_pool->getSync()->pdoQuery();
return new MysqlSyncHelp(null, $data);
} else {
$statement = $this->getStatement();
$holder = $this->getPlaceholderValues();
$sql = $this->getStatement(false);
$this->clear();
$mySqlCoroutine->setRequest($sql);
if ($set) {
$set($mySqlCoroutine);
}
$result = $this->mysql_pool->prepare($sql, $statement, $holder, $this->client, $mySqlCoroutine);
return $result;
}
}
/**
* @param null $sql
* @param callable|null $set
* @return MysqlSyncHelp
* @throws \Server\CoreBase\SwooleException
* @throws \Throwable
*/
public function query($sql = null, callable $set = null)
{
return $this->getProxy()->_query($sql, $set);
}
/**
* @param null $sql
* @param callable|null $set
* @return MysqlSyncHelp
* @throws \Throwable
*/
public function _query($sql = null, callable $set = null)
{
$mySqlCoroutine = Pool::getInstance()->get(MySqlCoroutine::class);
if (get_instance()->isTaskWorker()) {//如果是task进程自动转换为同步模式
$this->mergeInto($this->mysql_pool->getSync());
$this->clear();
$data = $this->mysql_pool->getSync()->pdoQuery($sql);
return new MysqlSyncHelp($sql, $data);
} else {
if ($sql != null) {
$mySqlCoroutine->setRequest($sql);
if ($set) {
$set($mySqlCoroutine);
}
$this->clear();
$result = $this->mysql_pool->query($sql, $this->client, $mySqlCoroutine);
return $result;
} else {
$sql = $this->getStatement(false);
$this->clear();
$mySqlCoroutine->setRequest($sql);
if ($set) {
$set($mySqlCoroutine);
}
$result = $this->mysql_pool->query($sql, $this->client, $mySqlCoroutine);
return $result;
}
}
}
public function clear()
{
$this->option = array();
$this->select = array();
$this->delete = array();
$this->set = array();
$this->from = array();
$this->join = array();
$this->where = array();
$this->groupBy = array();
$this->having = array();
$this->orderBy = array();
$this->limit = array();
$this->insert = array();
$this->replace = array();
$this->update = array();
$this->intoColums = array();
$this->intoValues = array();
$this->setPlaceholderValues = array();
$this->wherePlaceholderValues = array();
$this->havingPlaceholderValues = array();
$this->isInto = false;
}
/**
* 提交事务
*/
public function pdoCommitTrans()
{
$this->PdoConnection->commit();
}
/**
* 开始事务
*/
public function pdoBeginTrans()
{
$this->PdoConnection->beginTransaction();
}
/**
* 事务回滚
*/
public function pdoRollBackTrans()
{
if ($this->PdoConnection->inTransaction()) {
$this->PdoConnection->rollBack();
}
}
/**
* pdo Query
* @param string $sql
* @param array $palceholderValues
* @param int $fetchmode
* @return array|bool|int|null|string
*/
public function pdoQuery($sql = null, $palceholderValues = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$pdoStatement = $this->pdoExecute($sql, $palceholderValues);
if (!$pdoStatement) {
$data = false;
}
$data['result'] = 1;
$isSelect = false;
if ($sql != null) {//代表手动执行的sql
$str = strtolower(substr(trim($sql), 0, 6));
if ($str == 'select' || strripos($str, 'show') !== false) {
$isSelect = true;
}
}
if ($this->isSelect() || $isSelect) {
$data['result'] = $pdoStatement->fetchAll($fetchmode);
$data['insert_id'] = 0;
$data['affected_rows'] = 0;
} else {
$data['insert_id'] = $this->pdoInsertId();
$data['affected_rows'] = $pdoStatement->rowCount();
}
$pdoStatement->closeCursor();
$this->clear();
return $data;
}
/**
* Execute the statement using the PDO database connection.
* @param $sql string
* @param $palceholderValues array
* @return \PDOStatement|false executed statement or false if failed
*/
protected function pdoExecute($sql, $palceholderValues)
{
$PdoStatement = null;
$PdoConnection = $this->getPdoConnection();
// Without a PDO database connection, the statement cannot be executed.
if (!$PdoConnection) {
$this->pdoConnect($this->activeConfig);
}
if (empty($sql)) {
$statement = $this->getStatement();
} else {
$statement = $sql;
}
// Only execute if a statement is set.
if ($statement) {
try {
$PdoStatement = $PdoConnection->prepare($statement);
if (empty($palceholderValues)) {
$palceholderValues = $this->getPlaceholderValues();
}
$PdoStatement->execute($palceholderValues);
} catch (\PDOException $e) {
// 服务端断开时重连一次
if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
$this->setPdoConnection(null);
$this->pdoConnect($this->activeConfig);
try {
$PdoConnection = $this->getPdoConnection();
$PdoStatement = $PdoConnection->prepare($statement);
$PdoStatement->execute($this->getPlaceholderValues());
} catch (\PDOException $ex) {
$this->pdoRollBackTrans();
throw $ex;
}
} else {
$this->pdoRollBackTrans();
throw $e;
}
} catch (\Throwable $e) {
$this->setPdoConnection(null);
$this->pdoConnect($this->activeConfig);
try {
$PdoConnection = $this->getPdoConnection();
$PdoStatement = $PdoConnection->prepare($statement);
$PdoStatement->execute($this->getPlaceholderValues());
} catch (\PDOException $ex) {
$this->pdoRollBackTrans();
throw $ex;
}
}
return $PdoStatement;
} else {
return false;
}
}
/**
* PDO连接
* @param $activeConfig
*/
public function pdoConnect($activeConfig)
{
$this->activeConfig = $activeConfig;
$dsn = 'mysql:dbname=' . $activeConfig["database"] . ';host=' .
$activeConfig["host"] . ';port=' . $activeConfig['port'] ?? 3306;
$pdo = new \PDO(
$dsn,
$activeConfig["user"], $activeConfig["password"],
[\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $activeConfig['charset'] ?? 'utf8']
);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->setPdoConnection($pdo);
}
/**
* Get all placeholder values (SET, WHERE, and HAVING).
*
* @return array all placeholder values
*/
public function getPlaceholderValues()
{
$array = array_merge($this->getSetPlaceholderValues(),
$this->getWherePlaceholderValues(),
$this->getHavingPlaceholderValues());
return $array;
}
/**
* Get the SET placeholder values.
*
* @return array SET placeholder values
*/
public function getSetPlaceholderValues()
{
return $this->setPlaceholderValues;
}
/**
* Get the WHERE placeholder values.
*
* @return array WHERE placeholder values
*/
public function getWherePlaceholderValues()
{
return $this->wherePlaceholderValues;
}
/**
* Get the HAVING placeholder values.
*
* @return array HAVING placeholder values
*/
public function getHavingPlaceholderValues()
{
return $this->havingPlaceholderValues;
}
/**
* 返回 lastInsertId
*
* @return string
*/
public function pdoInsertId()
{
return $this->PdoConnection->lastInsertId();
}
public function destroy()
{
parent::destroy();
$this->clear();
$this->client = null;
Pool::getInstance()->push($this);
}
}
| {
"pile_set_name": "Github"
} |
%% -*- mode: erlang; tab-width: 4; indent-tabs-mode: 1; st-rulers: [70] -*-
%% vim: ts=4 sw=4 ft=erlang noet
-module(jose_jws_alg_rsa_pss_props).
-include_lib("public_key/include/public_key.hrl").
-include_lib("proper/include/proper.hrl").
% -compile(export_all).
base64url_binary() ->
?LET(Binary,
binary(),
jose_jwa_base64url:encode(Binary)).
binary_map() ->
?LET(List,
list({base64url_binary(), base64url_binary()}),
maps:from_list(List)).
alg() ->
oneof([
<<"PS256">>,
<<"PS384">>,
<<"PS512">>
]).
modulus_size() -> integer(1024, 1280). % integer(256, 8192) | pos_integer().
exponent_size() -> return(65537). % pos_integer().
rsa_keypair(ModulusSize) ->
?LET(ExponentSize,
exponent_size(),
begin
case public_key:generate_key({rsa, ModulusSize, ExponentSize}) of
PrivateKey=#'RSAPrivateKey'{modulus=Modulus, publicExponent=PublicExponent} ->
{PrivateKey, #'RSAPublicKey'{modulus=Modulus, publicExponent=PublicExponent}}
end
end).
jwk_jws_maps() ->
?LET({ModulusSize, ALG, {PrivateKey, PublicKey}},
?LET(ModulusSize,
modulus_size(),
{ModulusSize, alg(), rsa_keypair(ModulusSize)}),
begin
JWKSigner = jose_jwk:from_key(PrivateKey),
JWKVerifier = jose_jwk:from_key(PublicKey),
JWSMap = #{
<<"alg">> => ALG
},
{ModulusSize, {JWKSigner, JWKVerifier}, JWSMap}
end).
jwk_jws_gen() ->
?LET({ModulusSize, JWKs, JWSMap},
jwk_jws_maps(),
{ModulusSize, JWKs, jose_jws:from_map(JWSMap)}).
prop_from_map_and_to_map() ->
?FORALL(JWSMap,
?LET({ALG, Extras},
{alg(), binary_map()},
maps:merge(Extras, #{ <<"alg">> => ALG })),
begin
JWS = jose_jws:from_map(JWSMap),
JWSMap =:= element(2, jose_jws:to_map(JWS))
end).
prop_sign_and_verify() ->
?FORALL({{_ModulusSize, {JWKSigner, JWKVerifier}, JWS}, Message},
{jwk_jws_gen(), binary()},
begin
Signed = jose_jws:sign(JWKSigner, Message, JWS),
CompactSigned = jose_jws:compact(Signed),
{true, Message, JWS} =:= jose_jws:verify(JWKVerifier, Signed)
andalso {true, Message, JWS} =:= jose_jws:verify(JWKVerifier, CompactSigned)
end).
| {
"pile_set_name": "Github"
} |
// Catalano Android Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2012-2016
// diego.catalano at live.com
//
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Corners;
import Catalano.Core.IntPoint;
/**
* Feature Point class.
* @author Diego Catalano
*/
public class FeaturePoint implements Comparable<FeaturePoint>{
/**
* X axis coordinate.
*/
public int x;
/**
* Y axis coordinate.
*/
public int y;
/**
* Score.
*/
public int score;
/**
* Initializes a new instance of the FeaturePoint class.
*/
public FeaturePoint() {}
/**
* Initializes a new instance of the FeaturePoint class.
* @param x X axis coordinate.
* @param y Y axis coordinate.
*/
public FeaturePoint(int x, int y){
this.x = x;
this.y = y;
}
/**
* Initializes a new instance of the FeaturePoint class.
* @param x X axis coordinate.
* @param y Y axis coordinate.
* @param score Score.
*/
public FeaturePoint(int x, int y, int score) {
this.x = x;
this.y = y;
this.score = score;
}
/**
* Convert to IntPoint.
* @return IntPoint.
*/
public IntPoint toIntPoint(){
return new IntPoint(x, y);
}
@Override
public int compareTo(FeaturePoint o) {
if (o.score < this.score) return 1;
else if (o.score == this.score) return 0;
else return -1;
}
} | {
"pile_set_name": "Github"
} |
/*
// Copyright (c) 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include "space_to_depth_kernel_selector.h"
#include "space_to_depth_kernel_ref.h"
namespace kernel_selector {
space_to_depth_kernel_selector::space_to_depth_kernel_selector() { Attach<SpaceToDepthKernelRef>(); }
KernelsData space_to_depth_kernel_selector::GetBestKernels(const Params& params, const optional_params& options) const {
return GetNaiveBestKernel(params, options, KernelType::SPACE_TO_DEPTH);
}
} // namespace kernel_selector
| {
"pile_set_name": "Github"
} |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
gremlin.graph=org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph
gremlin.hadoop.graphReader=org.apache.tinkerpop.gremlin.hadoop.structure.io.gryo.GryoInputFormat
gremlin.hadoop.graphWriter=org.apache.tinkerpop.gremlin.hadoop.structure.io.gryo.GryoOutputFormat
gremlin.hadoop.jarsInDistributedCache=true
gremlin.hadoop.defaultGraphComputer=org.apache.tinkerpop.gremlin.spark.process.computer.SparkGraphComputer
gremlin.hadoop.inputLocation=tinkerpop-modern.kryo
gremlin.hadoop.outputLocation=output
####################################
# SparkGraphComputer org.finra.datagenerator.scaffolding.knowledge.Configuration #
####################################
spark.master=local[4]
spark.executor.memory=1g
spark.serializer=org.apache.tinkerpop.gremlin.spark.structure.io.gryo.GryoSerializer
# gremlin.spark.graphStorageLevel=MEMORY_AND_DISK
# gremlin.spark.persistContext=true
# gremlin.spark.graphWriter=org.apache.tinkerpop.gremlin.spark.structure.io.PersistedOutputRDD
# gremlin.spark.persistStorageLevel=DISK_ONLY
# spark.kryo.registrationRequired=true
# spark.storage.memoryFraction=0.2
# spark.eventLog.enabled=true
# spark.eventLog.dir=/tmp/spark-event-logs
# spark.ui.killEnabled=true
#####################################
# GiraphGraphComputer org.finra.datagenerator.scaffolding.knowledge.Configuration #
#####################################
giraph.minWorkers=2
giraph.maxWorkers=2
giraph.useOutOfCoreGraph=true
giraph.useOutOfCoreMessages=true
mapreduce.map.java.opts=-Xmx1024m
mapreduce.reduce.java.opts=-Xmx1024m
giraph.numInputThreads=2
giraph.numComputeThreads=2
# giraph.maxPartitionsInMemory=1
# giraph.userPartitionCount=2
## MapReduce of GiraphGraphComputer ##
# mapreduce.job.maps=2
# mapreduce.job.reduces=1 | {
"pile_set_name": "Github"
} |
## Windows directory walk using ctypes
Originally published: 2013-08-09 00:15:08
Last updated: 2013-08-09 00:17:00
Author: Shao-chuan Wang
Windows shell/explorer has a limit size of full path, but both NTFS and ReFS can support full path longer than the limit; this is making os.walk on Windows bad if files are in deeply nested folders, and therefore this recipe. | {
"pile_set_name": "Github"
} |
package net.zoneland.x.bpm.mobile.v1.zoneXBPM.app.bbs.publish
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.activity_bbs_publish_subject.*
import net.muliba.fancyfilepickerlibrary.PicturePicker
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.O2
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.R
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.app.base.BaseMVPActivity
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.core.component.api.APIAddressHelper
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.model.bo.BBSUploadImageBO
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.model.bo.api.bbs.SectionInfoJson
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.model.bo.api.bbs.SubjectPublishFormJson
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.utils.*
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.utils.extension.gone
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.utils.extension.hideSoftInput
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.utils.extension.visible
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.widgets.BBSSubjectTypePopupWindow
import org.jetbrains.anko.dip
import java.util.*
import kotlin.collections.ArrayList
class BBSPublishSubjectActivity : BaseMVPActivity<BBSPublishSubjectContract.View, BBSPublishSubjectContract.Presenter>(),
BBSPublishSubjectContract.View {
override var mPresenter: BBSPublishSubjectContract.Presenter = BBSPublishSubjectPresenter()
override fun layoutResId(): Int = R.layout.activity_bbs_publish_subject
companion object {
val BBS_SECTION_ID = "BBS_SECTION_ID"
val BBS_TAKE_FROM_PICTURES_CODE = 0
fun startBundleData(sectionId: String): Bundle {
val bundle = Bundle()
bundle.putString(BBS_SECTION_ID, sectionId)
return bundle
}
}
var sectionId = ""
private val typeList = ArrayList<String>()
private val newSubjectId: String by lazy { UUID.randomUUID().toString() }
private lateinit var popupWindow: BBSSubjectTypePopupWindow
private val uploadedImageMap = HashMap<String, BBSUploadImageBO>()//已上传的图片
private val uploadingImageMap = HashMap<String, BBSUploadImageBO>()//正在上传的图片
override fun afterSetContentView(savedInstanceState: Bundle?) {
sectionId = intent.extras?.getString(BBS_SECTION_ID) ?: ""
if (TextUtils.isEmpty(sectionId)) {
XToast.toastShort(this, "没有传入版块ID,无法发帖!")
finish()
return
}
setupToolBar(getString(R.string.bbs_publish), true)
layout_bbs_publish_subject_type_choose_button.setOnClickListener {
XLog.debug("选择主题类型")
hideSoftInput()
popupWindow.animationStyle = R.style.dir_popupwindow_anim
popupWindow.showAtLocation(image_bbs_publish_subject_attachment_add_button, Gravity.BOTTOM, 0, 0)
ZoneUtil.lightOff(this@BBSPublishSubjectActivity)
}
layout_bbs_publish_subject_attachment_list.viewTreeObserver.addOnGlobalLayoutListener {
if(layout_bbs_publish_subject_attachment_list.childCount != 0) {
image_bbs_publish_subject_attachment_add_button.setImageResource(R.mipmap.icon_choose_image_red)
} else {
image_bbs_publish_subject_attachment_add_button.setImageResource(R.mipmap.icon_choose_image_gray)
}
}
image_bbs_publish_subject_attachment_add_button.setOnClickListener {
XLog.debug("选择图片附件")
PicturePicker()
.withActivity(this)
.chooseType(PicturePicker.CHOOSE_TYPE_SINGLE)
.requestCode(BBS_TAKE_FROM_PICTURES_CODE)
.start()
}
//查询版块对象
mPresenter.querySectionById(sectionId)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_bbs_publish_subject, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_bbs_publish_subject -> {
XLog.debug("发表。。。。。。。。attachment:" + uploadedImageMap.size)
publishSubject()
}
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
BBS_TAKE_FROM_PICTURES_CODE -> {
val result = data?.extras?.getString(PicturePicker.FANCY_PICTURE_PICKER_SINGLE_RESULT_KEY, "")
if (!TextUtils.isEmpty(result)) {
readyUploadImages(result!!)
}
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun sectionInfo(info: SectionInfoJson) {
tv_bbs_publish_subject_section.text = info.sectionName
info.subjectType.split("|").filter { !TextUtils.isEmpty(it.trim()) }.map { typeList.add(it) }
popupWindow = BBSSubjectTypePopupWindow(this, typeList)
popupWindow.setOnDismissListener { ZoneUtil.lightOn(this@BBSPublishSubjectActivity) }
popupWindow.setListener { type ->
XLog.debug("choose type:" + type)
tv_bbs_publish_subject_type.text = type
popupWindow.dismiss()
}
}
override fun querySectionFail() {
XToast.toastShort(this, "版块信息查询失败!")
finish()
}
override fun publishFail() {
XToast.toastShort(this, "发布帖子失败!")
hideLoadingDialog()
}
override fun publishSuccess(id: String) {
XToast.toastShort(this, "发表成功!")
finish()
}
override fun uploadFail(tag: String) {
XToast.toastShort(this, "上传图片到服务器失败!")
val view = layout_bbs_publish_subject_attachment_list.findViewWithTag<RelativeLayout>(tag)
if (view != null) {
removeImageFromImageViewList(view)
}
uploadingImageMap.remove(tag)
}
override fun uploadSuccess(fileId: String, tag: String) {
val view = layout_bbs_publish_subject_attachment_list.findViewWithTag<RelativeLayout>(tag)
if (view != null) {
val loading = view.findViewById<LinearLayout>(R.id.linear_bbs_subject_image_upload_loading)
loading.gone()
val deleteIcon = view.findViewById<ImageView>(R.id.image_bbs_subject_image_upload_delete_button)
deleteIcon.visible()
val attachmentBaseView = view.findViewById<RelativeLayout>(R.id.relative_bbs_subject_image_upload_grid_top)
attachmentBaseView.setOnClickListener { _ ->
removeImageFromImageViewList(view)
uploadedImageMap.remove(tag)
}
val imageBean = uploadingImageMap[tag]
if (imageBean != null) {
imageBean.fileId = fileId
uploadedImageMap.put(tag, imageBean)
}
}
uploadingImageMap.remove(tag)
}
private fun publishSubject() {
val type = tv_bbs_publish_subject_type.text.toString()
if (TextUtils.isEmpty(type) || getString(R.string.bbs_publish_subject_type) == type) {
XToast.toastShort(this, "请选择主题分类")
return
}
val title = edit_bbs_publish_subject_title.text.toString()
if (TextUtils.isEmpty(title)) {
XToast.toastShort(this, "请填写主题")
return
}
val summary = edit_bbs_publish_subject_summary.text.toString()
if (!uploadingImageMap.isEmpty()) {
XToast.toastShort(this, "图片正在上传中。。。")
return
}
var content = edit_bbs_publish_subject_content.text.toString()
if (TextUtils.isEmpty(content) && uploadedImageMap.isEmpty()) {
XToast.toastShort(this, "请填写主题内容")
return
}
XLog.debug("content:" + content)
content = formatToHtml(content)
XLog.debug("content html:" + content)
content += addAttachmentToContent()
XLog.debug("content html and image:$content")
val form = SubjectPublishFormJson(newSubjectId,
type,
"信息",
title,
summary,
content,
sectionId,
AndroidUtils.getDeviceBrand() + AndroidUtils.getDeviceModelNumber(),
O2.DEVICE_TYPE,
attachmentList())
showLoadingDialog()
mPresenter.publishSubject(form)
}
private fun attachmentList(): ArrayList<String> {
val array = ArrayList<String>()
if (!uploadedImageMap.isEmpty()) {
uploadedImageMap.map { array.add(it.value.fileId) }
}
return array
}
private fun addAttachmentToContent(): String {
var content = ""
if (!uploadedImageMap.isEmpty()) {
uploadedImageMap.map {
val attachmentURL = APIAddressHelper.instance().getBBSAttachmentURL(it.value.fileId)
val path = "<p><img src=\"$attachmentURL\" style=\"display: block; margin: auto; width:${it.value.showWidth}px; max-width:100%;\" /></p>"
content += path
}
}
return content
}
private fun formatToHtml(content: String): String {
var ret = ""
if (!TextUtils.isEmpty(content)) {
val lineSeparator = System.getProperty("line.separator", "\n") ?: "\n"
content.split(lineSeparator).map {
ret += "<p>$it</p>"
}
}
return ret
}
private fun readyUploadImages(result: String) {
if (!uploadingImageMap.containsKey(result) && !uploadedImageMap.containsKey(result)) {
addToUploadingImageMap(result)
addToImageViewList(result)
mPresenter.uploadImage(result, newSubjectId)
}
}
private fun addToImageViewList(filePath: String) {
val view = LayoutInflater.from(this).inflate(R.layout.item_bbs_suject_image_upload_list, layout_bbs_publish_subject_attachment_list, false)
val imageView = view.findViewById<ImageView>(R.id.image_bbs_subject_image_upload_content)
val width = dip(48f)
val bitmap = BitmapUtil.getFitSampleBitmap(filePath, width, width)
imageView.setImageBitmap(bitmap)
view.tag = filePath
layout_bbs_publish_subject_attachment_list.addView(view)
}
private fun addToUploadingImageMap(filePath: String) {
val options = BitmapUtil.getImageOptions(filePath)
val width = options.outWidth
val height = options.outHeight
val bean = BBSUploadImageBO()
bean.width = width
bean.height = height
if (width > O2.BBS_IMAGE_MAX_WIDTH) {
val lv: Double = (width / O2.BBS_IMAGE_MAX_WIDTH).toDouble()
val showHeight = (height / lv).toInt()
bean.showWidth = O2.BBS_IMAGE_MAX_WIDTH
bean.showHeight = showHeight
} else {
bean.showHeight = height
bean.showWidth = width
}
uploadingImageMap.put(filePath, bean)
}
private fun removeImageFromImageViewList(view: View?) {
layout_bbs_publish_subject_attachment_list.removeView(view)
}
}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example19-production</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
</head>
<body ng-app="">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</body>
</html> | {
"pile_set_name": "Github"
} |
# created by tools/tclZIC.tcl - do not edit
if {![info exists TZData(Europe/Oslo)]} {
LoadTimeZoneFile Europe/Oslo
}
set TZData(:Atlantic/Jan_Mayen) $TZData(:Europe/Oslo)
| {
"pile_set_name": "Github"
} |
package matchers_test
import (
"fmt"
"io/ioutil"
"os"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type myStringer struct {
a string
}
func (s *myStringer) String() string {
return s.a
}
type StringAlias string
type myCustomType struct {
s string
n int
f float32
arr []string
}
func Test(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Gomega Matchers")
}
func readFileContents(filePath string) []byte {
f := openFile(filePath)
b, err := ioutil.ReadAll(f)
if err != nil {
panic(fmt.Errorf("failed to read file contents: %v", err))
}
return b
}
func openFile(filePath string) *os.File {
f, err := os.Open(filePath)
if err != nil {
panic(fmt.Errorf("failed to open file: %v", err))
}
return f
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build sparc64,linux
package unix
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
//sys Dup2(oldfd int, newfd int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error)
//sys Fstat(fd int, stat *Stat_t) (err error)
//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
//sys Ftruncate(fd int, length int64) (err error)
//sysnb Getegid() (egid int)
//sysnb Geteuid() (euid int)
//sysnb Getgid() (gid int)
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Getuid() (uid int)
//sysnb InotifyInit() (fd int, err error)
//sys Lchown(path string, uid int, gid int) (err error)
//sys Listen(s int, n int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error)
//sys Pause() (err error)
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Stat(path string, stat *Stat_t) (err error)
//sys Statfs(path string, buf *Statfs_t) (err error)
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
//sys Truncate(path string, length int64) (err error)
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
//sysnb setgroups(n int, list *_Gid_t) (err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
func Ioperm(from int, num int, on int) (err error) {
return ENOSYS
}
func Iopl(level int) (err error) {
return ENOSYS
}
//sys futimesat(dirfd int, path string, times *[2]Timeval) (err error)
//sysnb Gettimeofday(tv *Timeval) (err error)
func Time(t *Time_t) (tt Time_t, err error) {
var tv Timeval
err = Gettimeofday(&tv)
if err != nil {
return 0, err
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
//sys Utime(path string, buf *Utimbuf) (err error)
//sys utimes(path string, times *[2]Timeval) (err error)
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: int32(usec)}
}
func (r *PtraceRegs) PC() uint64 { return r.Tpc }
func (r *PtraceRegs) SetPC(pc uint64) { r.Tpc = pc }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint64(length)
}
func (msghdr *Msghdr) SetIovlen(length int) {
msghdr.Iovlen = uint64(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint64(length)
}
//sysnb pipe(p *[2]_C_int) (err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe(&pp)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
| {
"pile_set_name": "Github"
} |
//--------------------------------------------------------------------------------------------------
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
//
// QLEnv defines the interface for the environment where SQL engine is running.
//
// If we support different types of servers underneath SQL engine (which we don't), this class
// should be an abstract interface and let the server (such as proxy server) defines the content.
//--------------------------------------------------------------------------------------------------
#ifndef YB_YQL_CQL_QL_UTIL_QL_ENV_H_
#define YB_YQL_CQL_QL_UTIL_QL_ENV_H_
#include "yb/client/callbacks.h"
#include "yb/client/client.h"
#include "yb/client/transaction.h"
#include "yb/client/transaction_manager.h"
#include "yb/common/common.pb.h"
#include "yb/gutil/callback.h"
#include "yb/rpc/rpc_fwd.h"
#include "yb/server/hybrid_clock.h"
#include "yb/util/enums.h"
#include "yb/yql/cql/ql/ptree/pt_option.h"
#include "yb/yql/cql/ql/ql_session.h"
namespace yb {
namespace ql {
typedef std::function<client::TransactionPool*()> TransactionPoolProvider;
class QLEnv {
public:
//------------------------------------------------------------------------------------------------
// Public types.
typedef std::unique_ptr<QLEnv> UniPtr;
typedef std::unique_ptr<const QLEnv> UniPtrConst;
//------------------------------------------------------------------------------------------------
// Constructor & destructor.
QLEnv(client::YBClient* client,
std::shared_ptr<client::YBMetaDataCache> cache,
const server::ClockPtr& clock,
TransactionPoolProvider transaction_pool_provider);
virtual ~QLEnv();
//------------------------------------------------------------------------------------------------
// Table related methods.
virtual std::unique_ptr<client::YBTableCreator> NewTableCreator();
virtual std::unique_ptr<client::YBTableAlterer> NewTableAlterer(
const client::YBTableName& table_name);
virtual CHECKED_STATUS TruncateTable(const std::string& table_id);
virtual CHECKED_STATUS DeleteTable(const client::YBTableName& name);
virtual CHECKED_STATUS DeleteIndexTable(const client::YBTableName& name,
client::YBTableName* indexed_table_name);
virtual CHECKED_STATUS GetUpToDateTableSchemaVersion(const client::YBTableName& table_name,
uint32_t* ver);
virtual std::shared_ptr<client::YBTable> GetTableDesc(const client::YBTableName& table_name,
bool* cache_used);
virtual std::shared_ptr<client::YBTable> GetTableDesc(const TableId& table_id, bool* cache_used);
virtual void RemoveCachedTableDesc(const client::YBTableName& table_name);
virtual void RemoveCachedTableDesc(const TableId& table_id);
//------------------------------------------------------------------------------------------------
// Read/write related methods.
// Create a read/write session.
client::YBSessionPtr NewSession();
// Create a new transaction.
Result<client::YBTransactionPtr> NewTransaction(const client::YBTransactionPtr& transaction,
IsolationLevel isolation_level);
//------------------------------------------------------------------------------------------------
// Permission related methods.
// Grant/Revoke a permission with the given arguments.
virtual CHECKED_STATUS GrantRevokePermission(GrantRevokeStatementType statement_type,
const PermissionType& permission,
const ResourceType& resource_type,
const std::string& canonical_resource,
const char* resource_name,
const char* namespace_name,
const std::string& role_name);
//------------------------------------------------------------------------------------------------
// Keyspace related methods.
// Create a new keyspace with the given name.
virtual CHECKED_STATUS CreateKeyspace(const std::string& keyspace_name);
// Delete keyspace with the given name.
virtual CHECKED_STATUS DeleteKeyspace(const std::string& keyspace_name);
// Use keyspace with the given name.
virtual CHECKED_STATUS UseKeyspace(const std::string& keyspace_name);
// Alter keyspace with the given name.
virtual CHECKED_STATUS AlterKeyspace(const std::string& keyspace_name);
virtual std::string CurrentKeyspace() const {
return ql_session()->current_keyspace();
}
//------------------------------------------------------------------------------------------------
// Role related methods.
// Create role with the given arguments.
virtual CHECKED_STATUS CreateRole(const std::string& role_name,
const std::string& salted_hash,
const bool login, const bool superuser);
// Alter an existing role with the given arguments.
virtual CHECKED_STATUS AlterRole(const std::string& role_name,
const boost::optional<std::string>& salted_hash,
const boost::optional<bool> login,
const boost::optional<bool> superuser);
// Delete role by name.
virtual CHECKED_STATUS DeleteRole(const std::string& role_name);
virtual CHECKED_STATUS GrantRevokeRole(GrantRevokeStatementType statement_type,
const std::string& granted_role_name,
const std::string& recipient_role_name);
virtual std::string CurrentRoleName() const {
return ql_session()->current_role_name();
}
// Check the cache to determine whether the current role has been given permissions on a specific
// canonical resource.
// keyspace and table are only used to generate the error message.
// If the permission is not found, the client will refresh the cache from the master once.
virtual CHECKED_STATUS HasResourcePermission(const string& canonical_name,
const ql::ObjectType& object_type,
const PermissionType permission,
const NamespaceName& keyspace = "",
const TableName& table = "");
// Convenience methods to check whether the current role has the specified permission on the
// given table.
// These method call YBMetaDataCache::HasTablePermissionWithRetry which first checks if the
// keyspace has the permission. Otherwise, it checks whether the table has the permission.
virtual CHECKED_STATUS HasTablePermission(const NamespaceName& keyspace_name,
const TableName& table_name,
const PermissionType permission);
virtual CHECKED_STATUS HasTablePermission(const client::YBTableName table_name,
const PermissionType permission);
// Convenience method to check whether the current role has the specified permission on the given
// role.
virtual CHECKED_STATUS HasRolePermission(const RoleName& role_name,
const PermissionType permission);
//------------------------------------------------------------------------------------------------
// (User-defined) Type related methods.
// Create (user-defined) type with the given arguments.
CHECKED_STATUS CreateUDType(const std::string& keyspace_name,
const std::string& type_name,
const std::vector<std::string>& field_names,
const std::vector<std::shared_ptr<QLType>>& field_types);
// Delete (user-defined) type by name.
virtual CHECKED_STATUS DeleteUDType(const std::string& keyspace_name,
const std::string& type_name);
// Retrieve (user-defined) type by name.
std::shared_ptr<QLType> GetUDType(const std::string& keyspace_name,
const std::string& type_name,
bool* cache_used);
virtual void RemoveCachedUDType(const std::string& keyspace_name, const std::string& type_name);
//------------------------------------------------------------------------------------------------
// QLSession related methods.
void set_ql_session(const QLSession::SharedPtr& ql_session) {
ql_session_ = ql_session;
}
const QLSession::SharedPtr& ql_session() const {
if (!ql_session_) {
ql_session_.reset(new QLSession());
}
return ql_session_;
}
private:
//------------------------------------------------------------------------------------------------
// Persistent attributes.
// YBClient, an API that SQL engine uses to communicate with all servers.
client::YBClient* const client_;
// YBMetaDataCache, a cache to avoid creating a new table or type for each call.
// Also used to hold the permissions cache when authentication is enabled.
std::shared_ptr<client::YBMetaDataCache> metadata_cache_;
// Server clock.
const server::ClockPtr clock_;
// Transaction manager to create distributed transactions.
TransactionPoolProvider transaction_pool_provider_;
client::TransactionPool* transaction_pool_ = nullptr;
//------------------------------------------------------------------------------------------------
// Transient attributes.
// The following attributes are reset implicitly for every execution.
// The QL session processing the statement.
mutable QLSession::SharedPtr ql_session_;
};
} // namespace ql
} // namespace yb
#endif // YB_YQL_CQL_QL_UTIL_QL_ENV_H_
| {
"pile_set_name": "Github"
} |
# Nomad Security Group Rules Module
This folder contains a [Terraform](https://www.terraform.io/) module that defines the security group rules used by a
[Nomad](https://www.nomadproject.io/) cluster to control the traffic that is allowed to go in and out of the cluster.
Normally, you'd get these rules by default if you're using the [nomad-cluster module](https://github.com/hashicorp/terraform-aws-nomad/tree/master/modules/nomad-cluster), but if
you're running Nomad on top of a different cluster, then you can use this module to add the necessary security group
rules that that cluster. For example, imagine you were using the [consul-cluster
module](https://github.com/hashicorp/terraform-aws-consul/tree/master/modules/consul-cluster) to run a cluster of
servers that have both Nomad and Consul on each node:
```hcl
module "consul_servers" {
source = "github.com/hashicorp/terraform-aws-consul//modules/consul-cluster?ref=v0.7.7"
# This AMI has both Nomad and Consul installed
ami_id = "ami-1234abcd"
}
```
The `consul-cluster` module will provide the security group rules for Consul, but not for Nomad. To ensure those
servers have the necessary ports open for using Nomad, you can use this module as follows:
```hcl
module "security_group_rules" {
source = "github.com/hashicorp/terraform-aws-nomad//modules/nomad-security-group-rules?ref=v0.0.1"
security_group_id = module.consul_servers.security_group_id
# ... (other params omitted) ...
}
```
Note the following parameters:
- `source`: Use this parameter to specify the URL of this module. The double slash (`//`) is intentional
and required. Terraform uses it to specify subfolders within a Git repo (see [module
sources](https://www.terraform.io/docs/modules/sources.html)). The `ref` parameter specifies a specific Git tag in
this repo. That way, instead of using the latest version of this module from the `master` branch, which
will change every time you run Terraform, you're using a fixed version of the repo.
- `security_group_id`: Use this parameter to specify the ID of the security group to which the rules in this module
should be added.
You can find the other parameters in [variables.tf](variables.tf).
Check out the [nomad-consul-colocated-cluster example](https://github.com/hashicorp/terraform-aws-nomad/tree/master/examples/root-example) for working
sample code.
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Image" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_Access_contents_information_Permission</string> </key>
<value>
<tuple>
<string>Assignee</string>
<string>Assignor</string>
<string>Manager</string>
<string>Owner</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Add_portal_content_Permission</string> </key>
<value>
<tuple>
<string>Assignee</string>
<string>Assignor</string>
<string>Manager</string>
<string>Owner</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Change_local_roles_Permission</string> </key>
<value>
<tuple>
<string>Assignor</string>
<string>Manager</string>
</tuple>
</value>
</item>
<item>
<key> <string>_Modify_portal_content_Permission</string> </key>
<value>
<tuple>
<string>Assignee</string>
<string>Assignor</string>
<string>Manager</string>
<string>Owner</string>
</tuple>
</value>
</item>
<item>
<key> <string>_View_Permission</string> </key>
<value>
<tuple>
<string>Assignee</string>
<string>Assignor</string>
<string>Manager</string>
<string>Owner</string>
</tuple>
</value>
</item>
<item>
<key> <string>_count</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAI=</string> </persistent>
</value>
</item>
<item>
<key> <string>_mt_index</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAM=</string> </persistent>
</value>
</item>
<item>
<key> <string>_tree</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAQ=</string> </persistent>
</value>
</item>
<item>
<key> <string>content_md5</string> </key>
<value> <string>8dd4ece0e5b0ba3adf78433664e341ca</string> </value>
</item>
<item>
<key> <string>content_type</string> </key>
<value> <string>image/x-bmp</string> </value>
</item>
<item>
<key> <string>height</string> </key>
<value> <int>595</int> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>template_test_presentaion_odp_slide_view_bmp</string> </value>
</item>
<item>
<key> <string>portal_type</string> </key>
<value> <string>Image</string> </value>
</item>
<item>
<key> <string>width</string> </key>
<value> <int>842</int> </value>
</item>
</dictionary>
</pickle>
</record>
<record id="2" aka="AAAAAAAAAAI=">
<pickle>
<global name="Length" module="BTrees.Length"/>
</pickle>
<pickle> <int>0</int> </pickle>
</record>
<record id="3" aka="AAAAAAAAAAM=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
<record id="4" aka="AAAAAAAAAAQ=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faVolumeDown: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string; | {
"pile_set_name": "Github"
} |
# People who have agreed to one of the CLAs and can contribute patches.
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# https://developers.google.com/open-source/cla/individual
# https://developers.google.com/open-source/cla/corporate
#
# Names should be added to this file as:
# Name <email address>
Daniel Ziegler <[email protected]>
Daniel Ziegler <[email protected]>
David Leon Gil <[email protected]>
Dominic Hamon <[email protected]>
Drew Hintz <[email protected]>
Eduardo Vela Nava <[email protected]>
Frank Yellin <[email protected]>
KB Sriram <[email protected]>
Krzysztof Kotowicz <[email protected]>
Quan Nguyen <[email protected]>
Radoslav Vasilev <[email protected]>
Ryan Chan <[email protected]>
Ryan Chan <[email protected]>
Thai Duong <[email protected]>
Yan Zhu <[email protected]>
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "iphone",
"scale" : "1x"
},
{
"idiom" : "iphone",
"filename" : "PlayerBotWalk_7_04_100.png",
"scale" : "2x"
},
{
"idiom" : "iphone",
"filename" : "PlayerBotWalk_7_04_180.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"filename" : "PlayerBotWalk_7_04_120.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"filename" : "PlayerBotWalk_7_04_240.png",
"scale" : "2x"
},
{
"idiom" : "tv",
"filename" : "PlayerBotWalk_7_04_169.png",
"scale" : "1x"
},
{
"idiom" : "mac",
"filename" : "PlayerBotWalk_7_04_225.png",
"scale" : "1x"
},
{
"idiom" : "mac",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
// TnzCore includes
#include "tundo.h"
#include "tconvert.h"
#include "tstream.h"
// TnzBase includes
#include "tdoubleparam.h"
// STD includes
#include <set>
#include "tspectrumparam.h"
typedef std::pair<TDoubleParamP, TPixelParamP> ColorKeyParam;
//=========================================================
class TSpectrumParamImp {
TSpectrumParam *m_sp;
std::vector<ColorKeyParam> m_keys;
public:
bool m_draggingEnabled;
bool m_notificationEnabled;
bool m_isMatteEnabled;
std::set<TParamObserver *> m_observers;
public:
TSpectrumParamImp(TSpectrumParam *sp)
: m_sp(sp)
, m_keys()
, m_draggingEnabled(false)
, m_notificationEnabled(true)
, m_isMatteEnabled(true) {}
TSpectrumParamImp(const TSpectrumParamImp &s) { copy(s); }
void copy(const TSpectrumParamImp &src) {
m_keys.clear();
std::vector<ColorKeyParam>::const_iterator it = src.m_keys.begin();
for (; it != src.m_keys.end(); ++it) {
TDoubleParamP s(it->first->clone());
TPixelParamP c(it->second->clone());
m_keys.push_back(std::make_pair(s, c));
}
}
void addKey(const ColorKeyParam &colorKey) {
/*
m_sp->addParam(colorKey.first);
m_sp->addParam(colorKey.second);
*/
m_keys.push_back(colorKey);
}
void insertKey(int index, ColorKeyParam &colorKey) {
/*
m_sp->addParam(colorKey.first);
m_sp->addParam(colorKey.second);
*/
std::vector<ColorKeyParam>::iterator it = m_keys.begin() + index;
m_keys.insert(it, colorKey);
}
void eraseKey(int index) {
std::vector<ColorKeyParam>::iterator colorKeyIt = m_keys.begin() + index;
/*
m_sp->removeParam((*colorKeyIt).first);
m_sp->removeParam((*colorKeyIt).second);
*/
m_keys.erase(colorKeyIt);
}
int getKeyCount() const { return m_keys.size(); }
ColorKeyParam getKey(int index) const { return m_keys[index]; }
void clearKeys() { m_keys.clear(); }
void notify(const TParamChange &change) {
for (std::set<TParamObserver *>::iterator it = m_observers.begin();
it != m_observers.end(); ++it)
(*it)->onChange(change);
}
private:
TSpectrumParamImp &operator=(const TSpectrumParamImp &); // not implemented
};
//=========================================================
PERSIST_IDENTIFIER(TSpectrumParam, "spectrumParam")
//---------------------------------------------------------
TSpectrumParam::TSpectrumParam()
: m_imp(new TSpectrumParamImp(this)) // brutto...
{
ColorKeyParam ck1(TDoubleParamP(0.0), TPixelParamP(TPixel32::Black));
ColorKeyParam ck2(TDoubleParamP(1.0), TPixelParamP(TPixel32::White));
m_imp->addKey(ck1);
m_imp->addKey(ck2);
}
//---------------------------------------------------------
TSpectrumParam::TSpectrumParam(const TSpectrumParam &src)
: TParam(src.getName()), m_imp(new TSpectrumParamImp(*src.m_imp)) {}
//---------------------------------------------------------
void TSpectrumParam::addObserver(TParamObserver *obs) {
m_imp->m_observers.insert(obs);
}
//---------------------------------------------------------
void TSpectrumParam::removeObserver(TParamObserver *obs) {
m_imp->m_observers.erase(obs);
}
//---------------------------------------------------------
TSpectrumParam::TSpectrumParam(std::vector<TSpectrum::ColorKey> const &keys)
: m_imp(new TSpectrumParamImp(this)) {
for (auto const &key : keys) {
double v = key.first;
TPixel32 pix = key.second;
TDoubleParamP dp(v);
TPixelParamP pp(pix);
pp->enableMatte(m_imp->m_isMatteEnabled);
ColorKeyParam ck(dp, pp);
m_imp->addKey(ck);
}
}
//---------------------------------------------------------
void TSpectrumParam::copy(TParam *src) {
TSpectrumParam *p = dynamic_cast<TSpectrumParam *>(src);
if (!p) throw TException("invalid source for copy");
setName(src->getName());
m_imp->copy(*(p->m_imp));
}
//---------------------------------------------------------
TSpectrumParam::~TSpectrumParam() {}
//---------------------------------------------------------
TSpectrum TSpectrumParam::getValue(double frame) const {
assert(m_imp);
std::vector<TSpectrum::ColorKey> keys;
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam paramKey = m_imp->getKey(i);
TSpectrum::ColorKey key(paramKey.first->getValue(frame),
paramKey.second->getValue(frame));
keys.push_back(key);
}
return TSpectrum(keys.size(), &keys[0]);
}
//---------------------------------------------------------
TSpectrum64 TSpectrumParam::getValue64(double frame) const {
assert(m_imp);
std::vector<TSpectrum64::ColorKey> keys;
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam paramKey = m_imp->getKey(i);
TSpectrum64::ColorKey key(paramKey.first->getValue(frame),
toPixel64(paramKey.second->getValue(frame)));
keys.push_back(key);
}
return TSpectrum64(keys.size(), &keys[0]);
}
//---------------------------------------------------------
void TSpectrumParam::setValue(double frame, const TSpectrum &spectrum,
bool undoing) {
assert(getKeyCount() == spectrum.getKeyCount());
int keyCount = getKeyCount();
for (int i = 0; i < keyCount; i++) {
TSpectrum::Key key = spectrum.getKey(i);
setValue(frame, i, key.first, key.second, undoing);
}
}
//---------------------------------------------------------
TDoubleParamP TSpectrumParam::getPosition(int index) const {
assert(index <= m_imp->getKeyCount());
return m_imp->getKey(index).first;
}
//---------------------------------------------------------
TPixelParamP TSpectrumParam::getColor(int index) const {
assert(index <= m_imp->getKeyCount());
return m_imp->getKey(index).second;
}
//---------------------------------------------------------
int TSpectrumParam::getKeyCount() const {
assert(m_imp);
return m_imp->getKeyCount();
}
//---------------------------------------------------------
void TSpectrumParam::setValue(double frame, int index, double s,
const TPixel32 &color, bool undoing) {
assert(m_imp);
int keyCount = m_imp->getKeyCount();
if (index < 0 || index >= keyCount)
throw TException("TSpectrumParam::setValue. Index out of range");
ColorKeyParam key = m_imp->getKey(index);
// beginParameterChange();
key.first->setValue(frame, s);
key.second->setValue(frame, color);
// endParameterChange();
m_imp->notify(TParamChange(this, TParamChange::m_minFrame,
TParamChange::m_maxFrame, true,
m_imp->m_draggingEnabled, false));
}
//---------------------------------------------------------
void TSpectrumParam::setDefaultValue(const TSpectrum &value) {
assert(value.getKeyCount() == getKeyCount());
for (int i = 0; i < getKeyCount(); i++) {
ColorKeyParam dstKeyParam = m_imp->getKey(i);
TSpectrum::Key srcKey = value.getKey(i);
dstKeyParam.first->setDefaultValue(srcKey.first);
dstKeyParam.second->setDefaultValue(srcKey.second);
}
}
//---------------------------------------------------------
void TSpectrumParam::insertKey(int index, double s, const TPixel32 &color) {
assert(m_imp);
int keyCount = m_imp->getKeyCount();
if (index < 0)
index = 0;
else if (index >= keyCount)
index = keyCount;
TDoubleParamP dp(s);
TPixelParamP pp(color);
pp->enableMatte(m_imp->m_isMatteEnabled);
ColorKeyParam ck(dp, pp);
m_imp->insertKey(index, ck);
}
//---------------------------------------------------------
void TSpectrumParam::addKey(double s, const TPixel32 &color) {
/*
assert(m_imp);
insertKey(m_imp->getKeyCount(), s,color);
*/
int index = m_imp->getKeyCount();
assert(m_imp);
int keyCount = m_imp->getKeyCount();
if (index < 0)
index = 0;
else if (index >= keyCount)
index = keyCount;
TDoubleParamP dp(s);
TPixelParamP pp(color);
pp->enableMatte(m_imp->m_isMatteEnabled);
ColorKeyParam ck(dp, pp);
m_imp->insertKey(index, ck);
}
//---------------------------------------------------------
void TSpectrumParam::removeKey(int index) {
assert(m_imp);
int keyCount = m_imp->getKeyCount();
if (index < 0 || index >= keyCount)
throw TException("TSpectrumParam::removeKey. Index out of range");
m_imp->eraseKey(index);
}
//---------------------------------------------------------
bool TSpectrumParam::isKeyframe(double frame) const {
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam currentKey = m_imp->getKey(i);
if (currentKey.first->isKeyframe(frame)) return true;
if (currentKey.second->isKeyframe(frame)) return true;
}
return false;
}
//---------------------------------------------------------
void TSpectrumParam::deleteKeyframe(double frame) {
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam currentKey = m_imp->getKey(i);
currentKey.first->deleteKeyframe(frame);
currentKey.second->deleteKeyframe(frame);
}
}
//---------------------------------------------------------
void TSpectrumParam::clearKeyframes() {
assert(m_imp);
int k, keyCount = m_imp->getKeyCount();
for (k = 0; k < keyCount; ++k) {
const ColorKeyParam &key = m_imp->getKey(k);
key.first->clearKeyframes();
key.second->clearKeyframes();
}
m_imp->notify(TParamChange(this, TParamChange::m_minFrame,
TParamChange::m_maxFrame, true,
m_imp->m_draggingEnabled, false));
}
//---------------------------------------------------------
void TSpectrumParam::assignKeyframe(double frame, const TParamP &src,
double srcFrame, bool changedOnly) {
TSpectrumParamP spectrum = src;
if (!spectrum) return;
int keyCount = m_imp->getKeyCount();
if (keyCount != spectrum->m_imp->getKeyCount()) return;
for (int i = 0; i < keyCount; i++) {
ColorKeyParam dstKey = m_imp->getKey(i);
ColorKeyParam srcKey = spectrum->m_imp->getKey(i);
dstKey.first->setValue(frame, srcKey.first->getValue(srcFrame));
dstKey.second->setValue(frame, srcKey.second->getValue(srcFrame));
}
}
//---------------------------------------------------------
void TSpectrumParam::loadData(TIStream &is) {
assert(m_imp);
m_imp->clearKeys();
std::string tagName;
is.openChild(tagName);
assert(tagName == "spectrum");
while (!is.eos()) {
TDoubleParamP pos(0.0);
TPixelParamP color(TPixel32::Black);
is.openChild(tagName);
pos->loadData(is);
is.closeChild();
is.openChild(tagName);
color->loadData(is);
is.closeChild();
ColorKeyParam ck(pos, color);
m_imp->addKey(ck);
}
is.closeChild();
}
//---------------------------------------------------------
void TSpectrumParam::saveData(TOStream &os) {
assert(m_imp);
int keyCount = m_imp->getKeyCount();
os.openChild("spectrum");
for (int i = 0; i < keyCount; i++) {
ColorKeyParam key = m_imp->getKey(i);
os.openChild("s_value");
key.first->saveData(os);
os.closeChild();
os.openChild("col_value");
key.second->saveData(os);
os.closeChild();
}
os.closeChild();
}
//---------------------------------------------------------
void TSpectrumParam::enableDragging(bool on) { m_imp->m_draggingEnabled = on; }
//---------------------------------------------------------
void TSpectrumParam::enableNotification(bool on) {
m_imp->m_notificationEnabled = on;
}
//---------------------------------------------------------
bool TSpectrumParam::isNotificationEnabled() const {
return m_imp->m_notificationEnabled;
}
//---------------------------------------------------------
namespace {
inline std::string to_string(const TPixel32 &color) {
std::string alias = "(";
alias += std::to_string(color.r) + ",";
alias += std::to_string(color.g) + ",";
alias += std::to_string(color.b) + ",";
alias += std::to_string(color.m);
alias += ")";
return alias;
}
inline std::string toString(const TSpectrum::ColorKey &key, int precision) {
std::string alias = "(";
alias += ::to_string(key.first, precision) + ",";
alias += to_string(key.second);
alias += ")";
return alias;
}
} // namespace
std::string TSpectrumParam::getValueAlias(double frame, int precision) {
std::vector<TSpectrum::ColorKey> keys;
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam paramKey = m_imp->getKey(i);
TSpectrum::ColorKey key(paramKey.first->getValue(frame),
paramKey.second->getValue(frame));
keys.push_back(key);
}
std::string alias = "(";
if (!keys.empty()) {
std::vector<TSpectrum::ColorKey>::iterator it = keys.begin();
std::vector<TSpectrum::ColorKey>::iterator end = keys.begin();
std::advance(end, keys.size() - 1);
for (; it != end; ++it) {
alias += toString(*it, precision);
alias += ",";
}
alias += toString(*it, precision);
}
alias += ")";
return alias;
}
//=========================================================
//---------------------------------------------------------
void TSpectrumParam::enableMatte(bool on) { m_imp->m_isMatteEnabled = on; }
//---------------------------------------------------------
bool TSpectrumParam::isMatteEnabled() const { return m_imp->m_isMatteEnabled; }
//---------------------------------------------------------
bool TSpectrumParam::hasKeyframes() const {
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam currentKey = m_imp->getKey(i);
if (currentKey.first->hasKeyframes() || currentKey.second->hasKeyframes())
return true;
}
return false;
}
//---------------------------------------------------------
void TSpectrumParam::getKeyframes(std::set<double> &frames) const {
int keyCount = m_imp->getKeyCount();
for (int i = 0; i < keyCount; i++) {
ColorKeyParam currentKey = m_imp->getKey(i);
currentKey.first->getKeyframes(frames);
currentKey.second->getKeyframes(frames);
}
}
//---------------------------------------------------------
int TSpectrumParam::getNextKeyframe(double frame) const {
std::set<double> frames;
getKeyframes(frames);
std::set<double>::iterator it = frames.upper_bound(frame);
if (it == frames.end())
return -1;
else
return std::distance(frames.begin(), it);
}
//---------------------------------------------------------
int TSpectrumParam::getPrevKeyframe(double frame) const {
std::set<double> frames;
getKeyframes(frames);
std::set<double>::iterator it = frames.lower_bound(frame);
if (it == frames.begin())
return -1;
else {
--it;
return std::distance(frames.begin(), it);
}
}
//---------------------------------------------------------
double TSpectrumParam::keyframeIndexToFrame(int index) const {
std::set<double> frames;
getKeyframes(frames);
assert(0 <= index && index < (int)frames.size());
std::set<double>::const_iterator it = frames.begin();
std::advance(it, index);
return *it;
}
TIStream &operator>>(TIStream &in, TSpectrumParamP &p) {
TPersist *tmp;
in >> tmp;
p = TSpectrumParamP(dynamic_cast<TSpectrumParam *>(tmp));
return in;
}
| {
"pile_set_name": "Github"
} |
exclude :test_install_into, "needs investigation"
exclude :test_install_into_development_shallow, "needs investigation"
| {
"pile_set_name": "Github"
} |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tangxiaolv.sdk">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true">
<activity android:name=".SDKActivity"/>
</application>
</manifest>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/python
##-------------------------------------------------------------------
## @copyright 2017 DennyZhang.com
## Licensed under MIT
## https://www.dennyzhang.com/wp-content/mit_license.txt
##
## File : enforce_rubocopcheck.py
## Author : Denny <[email protected]>
## Description :
##
## More reading: TODO
##
## --
## Created : <2017-04-02>
## Updated: Time-stamp: <2017-09-07 21:36:06>
##-------------------------------------------------------------------
import argparse
import sys
import os
import subprocess
import re
def ignore_folder(code_dir, check_ignore_folder):
ignore_folder_list = []
if check_ignore_folder != "":
with open(check_ignore_folder) as f:
ignore_folder_list = f.readlines()
folder_list = []
for f in os.listdir(code_dir):
if os.path.isfile(f) is False:
folder_list.append("%s/%s" % (code_dir, f))
l = []
for folder in folder_list:
skip = False
for ignore_folder_pattern in ignore_folder_list:
ignore_folder_pattern = ignore_folder_pattern.strip().strip("\n")
if ignore_folder_pattern == "":
continue
if re.search(ignore_folder_pattern, folder) is not None :
skip = True
break
if skip is False:
l.append(folder)
return l
def run_check(code_folder, check_pattern):
has_error = False
os.chdir(code_folder)
print("Run check command: %s, under %s" % (check_pattern, code_folder))
returncode = subprocess.call(check_pattern, shell=True)
if returncode != 0:
has_error = True
print("Error to run '%s'. Return code: %d" % (check_pattern, returncode))
return has_error
################################################################################
#
# wget -O /tmp/enforce_rubocopcheck.py https://raw.githubusercontent.com/DennyZhang/devops_public/tag_v6/python/enforce_rubocopcheck/enforce_rubocopcheck.py
# python /tmp/enforce_rubocopcheck.py --code_dir devops_code/devops_public
################################################################################
if __name__ == '__main__':
# get parameters from users
parser = argparse.ArgumentParser()
parser.add_argument('--code_dir', required=False, default=".", \
help="Source code directory to be scanned", type=str)
parser.add_argument('--check_ignore_folder', required=False, default="", \
help="file pattern listed in the file will be skipped for scan", type=str)
l = parser.parse_args()
code_dir = os.path.expanduser(l.code_dir)
check_ignore_folder = l.check_ignore_folder
if len(os.listdir(code_dir)) == 0:
print("ERROR: code directory(%s) is empty." % (code_dir))
sys.exit(1)
if check_ignore_folder != "":
check_ignore_folder = os.path.expanduser(l.check_ignore_folder)
print("Run rubocop for *.rb under %s" % (code_dir))
folder_list = ignore_folder(code_dir, check_ignore_folder)
has_error = False
for folder in folder_list:
if run_check(folder, "rubocop .") is True:
has_error = True
if has_error is False:
print("OK: no error detected from rubocop check")
sys.exit(0)
else:
print("ERROR: %s has failed." % (os.path.basename(__file__)))
sys.exit(1)
## File : enforce_rubocopcheck.py ends
| {
"pile_set_name": "Github"
} |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.concurrency
import com.intellij.util.ThreeState
import org.jetbrains.annotations.ApiStatus
internal val OBSOLETE_ERROR: RuntimeException = MessageError("Obsolete", false)
internal fun isHandlerObsolete(handler: Any): Boolean {
return handler is Obsolescent && handler.isObsolete
}
internal interface CompletablePromise<T> : Promise<T> {
fun setResult(t: T?)
fun setError(error: Throwable): Boolean
}
@ApiStatus.Internal
internal class MessageError(message: String, isLog: Boolean) : RuntimeException(message) {
val log: ThreeState = ThreeState.fromBoolean(isLog)
@Synchronized
override fun fillInStackTrace() = this
}
@ApiStatus.Internal
fun isMessageError(exception: Exception): Boolean {
return exception is MessageError
}
internal class PromiseValue<T> private constructor(val result: T?, val error: Throwable?) {
companion object {
@JvmStatic
fun <T : Any?> createFulfilled(result: T?): PromiseValue<T> {
return PromiseValue(result, null)
}
fun <T : Any?> createRejected(error: Throwable?): PromiseValue<T> {
return PromiseValue(null, error)
}
}
val state: Promise.State
get() = if (error == null) Promise.State.SUCCEEDED else Promise.State.REJECTED
val isCancelled: Boolean
get() = error === OBSOLETE_ERROR
fun getResultOrThrowError(): T? {
return when {
error == null -> result
error === OBSOLETE_ERROR -> null
else -> throw error.cause ?: error
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val value = other as PromiseValue<*>
return result == value.result && error == value.error
}
override fun hashCode(): Int {
return 31 * (result?.hashCode() ?: 0) + (error?.hashCode() ?: 0)
}
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace PrestaShopBundle\Form\Admin\Improve\Payment\Preferences;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
use PrestaShop\PrestaShop\Core\Form\FormDataProviderInterface;
/**
* Class PaymentPreferencesFormDataProvider is responsible for handling "Improve > Payment > Preferences" form data.
*/
final class PaymentPreferencesFormDataProvider implements FormDataProviderInterface
{
/**
* @var DataConfigurationInterface
*/
private $paymentModulePreferencesConfiguration;
/**
* @param DataConfigurationInterface $paymentModulePreferencesConfiguration
*/
public function __construct(
DataConfigurationInterface $paymentModulePreferencesConfiguration
) {
$this->paymentModulePreferencesConfiguration = $paymentModulePreferencesConfiguration;
}
/**
* {@inheritdoc}
*/
public function getData()
{
return $this->paymentModulePreferencesConfiguration->getConfiguration();
}
/**
* {@inheritdoc}
*/
public function setData(array $data)
{
return $this->paymentModulePreferencesConfiguration->updateConfiguration($data);
}
}
| {
"pile_set_name": "Github"
} |
{
"_args": [
[
{
"raw": "[email protected]",
"scope": null,
"escapedName": "vm-browserify",
"name": "vm-browserify",
"rawSpec": "0.0.4",
"spec": "0.0.4",
"type": "version"
},
"D:\\Users\\aakash.h\\Desktop\\Ang5\\mat\\node_modules\\node-libs-browser"
]
],
"_from": "[email protected]",
"_id": "[email protected]",
"_inCache": true,
"_location": "/vm-browserify",
"_npmUser": {
"name": "substack",
"email": "[email protected]"
},
"_npmVersion": "1.3.21",
"_phantomChildren": {},
"_requested": {
"raw": "[email protected]",
"scope": null,
"escapedName": "vm-browserify",
"name": "vm-browserify",
"rawSpec": "0.0.4",
"spec": "0.0.4",
"type": "version"
},
"_requiredBy": [
"/node-libs-browser"
],
"_resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz",
"_shasum": "5d7ea45bbef9e4a6ff65f95438e0a87c357d5a73",
"_shrinkwrap": null,
"_spec": "[email protected]",
"_where": "D:\\Users\\aakash.h\\Desktop\\Ang5\\mat\\node_modules\\node-libs-browser",
"author": {
"name": "James Halliday",
"email": "[email protected]",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/vm-browserify/issues"
},
"dependencies": {
"indexof": "0.0.1"
},
"description": "vm module for the browser",
"devDependencies": {
"tape": "~2.3.2"
},
"directories": {},
"dist": {
"shasum": "5d7ea45bbef9e4a6ff65f95438e0a87c357d5a73",
"tarball": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz"
},
"homepage": "https://github.com/substack/vm-browserify",
"keywords": [
"vm",
"browser",
"eval"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "substack",
"email": "[email protected]"
}
],
"name": "vm-browserify",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/substack/vm-browserify.git"
},
"scripts": {
"test": "tap test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/6..latest",
"firefox/16..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"version": "0.0.4"
}
| {
"pile_set_name": "Github"
} |
#ifndef MODEM_OUTPUT_STREAM_H
#define MODEM_OUTPUT_STREAM_H
#include <Arduino.h>
#include <Stream.h>
namespace firebase {
namespace modem {
class OutputStream {
public:
virtual int println(const String& string) = 0;
virtual int println(const int value) = 0;
virtual int print(const String& string) = 0;
};
class ArduinoOutputStream : public OutputStream {
public:
ArduinoOutputStream(Stream* stream) : stream_(stream) {}
int println(const String& string) override {
return stream_->println(string.c_str());
}
int println(const int value) override {
return stream_->println(value);
}
int print(const String& string) override {
return stream_->print(string.c_str());
}
private:
Stream* stream_;
};
} // modem
} // firebase
#endif // MODEM_OUTPUT_STREAM
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for AppState (v1).
*
* <p>
* The Google App State API.
* </p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/games/services/web/api/states" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_AppState extends Google_Service
{
/** View and manage your data for this application. */
const APPSTATE = "https://www.googleapis.com/auth/appstate";
public $states;
/**
* Constructs the internal representation of the AppState service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->servicePath = 'appstate/v1/';
$this->version = 'v1';
$this->serviceName = 'appstate';
$this->states = new Google_Service_AppState_States_Resource(
$this,
$this->serviceName,
'states',
array(
'methods' => array(
'clear' => array(
'path' => 'states/{stateKey}/clear',
'httpMethod' => 'POST',
'parameters' => array(
'stateKey' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
'currentDataVersion' => array(
'location' => 'query',
'type' => 'string',
),
),
),'delete' => array(
'path' => 'states/{stateKey}',
'httpMethod' => 'DELETE',
'parameters' => array(
'stateKey' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
),
),'get' => array(
'path' => 'states/{stateKey}',
'httpMethod' => 'GET',
'parameters' => array(
'stateKey' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
),
),'list' => array(
'path' => 'states',
'httpMethod' => 'GET',
'parameters' => array(
'includeData' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'states/{stateKey}',
'httpMethod' => 'PUT',
'parameters' => array(
'stateKey' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
'currentStateVersion' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
/**
* The "states" collection of methods.
* Typical usage is:
* <code>
* $appstateService = new Google_Service_AppState(...);
* $states = $appstateService->states;
* </code>
*/
class Google_Service_AppState_States_Resource extends Google_Service_Resource
{
/**
* Clears (sets to empty) the data for the passed key if and only if the passed
* version matches the currently stored version. This method results in a
* conflict error on version mismatch. (states.clear)
*
* @param int $stateKey
* The key for the data to be retrieved.
* @param array $optParams Optional parameters.
*
* @opt_param string currentDataVersion
* The version of the data to be cleared. Version strings are returned by the server.
* @return Google_Service_AppState_WriteResult
*/
public function clear($stateKey, $optParams = array())
{
$params = array('stateKey' => $stateKey);
$params = array_merge($params, $optParams);
return $this->call('clear', array($params), "Google_Service_AppState_WriteResult");
}
/**
* Deletes a key and the data associated with it. The key is removed and no
* longer counts against the key quota. Note that since this method is not safe
* in the face of concurrent modifications, it should only be used for
* development and testing purposes. Invoking this method in shipping code can
* result in data loss and data corruption. (states.delete)
*
* @param int $stateKey
* The key for the data to be retrieved.
* @param array $optParams Optional parameters.
*/
public function delete($stateKey, $optParams = array())
{
$params = array('stateKey' => $stateKey);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Retrieves the data corresponding to the passed key. If the key does not exist
* on the server, an HTTP 404 will be returned. (states.get)
*
* @param int $stateKey
* The key for the data to be retrieved.
* @param array $optParams Optional parameters.
* @return Google_Service_AppState_GetResponse
*/
public function get($stateKey, $optParams = array())
{
$params = array('stateKey' => $stateKey);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_AppState_GetResponse");
}
/**
* Lists all the states keys, and optionally the state data. (states.listStates)
*
* @param array $optParams Optional parameters.
*
* @opt_param bool includeData
* Whether to include the full data in addition to the version number
* @return Google_Service_AppState_ListResponse
*/
public function listStates($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AppState_ListResponse");
}
/**
* Update the data associated with the input key if and only if the passed
* version matches the currently stored version. This method is safe in the face
* of concurrent writes. Maximum per-key size is 128KB. (states.update)
*
* @param int $stateKey
* The key for the data to be retrieved.
* @param Google_UpdateRequest $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string currentStateVersion
* The version of the app state your application is attempting to update. If this does not match
* the current version, this method will return a conflict error. If there is no data stored on the
* server for this key, the update will succeed irrespective of the value of this parameter.
* @return Google_Service_AppState_WriteResult
*/
public function update($stateKey, Google_Service_AppState_UpdateRequest $postBody, $optParams = array())
{
$params = array('stateKey' => $stateKey, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_AppState_WriteResult");
}
}
class Google_Service_AppState_GetResponse extends Google_Model
{
public $currentStateVersion;
public $data;
public $kind;
public $stateKey;
public function setCurrentStateVersion($currentStateVersion)
{
$this->currentStateVersion = $currentStateVersion;
}
public function getCurrentStateVersion()
{
return $this->currentStateVersion;
}
public function setData($data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setStateKey($stateKey)
{
$this->stateKey = $stateKey;
}
public function getStateKey()
{
return $this->stateKey;
}
}
class Google_Service_AppState_ListResponse extends Google_Collection
{
protected $collection_key = 'items';
protected $itemsType = 'Google_Service_AppState_GetResponse';
protected $itemsDataType = 'array';
public $kind;
public $maximumKeyCount;
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setMaximumKeyCount($maximumKeyCount)
{
$this->maximumKeyCount = $maximumKeyCount;
}
public function getMaximumKeyCount()
{
return $this->maximumKeyCount;
}
}
class Google_Service_AppState_UpdateRequest extends Google_Model
{
public $data;
public $kind;
public function setData($data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_AppState_WriteResult extends Google_Model
{
public $currentStateVersion;
public $kind;
public $stateKey;
public function setCurrentStateVersion($currentStateVersion)
{
$this->currentStateVersion = $currentStateVersion;
}
public function getCurrentStateVersion()
{
return $this->currentStateVersion;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setStateKey($stateKey)
{
$this->stateKey = $stateKey;
}
public function getStateKey()
{
return $this->stateKey;
}
}
| {
"pile_set_name": "Github"
} |
{
'org.eclipse.jetty:jetty-project':[
0,
0,
0,
0,
0,
0,
0,
0,
],
}
| {
"pile_set_name": "Github"
} |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Navigation
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class FrameNavigationOptions
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.UI.Xaml.Media.Animation.NavigationTransitionInfo TransitionInfoOverride
{
get
{
throw new global::System.NotImplementedException("The member NavigationTransitionInfo FrameNavigationOptions.TransitionInfoOverride is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Navigation.FrameNavigationOptions", "NavigationTransitionInfo FrameNavigationOptions.TransitionInfoOverride");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public bool IsNavigationStackEnabled
{
get
{
throw new global::System.NotImplementedException("The member bool FrameNavigationOptions.IsNavigationStackEnabled is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Navigation.FrameNavigationOptions", "bool FrameNavigationOptions.IsNavigationStackEnabled");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public FrameNavigationOptions()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Navigation.FrameNavigationOptions", "FrameNavigationOptions.FrameNavigationOptions()");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Navigation.FrameNavigationOptions.FrameNavigationOptions()
// Forced skipping of method Windows.UI.Xaml.Navigation.FrameNavigationOptions.IsNavigationStackEnabled.get
// Forced skipping of method Windows.UI.Xaml.Navigation.FrameNavigationOptions.IsNavigationStackEnabled.set
// Forced skipping of method Windows.UI.Xaml.Navigation.FrameNavigationOptions.TransitionInfoOverride.get
// Forced skipping of method Windows.UI.Xaml.Navigation.FrameNavigationOptions.TransitionInfoOverride.set
}
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
/* Copyright (c) 2018, Intel Corporation. */
#ifndef _ICE_H_
#define _ICE_H_
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/firmware.h>
#include <linux/netdevice.h>
#include <linux/compiler.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/cpumask.h>
#include <linux/rtnetlink.h>
#include <linux/if_vlan.h>
#include <linux/dma-mapping.h>
#include <linux/pci.h>
#include <linux/workqueue.h>
#include <linux/wait.h>
#include <linux/aer.h>
#include <linux/interrupt.h>
#include <linux/ethtool.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/bitmap.h>
#include <linux/log2.h>
#include <linux/ip.h>
#include <linux/sctp.h>
#include <linux/ipv6.h>
#include <linux/pkt_sched.h>
#include <linux/if_bridge.h>
#include <linux/ctype.h>
#include <linux/bpf.h>
#include <linux/avf/virtchnl.h>
#include <linux/cpu_rmap.h>
#include <net/devlink.h>
#include <net/ipv6.h>
#include <net/xdp_sock.h>
#include <net/geneve.h>
#include <net/gre.h>
#include <net/udp_tunnel.h>
#include <net/vxlan.h>
#include "ice_devids.h"
#include "ice_type.h"
#include "ice_txrx.h"
#include "ice_dcb.h"
#include "ice_switch.h"
#include "ice_common.h"
#include "ice_sched.h"
#include "ice_virtchnl_pf.h"
#include "ice_sriov.h"
#include "ice_fdir.h"
#include "ice_xsk.h"
#include "ice_arfs.h"
#define ICE_BAR0 0
#define ICE_REQ_DESC_MULTIPLE 32
#define ICE_MIN_NUM_DESC 64
#define ICE_MAX_NUM_DESC 8160
#define ICE_DFLT_MIN_RX_DESC 512
#define ICE_DFLT_NUM_TX_DESC 256
#define ICE_DFLT_NUM_RX_DESC 2048
#define ICE_DFLT_TRAFFIC_CLASS BIT(0)
#define ICE_INT_NAME_STR_LEN (IFNAMSIZ + 16)
#define ICE_AQ_LEN 64
#define ICE_MBXSQ_LEN 64
#define ICE_MIN_MSIX 2
#define ICE_FDIR_MSIX 1
#define ICE_NO_VSI 0xffff
#define ICE_VSI_MAP_CONTIG 0
#define ICE_VSI_MAP_SCATTER 1
#define ICE_MAX_SCATTER_TXQS 16
#define ICE_MAX_SCATTER_RXQS 16
#define ICE_Q_WAIT_RETRY_LIMIT 10
#define ICE_Q_WAIT_MAX_RETRY (5 * ICE_Q_WAIT_RETRY_LIMIT)
#define ICE_MAX_LG_RSS_QS 256
#define ICE_RES_VALID_BIT 0x8000
#define ICE_RES_MISC_VEC_ID (ICE_RES_VALID_BIT - 1)
#define ICE_INVAL_Q_INDEX 0xffff
#define ICE_INVAL_VFID 256
#define ICE_MAX_RESET_WAIT 20
#define ICE_VSIQF_HKEY_ARRAY_SIZE ((VSIQF_HKEY_MAX_INDEX + 1) * 4)
#define ICE_DFLT_NETIF_M (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK)
#define ICE_MAX_MTU (ICE_AQ_SET_MAC_FRAME_SIZE_MAX - ICE_ETH_PKT_HDR_PAD)
#define ICE_UP_TABLE_TRANSLATE(val, i) \
(((val) << ICE_AQ_VSI_UP_TABLE_UP##i##_S) & \
ICE_AQ_VSI_UP_TABLE_UP##i##_M)
#define ICE_TX_DESC(R, i) (&(((struct ice_tx_desc *)((R)->desc))[i]))
#define ICE_RX_DESC(R, i) (&(((union ice_32b_rx_flex_desc *)((R)->desc))[i]))
#define ICE_TX_CTX_DESC(R, i) (&(((struct ice_tx_ctx_desc *)((R)->desc))[i]))
#define ICE_TX_FDIRDESC(R, i) (&(((struct ice_fltr_desc *)((R)->desc))[i]))
/* Macro for each VSI in a PF */
#define ice_for_each_vsi(pf, i) \
for ((i) = 0; (i) < (pf)->num_alloc_vsi; (i)++)
/* Macros for each Tx/Rx ring in a VSI */
#define ice_for_each_txq(vsi, i) \
for ((i) = 0; (i) < (vsi)->num_txq; (i)++)
#define ice_for_each_rxq(vsi, i) \
for ((i) = 0; (i) < (vsi)->num_rxq; (i)++)
/* Macros for each allocated Tx/Rx ring whether used or not in a VSI */
#define ice_for_each_alloc_txq(vsi, i) \
for ((i) = 0; (i) < (vsi)->alloc_txq; (i)++)
#define ice_for_each_alloc_rxq(vsi, i) \
for ((i) = 0; (i) < (vsi)->alloc_rxq; (i)++)
#define ice_for_each_q_vector(vsi, i) \
for ((i) = 0; (i) < (vsi)->num_q_vectors; (i)++)
#define ICE_UCAST_PROMISC_BITS (ICE_PROMISC_UCAST_TX | ICE_PROMISC_MCAST_TX | \
ICE_PROMISC_UCAST_RX | ICE_PROMISC_MCAST_RX)
#define ICE_UCAST_VLAN_PROMISC_BITS (ICE_PROMISC_UCAST_TX | \
ICE_PROMISC_MCAST_TX | \
ICE_PROMISC_UCAST_RX | \
ICE_PROMISC_MCAST_RX | \
ICE_PROMISC_VLAN_TX | \
ICE_PROMISC_VLAN_RX)
#define ICE_MCAST_PROMISC_BITS (ICE_PROMISC_MCAST_TX | ICE_PROMISC_MCAST_RX)
#define ICE_MCAST_VLAN_PROMISC_BITS (ICE_PROMISC_MCAST_TX | \
ICE_PROMISC_MCAST_RX | \
ICE_PROMISC_VLAN_TX | \
ICE_PROMISC_VLAN_RX)
#define ice_pf_to_dev(pf) (&((pf)->pdev->dev))
struct ice_txq_meta {
u32 q_teid; /* Tx-scheduler element identifier */
u16 q_id; /* Entry in VSI's txq_map bitmap */
u16 q_handle; /* Relative index of Tx queue within TC */
u16 vsi_idx; /* VSI index that Tx queue belongs to */
u8 tc; /* TC number that Tx queue belongs to */
};
struct ice_tc_info {
u16 qoffset;
u16 qcount_tx;
u16 qcount_rx;
u8 netdev_tc;
};
struct ice_tc_cfg {
u8 numtc; /* Total number of enabled TCs */
u8 ena_tc; /* Tx map */
struct ice_tc_info tc_info[ICE_MAX_TRAFFIC_CLASS];
};
struct ice_res_tracker {
u16 num_entries;
u16 end;
u16 list[1];
};
struct ice_qs_cfg {
struct mutex *qs_mutex; /* will be assigned to &pf->avail_q_mutex */
unsigned long *pf_map;
unsigned long pf_map_size;
unsigned int q_count;
unsigned int scatter_count;
u16 *vsi_map;
u16 vsi_map_offset;
u8 mapping_mode;
};
struct ice_sw {
struct ice_pf *pf;
u16 sw_id; /* switch ID for this switch */
u16 bridge_mode; /* VEB/VEPA/Port Virtualizer */
struct ice_vsi *dflt_vsi; /* default VSI for this switch */
u8 dflt_vsi_ena:1; /* true if above dflt_vsi is enabled */
};
enum ice_state {
__ICE_TESTING,
__ICE_DOWN,
__ICE_NEEDS_RESTART,
__ICE_PREPARED_FOR_RESET, /* set by driver when prepared */
__ICE_RESET_OICR_RECV, /* set by driver after rcv reset OICR */
__ICE_DCBNL_DEVRESET, /* set by dcbnl devreset */
__ICE_PFR_REQ, /* set by driver and peers */
__ICE_CORER_REQ, /* set by driver and peers */
__ICE_GLOBR_REQ, /* set by driver and peers */
__ICE_CORER_RECV, /* set by OICR handler */
__ICE_GLOBR_RECV, /* set by OICR handler */
__ICE_EMPR_RECV, /* set by OICR handler */
__ICE_SUSPENDED, /* set on module remove path */
__ICE_RESET_FAILED, /* set by reset/rebuild */
/* When checking for the PF to be in a nominal operating state, the
* bits that are grouped at the beginning of the list need to be
* checked. Bits occurring before __ICE_STATE_NOMINAL_CHECK_BITS will
* be checked. If you need to add a bit into consideration for nominal
* operating state, it must be added before
* __ICE_STATE_NOMINAL_CHECK_BITS. Do not move this entry's position
* without appropriate consideration.
*/
__ICE_STATE_NOMINAL_CHECK_BITS,
__ICE_ADMINQ_EVENT_PENDING,
__ICE_MAILBOXQ_EVENT_PENDING,
__ICE_MDD_EVENT_PENDING,
__ICE_VFLR_EVENT_PENDING,
__ICE_FLTR_OVERFLOW_PROMISC,
__ICE_VF_DIS,
__ICE_CFG_BUSY,
__ICE_SERVICE_SCHED,
__ICE_SERVICE_DIS,
__ICE_FD_FLUSH_REQ,
__ICE_OICR_INTR_DIS, /* Global OICR interrupt disabled */
__ICE_MDD_VF_PRINT_PENDING, /* set when MDD event handle */
__ICE_VF_RESETS_DISABLED, /* disable resets during ice_remove */
__ICE_LINK_DEFAULT_OVERRIDE_PENDING,
__ICE_PHY_INIT_COMPLETE,
__ICE_STATE_NBITS /* must be last */
};
enum ice_vsi_flags {
ICE_VSI_FLAG_UMAC_FLTR_CHANGED,
ICE_VSI_FLAG_MMAC_FLTR_CHANGED,
ICE_VSI_FLAG_VLAN_FLTR_CHANGED,
ICE_VSI_FLAG_PROMISC_CHANGED,
ICE_VSI_FLAG_NBITS /* must be last */
};
/* struct that defines a VSI, associated with a dev */
struct ice_vsi {
struct net_device *netdev;
struct ice_sw *vsw; /* switch this VSI is on */
struct ice_pf *back; /* back pointer to PF */
struct ice_port_info *port_info; /* back pointer to port_info */
struct ice_ring **rx_rings; /* Rx ring array */
struct ice_ring **tx_rings; /* Tx ring array */
struct ice_q_vector **q_vectors; /* q_vector array */
irqreturn_t (*irq_handler)(int irq, void *data);
u64 tx_linearize;
DECLARE_BITMAP(state, __ICE_STATE_NBITS);
DECLARE_BITMAP(flags, ICE_VSI_FLAG_NBITS);
unsigned int current_netdev_flags;
u32 tx_restart;
u32 tx_busy;
u32 rx_buf_failed;
u32 rx_page_failed;
u32 rx_gro_dropped;
u16 num_q_vectors;
u16 base_vector; /* IRQ base for OS reserved vectors */
enum ice_vsi_type type;
u16 vsi_num; /* HW (absolute) index of this VSI */
u16 idx; /* software index in pf->vsi[] */
s16 vf_id; /* VF ID for SR-IOV VSIs */
u16 ethtype; /* Ethernet protocol for pause frame */
u16 num_gfltr;
u16 num_bfltr;
/* RSS config */
u16 rss_table_size; /* HW RSS table size */
u16 rss_size; /* Allocated RSS queues */
u8 *rss_hkey_user; /* User configured hash keys */
u8 *rss_lut_user; /* User configured lookup table entries */
u8 rss_lut_type; /* used to configure Get/Set RSS LUT AQ call */
/* aRFS members only allocated for the PF VSI */
#define ICE_MAX_ARFS_LIST 1024
#define ICE_ARFS_LST_MASK (ICE_MAX_ARFS_LIST - 1)
struct hlist_head *arfs_fltr_list;
struct ice_arfs_active_fltr_cntrs *arfs_fltr_cntrs;
spinlock_t arfs_lock; /* protects aRFS hash table and filter state */
atomic_t *arfs_last_fltr_id;
u16 max_frame;
u16 rx_buf_len;
struct ice_aqc_vsi_props info; /* VSI properties */
/* VSI stats */
struct rtnl_link_stats64 net_stats;
struct ice_eth_stats eth_stats;
struct ice_eth_stats eth_stats_prev;
struct list_head tmp_sync_list; /* MAC filters to be synced */
struct list_head tmp_unsync_list; /* MAC filters to be unsynced */
u8 irqs_ready:1;
u8 current_isup:1; /* Sync 'link up' logging */
u8 stat_offsets_loaded:1;
u8 vlan_ena:1;
u16 num_vlan;
/* queue information */
u8 tx_mapping_mode; /* ICE_MAP_MODE_[CONTIG|SCATTER] */
u8 rx_mapping_mode; /* ICE_MAP_MODE_[CONTIG|SCATTER] */
u16 *txq_map; /* index in pf->avail_txqs */
u16 *rxq_map; /* index in pf->avail_rxqs */
u16 alloc_txq; /* Allocated Tx queues */
u16 num_txq; /* Used Tx queues */
u16 alloc_rxq; /* Allocated Rx queues */
u16 num_rxq; /* Used Rx queues */
u16 req_txq; /* User requested Tx queues */
u16 req_rxq; /* User requested Rx queues */
u16 num_rx_desc;
u16 num_tx_desc;
struct ice_tc_cfg tc_cfg;
struct bpf_prog *xdp_prog;
struct ice_ring **xdp_rings; /* XDP ring array */
u16 num_xdp_txq; /* Used XDP queues */
u8 xdp_mapping_mode; /* ICE_MAP_MODE_[CONTIG|SCATTER] */
struct xdp_umem **xsk_umems;
u16 num_xsk_umems_used;
u16 num_xsk_umems;
} ____cacheline_internodealigned_in_smp;
/* struct that defines an interrupt vector */
struct ice_q_vector {
struct ice_vsi *vsi;
u16 v_idx; /* index in the vsi->q_vector array. */
u16 reg_idx;
u8 num_ring_rx; /* total number of Rx rings in vector */
u8 num_ring_tx; /* total number of Tx rings in vector */
u8 itr_countdown; /* when 0 should adjust adaptive ITR */
/* in usecs, need to use ice_intrl_to_usecs_reg() before writing this
* value to the device
*/
u8 intrl;
struct napi_struct napi;
struct ice_ring_container rx;
struct ice_ring_container tx;
cpumask_t affinity_mask;
struct irq_affinity_notify affinity_notify;
char name[ICE_INT_NAME_STR_LEN];
} ____cacheline_internodealigned_in_smp;
enum ice_pf_flags {
ICE_FLAG_FLTR_SYNC,
ICE_FLAG_RSS_ENA,
ICE_FLAG_SRIOV_ENA,
ICE_FLAG_SRIOV_CAPABLE,
ICE_FLAG_DCB_CAPABLE,
ICE_FLAG_DCB_ENA,
ICE_FLAG_FD_ENA,
ICE_FLAG_ADV_FEATURES,
ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA,
ICE_FLAG_TOTAL_PORT_SHUTDOWN_ENA,
ICE_FLAG_NO_MEDIA,
ICE_FLAG_FW_LLDP_AGENT,
ICE_FLAG_ETHTOOL_CTXT, /* set when ethtool holds RTNL lock */
ICE_FLAG_LEGACY_RX,
ICE_FLAG_VF_TRUE_PROMISC_ENA,
ICE_FLAG_MDD_AUTO_RESET_VF,
ICE_FLAG_LINK_LENIENT_MODE_ENA,
ICE_PF_FLAGS_NBITS /* must be last */
};
struct ice_pf {
struct pci_dev *pdev;
/* devlink port data */
struct devlink_port devlink_port;
struct devlink_region *nvm_region;
struct devlink_region *devcaps_region;
/* OS reserved IRQ details */
struct msix_entry *msix_entries;
struct ice_res_tracker *irq_tracker;
/* First MSIX vector used by SR-IOV VFs. Calculated by subtracting the
* number of MSIX vectors needed for all SR-IOV VFs from the number of
* MSIX vectors allowed on this PF.
*/
u16 sriov_base_vector;
u16 ctrl_vsi_idx; /* control VSI index in pf->vsi array */
struct ice_vsi **vsi; /* VSIs created by the driver */
struct ice_sw *first_sw; /* first switch created by firmware */
/* Virtchnl/SR-IOV config info */
struct ice_vf *vf;
u16 num_alloc_vfs; /* actual number of VFs allocated */
u16 num_vfs_supported; /* num VFs supported for this PF */
u16 num_qps_per_vf;
u16 num_msix_per_vf;
/* used to ratelimit the MDD event logging */
unsigned long last_printed_mdd_jiffies;
DECLARE_BITMAP(state, __ICE_STATE_NBITS);
DECLARE_BITMAP(flags, ICE_PF_FLAGS_NBITS);
unsigned long *avail_txqs; /* bitmap to track PF Tx queue usage */
unsigned long *avail_rxqs; /* bitmap to track PF Rx queue usage */
unsigned long serv_tmr_period;
unsigned long serv_tmr_prev;
struct timer_list serv_tmr;
struct work_struct serv_task;
struct mutex avail_q_mutex; /* protects access to avail_[rx|tx]qs */
struct mutex sw_mutex; /* lock for protecting VSI alloc flow */
struct mutex tc_mutex; /* lock to protect TC changes */
u32 msg_enable;
/* spinlock to protect the AdminQ wait list */
spinlock_t aq_wait_lock;
struct hlist_head aq_wait_list;
wait_queue_head_t aq_wait_queue;
u32 hw_csum_rx_error;
u16 oicr_idx; /* Other interrupt cause MSIX vector index */
u16 num_avail_sw_msix; /* remaining MSIX SW vectors left unclaimed */
u16 max_pf_txqs; /* Total Tx queues PF wide */
u16 max_pf_rxqs; /* Total Rx queues PF wide */
u16 num_lan_msix; /* Total MSIX vectors for base driver */
u16 num_lan_tx; /* num LAN Tx queues setup */
u16 num_lan_rx; /* num LAN Rx queues setup */
u16 next_vsi; /* Next free slot in pf->vsi[] - 0-based! */
u16 num_alloc_vsi;
u16 corer_count; /* Core reset count */
u16 globr_count; /* Global reset count */
u16 empr_count; /* EMP reset count */
u16 pfr_count; /* PF reset count */
u8 wol_ena : 1; /* software state of WoL */
u32 wakeup_reason; /* last wakeup reason */
struct ice_hw_port_stats stats;
struct ice_hw_port_stats stats_prev;
struct ice_hw hw;
u8 stat_prev_loaded:1; /* has previous stats been loaded */
#ifdef CONFIG_DCB
u16 dcbx_cap;
#endif /* CONFIG_DCB */
u32 tx_timeout_count;
unsigned long tx_timeout_last_recovery;
u32 tx_timeout_recovery_level;
char int_name[ICE_INT_NAME_STR_LEN];
u32 sw_int_count;
__le64 nvm_phy_type_lo; /* NVM PHY type low */
__le64 nvm_phy_type_hi; /* NVM PHY type high */
struct ice_link_default_override_tlv link_dflt_override;
};
struct ice_netdev_priv {
struct ice_vsi *vsi;
};
/**
* ice_irq_dynamic_ena - Enable default interrupt generation settings
* @hw: pointer to HW struct
* @vsi: pointer to VSI struct, can be NULL
* @q_vector: pointer to q_vector, can be NULL
*/
static inline void
ice_irq_dynamic_ena(struct ice_hw *hw, struct ice_vsi *vsi,
struct ice_q_vector *q_vector)
{
u32 vector = (vsi && q_vector) ? q_vector->reg_idx :
((struct ice_pf *)hw->back)->oicr_idx;
int itr = ICE_ITR_NONE;
u32 val;
/* clear the PBA here, as this function is meant to clean out all
* previous interrupts and enable the interrupt
*/
val = GLINT_DYN_CTL_INTENA_M | GLINT_DYN_CTL_CLEARPBA_M |
(itr << GLINT_DYN_CTL_ITR_INDX_S);
if (vsi)
if (test_bit(__ICE_DOWN, vsi->state))
return;
wr32(hw, GLINT_DYN_CTL(vector), val);
}
/**
* ice_netdev_to_pf - Retrieve the PF struct associated with a netdev
* @netdev: pointer to the netdev struct
*/
static inline struct ice_pf *ice_netdev_to_pf(struct net_device *netdev)
{
struct ice_netdev_priv *np = netdev_priv(netdev);
return np->vsi->back;
}
static inline bool ice_is_xdp_ena_vsi(struct ice_vsi *vsi)
{
return !!vsi->xdp_prog;
}
static inline void ice_set_ring_xdp(struct ice_ring *ring)
{
ring->flags |= ICE_TX_FLAGS_RING_XDP;
}
/**
* ice_xsk_umem - get XDP UMEM bound to a ring
* @ring - ring to use
*
* Returns a pointer to xdp_umem structure if there is an UMEM present,
* NULL otherwise.
*/
static inline struct xdp_umem *ice_xsk_umem(struct ice_ring *ring)
{
struct xdp_umem **umems = ring->vsi->xsk_umems;
u16 qid = ring->q_index;
if (ice_ring_is_xdp(ring))
qid -= ring->vsi->num_xdp_txq;
if (qid >= ring->vsi->num_xsk_umems || !umems || !umems[qid] ||
!ice_is_xdp_ena_vsi(ring->vsi))
return NULL;
return umems[qid];
}
/**
* ice_get_main_vsi - Get the PF VSI
* @pf: PF instance
*
* returns pf->vsi[0], which by definition is the PF VSI
*/
static inline struct ice_vsi *ice_get_main_vsi(struct ice_pf *pf)
{
if (pf->vsi)
return pf->vsi[0];
return NULL;
}
/**
* ice_get_ctrl_vsi - Get the control VSI
* @pf: PF instance
*/
static inline struct ice_vsi *ice_get_ctrl_vsi(struct ice_pf *pf)
{
/* if pf->ctrl_vsi_idx is ICE_NO_VSI, control VSI was not set up */
if (!pf->vsi || pf->ctrl_vsi_idx == ICE_NO_VSI)
return NULL;
return pf->vsi[pf->ctrl_vsi_idx];
}
#define ICE_FD_STAT_CTR_BLOCK_COUNT 256
#define ICE_FD_STAT_PF_IDX(base_idx) \
((base_idx) * ICE_FD_STAT_CTR_BLOCK_COUNT)
#define ICE_FD_SB_STAT_IDX(base_idx) ICE_FD_STAT_PF_IDX(base_idx)
int ice_vsi_setup_tx_rings(struct ice_vsi *vsi);
int ice_vsi_setup_rx_rings(struct ice_vsi *vsi);
int ice_vsi_open_ctrl(struct ice_vsi *vsi);
void ice_set_ethtool_ops(struct net_device *netdev);
void ice_set_ethtool_safe_mode_ops(struct net_device *netdev);
u16 ice_get_avail_txq_count(struct ice_pf *pf);
u16 ice_get_avail_rxq_count(struct ice_pf *pf);
int ice_vsi_recfg_qs(struct ice_vsi *vsi, int new_rx, int new_tx);
void ice_update_vsi_stats(struct ice_vsi *vsi);
void ice_update_pf_stats(struct ice_pf *pf);
int ice_up(struct ice_vsi *vsi);
int ice_down(struct ice_vsi *vsi);
int ice_vsi_cfg(struct ice_vsi *vsi);
struct ice_vsi *ice_lb_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi);
int ice_prepare_xdp_rings(struct ice_vsi *vsi, struct bpf_prog *prog);
int ice_destroy_xdp_rings(struct ice_vsi *vsi);
int
ice_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **frames,
u32 flags);
int ice_set_rss(struct ice_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size);
int ice_get_rss(struct ice_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size);
void ice_fill_rss_lut(u8 *lut, u16 rss_table_size, u16 rss_size);
int ice_schedule_reset(struct ice_pf *pf, enum ice_reset_req reset);
void ice_print_link_msg(struct ice_vsi *vsi, bool isup);
const char *ice_stat_str(enum ice_status stat_err);
const char *ice_aq_str(enum ice_aq_err aq_err);
bool ice_is_wol_supported(struct ice_pf *pf);
int
ice_fdir_write_fltr(struct ice_pf *pf, struct ice_fdir_fltr *input, bool add,
bool is_tun);
void ice_vsi_manage_fdir(struct ice_vsi *vsi, bool ena);
int ice_add_fdir_ethtool(struct ice_vsi *vsi, struct ethtool_rxnfc *cmd);
int ice_del_fdir_ethtool(struct ice_vsi *vsi, struct ethtool_rxnfc *cmd);
int ice_get_ethtool_fdir_entry(struct ice_hw *hw, struct ethtool_rxnfc *cmd);
int
ice_get_fdir_fltr_ids(struct ice_hw *hw, struct ethtool_rxnfc *cmd,
u32 *rule_locs);
void ice_fdir_release_flows(struct ice_hw *hw);
void ice_fdir_replay_flows(struct ice_hw *hw);
void ice_fdir_replay_fltrs(struct ice_pf *pf);
int ice_fdir_create_dflt_rules(struct ice_pf *pf);
int ice_aq_wait_for_event(struct ice_pf *pf, u16 opcode, unsigned long timeout,
struct ice_rq_event_info *event);
int ice_open(struct net_device *netdev);
int ice_stop(struct net_device *netdev);
void ice_service_task_schedule(struct ice_pf *pf);
#endif /* _ICE_H_ */
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29920.165
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloSlide", "HelloSlide.vcxproj", "{9AFA8D77-D1F0-49E4-BDB5-5D06ED2F10FB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UIcode", "..\UIcode\UIcode.vcxproj", "{8BE32B2A-F5E4-49E7-A2C9-0FAEA62B7FED}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9AFA8D77-D1F0-49E4-BDB5-5D06ED2F10FB}.Debug|x86.ActiveCfg = Debug|Win32
{9AFA8D77-D1F0-49E4-BDB5-5D06ED2F10FB}.Debug|x86.Build.0 = Debug|Win32
{9AFA8D77-D1F0-49E4-BDB5-5D06ED2F10FB}.Release|x86.ActiveCfg = Release|Win32
{9AFA8D77-D1F0-49E4-BDB5-5D06ED2F10FB}.Release|x86.Build.0 = Release|Win32
{8BE32B2A-F5E4-49E7-A2C9-0FAEA62B7FED}.Debug|x86.ActiveCfg = Debug|Win32
{8BE32B2A-F5E4-49E7-A2C9-0FAEA62B7FED}.Debug|x86.Build.0 = Debug|Win32
{8BE32B2A-F5E4-49E7-A2C9-0FAEA62B7FED}.Release|x86.ActiveCfg = Release|Win32
{8BE32B2A-F5E4-49E7-A2C9-0FAEA62B7FED}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5DE851B4-4487-4E0D-814F-C9078B5C7821}
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
<cbid>service</cbid>
<replay>
<read><delim>\x0a</delim><match><data>2D Particle Simulator\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>Enter the number of particles to simulate \x281-10\x29:\x0a</data></match></read>
<write><data>2\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Position (x,y):\x0a</data></match></read>
<write><data>118.44362,164.92991\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Velocity (x,y):\x0a</data></match></read>
<write><data>8.58466,5.44071\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Mass:\x0a</data></match></read>
<write><data>1.12171\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Radius:\x0a</data></match></read>
<write><data>8.12645\x0a</data></write>
<read><delim>\x0a</delim><match><data>Particle #1 added at (118.44362,164.92991) velocity(8.58466,5.44071) mass(1.12171) radius(8.12645).\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>Enter Position (x,y):\x0a</data></match></read>
<write><data>176.34315,122.04550\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Velocity (x,y):\x0a</data></match></read>
<write><data>4.94155,2.62676\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Mass:\x0a</data></match></read>
<write><data>8.96948\x0a</data></write>
<read><delim>\x0a</delim><match><data>Enter Radius:\x0a</data></match></read>
<write><data>5.49416\x0a</data></write>
<read><delim>\x0a</delim><match><data>Particle #2 added at (176.34315,122.04550) velocity(4.94155,2.62676) mass(8.96948) radius(5.49416).\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>Running simulation with...\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>2 total particles:\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>0: Position (118.44000,164.92000) Velocity (8.58000,5.44000) mass (1.12000) radius (8.12000).\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>1: Position (176.34000,122.04000) Velocity (4.94000,2.62000) mass (8.96000) radius (5.49000).\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>--------------------\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00010000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000010000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>--------------------\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>Simulation complete, 0 collisions simulated over 10 seconds in 20 frames.\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>2 total particles:\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>0: Position (179.52000,164.44000) Velocity (-8.58000,-5.44000) mass (1.12000) radius (8.12000).\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>1: Position (163.28000,148.24000) Velocity (-4.94000,2.62000) mass (8.96000) radius (5.49000).\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>--------------------\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000010000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000010000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>00000000000000000000\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>--------------------\x0a</data></match></read>
<read><delim>\x0a</delim><match><data>Goodbye\x0a</data></match></read>
</replay>
</pov>
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<!--
<meta name="authorization" content="Basic YWRtaW46YWRtaW4=">
-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>ACHE Crawler</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "TInfoWindowControllerBase.h"
@interface TInspectorWindowController : TInfoWindowControllerBase
{
}
+ (unsigned long long)styleMask;
+ (id)inspectorWindowController;
+ (void)updateWithNodes:(const struct TFENodeVector *)arg1;
+ (void)restoreWindowWithIdentifier:(id)arg1 state:(id)arg2 completionHandler:(CDUnknownBlockType)arg3;
+ (void)toggleWindowVisibility:(const struct TFENodeVector *)arg1;
- (void)positionWindow;
- (void)windowWillClose:(id)arg1;
- (void)initCommon;
- (id)infoWindow;
@end
| {
"pile_set_name": "Github"
} |
* :doc:`/developer/configuration/channels`
* :doc:`/developer/configuration/locales`
* :doc:`/developer/configuration/currencies`
| {
"pile_set_name": "Github"
} |
{
"name": "BMJ Publishing Group Limited",
"displayName": "BMJ Publishing Group",
"properties": [
"bmj.com"
],
"prevalence": {
"tracking": 0,
"nonTracking": 0.0000139,
"total": 0.0000139
}
} | {
"pile_set_name": "Github"
} |
<m-chartV2
*ngIf="selectedMetric && selectedTimespan"
[interval]="selectedTimespan.interval"
[unit]="selectedMetric?.unit"
[label]="selectedMetric?.label"
[segments]="selectedMetric.visualisation.segments"
></m-chartV2>
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <map>
#include <unordered_map>
#include <boost/noncopyable.hpp>
#include "ExportedStat.h"
namespace fbzmq {
/**
* Thread storage for storing flat counters, timeseries counters and stats. This
* can be extended to store histograms and string values.
*
* The idea has been borrowed from the fbcode:ServiceData however we have no
* singleton here. The ThreadData is not thread safe and it is assumed to be
* used within a single thread only.
*
* If you want to use within multiple threads then use your own locks :P
*/
class ThreadData : public boost::noncopyable {
public:
ThreadData() = default;
~ThreadData() = default;
/**
* Clear all counters and exported stats etc. You must call
* addStatExportType/addStatExports/addHistogram again to
* re-add statistics.
*/
void resetAllData();
/**
* Exports the given stat value to the counters, using the given export type.
* In other words, after calling for key = "foo", calls to getCounters() will
* contains several counters of the form.
*
* type SUM: foo.SUM, foo.SUM.60, foo.SUM.600, foo.SUM.3600
* type COUNT: foo.COUNT, foo.COUNT.60, foo.COUNT.600, foo.COUNT.3600
* type AVG: foo.avg, foo.avg.60, foo.avg.600, foo.avg.3600
* so on for other types
*/
void addStatExportType(std::string const& key, ExportType type);
void clearStatExportType(std::string const& key, ExportType type);
/**
* Adds a value to the historical statistics for a given key. Checkout the
* documentation of `addStatExportType` to see how to make these statistics
* available via calls to getCounters().
*/
void addStatValue(std::string const& key, int64_t value);
/**
* Same as above but allows you to specify the export type on the fly.
*/
void addStatValue(std::string const& key, int64_t value, ExportType type);
/**
* API to set a flat counter.
*/
void setCounter(std::string const& key, int64_t value);
/**
* Clear/Remove the counter from internal map.
*/
void clearCounter(std::string const& key);
/**
* Utility function to increment the flat-counter
*/
int64_t incrementCounter(std::string const& key, int64_t amount = 1);
/**
* Returns all the counters (flat + exportedStats) as a map of key, vals.
*/
std::unordered_map<std::string, int64_t> getCounters();
private:
// Exported stats
std::unordered_map<std::string /* key */, ExportedStat> stats_{};
// Simple flat counters.
std::unordered_map<std::string /* key */, int64_t> counters_{};
};
} // namespace fbzmq
| {
"pile_set_name": "Github"
} |
{
"multipart": [
{
"apply": {
"model": "mekanismadditions:block/plastic/fence_post"
}
},
{
"when": {
"north": "true"
},
"apply": {
"model": "mekanismadditions:block/plastic/fence_side",
"uvlock": true
}
},
{
"when": {
"east": "true"
},
"apply": {
"model": "mekanismadditions:block/plastic/fence_side",
"y": 90,
"uvlock": true
}
},
{
"when": {
"south": "true"
},
"apply": {
"model": "mekanismadditions:block/plastic/fence_side",
"y": 180,
"uvlock": true
}
},
{
"when": {
"west": "true"
},
"apply": {
"model": "mekanismadditions:block/plastic/fence_side",
"y": 270,
"uvlock": true
}
}
]
} | {
"pile_set_name": "Github"
} |
// Copyright (C) 2005 Arkadiy Vertleyb
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt)
#if defined(_MSC_VER) && defined BOOST_TYPEOF_MESSAGES
# pragma message(BOOST_TYPEOF_TEXT)
#endif
#undef BOOST_TYPEOF_TEXT
| {
"pile_set_name": "Github"
} |
---
title: Environment Variables
sidebar_label: "source: env"
---
import FragmentVarsName from '../../fragments/vars-name.mdx';
import FragmentVarsDefault from '../../fragments/vars-default.mdx';
If the `source` is `env`, DevSpace will **<u>not</u>** ask the user a question and instead use environment variables to determine the value of the variable.
```yaml {3,5-7}
images:
database:
image: "mysql:${MYSQL_VERSION}"
vars:
- name: MYSQL_VERSION
source: env
default: "5.5"
```
:::info
If `source` is `env` and the environment variable is **not** defined, DevSpace will use the [`default` value](#default) or terminate with a fatal error, if there is **no** [`default` value](#default) configured.
:::
## Configuration
### `name`
<FragmentVarsName/>
### `default`
<FragmentVarsDefault/>
| {
"pile_set_name": "Github"
} |
/// Tests that parser handles spans correctly.
use prusti_contracts::*;
#[requires( 12345 ==> true)]
pub fn test_1(x: i32) {}
#[requires( true ==> 12345 )]
pub fn test_2(x: i32) {}
#[requires( true ==> (true && 12345 && true))]
pub fn test_3(x: i32) {}
#[requires( true ==> (true && 12345 ==> true))]
pub fn test_4(x: i32) {}
#[requires( true ==> (true && 12345 ==> true && 12345))]
pub fn test_5(x: i32) {}
fn main() {}
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2006 Tobias Schwinger
http://spirit.sourceforge.net/
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_SYMBOLS_TYPEOF_HPP)
#define BOOST_SPIRIT_SYMBOLS_TYPEOF_HPP
#include <boost/typeof/typeof.hpp>
#include <boost/spirit/home/classic/symbols/symbols_fwd.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::symbols,3)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::symbol_inserter,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::impl::tst,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::symbols,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::symbols,1)
#endif
| {
"pile_set_name": "Github"
} |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import os
import shutil
from os import listdir
import tarfile
import argparse
from sys import version_info
from sklearn.model_selection import train_test_split
if version_info.major == 2:
import urllib as urldownload
else:
import urllib.request as urldownload
class NewsGroup(object):
def __init__(self, params):
self.params = params
self.url = "http://archive.ics.uci.edu/ml/machine-learning-databases/20newsgroups-mld/20_newsgroups.tar.gz"
self.file_name = '20_newsgroups.tar.gz'
self.dirname = '20_newsgroups'
def download_or_zip(self):
if not os.path.exists(self.params.root_dir):
os.mkdir(self.params.root_dir)
path = os.path.join(self.params.root_dir, self.dirname)
if not os.path.isdir(path):
file_path = os.path.join(self.params.root_dir, self.file_name)
if not os.path.isfile(file_path):
print('DownLoading...')
urldownload.urlretrieve(self.url, file_path)
with tarfile.open(file_path, 'r', encoding='utf-8') as fin:
print('Extracting...')
fin.extractall(self.params.root_dir)
return path
def read_process_file(self, file_path):
text_lines = []
with open(file_path, 'rb') as fin:
for single_line in fin:
text_lines.append(str(single_line))
return ''.join(text_lines).replace('\n', ' ').replace('\t', ' ')
def data_combination(self):
data_dir_path = self.download_or_zip()
class_name_folders = listdir(data_dir_path)
assert len(class_name_folders) == 20, 'The 20_newsgroups data has 20 classes and 20 sub folder accordingly, but we found %d' % len(class_name_folders)
pathname_list = []
label_list = []
for sub_folder in class_name_folders:
sub_folder_path = os.path.join(data_dir_path, sub_folder)
for single_file in listdir(sub_folder_path):
pathname_list.append(os.path.join(sub_folder_path, single_file))
label_list.append(sub_folder)
# prepare folder and write data
if not os.path.exists(self.params.output_dir):
os.mkdir(self.params.output_dir)
data_all = []
print('Preprocessing...')
for single_file_path, singel_label in zip(pathname_list, label_list):
text_line = '%s\t%s\n' % (singel_label, self.read_process_file(single_file_path))
data_all.append(text_line)
print('Write output file...')
if self.params.isSplit:
output_train_file_path = os.path.join(self.params.output_dir, 'train.tsv')
output_test_file_path = os.path.join(self.params.output_dir, 'test.tsv')
train_data, test_data = train_test_split(data_all, test_size=self.params.test_size, random_state=123)
with open(output_train_file_path, 'w', encoding='utf-8') as fout:
fout.writelines(train_data)
with open(output_test_file_path, 'w', encoding='utf-8') as fout:
fout.writelines(test_data)
else:
output_file_path = os.path.join(self.output_dir, 'output.tsv')
with open(output_file_path, 'w', encoding='utf-8') as fout:
fout.writelines(data_all)
try:
if os.path.exists(self.params.root_dir):
shutil.rmtree(self.params.root_dir)
except:
pass
if __name__ == '__main__':
parse = argparse.ArgumentParser(description='20_newsgroups data preprocess')
parse.add_argument("--root_dir", type=str, default='./data', help='the folder path of saving download file and untar files')
parse.add_argument("--output_dir", type=str, default='20_newsgroups', help='the folder path of saving tsv format files after preprocess')
parse.add_argument("--isSplit", type=bool, default=True, help='appoint split data into train dataset and test dataset or not')
parse.add_argument("--test_size", type=float, default=0.2)
params, _ = parse.parse_known_args()
newsgroup = NewsGroup(params)
newsgroup.data_combination()
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.