text
stringlengths 2
100k
| meta
dict |
---|---|
doctype html
div.wrapper.roles(
ng-init="section='admin'"
ng-controller="ContribController as ctrl"
)
tg-project-menu
sidebar.menu-secondary.sidebar.settings-nav(tg-admin-navigation="contrib")
include ../includes/modules/admin-menu
sidebar.menu-tertiary.sidebar
include ../includes/modules/admin/admin-submenu-contrib
section.main.admin-common.admin-contrib(ng-include="currentPlugin.template")
| {
"pile_set_name": "Github"
} |
# $NetBSD: Makefile,v 1.10 2014/01/16 01:15:32 christos Exp $
TOP= ${.CURDIR}/..
WARNS=1
DBG= -Os
.include "${TOP}/Makefile.inc"
IMAGE= ramdisk.fs
CBIN= ramdiskbin
MOUNT_POINT?= /mnt
# DEV/RDEV file system device, CDEV/RDEV vnconfig device
VND?= vnd0
VND_DEV= /dev/${VND}a
VND_RDEV= /dev/r${VND}a
VND_CDEV= /dev/${VND}d
VND_CRDEV= /dev/r${VND}d
IMAGE?= xxx.fs
MDEC= ${DESTDIR}/usr/mdec
DISKLABEL?= disklabel
MOUNT?= mount
NEWFS?= newfs
UMOUNT?= umount
VNCONFIG?= vnconfig
LISTS= ${.CURDIR}/../ramdiskcommon/list
CRUNCHCONF= ../ramdiskcommon/${CBIN}.conf
MTREECONF= ../ramdiskcommon/mtree.conf
RAMDISKSPC= 128
RAMDISKCYLS= 54
RAMDISKSIZE!= expr ${RAMDISKSPC} \* ${RAMDISKCYLS}
realall: ${IMAGE}
${IMAGE}: ${CBIN} ${MTREECONF} ${LISTS}
rm -f ${IMAGE}.tmp
dd if=/dev/zero of=${IMAGE}.tmp count=${RAMDISKSIZE}
${VNCONFIG} -v -c ${VND_CDEV} ${IMAGE}.tmp \
512/${RAMDISKSPC}/1/${RAMDISKCYLS}
-${DISKLABEL} ${VND_CDEV} >tmplabel
${DISKLABEL} -r -R ${VND_CDEV} tmplabel
${NEWFS} -B be -m 0 -o space ${VND_RDEV}
${MOUNT} ${VND_DEV} ${MOUNT_POINT}
${TOOL_MTREE} -def ${.CURDIR}/${MTREECONF} -p ${MOUNT_POINT}/ -U
TOPDIR=${TOP} CURDIR=${.CURDIR} OBJDIR=${.OBJDIR} \
KERNOBJDIR=${KERNOBJDIR} TARGDIR=${MOUNT_POINT} ${HOST_SH} \
${NETBSDSRCDIR}/distrib/common/runlist.sh ${LISTS}
@echo ""
@df -i ${MOUNT_POINT}
@echo ""
${UMOUNT} ${MOUNT_POINT}
${VNCONFIG} -u ${VND_CDEV}
mv -f ${IMAGE}.tmp ${IMAGE}
unconfig:
-${UMOUNT} -f ${MOUNT_POINT}
-${VNCONFIG} -u ${VND_DEV}
-/bin/rm -f ${IMAGE}.tmp
${CBIN}.mk ${CBIN}.cache ${CBIN}.c: ${CRUNCHCONF}
${TOOL_CRUNCHGEN} -D ${TOP}/../../.. -L ${.CURDIR} ${.ALLSRC}
${CBIN}: ${CBIN}.mk ${CBIN}.cache ${CBIN}.c
${MAKE} -f ${CBIN}.mk all
# Use stubs to eliminate some large stuff from libc
HACKSRC= ${DISTRIBDIR}/utils/libhack
HACKOBJS= gethost.o
.include "${HACKSRC}/Makefile.inc"
${CBIN}: libhack.o
mount:
${VNCONFIG} -v -c ${VND_CDEV} ${IMAGE} \
512/${RAMDISKSPC}/1/${RAMDISKCYLS}
${MOUNT} ${VND_DEV} ${MOUNT_POINT}
clean cleandir distclean:
/bin/rm -f ${AUXCLEAN} *.core ${IMAGE} ${IMAGE}.tmp ${CBIN} \
${CBIN}.mk ${CBIN}.cache *.o *.cro *.c tmplabel
.include <bsd.own.mk>
.include <bsd.obj.mk>
.include <bsd.subdir.mk>
.include <bsd.files.mk>
| {
"pile_set_name": "Github"
} |
# Doxyfile 1.7.4
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (" ").
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# This tag specifies the encoding used for all characters in the config file
# that follow. The default is UTF-8 which is also the encoding used for all
# text before the first occurrence of this tag. Doxygen uses libiconv (or the
# iconv built into libc) for the transcoding. See
# http://www.gnu.org/software/libiconv for the list of possible encodings.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
# by quotes) that should identify the project.
PROJECT_NAME = libosmogsm
# The PROJECT_NUMBER tag can be used to enter a project or revision number.
# This could be handy for archiving the generated documentation or
# if some version control system is used.
PROJECT_NUMBER = @VERSION@
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer
# a quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF = "Osmocom GSM library"
# With the PROJECT_LOGO tag one can specify an logo or icon that is
# included in the documentation. The maximum height of the logo should not
# exceed 55 pixels and the maximum width should not exceed 200 pixels.
# Doxygen will copy the logo to the output directory.
PROJECT_LOGO =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
# base path where the generated documentation will be put.
# If a relative path is entered, it will be relative to the location
# where doxygen was started. If left blank the current directory will be used.
OUTPUT_DIRECTORY = doc/gsm
# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
# 4096 sub-directories (in 2 levels) under the output directory of each output
# format and will distribute the generated files over these directories.
# Enabling this option can be useful when feeding doxygen a huge amount of
# source files, where putting all generated files in the same directory would
# otherwise cause performance problems for the file system.
CREATE_SUBDIRS = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# The default language is English, other supported languages are:
# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
# include brief member descriptions after the members that are listed in
# the file and class documentation (similar to JavaDoc).
# Set to NO to disable this.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
# the brief description of a member or function before the detailed description.
# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator
# that is used to form the text in various listings. Each string
# in this list, if found as the leading text of the brief description, will be
# stripped from the text and the result after processing the whole list, is
# used as the annotated text. Otherwise, the brief description is used as-is.
# If left blank, the following values are used ("$name" is automatically
# replaced with the name of the entity): "The $name class" "The $name widget"
# "The $name file" "is" "provides" "specifies" "contains"
# "represents" "a" "an" "the"
ABBREVIATE_BRIEF =
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# Doxygen will generate a detailed section even if there is only a brief
# description.
ALWAYS_DETAILED_SEC = NO
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
INLINE_INHERITED_MEMB = NO
# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
# path before files name in the file list and in the header files. If set
# to NO the shortest path that makes the file name unique will be used.
FULL_PATH_NAMES = YES
# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
# can be used to strip a user-defined part of the path. Stripping is
# only done if one of the specified strings matches the left-hand part of
# the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the
# path to strip.
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
# the path mentioned in the documentation of a class, which tells
# the reader which header file to include in order to use a class.
# If left blank only the name of the header file containing the class
# definition is used. Otherwise one should specify the include paths that
# are normally passed to the compiler using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
# (but less readable) file names. This can be useful if your file system
# doesn't support long names like on DOS, Mac, or CD-ROM.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
# will interpret the first line (until the first dot) of a JavaDoc-style
# comment as the brief description. If set to NO, the JavaDoc
# comments will behave just like regular Qt-style comments
# (thus requiring an explicit @brief command for a brief description.)
JAVADOC_AUTOBRIEF = NO
# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
# interpret the first line (until the first dot) of a Qt-style
# comment as the brief description. If set to NO, the comments
# will behave just like regular Qt-style comments (thus requiring
# an explicit \brief command for a brief description.)
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
# treat a multi-line C++ special comment block (i.e. a block of //! or ///
# comments) as a brief description. This used to be the default behaviour.
# The new default is to treat a multi-line C++ comment block as a detailed
# description. Set this tag to YES if you prefer the old behaviour instead.
MULTILINE_CPP_IS_BRIEF = NO
# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
# member inherits the documentation from any documented member that it
# re-implements.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
# a new page for each member. If set to NO, the documentation of a member will
# be part of the file/class/namespace that contains it.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab.
# Doxygen uses this value to replace tabs by spaces in code fragments.
TAB_SIZE = 8
# This tag can be used to specify a number of aliases that acts
# as commands in the documentation. An alias has the form "name=value".
# For example adding "sideeffect=\par Side Effects:\n" will allow you to
# put the command \sideeffect (or @sideeffect) in the documentation, which
# will result in a user-defined paragraph with heading "Side Effects:".
# You can put \n's in the value part of an alias to insert newlines.
ALIASES =
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
# sources only. Doxygen will then generate output that is more tailored for C.
# For instance, some of the names that are used will be different. The list
# of all members will be omitted, etc.
OPTIMIZE_OUTPUT_FOR_C = YES
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
# sources only. Doxygen will then generate output that is more tailored for
# Java. For instance, namespaces will be presented as packages, qualified
# scopes will look different, etc.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources only. Doxygen will then generate output that is more tailored for
# Fortran.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for
# VHDL.
OPTIMIZE_OUTPUT_VHDL = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given extension.
# Doxygen has a built-in mapping, but you can override or extend it using this
# tag. The format is ext=language, where ext is a file extension, and language
# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C,
# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make
# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions
# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
EXTENSION_MAPPING =
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should
# set this tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
# func(std::string) {}). This also makes the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
BUILTIN_STL_SUPPORT = NO
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
# Doxygen will parse them like normal C++ but will assume all classes use public
# instead of private inheritance when no explicit protection keyword is present.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate getter
# and setter methods for a property. Setting this option to YES (the default)
# will make doxygen replace the get and set methods by a property in the
# documentation. This will only work if the methods are indeed getting or
# setting a simple type. If this is not the case, or you want to show the
# methods anyway, you should set this option to NO.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES, then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
DISTRIBUTE_GROUP_DOC = NO
# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
# the same type (for instance a group of public functions) to be put as a
# subgroup of that type (e.g. under the Public Functions section). Set it to
# NO to prevent subgrouping. Alternatively, this can be done per class using
# the \nosubgrouping command.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
# unions are shown inside the group in which they are included (e.g. using
# @ingroup) instead of on a separate page (for HTML and Man pages) or
# section (for LaTeX and RTF).
INLINE_GROUPED_CLASSES = NO
# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
# is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically
# be useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
TYPEDEF_HIDES_STRUCT = NO
# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
# determine which symbols to keep in memory and which to flush to disk.
# When the cache is full, less often used symbols will be written to disk.
# For small to medium size projects (<1000 input files) the default value is
# probably good enough. For larger projects a too small cache size can cause
# doxygen to be busy swapping symbols to and from disk most of the time
# causing a significant performance penalty.
# If the system has enough physical memory increasing the cache will improve the
# performance by keeping more symbols in memory. Note that the value works on
# a logarithmic scale so increasing the size by one will roughly double the
# memory usage. The cache size is given by this formula:
# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
# corresponding to a cache size of 2^16 = 65536 symbols
SYMBOL_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
# documentation are documented, even if no documentation was available.
# Private class members and static file members will be hidden unless
# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
EXTRACT_ALL = NO
# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
# will be included in the documentation.
EXTRACT_PRIVATE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file
# will be included in the documentation.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
# defined locally in source files will be included in the documentation.
# If set to NO only classes defined in header files are included.
EXTRACT_LOCAL_CLASSES = YES
# This flag is only useful for Objective-C code. When set to YES local
# methods, which are defined in the implementation section but not in
# the interface are included in the documentation.
# If set to NO (the default) only methods in the interface are included.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base
# name of the file that contains the anonymous namespace. By default
# anonymous namespaces are hidden.
EXTRACT_ANON_NSPACES = NO
# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
# undocumented members of documented classes, files or namespaces.
# If set to NO (the default) these members will be included in the
# various overviews, but no documentation section is generated.
# This option has no effect if EXTRACT_ALL is enabled.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy.
# If set to NO (the default) these classes will be included in the various
# overviews. This option has no effect if EXTRACT_ALL is enabled.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
# friend (class|struct|union) declarations.
# If set to NO (the default) these declarations will be included in the
# documentation.
HIDE_FRIEND_COMPOUNDS = NO
# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
# documentation blocks found inside the body of a function.
# If set to NO (the default) these blocks will be appended to the
# function's detailed documentation block.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation
# that is typed after a \internal command is included. If the tag is set
# to NO (the default) then the documentation will be excluded.
# Set it to YES to include the internal documentation.
INTERNAL_DOCS = NO
# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
# file names in lower-case letters. If set to YES upper-case letters are also
# allowed. This is useful if you have classes or files whose names only differ
# in case and if your file system supports case sensitive file names. Windows
# and Mac users are advised to set this option to NO.
CASE_SENSE_NAMES = YES
# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
# will show members with their full class and namespace scopes in the
# documentation. If set to YES the scope will be hidden.
HIDE_SCOPE_NAMES = NO
# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
# will put a list of the files that are included by a file in the documentation
# of that file.
SHOW_INCLUDE_FILES = YES
# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
# will list include files with double quotes in the documentation
# rather than with sharp brackets.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
# is inserted in the documentation for inline members.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
# will sort the (detailed) documentation of file and class members
# alphabetically by member name. If set to NO the members will appear in
# declaration order.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
# brief documentation of file, namespace and class members alphabetically
# by member name. If set to NO (the default) the members will appear in
# declaration order.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
# will sort the (brief and detailed) documentation of class members so that
# constructors and destructors are listed first. If set to NO (the default)
# the constructors will appear in the respective orders defined by
# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
# hierarchy of group names into alphabetical order. If set to NO (the default)
# the group names will appear in their defined order.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
# sorted by fully-qualified names, including namespaces. If set to
# NO (the default), the class list will be sorted only by class name,
# not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the
# alphabetical list.
SORT_BY_SCOPE_NAME = NO
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
# do proper type resolution of all parameters of a function it will reject a
# match between the prototype and the implementation of a member function even
# if there is only one candidate or it is obvious which candidate to choose
# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
# will still accept a match between prototype and implementation in such cases.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable (YES) or
# disable (NO) the todo list. This list is created by putting \todo
# commands in the documentation.
GENERATE_TODOLIST = YES
# The GENERATE_TESTLIST tag can be used to enable (YES) or
# disable (NO) the test list. This list is created by putting \test
# commands in the documentation.
GENERATE_TESTLIST = YES
# The GENERATE_BUGLIST tag can be used to enable (YES) or
# disable (NO) the bug list. This list is created by putting \bug
# commands in the documentation.
GENERATE_BUGLIST = YES
# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
# disable (NO) the deprecated list. This list is created by putting
# \deprecated commands in the documentation.
GENERATE_DEPRECATEDLIST= YES
# The ENABLED_SECTIONS tag can be used to enable conditional
# documentation sections, marked by \if sectionname ... \endif.
ENABLED_SECTIONS =
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
# the initial value of a variable or macro consists of for it to appear in
# the documentation. If the initializer consists of more lines than specified
# here it will be hidden. Use a value of 0 to hide initializers completely.
# The appearance of the initializer of individual variables and macros in the
# documentation can be controlled using \showinitializer or \hideinitializer
# command in the documentation regardless of this setting.
MAX_INITIALIZER_LINES = 30
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
# at the bottom of the documentation of classes and structs. If set to YES the
# list will mention the files that were used to generate the documentation.
SHOW_USED_FILES = YES
# If the sources in your project are distributed over multiple directories
# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
# in the documentation. The default is NO.
SHOW_DIRECTORIES = NO
# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
# This will remove the Files entry from the Quick Index and from the
# Folder Tree View (if specified). The default is YES.
SHOW_FILES = YES
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
# Namespaces page.
# This will remove the Namespaces entry from the Quick Index
# and from the Folder Tree View (if specified). The default is YES.
SHOW_NAMESPACES = YES
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command <command> <input-file>, where <command> is the value of
# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
# provided by doxygen. Whatever the program writes to standard output
# is used as the file version. See the manual for examples.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. The create the layout file
# that represents doxygen's defaults, run doxygen with the -l option.
# You can optionally specify a file name after the option, if omitted
# DoxygenLayout.xml will be used as the name of the layout file.
LAYOUT_FILE =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated
# by doxygen. Possible values are YES and NO. If left blank NO is used.
QUIET = NO
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated by doxygen. Possible values are YES and NO. If left blank
# NO is used.
WARNINGS = YES
# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
# automatically be disabled.
WARN_IF_UNDOCUMENTED = YES
# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as not documenting some
# parameters in a documented function, or documenting parameters that
# don't exist or using markup commands wrongly.
WARN_IF_DOC_ERROR = YES
# The WARN_NO_PARAMDOC option can be enabled to get warnings for
# functions that are documented, but have no documentation for their parameters
# or return value. If set to NO (the default) doxygen will only warn about
# wrong or incomplete parameter documentation, but not about the absence of
# documentation.
WARN_NO_PARAMDOC = NO
# The WARN_FORMAT tag determines the format of the warning messages that
# doxygen can produce. The string should contain the $file, $line, and $text
# tags, which will be replaced by the file and line number from which the
# warning originated and the warning text. Optionally the format may contain
# $version, which will be replaced by the version of the file (if it could
# be obtained via FILE_VERSION_FILTER)
WARN_FORMAT = "$file:$line: $text"
# The WARN_LOGFILE tag can be used to specify a file to which warning
# and error messages should be written. If left blank the output is written
# to stderr.
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag can be used to specify the files and/or directories that contain
# documented source files. You may enter file names like "myfile.cpp" or
# directories like "/usr/src/myproject". Separate the files or directories
# with spaces.
INPUT = include/osmocom/gsm include/osmocom/gsm/protocol src/gsm
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
# also the default input encoding. Doxygen uses libiconv (or the iconv built
# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
# the list of possible encodings.
INPUT_ENCODING = UTF-8
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
# and *.h) to filter out the source-files in the directories. If left
# blank the following patterns are tested:
# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
# *.f90 *.f *.for *.vhd *.vhdl
FILE_PATTERNS =
# The RECURSIVE tag can be used to turn specify whether or not subdirectories
# should be searched for input files as well. Possible values are YES and NO.
# If left blank NO is used.
RECURSIVE = YES
# The EXCLUDE tag can be used to specify files and/or directories that should
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
EXCLUDE =
# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories. Note that the wildcards are matched
# against the file with absolute path, so to exclude all test directories
# for example use the pattern */test/*
EXCLUDE_PATTERNS =
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# AClass::ANamespace, ANamespace::*Test
EXCLUDE_SYMBOLS =
# The EXAMPLE_PATH tag can be used to specify one or more files or
# directories that contain example code fragments that are included (see
# the \include command).
EXAMPLE_PATH =
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
# and *.h) to filter out the source-files in the directories. If left
# blank all files are included.
EXAMPLE_PATTERNS =
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude
# commands irrespective of the value of the RECURSIVE tag.
# Possible values are YES and NO. If left blank NO is used.
EXAMPLE_RECURSIVE = NO
# The IMAGE_PATH tag can be used to specify one or more files or
# directories that contain image that are included in the documentation (see
# the \image command).
IMAGE_PATH = images/
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command <filter> <input-file>, where <filter>
# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
# input file. Doxygen will then use the output that the filter program writes
# to standard output.
# If FILTER_PATTERNS is specified, this tag will be
# ignored.
INPUT_FILTER =
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis.
# Doxygen will compare the file name with each pattern and apply the
# filter if there is a match.
# The filters are a list of the form:
# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
# info on how filters are used. If FILTER_PATTERNS is empty or if
# non of the patterns match the file name, INPUT_FILTER is applied.
FILTER_PATTERNS =
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER) will be used to filter the input files when producing source
# files to browse (i.e. when SOURCE_BROWSER is set to YES).
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
# and it is also possible to disable source filtering for a specific pattern
# using *.ext= (so without naming a filter). This option only has effect when
# FILTER_SOURCE_FILES is enabled.
FILTER_SOURCE_PATTERNS =
#---------------------------------------------------------------------------
# configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will
# be generated. Documented entities will be cross-referenced with these sources.
# Note: To get rid of all source code in the generated output, make sure also
# VERBATIM_HEADERS is set to NO.
SOURCE_BROWSER = NO
# Setting the INLINE_SOURCES tag to YES will include the body
# of functions and classes directly in the documentation.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
# doxygen to hide any special comment blocks from generated source code
# fragments. Normal C and C++ comments will always remain visible.
STRIP_CODE_COMMENTS = YES
# If the REFERENCED_BY_RELATION tag is set to YES
# then for each documented function all documented
# functions referencing it will be listed.
REFERENCED_BY_RELATION = YES
# If the REFERENCES_RELATION tag is set to YES
# then for each documented function all documented entities
# called/used by that function will be listed.
REFERENCES_RELATION = YES
# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
# link to the source code.
# Otherwise they will link to the documentation.
REFERENCES_LINK_SOURCE = YES
# If the USE_HTAGS tag is set to YES then the references to source code
# will point to the HTML generated by the htags(1) tool instead of doxygen
# built-in source browser. The htags tool is part of GNU's global source
# tagging system (see http://www.gnu.org/software/global/global.html). You
# will need version 4.8.6 or higher.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
# will generate a verbatim copy of the header file for each class for
# which an include is specified. Set to NO to disable this.
VERBATIM_HEADERS = YES
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
# of all compounds will be generated. Enable this if the project
# contains a lot of classes, structs, unions or interfaces.
ALPHABETICAL_INDEX = NO
# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
# in which this list will be split (can be a number in the range [1..20])
COLS_IN_ALPHA_INDEX = 5
# In case all classes in a project start with a common prefix, all
# classes will be put under the same header in the alphabetical index.
# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
# should be ignored while generating the index headers.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
# generate HTML output.
GENERATE_HTML = YES
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `html' will be used as the default path.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
# doxygen will generate files with .html extension.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a personal HTML header for
# each generated HTML page. If it is left blank doxygen will generate a
# standard header. Note that when using a custom header you are responsible
# for the proper inclusion of any scripts and style sheets that doxygen
# needs, which is dependent on the configuration options used.
# It is adviced to generate a default header using "doxygen -w html
# header.html footer.html stylesheet.css YourConfigFile" and then modify
# that header. Note that the header is subject to change so you typically
# have to redo this when upgrading to a newer version of doxygen or when changing the value of configuration settings such as GENERATE_TREEVIEW!
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a personal HTML footer for
# each generated HTML page. If it is left blank doxygen will generate a
# standard footer.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
# style sheet that is used by each HTML page. It can be used to
# fine-tune the look of the HTML output. If the tag is left blank doxygen
# will generate a default style sheet. Note that doxygen will try to copy
# the style sheet file to the HTML output directory, so don't put your own
# stylesheet in the HTML output directory as well, or it will be erased!
HTML_STYLESHEET =
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that
# the files will be copied as-is; there are no commands or markers available.
HTML_EXTRA_FILES =
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
# Doxygen will adjust the colors in the stylesheet and background images
# according to this color. Hue is specified as an angle on a colorwheel,
# see http://en.wikipedia.org/wiki/Hue for more information.
# For instance the value 0 represents red, 60 is yellow, 120 is green,
# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
# The allowed range is 0 to 359.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
# the colors in the HTML output. For a value of 0 the output will use
# grayscales only. A value of 255 will produce the most vivid colors.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
# the luminance component of the colors in the HTML output. Values below
# 100 gradually make the output lighter, whereas values above 100 make
# the output darker. The value divided by 100 is the actual gamma applied,
# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
# and 100 does not change the gamma.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting
# this to NO can help when comparing the output of multiple runs.
HTML_TIMESTAMP = YES
# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
# files or namespaces will be aligned in HTML using tables. If set to
# NO a bullet list will be used.
HTML_ALIGN_MEMBERS = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded. For this to work a browser that supports
# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
HTML_DYNAMIC_SECTIONS = NO
# If the GENERATE_DOCSET tag is set to YES, additional index files
# will be generated that can be used as input for Apple's Xcode 3
# integrated development environment, introduced with OSX 10.5 (Leopard).
# To create a documentation set, doxygen will generate a Makefile in the
# HTML output directory. Running make will produce the docset in that
# directory and running "make install" will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
# it at startup.
# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
# for more information.
GENERATE_DOCSET = NO
# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
# feed. A documentation feed provides an umbrella under which multiple
# documentation sets from a single provider (such as a company or product suite)
# can be grouped.
DOCSET_FEEDNAME = "Doxygen generated docs"
# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
# should uniquely identify the documentation set bundle. This should be a
# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
# will append .docset to the name.
DOCSET_BUNDLE_ID = org.doxygen.Project
# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES, additional index files
# will be generated that can be used as input for tools like the
# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
# of the generated HTML documentation.
GENERATE_HTMLHELP = NO
# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
# be used to specify the file name of the resulting .chm file. You
# can add a path in front of the file if the result should not be
# written to the html output directory.
CHM_FILE =
# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
# be used to specify the location (absolute path including file name) of
# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
# the HTML help compiler on the generated index.hhp.
HHC_LOCATION =
# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
# controls if a separate .chi index file is generated (YES) or that
# it should be included in the master .chm file (NO).
GENERATE_CHI = NO
# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
# is used to encode HtmlHelp index (hhk), content (hhc) and project file
# content.
CHM_INDEX_ENCODING =
# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
# controls whether a binary table of contents is generated (YES) or a
# normal table of contents (NO) in the .chm file.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members
# to the contents of the HTML help documentation and to the tree view.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
# that can be used as input for Qt's qhelpgenerator to generate a
# Qt Compressed Help (.qch) of the generated HTML documentation.
GENERATE_QHP = NO
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
# be used to specify the file name of the resulting .qch file.
# The path specified is relative to the HTML output folder.
QCH_FILE =
# The QHP_NAMESPACE tag specifies the namespace to use when generating
# Qt Help Project output. For more information please see
# http://doc.trolltech.com/qthelpproject.html#namespace
QHP_NAMESPACE = org.doxygen.Project
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
# Qt Help Project output. For more information please see
# http://doc.trolltech.com/qthelpproject.html#virtual-folders
QHP_VIRTUAL_FOLDER = doc
# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
# add. For more information please see
# http://doc.trolltech.com/qthelpproject.html#custom-filters
QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see
# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
# Qt Help Project / Custom Filters</a>.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's
# filter section matches.
# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
# Qt Help Project / Filter Attributes</a>.
QHP_SECT_FILTER_ATTRS =
# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
# be used to specify the location of Qt's qhelpgenerator.
# If non-empty doxygen will try to run qhelpgenerator on the generated
# .qhp file.
QHG_LOCATION =
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
# will be generated, which together with the HTML files, form an Eclipse help
# plugin. To install this plugin and make it available under the help contents
# menu in Eclipse, the contents of the directory containing the HTML and XML
# files needs to be copied into the plugins directory of eclipse. The name of
# the directory within the plugins directory should be the same as
# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
# the help appears.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have
# this name.
ECLIPSE_DOC_ID = org.doxygen.Project
# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
# top of each HTML page. The value NO (the default) enables the index and
# the value YES disables it.
DISABLE_INDEX = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
# (range [0,1..20]) that doxygen will group on one line in the generated HTML
# documentation. Note that a value of 0 will completely suppress the enum
# values from appearing in the overview section.
ENUM_VALUES_PER_LINE = 4
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information.
# If the tag value is set to YES, a side panel will be generated
# containing a tree-like index structure (just like the one that
# is generated for HTML Help). For this to work a browser that supports
# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
# Windows users are probably better off using the HTML help feature.
GENERATE_TREEVIEW = YES
# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
# and Class Hierarchy pages using a tree view instead of an ordered list.
USE_INLINE_TREES = NO
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
# used to set the initial width (in pixels) of the frame in which the tree
# is shown.
TREEVIEW_WIDTH = 250
# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
# links to external symbols imported via tag files in a separate window.
EXT_LINKS_IN_WINDOW = NO
# Use this tag to change the font size of Latex formulas included
# as images in the HTML documentation. The default is 10. Note that
# when you change the font size after a successful doxygen run you need
# to manually remove any form_*.png images from the HTML output directory
# to force them to be regenerated.
FORMULA_FONTSIZE = 10
# Use the FORMULA_TRANPARENT tag to determine whether or not the images
# generated for formulas are transparent PNGs. Transparent PNGs are
# not supported properly for IE 6.0, but are supported on all modern browsers.
# Note that when changing this option you need to delete any form_*.png files
# in the HTML output before the changes have effect.
FORMULA_TRANSPARENT = YES
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
# (see http://www.mathjax.org) which uses client side Javascript for the
# rendering instead of using prerendered bitmaps. Use this if you do not
# have LaTeX installed or if you want to formulas look prettier in the HTML
# output. When enabled you also need to install MathJax separately and
# configure the path to it using the MATHJAX_RELPATH option.
USE_MATHJAX = NO
# When MathJax is enabled you need to specify the location relative to the
# HTML output directory using the MATHJAX_RELPATH option. The destination
# directory should contain the MathJax.js script. For instance, if the mathjax
# directory is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the
# mathjax.org site, so you can quickly see the result without installing
# MathJax, but it is strongly recommended to install a local copy of MathJax
# before deployment.
MATHJAX_RELPATH = http://www.mathjax.org/mathjax
# When the SEARCHENGINE tag is enabled doxygen will generate a search box
# for the HTML output. The underlying search engine uses javascript
# and DHTML and should work on any modern browser. Note that when using
# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
# (GENERATE_DOCSET) there is already a search function so this one should
# typically be disabled. For large projects the javascript based search engine
# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
SEARCHENGINE = NO
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a PHP enabled web server instead of at the web client
# using Javascript. Doxygen will generate the search PHP script and index
# file to put on the web server. The advantage of the server
# based approach is that it scales better to large projects and allows
# full text search. The disadvantages are that it is more difficult to setup
# and does not have live searching capabilities.
SERVER_BASED_SEARCH = NO
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
# generate Latex output.
GENERATE_LATEX = YES
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `latex' will be used as the default path.
LATEX_OUTPUT = latex
# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked. If left blank `latex' will be used as the default command name.
# Note that when enabling USE_PDFLATEX this option is only used for
# generating bitmaps for formulas in the HTML output, but not in the
# Makefile that is written to the output directory.
LATEX_CMD_NAME = latex
# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
# generate index for LaTeX. If left blank `makeindex' will be used as the
# default command name.
MAKEINDEX_CMD_NAME = makeindex
# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
# LaTeX documents. This may be useful for small projects and may help to
# save some trees in general.
COMPACT_LATEX = NO
# The PAPER_TYPE tag can be used to set the paper type that is used
# by the printer. Possible values are: a4, letter, legal and
# executive. If left blank a4wide will be used.
PAPER_TYPE = a4wide
# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
# packages that should be included in the LaTeX output.
EXTRA_PACKAGES =
# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
# the generated latex document. The header should contain everything until
# the first chapter. If it is left blank doxygen will generate a
# standard header. Notice: only use this tag if you know what you are doing!
LATEX_HEADER =
# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
# the generated latex document. The footer should contain everything after
# the last chapter. If it is left blank doxygen will generate a
# standard footer. Notice: only use this tag if you know what you are doing!
LATEX_FOOTER =
# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
# is prepared for conversion to pdf (using ps2pdf). The pdf file will
# contain links (just like the HTML output) instead of page references
# This makes the output suitable for online browsing using a pdf viewer.
PDF_HYPERLINKS = NO
# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
# plain latex in the generated Makefile. Set this option to YES to get a
# higher quality PDF documentation.
USE_PDFLATEX = NO
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
# command to the generated LaTeX files. This will instruct LaTeX to keep
# running if errors occur, instead of asking the user for help.
# This option is also used when generating formulas in HTML.
LATEX_BATCHMODE = NO
# If LATEX_HIDE_INDICES is set to YES then doxygen will not
# include the index chapters (such as File Index, Compound Index, etc.)
# in the output.
LATEX_HIDE_INDICES = NO
# If LATEX_SOURCE_CODE is set to YES then doxygen will include
# source code with syntax highlighting in the LaTeX output.
# Note that which sources are shown also depends on other settings
# such as SOURCE_BROWSER.
LATEX_SOURCE_CODE = NO
#---------------------------------------------------------------------------
# configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
# The RTF output is optimized for Word 97 and may not look very pretty with
# other RTF readers or editors.
GENERATE_RTF = NO
# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `rtf' will be used as the default path.
RTF_OUTPUT = rtf
# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
# RTF documents. This may be useful for small projects and may help to
# save some trees in general.
COMPACT_RTF = NO
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
# will contain hyperlink fields. The RTF file will
# contain links (just like the HTML output) instead of page references.
# This makes the output suitable for online browsing using WORD or other
# programs which support those fields.
# Note: wordpad (write) and others do not support links.
RTF_HYPERLINKS = NO
# Load stylesheet definitions from file. Syntax is similar to doxygen's
# config file, i.e. a series of assignments. You only have to provide
# replacements, missing definitions are set to their default value.
RTF_STYLESHEET_FILE =
# Set optional variables used in the generation of an rtf document.
# Syntax is similar to doxygen's config file.
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
# generate man pages
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `man' will be used as the default path.
MAN_OUTPUT = man
# The MAN_EXTENSION tag determines the extension that is added to
# the generated man pages (default is the subroutine's section .3)
MAN_EXTENSION = .3
# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
# then it will generate one additional man file for each entity
# documented in the real man page(s). These additional files
# only source the real man page, but without them the man command
# would be unable to find the correct page. The default is NO.
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
#---------------------------------------------------------------------------
# If the GENERATE_XML tag is set to YES Doxygen will
# generate an XML file that captures the structure of
# the code including all documentation.
GENERATE_XML = NO
# The XML_OUTPUT tag is used to specify where the XML pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `xml' will be used as the default path.
XML_OUTPUT = xml
# The XML_SCHEMA tag can be used to specify an XML schema,
# which can be used by a validating XML parser to check the
# syntax of the XML files.
XML_SCHEMA =
# The XML_DTD tag can be used to specify an XML DTD,
# which can be used by a validating XML parser to check the
# syntax of the XML files.
XML_DTD =
# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
# dump the program listings (including syntax highlighting
# and cross-referencing information) to the XML output. Note that
# enabling this will significantly increase the size of the XML output.
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
# generate an AutoGen Definitions (see autogen.sf.net) file
# that captures the structure of the code including all
# documentation. Note that this feature is still experimental
# and incomplete at the moment.
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
#---------------------------------------------------------------------------
# If the GENERATE_PERLMOD tag is set to YES Doxygen will
# generate a Perl module file that captures the structure of
# the code including all documentation. Note that this
# feature is still experimental and incomplete at the
# moment.
GENERATE_PERLMOD = NO
# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
# the necessary Makefile rules, Perl scripts and LaTeX code to be able
# to generate PDF and DVI output from the Perl module output.
PERLMOD_LATEX = NO
# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
# nicely formatted so it can be parsed by a human reader.
# This is useful
# if you want to understand what is going on.
# On the other hand, if this
# tag is set to NO the size of the Perl module output will be much smaller
# and Perl will parse it just the same.
PERLMOD_PRETTY = YES
# The names of the make variables in the generated doxyrules.make file
# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
# This is useful so different doxyrules.make files included by the same
# Makefile don't overwrite each other's variables.
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
# evaluate all C-preprocessor directives found in the sources and include
# files.
ENABLE_PREPROCESSING = NO
# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
# names in the source code. If set to NO (the default) only conditional
# compilation will be performed. Macro expansion can be done in a controlled
# way by setting EXPAND_ONLY_PREDEF to YES.
MACRO_EXPANSION = NO
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
# then the macro expansion is limited to the macros specified with the
# PREDEFINED and EXPAND_AS_DEFINED tags.
EXPAND_ONLY_PREDEF = NO
# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
# pointed to by INCLUDE_PATH will be searched when a #include is found.
SEARCH_INCLUDES = YES
# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by
# the preprocessor.
INCLUDE_PATH =
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will
# be used.
INCLUDE_FILE_PATTERNS =
# The PREDEFINED tag can be used to specify one or more macro names that
# are defined before the preprocessor is started (similar to the -D option of
# gcc). The argument of the tag is a list of macros of the form: name
# or name=definition (no spaces). If the definition and the = are
# omitted =1 is assumed. To prevent a macro definition from being
# undefined via #undef or recursively expanded use the := operator
# instead of the = operator.
PREDEFINED =
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
# this tag can be used to specify a list of macro names that should be expanded.
# The macro definition that is found in the sources will be used.
# Use the PREDEFINED tag if you want to use a different macro definition that
# overrules the definition found in the source code.
EXPAND_AS_DEFINED =
# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
# doxygen's preprocessor will remove all references to function-like macros
# that are alone on a line, have an all uppercase name, and do not end with a
# semicolon, because these will confuse the parser if not removed.
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
#---------------------------------------------------------------------------
# The TAGFILES option can be used to specify one or more tagfiles.
# Optionally an initial location of the external documentation
# can be added for each tagfile. The format of a tag file without
# this location is as follows:
#
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
#
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where "loc1" and "loc2" can be relative or absolute paths or
# URLs. If a location is present for each tag, the installdox tool
# does not have to be run to correct the links.
# Note that each tag file must have a unique name
# (where the name does NOT include the path)
# If a tag file is not located in the directory in which doxygen
# is run, you must also specify the path to the tagfile here.
TAGFILES =
# When a file name is specified after GENERATE_TAGFILE, doxygen will create
# a tag file that is based on the input files it reads.
GENERATE_TAGFILE =
# If the ALLEXTERNALS tag is set to YES all external classes will be listed
# in the class index. If set to NO only the inherited external classes
# will be listed.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
# in the modules index. If set to NO, only the current project's groups will
# be listed.
EXTERNAL_GROUPS = YES
# The PERL_PATH should be the absolute path and name of the perl script
# interpreter (i.e. the result of `which perl').
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
# or super classes. Setting the tag to NO turns the diagrams off. Note that
# this option also works with HAVE_DOT disabled, but it is recommended to
# install and use dot, since it yields more powerful graphs.
CLASS_DIAGRAMS = YES
# You can define message sequence charts within doxygen comments using the \msc
# command. Doxygen will then run the mscgen tool (see
# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
# documentation. The MSCGEN_PATH tag allows you to specify the directory where
# the mscgen tool resides. If left empty the tool is assumed to be found in the
# default search path.
MSCGEN_PATH =
# If set to YES, the inheritance and collaboration graphs will hide
# inheritance and usage relations if the target is undocumented
# or is not a class.
HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz, a graph visualization
# toolkit from AT&T and Lucent Bell Labs. The other options in this section
# have no effect if this option is set to NO (the default)
HAVE_DOT = NO
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
# allowed to run in parallel. When set to 0 (the default) doxygen will
# base this on the number of processors available in the system. You can set it
# explicitly to a value larger than 0 to get control over the balance
# between CPU load and processing speed.
DOT_NUM_THREADS = 0
# By default doxygen will write a font called Helvetica to the output
# directory and reference it in all dot files that doxygen generates.
# When you want a differently looking font you can specify the font name
# using DOT_FONTNAME. You need to make sure dot is able to find the font,
# which can be done by putting it in a standard location or by setting the
# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
# containing the font.
DOT_FONTNAME = Helvetica
# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
# The default size is 10pt.
DOT_FONTSIZE = 10
# By default doxygen will tell dot to use the output directory to look for the
# FreeSans.ttf font (which doxygen will put there itself). If you specify a
# different font using DOT_FONTNAME you can set the path where dot
# can find it using this tag.
DOT_FONTPATH =
# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
# will generate a graph for each documented class showing the direct and
# indirect inheritance relations. Setting this tag to YES will force the
# the CLASS_DIAGRAMS tag to NO.
CLASS_GRAPH = YES
# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
# will generate a graph for each documented class showing the direct and
# indirect implementation dependencies (inheritance, containment, and
# class references variables) of the class with other documented classes.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
# will generate a graph for groups, showing the direct groups dependencies
GROUP_GRAPHS = YES
# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
UML_LOOK = NO
# If set to YES, the inheritance and collaboration graphs will show the
# relations between templates and their instances.
TEMPLATE_RELATIONS = NO
# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
# tags are set to YES then doxygen will generate a graph for each documented
# file showing the direct and indirect include dependencies of the file with
# other documented files.
INCLUDE_GRAPH = YES
# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
# documented header file showing the documented files that directly or
# indirectly include this file.
INCLUDED_BY_GRAPH = YES
# If the CALL_GRAPH and HAVE_DOT options are set to YES then
# doxygen will generate a call dependency graph for every global function
# or class method. Note that enabling this option will significantly increase
# the time of a run. So in most cases it will be better to enable call graphs
# for selected functions only using the \callgraph command.
CALL_GRAPH = NO
# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
# doxygen will generate a caller dependency graph for every global function
# or class method. Note that enabling this option will significantly increase
# the time of a run. So in most cases it will be better to enable caller
# graphs for selected functions only using the \callergraph command.
CALLER_GRAPH = NO
# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
# will generate a graphical hierarchy of all classes instead of a textual one.
GRAPHICAL_HIERARCHY = YES
# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
# then doxygen will show the dependencies a directory has on other directories
# in a graphical way. The dependency relations are determined by the #include
# relations between the files in the directories.
DIRECTORY_GRAPH = YES
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot. Possible values are svg, png, jpg, or gif.
# If left blank png will be used.
DOT_IMAGE_FORMAT = png
# The tag DOT_PATH can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
DOT_PATH = /usr/bin/dot
# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the
# \dotfile command).
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the
# \mscfile command).
MSCFILE_DIRS =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
# nodes that will be shown in the graph. If the number of nodes in a graph
# becomes larger than this value, doxygen will truncate the graph, which is
# visualized by representing a node as a red box. Note that doxygen if the
# number of direct children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
DOT_GRAPH_MAX_NODES = 50
# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
# graphs generated by dot. A depth value of 3 means that only nodes reachable
# from the root by following a path via at most 3 edges will be shown. Nodes
# that lay further from the root node will be omitted. Note that setting this
# option to 1 or 2 may greatly reduce the computation time needed for large
# code bases. Also note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
MAX_DOT_GRAPH_DEPTH = 0
# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
# background. This is disabled by default, because dot on Windows does not
# seem to support this out of the box. Warning: Depending on the platform used,
# enabling this option may lead to badly anti-aliased labels on the edges of
# a graph (i.e. they become hard to read).
DOT_TRANSPARENT = NO
# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10)
# support this, this feature is disabled by default.
DOT_MULTI_TARGETS = NO
# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
# generate a legend page explaining the meaning of the various boxes and
# arrows in the dot generated graphs.
GENERATE_LEGEND = YES
# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
# remove the intermediate dot files that are used to generate
# the various graphs.
DOT_CLEANUP = YES
| {
"pile_set_name": "Github"
} |
/*
===========================================================================
Wolfenstein: Enemy Territory GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Wolfenstein: Enemy Territory GPL Source Code (Wolf ET Source Code).
Wolf ET Source Code 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.
Wolf ET Source 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 for more details.
You should have received a copy of the GNU General Public License
along with Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Wolf: ET Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Wolf ET Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
//===========================================================================
//
// Name: b_aas_bspc.c
// Function: Area Awareness System
// Programmer: Mr Elusive ([email protected])
// Last update: 1999-09-14
// Tab Size: 3
//===========================================================================
#include "../game/q_shared.h"
#include "../bspc/l_log.h"
#include "../bspc/l_qfiles.h"
#include "../botlib/l_memory.h"
#include "../botlib/l_script.h"
#include "../botlib/l_precomp.h"
#include "../botlib/l_struct.h"
#include "../botlib/aasfile.h"
#include "../game/botlib.h"
#include "../game/be_aas.h"
#include "../botlib/be_aas_def.h"
#include "../qcommon/cm_public.h"
//#define BSPC
extern botlib_import_t botimport;
extern qboolean capsule_collision;
//#define AAS_MOVE_DEBUG
botlib_import_t botimport;
clipHandle_t worldmodel;
void Error( char *error, ... );
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_Error( char *fmt, ... ) {
va_list argptr;
char text[1024];
va_start( argptr, fmt );
Q_vsnprintf( text, sizeof( text ), fmt, argptr );
va_end( argptr );
Error( text );
} //end of the function AAS_Error
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int Sys_MilliSeconds( void ) {
return clock() * 1000 / CLOCKS_PER_SEC;
} //end of the function Sys_MilliSeconds
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_DebugLine( vec3_t start, vec3_t end, int color ) {
} //end of the function AAS_DebugLine
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_ClearShownDebugLines( void ) {
} //end of the function AAS_ClearShownDebugLines
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
char *BotImport_BSPEntityData( void ) {
return CM_EntityString();
} //end of the function AAS_GetEntityData
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotImport_Trace( bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask ) {
trace_t result;
CM_BoxTrace( &result, start, end, mins, maxs, worldmodel, contentmask, capsule_collision );
bsptrace->allsolid = result.allsolid;
bsptrace->contents = result.contents;
VectorCopy( result.endpos, bsptrace->endpos );
bsptrace->ent = result.entityNum;
bsptrace->fraction = result.fraction;
bsptrace->exp_dist = 0;
bsptrace->plane.dist = result.plane.dist;
VectorCopy( result.plane.normal, bsptrace->plane.normal );
bsptrace->plane.signbits = result.plane.signbits;
bsptrace->plane.type = result.plane.type;
bsptrace->sidenum = 0;
bsptrace->startsolid = result.startsolid;
bsptrace->surface.flags = result.surfaceFlags;
} //end of the function BotImport_Trace
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotImport_PointContents( vec3_t p ) {
return CM_PointContents( p, worldmodel );
} //end of the function BotImport_PointContents
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void *BotImport_GetMemory( int size ) {
return GetMemory( size );
} //end of the function BotImport_GetMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotImport_Print( int type, char *fmt, ... ) {
va_list argptr;
char buf[1024];
va_start( argptr, fmt );
Q_vsnprintf( buf, sizeof( buf ), fmt, argptr );
printf( buf );
if ( buf[0] != '\r' ) {
Log_Write( buf );
}
va_end( argptr );
} //end of the function BotImport_Print
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotImport_BSPModelMinsMaxsOrigin( int modelnum, vec3_t angles, vec3_t outmins, vec3_t outmaxs, vec3_t origin ) {
clipHandle_t h;
vec3_t mins, maxs;
float max;
int i;
h = CM_InlineModel( modelnum );
CM_ModelBounds( h, mins, maxs );
//if the model is rotated
if ( ( angles[0] || angles[1] || angles[2] ) ) { // expand for rotation
max = RadiusFromBounds( mins, maxs );
for ( i = 0; i < 3; i++ )
{
mins[i] = ( mins[i] + maxs[i] ) * 0.5 - max;
maxs[i] = ( mins[i] + maxs[i] ) * 0.5 + max;
} //end for
} //end if
if ( outmins ) {
VectorCopy( mins, outmins );
}
if ( outmaxs ) {
VectorCopy( maxs, outmaxs );
}
if ( origin ) {
VectorClear( origin );
}
} //end of the function BotImport_BSPModelMinsMaxsOrigin
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Com_DPrintf( char *fmt, ... ) {
va_list argptr;
char buf[1024];
va_start( argptr, fmt );
Q_vsnprintf( buf, sizeof( buf ), fmt, argptr );
printf( buf );
if ( buf[0] != '\r' ) {
Log_Write( buf );
}
va_end( argptr );
} //end of the function Com_DPrintf
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int COM_Compress( char *data_p ) {
return strlen( data_p );
}
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Com_Memset( void* dest, const int val, const size_t count ) {
memset( dest, val, count );
}
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Com_Memcpy( void* dest, const void* src, const size_t count ) {
memcpy( dest, src, count );
}
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_InitBotImport( void ) {
botimport.BSPEntityData = BotImport_BSPEntityData;
botimport.GetMemory = BotImport_GetMemory;
botimport.FreeMemory = FreeMemory;
botimport.Trace = BotImport_Trace;
botimport.PointContents = BotImport_PointContents;
botimport.Print = BotImport_Print;
botimport.BSPModelMinsMaxsOrigin = BotImport_BSPModelMinsMaxsOrigin;
} //end of the function AAS_InitBotImport
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_SetViewPortalsAsClusterPortals( void );
void AAS_CalcReachAndClusters( struct quakefile_s *qf ) {
float time;
Log_Print( "loading collision map...\n" );
//
if ( !qf->pakfile[0] ) {
strcpy( qf->pakfile, qf->filename );
}
//load the map
CM_LoadMap( (char *) qf, qfalse, &( *aasworld ).bspchecksum );
//get a handle to the world model
worldmodel = CM_InlineModel( 0 ); // 0 = world, 1 + are bmodels
//initialize bot import structure
AAS_InitBotImport();
//load the BSP entity string
AAS_LoadBSPFile();
//init physics settings
AAS_InitSettings();
//initialize AAS link heap
AAS_InitAASLinkHeap();
//initialize the AAS linked entities for the new map
AAS_InitAASLinkedEntities();
//reset all reachabilities and clusters
( *aasworld ).reachabilitysize = 0;
( *aasworld ).numclusters = 0;
//set all view portals as cluster portals in case we re-calculate the reachabilities and clusters (with -reach)
AAS_SetViewPortalsAsClusterPortals();
//calculate reachabilities
AAS_InitReachability();
time = 0;
while ( AAS_ContinueInitReachability( time ) ) time++;
//calculate clusters
AAS_InitClustering();
} //end of the function AAS_CalcReachAndClusters
// Ridah
void AAS_SetWorldPointer( aas_t *newaasworld ) {
aasworld = newaasworld;
}
// done.
| {
"pile_set_name": "Github"
} |
The MIT License (MIT)
Copyright (c) 2013 TOML authors
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.
| {
"pile_set_name": "Github"
} |
package com.example.appsqlitedemo1;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
//http://android-codes-examples.blogspot.com.br/2011/09/using-sqlite-to-populate-listview-in.html <<----------
//http://www.coderzheaven.com/2012/12/23/store-image-android-sqlite-retrieve-it/ <<---------------
//http://www.coderzheaven.com/2011/04/17/using-sqlite-in-android-a-really-simple-example/
//http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
//http://androidexample.com/SQLite_Database_Manipulation_Class_-_Android_Example/index.php?view=article_discription&aid=51
//http://javapapers.com/android/android-sqlite-database/ <<-------------------
//http://chintankhetiya.wordpress.com/2013/06/01/sqlite-database-example/
//http://androidituts.com/android-sqlite-database-insert-example/
//http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android <<---------------
//http://stackoverflow.com/questions/5742101/how-using-sqliteopenhelper-with-database-on-sd-card
/*
* LAMW - LAZARUS ANDROID MODULE WIZARD
* https://github.com/jmpessoa/lazandroidmodulewizard
* Review by TR3E 2019/08/23
*/
public class jSqliteCursor {
private long PasObj = 0; // Pascal Obj
private Controls controls = null; // Control Class for Event
private int mCursorPos = -1;
private int mCursorColumnCount = 0;
private int mCursorRowCount = 0;
public Cursor mCursor = null;
public Bitmap bufBmp = null;
//Constructor
public jSqliteCursor(Controls ctrls, long pasobj ) {
//Connect Pascal I/F
PasObj = pasobj;
controls = ctrls;
mCursorColumnCount = 0;
mCursorRowCount = 0;
mCursorPos = -1;
}
public void SetCursor(Cursor curs) {
mCursor = curs;
if( mCursor != null ){
mCursorColumnCount = mCursor.getColumnCount();
mCursorRowCount = mCursor.getCount();
mCursorPos = mCursor.getPosition();
}else{
mCursorColumnCount = 0;
mCursorRowCount = 0;
mCursorPos = -1;
}
}
public Cursor GetCursor() {
return mCursor;
}
public int GetRowCount() {
return mCursorRowCount;
}
public void MoveToFirst() {
if (mCursor != null){
mCursor.moveToFirst();
mCursorPos = mCursor.getPosition();
}
}
public void MoveToNext() {
if (mCursor != null){
mCursor.moveToNext();
mCursorPos = mCursor.getPosition();
}
}
public void MoveToPrev() {
if (mCursor != null){
mCursor.moveToPrevious();
mCursorPos = mCursor.getPosition();
}
}
public void MoveToLast() {
if (mCursor != null){
mCursor.moveToLast();
mCursorPos = mCursor.getPosition();
}
}
public void MoveToPosition(int position) {
if ((mCursor == null) || (position < 0) || (position >= mCursorRowCount)) return;
mCursor.moveToPosition(position);
mCursorPos = mCursor.getPosition();
}
public int GetPosition() {
if (mCursor == null) return -1;
return mCursor.getPosition();
}
public int GetColumnIndex(String colName) {
if (mCursor == null) return -1;
return mCursor.getColumnIndex(colName);
}
public String GetValueAsString(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return "";
return mCursor.getString(columnIndex);
}
//Cursor.FIELD_TYPE_BLOB; //4
//Cursor.FIELD_TYPE_FLOAT//2
//Cursor.FIELD_TYPE_INTEGER//1
//Cursor.FIELD_TYPE_STRING//3
//Cursor.FIELD_TYPE_NULL //0
public int GetColType(int columnIndex) {
if ((mCursor == null) || (columnIndex < 0) || (columnIndex >= mCursorColumnCount))
return Cursor.FIELD_TYPE_NULL;
return mCursor.getType(columnIndex);
}
public byte[] GetValueAsBlod(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return null;
return mCursor.getBlob(columnIndex);
}
public Bitmap GetValueAsBitmap(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return null;
byte[] image = mCursor.getBlob(columnIndex);
if( image == null ) return null;
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
public int GetValueAsInteger(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return -1;
return mCursor.getInt(columnIndex);
}
public short GetValueAsShort(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return -1;
return mCursor.getShort(columnIndex);
}
public long GetValueAsLong(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return -1;
return mCursor.getLong(columnIndex);
}
public float GetValueAsFloat(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return -1;
return mCursor.getFloat(columnIndex);
}
public double GetValueAsDouble(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return -1;
return mCursor.getDouble(columnIndex);
}
public int GetColumnCount() {
return mCursorColumnCount;
}
public String GetColumName(int columnIndex) {
if ((mCursor == null) || (columnIndex < 0) || (columnIndex >= mCursorColumnCount)) return "";
return mCursor.getColumnName(columnIndex);
}
//Cursor.FIELD_TYPE_BLOB; //4
//Cursor.FIELD_TYPE_FLOAT//2
//Cursor.FIELD_TYPE_INTEGER//1
//Cursor.FIELD_TYPE_STRING//3
//Cursor.FIELD_TYPE_NULL //0
public String GetValueToString(int columnIndex) {
if ((mCursor == null) ||
(columnIndex < 0) || (columnIndex >= mCursorColumnCount) ||
(mCursorPos < 0) || (mCursorPos >= mCursorRowCount)) return "";
String colValue = "";
switch (mCursor.getType(columnIndex)) {
case Cursor.FIELD_TYPE_INTEGER: colValue = Integer.toString(mCursor.getInt(columnIndex)); break;
case Cursor.FIELD_TYPE_STRING : colValue = mCursor.getString(columnIndex); break;
case Cursor.FIELD_TYPE_FLOAT : colValue = String.format("%.2f", mCursor.getFloat(columnIndex)); break;
case Cursor.FIELD_TYPE_BLOB : colValue = "BLOB"; break;
case Cursor.FIELD_TYPE_NULL : colValue = "NULL"; break;
default: colValue = "UNKNOW";
}
return colValue;
}
public void Free() {
mCursor = null;
bufBmp = null;
}
}
| {
"pile_set_name": "Github"
} |
CONFIG_SMP=y
CONFIG_NR_CPUS=54
CONFIG_PREEMPT_NONE=n
CONFIG_PREEMPT_VOLUNTARY=n
CONFIG_PREEMPT=y
#CHECK#CONFIG_PREEMPT_RCU=y
CONFIG_HZ_PERIODIC=n
CONFIG_NO_HZ_IDLE=y
CONFIG_NO_HZ_FULL=n
CONFIG_RCU_FAST_NO_HZ=n
CONFIG_HOTPLUG_CPU=n
CONFIG_SUSPEND=n
CONFIG_HIBERNATION=n
CONFIG_RCU_FANOUT=3
CONFIG_RCU_FANOUT_LEAF=2
CONFIG_RCU_NOCB_CPU=n
CONFIG_DEBUG_LOCK_ALLOC=n
CONFIG_PROVE_LOCKING=n
CONFIG_RCU_BOOST=n
CONFIG_DEBUG_OBJECTS_RCU_HEAD=n
CONFIG_RCU_EXPERT=y
CONFIG_RCU_TRACE=y
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Folder" module="OFS.Folder"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_objects</string> </key>
<value>
<tuple/>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>MultiRelationStringField</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
---
title: "SHOW TABLES in Riak TS"
description: "Using the SHOW TABLES statement in Riak TS"
menu:
riak_ts-1.5.1:
name: "SHOW TABLES"
identifier: "show_tables_riakts"
weight: 300
parent: "querying_data_riakts"
project: "riak_ts"
project_version: "1.5.1"
toc: true
aliases:
- /riakts/1.5.1/using/querying/show-tables
canonical_link: "https://docs.basho.com/riak/ts/latest/using/querying/show-tables"
---
[riak shell]: /riak/ts/1.5.1/using/riakshell
You can use the SHOW TABLES statement to enumerate the Riak TS tables you have set up. This document will show you how to execute `SHOW TABLES` in TS.
The SHOW TABLES statement returns a list of tables you've created in a single column with one row per table name.
For example:
```sql
SHOW TABLES
```
Returns:
```sql
+---------------+------------+
| Table | Status |
+---------------+------------|
| RandomTable | Active |
| GeoCheckin | Active |
| UpcomingTable | Not Active |
|AnotherTable | Active |
| FinalTable | Active |
+---------------+------------+
```
You can use `SHOW TABLES` in [riak shell]:
```
riak-shell>show tables;
+---------------+------------+
| Table | Status |
+---------------+------------|
| RandomTable | Active |
| GeoCheckin | Active |
| UpcomingTable | Not Active |
|AnotherTable | Active |
| FinalTable | Active |
+---------------+------------+
```
Using TS's supported clients, a successful `SHOW TABLE` will return a regular successful query result:
```
+---------------+------------+
| Table | Status |
+---------------+------------|
| RandomTable | Active |
| GeoCheckin | Active |
| UpcomingTable | Not Active |
|AnotherTable | Active |
| FinalTable | Active |
+---------------+------------+
```
| {
"pile_set_name": "Github"
} |
D
| {
"pile_set_name": "Github"
} |
/*
* MaplyBasicClusterGenerator.java
* WhirlyGlobeLib
*
* Created by jmnavarro
* Copyright 2011-2014 mousebird consulting
*
* 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.mousebird.maply;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import java.awt.font.TextAttribute;
import java.util.HashMap;
/**
* The basic cluster generator installed by default.
* <p>
* This cluster generator will make images for grouped clusters of markers/labels.
*
*/
public class BasicClusterGenerator extends ClusterGenerator {
/**
* The ID number corresponding to the cluster. Every marker/label with this cluster ID will be grouped together.
*/
private int clusterNumber;
/**
* The size of the cluster that will be created.
* <p>
* This is the biggest cluster you're likely to create. We use it to figure overlaps between clusters.
*/
private Point2d clusterLayoutSize;
/**
* Set this if you want cluster to be user selectable. On by default.
*/
private boolean selectable;
/**
* How long to animate markers the join and leave a cluster
*/
private double markerAnimationTime;
/**
* The shader to use when moving objects around
* <p>
* When warping objects to their new locations we use a motion shader. Set this if you want to override the default.
*/
// private Shader motionShader;
private int[] colors;
private Bitmap bitmap;
private Point2d size;
//TODO Font still not supported
private TextAttribute font;
private float scale;
private float textSize = 0.f;
private HashMap<Integer, MaplyTexture> texByNumber;
private MaplyBaseController viewC;
private boolean correct = false;
private Activity activity;
/**
* Initialize with a list of colors.
* <p>
* Each order of magnitude will use another color. Must provide at least 1.
*/
public BasicClusterGenerator(int[] colors, int clusterNumber, Point2d markerSize, MaplyBaseController viewC, Activity activity) {
correct = (colors.length > 0);
if (!correct) {
return;
}
this.colors = colors;
this.size = markerSize;
this.clusterNumber = clusterNumber;
this.scale = 1;
this.activity = activity;
this.clusterLayoutSize = markerSize;
this.selectable = true;
this.markerAnimationTime = 0.2;
this.viewC = viewC;
}
public BasicClusterGenerator(Bitmap bitmap,int clusterNumber, Point2d markerSize,float textSize, MaplyBaseController viewC, Activity activity)
{
correct = true;
this.bitmap = bitmap;
this.size = markerSize;
this.textSize = textSize;
this.clusterNumber = clusterNumber;
this.scale = 1;
this.activity = activity;
this.clusterLayoutSize = markerSize;
this.selectable = true;
this.markerAnimationTime = 0.2;
this.viewC = viewC;
}
public void shutdown()
{
viewC = null;
activity = null;
}
@Override
public void startClusterGroup() {
super.startClusterGroup();
this.texByNumber = new HashMap<Integer, MaplyTexture>();
}
MaplyBaseController.TextureSettings texSettings = new MaplyBaseController.TextureSettings();
@Override
public ClusterGroup makeClusterGroup(ClusterInfo clusterInfo) {
if (!correct)
return null;
ClusterGroup group = new ClusterGroup();
MaplyTexture tex = this.texByNumber.get(clusterInfo.numObjects);
if (tex == null) {
//Note: Pick the color based on number of markers
//Create the Bitmap
Bitmap image = Bitmap.createBitmap((int) this.size.getX(), (int) this.size.getY(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(image);
//Configure Background
Paint background = new Paint();
if (this.colors != null) {
background.setColor(this.colors[0]);
background.setStyle(Paint.Style.FILL);
}
//Configure Stroke
Paint stroke = new Paint();
stroke.setColor(Color.WHITE);
stroke.setStyle(Paint.Style.STROKE);
//Configure Text
TextPaint text = new TextPaint();
text.setColor(Color.WHITE);
if (textSize != 0.0)
text.setTextSize(textSize);
else
text.setTextSize((float) (size.getX()/2));
text.setTextAlign(Paint.Align.CENTER);
if (this.colors != null) {
// Compute Circle Position
float x = (c.getWidth() / 2);
float y = (c.getHeight() / 2);
float radius = c.getWidth() / 2;
//Draw Circle and Stroke
c.drawCircle(x, y, radius, background);
c.drawCircle(x, y, radius, stroke);
} else {
c.drawBitmap(this.bitmap,new Rect(0,0,this.bitmap.getWidth(),this.bitmap.getHeight()),
new Rect(0,0,(int)this.size.getX(),(int)this.size.getY()),stroke);
}
// Compute Text Position
int xPos = (c.getWidth() / 2);
int yPos = (int) ((c.getHeight() / 2) - ((text.descent() + text.ascent()) / 2));
//Draw Text
c.drawText(Integer.toString(clusterInfo.numObjects), xPos, yPos, text);
tex = baseController.addTexture(image, texSettings, MaplyBaseController.ThreadMode.ThreadCurrent);
texByNumber.put(clusterInfo.numObjects, tex);
}
group.tex = tex;
group.size = this.size;
return group;
}
@Override
public void endClusterGroup() {
super.endClusterGroup();
this.texByNumber.clear();
this.texByNumber = null;
}
@Override
public int clusterNumber() {
return this.clusterNumber;
}
@Override
public Point2d clusterLayoutSize() {
return this.clusterLayoutSize;
}
@Override
public boolean selectable() {
return this.selectable;
}
@Override
public double markerAnimationTime() {
return this.markerAnimationTime;
}
// @Override
// public Shader motionShader() {
// return this.motionShader;
// }
}
| {
"pile_set_name": "Github"
} |
---
- name: stop metrics
include_tasks: stop_metrics.yaml
- name: remove metrics components
command: >
{{ openshift_client_binary }} -n {{ openshift_metrics_project }} --config={{ mktemp.stdout }}/admin.kubeconfig
delete --ignore-not-found --selector=metrics-infra
all,sa,secrets,templates,routes,pvc,rolebindings,clusterrolebindings,clusterrole
register: delete_metrics
changed_when: delete_metrics.stdout != 'No resources found'
- name: remove rolebindings
command: >
{{ openshift_client_binary }} -n {{ openshift_metrics_project }} --config={{ mktemp.stdout }}/admin.kubeconfig
delete --ignore-not-found
rolebinding/hawkular-view
clusterrolebinding/heapster-cluster-reader
clusterrolebinding/hawkular-metrics
changed_when: delete_metrics.stdout != 'No resources found'
# Update the web config in openshift-web-console namespace
- name: Remove metrics route information from the web console config
include_role:
name: openshift_web_console
tasks_from: update_console_config.yml
vars:
console_config_edits:
- key: clusterInfo#metricsPublicURL
value: ""
when:
- openshift_web_console_install | default(true) | bool
| {
"pile_set_name": "Github"
} |
var api = require('../../utils/api.js')
Page({
data: {
array: ['中国', '新加坡', '日本', '香港', '韩国', '台湾', '澳门'],
arrayNum: ['86', '65', '81', '852', '82', '886', '853'],
index: 0,
mobile: 0
},
onLoad () {
},
onPullDownRefresh () {
wx.stopPullDownRefresh()
},
bindPickerChange (e) {
this.setData({
index: e.detail.value
})
},
bindMobileInput (e) {
console.log(e.detail.value)
this.setData({
mobile: e.detail.value
})
},
bindGetVerification () {
let that = this
api.post(api.GET_VERIFICATION, {
area: parseInt(this.data.arrayNum[this.data.index]),
mobile: parseInt(this.data.mobile),
type: 'sign'
}).then(res => {
console.log(res)
// 后台验证了来源,故无法获取正确返回
})
},
formSubmit: function(e) {
console.log(e.detail.value)
}
})
| {
"pile_set_name": "Github"
} |
package token
import "fmt"
// Pos describes an arbitrary source position
// including the file, line, and column location.
// A Position is valid if the line number is > 0.
type Pos struct {
Filename string // filename, if any
Offset int // offset, starting at 0
Line int // line number, starting at 1
Column int // column number, starting at 1 (character count)
}
// IsValid returns true if the position is valid.
func (p *Pos) IsValid() bool { return p.Line > 0 }
// String returns a string in one of several forms:
//
// file:line:column valid position with file name
// line:column valid position without file name
// file invalid position with file name
// - invalid position without file name
func (p Pos) String() string {
s := p.Filename
if p.IsValid() {
if s != "" {
s += ":"
}
s += fmt.Sprintf("%d:%d", p.Line, p.Column)
}
if s == "" {
s = "-"
}
return s
}
// Before reports whether the position p is before u.
func (p Pos) Before(u Pos) bool {
return u.Offset > p.Offset || u.Line > p.Line
}
// After reports whether the position p is after u.
func (p Pos) After(u Pos) bool {
return u.Offset < p.Offset || u.Line < p.Line
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
module ooo { module vba { module word {
constants WdEnableCancelKey {
const long wdCancelDisabled = 0;
const long wdCancelInterrupt = 1;
};
}; }; };
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| {
"pile_set_name": "Github"
} |
//
// AppDelegate.h
// LearnOpenGLES
//
// Created by loyinglin on 16/5/10.
// Copyright © 2016年 loyinglin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2015 Kaprica Security, Inc.
*
* 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.
*
*/
#ifndef STRING_H_
#define STRING_H_
#include "cgc_stdlib.h"
void *cgc_memcpy(void *dst, const void *src, cgc_size_t n);
void *cgc_memmove(void *dst, const void *src, cgc_size_t n);
int cgc_memcmp(const void *s1, const void *s2, cgc_size_t n);
void *cgc_memchr(const void *s, int c, cgc_size_t n);
void *cgc_memset(void *s, int c, cgc_size_t n);
cgc_size_t cgc_strlen(const char *s);
char *cgc_strcpy(char *dst, const char *src);
char *cgc_strncpy(char *dst, const char *src, cgc_size_t len);
char *cgc_strchr(const char *s, int c);
char *cgc_strsep(char **stringp, const char *delim);
char *cgc_strstr(const char *haystack, const char *needle);
char *cgc_strcasestr(const char *haystack, const char *needle);
int cgc_strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, cgc_size_t n);
int strcasecmp(const char *s1, const char *s2);
int cgc_strncasecmp(const char *s1, const char *s2, cgc_size_t n);
char *cgc_strdup(const char *s1);
char *cgc_strndup(const char *s1, cgc_size_t n);
#endif
| {
"pile_set_name": "Github"
} |
# debug
tiny node.js debugging utility modelled after node core's debugging technique.
## Installation
```
$ npm install debug
```
## Usage
With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.
Example _app.js_:
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %s', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example _worker.js_:
```js
var debug = require('debug')('worker');
setInterval(function(){
debug('doing some work');
}, 1000);
```
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:


## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.

When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:

## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:".
## Browser support
Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
a('doing some work');
}, 1200);
```
## License
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <[email protected]>
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.
| {
"pile_set_name": "Github"
} |
package config
import (
"bytes"
"fmt"
"sort"
"strings"
)
// TestString is a Stringer-like function that outputs a string that can
// be used to easily compare multiple Config structures in unit tests.
//
// This function has no practical use outside of unit tests and debugging.
func (c *Config) TestString() string {
if c == nil {
return "<nil config>"
}
var buf bytes.Buffer
if len(c.Modules) > 0 {
buf.WriteString("Modules:\n\n")
buf.WriteString(modulesStr(c.Modules))
buf.WriteString("\n\n")
}
if len(c.Variables) > 0 {
buf.WriteString("Variables:\n\n")
buf.WriteString(variablesStr(c.Variables))
buf.WriteString("\n\n")
}
if len(c.ProviderConfigs) > 0 {
buf.WriteString("Provider Configs:\n\n")
buf.WriteString(providerConfigsStr(c.ProviderConfigs))
buf.WriteString("\n\n")
}
if len(c.Resources) > 0 {
buf.WriteString("Resources:\n\n")
buf.WriteString(resourcesStr(c.Resources))
buf.WriteString("\n\n")
}
if len(c.Outputs) > 0 {
buf.WriteString("Outputs:\n\n")
buf.WriteString(outputsStr(c.Outputs))
buf.WriteString("\n")
}
return strings.TrimSpace(buf.String())
}
func modulesStr(ms []*Module) string {
result := ""
order := make([]int, 0, len(ms))
ks := make([]string, 0, len(ms))
mapping := make(map[string]int)
for i, m := range ms {
k := m.Id()
ks = append(ks, k)
mapping[k] = i
}
sort.Strings(ks)
for _, k := range ks {
order = append(order, mapping[k])
}
for _, i := range order {
m := ms[i]
result += fmt.Sprintf("%s\n", m.Id())
ks := make([]string, 0, len(m.RawConfig.Raw))
for k, _ := range m.RawConfig.Raw {
ks = append(ks, k)
}
sort.Strings(ks)
result += fmt.Sprintf(" source = %s\n", m.Source)
for _, k := range ks {
result += fmt.Sprintf(" %s\n", k)
}
}
return strings.TrimSpace(result)
}
func outputsStr(os []*Output) string {
ns := make([]string, 0, len(os))
m := make(map[string]*Output)
for _, o := range os {
ns = append(ns, o.Name)
m[o.Name] = o
}
sort.Strings(ns)
result := ""
for _, n := range ns {
o := m[n]
result += fmt.Sprintf("%s\n", n)
if len(o.RawConfig.Variables) > 0 {
result += fmt.Sprintf(" vars\n")
for _, rawV := range o.RawConfig.Variables {
kind := "unknown"
str := rawV.FullKey()
switch rawV.(type) {
case *ResourceVariable:
kind = "resource"
case *UserVariable:
kind = "user"
}
result += fmt.Sprintf(" %s: %s\n", kind, str)
}
}
}
return strings.TrimSpace(result)
}
// This helper turns a provider configs field into a deterministic
// string value for comparison in tests.
func providerConfigsStr(pcs []*ProviderConfig) string {
result := ""
ns := make([]string, 0, len(pcs))
m := make(map[string]*ProviderConfig)
for _, n := range pcs {
ns = append(ns, n.Name)
m[n.Name] = n
}
sort.Strings(ns)
for _, n := range ns {
pc := m[n]
result += fmt.Sprintf("%s\n", n)
keys := make([]string, 0, len(pc.RawConfig.Raw))
for k, _ := range pc.RawConfig.Raw {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
result += fmt.Sprintf(" %s\n", k)
}
if len(pc.RawConfig.Variables) > 0 {
result += fmt.Sprintf(" vars\n")
for _, rawV := range pc.RawConfig.Variables {
kind := "unknown"
str := rawV.FullKey()
switch rawV.(type) {
case *ResourceVariable:
kind = "resource"
case *UserVariable:
kind = "user"
}
result += fmt.Sprintf(" %s: %s\n", kind, str)
}
}
}
return strings.TrimSpace(result)
}
// This helper turns a resources field into a deterministic
// string value for comparison in tests.
func resourcesStr(rs []*Resource) string {
result := ""
order := make([]int, 0, len(rs))
ks := make([]string, 0, len(rs))
mapping := make(map[string]int)
for i, r := range rs {
k := r.Id()
ks = append(ks, k)
mapping[k] = i
}
sort.Strings(ks)
for _, k := range ks {
order = append(order, mapping[k])
}
for _, i := range order {
r := rs[i]
result += fmt.Sprintf(
"%s (x%s)\n",
r.Id(),
r.RawCount.Value())
ks := make([]string, 0, len(r.RawConfig.Raw))
for k, _ := range r.RawConfig.Raw {
ks = append(ks, k)
}
sort.Strings(ks)
for _, k := range ks {
result += fmt.Sprintf(" %s\n", k)
}
if len(r.Provisioners) > 0 {
result += fmt.Sprintf(" provisioners\n")
for _, p := range r.Provisioners {
result += fmt.Sprintf(" %s\n", p.Type)
ks := make([]string, 0, len(p.RawConfig.Raw))
for k, _ := range p.RawConfig.Raw {
ks = append(ks, k)
}
sort.Strings(ks)
for _, k := range ks {
result += fmt.Sprintf(" %s\n", k)
}
}
}
if len(r.DependsOn) > 0 {
result += fmt.Sprintf(" dependsOn\n")
for _, d := range r.DependsOn {
result += fmt.Sprintf(" %s\n", d)
}
}
if len(r.RawConfig.Variables) > 0 {
result += fmt.Sprintf(" vars\n")
ks := make([]string, 0, len(r.RawConfig.Variables))
for k, _ := range r.RawConfig.Variables {
ks = append(ks, k)
}
sort.Strings(ks)
for _, k := range ks {
rawV := r.RawConfig.Variables[k]
kind := "unknown"
str := rawV.FullKey()
switch rawV.(type) {
case *ResourceVariable:
kind = "resource"
case *UserVariable:
kind = "user"
}
result += fmt.Sprintf(" %s: %s\n", kind, str)
}
}
}
return strings.TrimSpace(result)
}
// This helper turns a variables field into a deterministic
// string value for comparison in tests.
func variablesStr(vs []*Variable) string {
result := ""
ks := make([]string, 0, len(vs))
m := make(map[string]*Variable)
for _, v := range vs {
ks = append(ks, v.Name)
m[v.Name] = v
}
sort.Strings(ks)
for _, k := range ks {
v := m[k]
required := ""
if v.Required() {
required = " (required)"
}
declaredType := ""
if v.DeclaredType != "" {
declaredType = fmt.Sprintf(" (%s)", v.DeclaredType)
}
if v.Default == nil || v.Default == "" {
v.Default = "<>"
}
if v.Description == "" {
v.Description = "<>"
}
result += fmt.Sprintf(
"%s%s%s\n %v\n %s\n",
k,
required,
declaredType,
v.Default,
v.Description)
}
return strings.TrimSpace(result)
}
| {
"pile_set_name": "Github"
} |
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to 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)
#ifndef BOOST_GEOMETRY_GEOMETRIES_REGISTER_SEGMENT_HPP
#define BOOST_GEOMETRY_GEOMETRIES_REGISTER_SEGMENT_HPP
#ifndef DOXYGEN_NO_SPECIALIZATIONS
#define BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_ACCESS(Segment, Point, Index0, Index1) \
template <size_t D> \
struct indexed_access<Segment, min_corner, D> \
{ \
typedef typename coordinate_type<Point>::type ct; \
static inline ct get(Segment const& b) \
{ return geometry::get<D>(b. Index0); } \
static inline void set(Segment& b, ct const& value) \
{ geometry::set<D>(b. Index0, value); } \
}; \
template <size_t D> \
struct indexed_access<Segment, max_corner, D> \
{ \
typedef typename coordinate_type<Point>::type ct; \
static inline ct get(Segment const& b) \
{ return geometry::get<D>(b. Index1); } \
static inline void set(Segment& b, ct const& value) \
{ geometry::set<D>(b. Index1, value); } \
};
#define BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_ACCESS_TEMPLATIZED(Segment, Index0, Index1) \
template <typename P, size_t D> \
struct indexed_access<Segment<P>, min_corner, D> \
{ \
typedef typename coordinate_type<P>::type ct; \
static inline ct get(Segment<P> const& b) \
{ return geometry::get<D>(b. Index0); } \
static inline void set(Segment<P>& b, ct const& value) \
{ geometry::set<D>(b. Index0, value); } \
}; \
template <typename P, size_t D> \
struct indexed_access<Segment<P>, max_corner, D> \
{ \
typedef typename coordinate_type<P>::type ct; \
static inline ct get(Segment<P> const& b) \
{ return geometry::get<D>(b. Index1); } \
static inline void set(Segment<P>& b, ct const& value) \
{ geometry::set<D>(b. Index1, value); } \
};
#define BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_ACCESS_4VALUES(Segment, Point, Left, Bottom, Right, Top) \
template <> struct indexed_access<Segment, min_corner, 0> \
{ \
typedef coordinate_type<Point>::type ct; \
static inline ct get(Segment const& b) { return b. Left; } \
static inline void set(Segment& b, ct const& value) { b. Left = value; } \
}; \
template <> struct indexed_access<Segment, min_corner, 1> \
{ \
typedef coordinate_type<Point>::type ct; \
static inline ct get(Segment const& b) { return b. Bottom; } \
static inline void set(Segment& b, ct const& value) { b. Bottom = value; } \
}; \
template <> struct indexed_access<Segment, max_corner, 0> \
{ \
typedef coordinate_type<Point>::type ct; \
static inline ct get(Segment const& b) { return b. Right; } \
static inline void set(Segment& b, ct const& value) { b. Right = value; } \
}; \
template <> struct indexed_access<Segment, max_corner, 1> \
{ \
typedef coordinate_type<Point>::type ct; \
static inline ct get(Segment const& b) { return b. Top; } \
static inline void set(Segment& b, ct const& value) { b. Top = value; } \
};
#define BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_TRAITS(Segment, PointType) \
template<> struct tag<Segment > { typedef segment_tag type; }; \
template<> struct point_type<Segment > { typedef PointType type; };
#define BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_TRAITS_TEMPLATIZED(Segment) \
template<typename P> struct tag<Segment<P> > { typedef segment_tag type; }; \
template<typename P> struct point_type<Segment<P> > { typedef P type; };
#endif // DOXYGEN_NO_SPECIALIZATIONS
#define BOOST_GEOMETRY_REGISTER_SEGMENT(Segment, PointType, Index0, Index1) \
namespace boost { namespace geometry { namespace traits { \
BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_TRAITS(Segment, PointType) \
BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_ACCESS(Segment, PointType, Index0, Index1) \
}}}
#define BOOST_GEOMETRY_REGISTER_SEGMENT_TEMPLATIZED(Segment, Index0, Index1) \
namespace boost { namespace geometry { namespace traits { \
BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_TRAITS_TEMPLATIZED(Segment) \
BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_ACCESS_TEMPLATIZED(Segment, Index0, Index1) \
}}}
#define BOOST_GEOMETRY_REGISTER_SEGMENT_2D_4VALUES(Segment, PointType, Left, Bottom, Right, Top) \
namespace boost { namespace geometry { namespace traits { \
BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_TRAITS(Segment, PointType) \
BOOST_GEOMETRY_DETAIL_SPECIALIZE_SEGMENT_ACCESS_4VALUES(Segment, PointType, Left, Bottom, Right, Top) \
}}}
// CONST versions are for segments probably not that common. Postponed.
#endif // BOOST_GEOMETRY_GEOMETRIES_REGISTER_SEGMENT_HPP
| {
"pile_set_name": "Github"
} |
# coding: utf-8
"""
webencodings
~~~~~~~~~~~~
This is a Python implementation of the `WHATWG Encoding standard
<http://encoding.spec.whatwg.org/>`. See README for details.
:copyright: Copyright 2012 by Simon Sapin
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
import codecs
from .labels import LABELS
VERSION = '0.5.1'
# Some names in Encoding are not valid Python aliases. Remap these.
PYTHON_NAMES = {
'iso-8859-8-i': 'iso-8859-8',
'x-mac-cyrillic': 'mac-cyrillic',
'macintosh': 'mac-roman',
'windows-874': 'cp874'}
CACHE = {}
def ascii_lower(string):
r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.
:param string: An Unicode string.
:returns: A new Unicode string.
This is used for `ASCII case-insensitive
<http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_
matching of encoding labels.
The same matching is also used, among other things,
for `CSS keywords <http://dev.w3.org/csswg/css-values/#keywords>`_.
This is different from the :meth:`~py:str.lower` method of Unicode strings
which also affect non-ASCII characters,
sometimes mapping them into the ASCII range:
>>> keyword = u'Bac\N{KELVIN SIGN}ground'
>>> assert keyword.lower() == u'background'
>>> assert ascii_lower(keyword) != keyword.lower()
>>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground'
"""
# This turns out to be faster than unicode.translate()
return string.encode('utf8').lower().decode('utf8')
def lookup(label):
"""
Look for an encoding by its label.
This is the spec’s `get an encoding
<http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm.
Supported labels are listed there.
:param label: A string.
:returns:
An :class:`Encoding` object, or :obj:`None` for an unknown label.
"""
# Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020.
label = ascii_lower(label.strip('\t\n\f\r '))
name = LABELS.get(label)
if name is None:
return None
encoding = CACHE.get(name)
if encoding is None:
if name == 'x-user-defined':
from .x_user_defined import codec_info
else:
python_name = PYTHON_NAMES.get(name, name)
# Any python_name value that gets to here should be valid.
codec_info = codecs.lookup(python_name)
encoding = Encoding(name, codec_info)
CACHE[name] = encoding
return encoding
def _get_encoding(encoding_or_label):
"""
Accept either an encoding object or label.
:param encoding: An :class:`Encoding` object or a label string.
:returns: An :class:`Encoding` object.
:raises: :exc:`~exceptions.LookupError` for an unknown label.
"""
if hasattr(encoding_or_label, 'codec_info'):
return encoding_or_label
encoding = lookup(encoding_or_label)
if encoding is None:
raise LookupError('Unknown encoding label: %r' % encoding_or_label)
return encoding
class Encoding(object):
"""Reresents a character encoding such as UTF-8,
that can be used for decoding or encoding.
.. attribute:: name
Canonical name of the encoding
.. attribute:: codec_info
The actual implementation of the encoding,
a stdlib :class:`~codecs.CodecInfo` object.
See :func:`codecs.register`.
"""
def __init__(self, name, codec_info):
self.name = name
self.codec_info = codec_info
def __repr__(self):
return '<Encoding %s>' % self.name
#: The UTF-8 encoding. Should be used for new content and formats.
UTF8 = lookup('utf-8')
_UTF16LE = lookup('utf-16le')
_UTF16BE = lookup('utf-16be')
def decode(input, fallback_encoding, errors='replace'):
"""
Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:return:
A ``(output, encoding)`` tuple of an Unicode string
and an :obj:`Encoding`.
"""
# Fail early if `encoding` is an invalid label.
fallback_encoding = _get_encoding(fallback_encoding)
bom_encoding, input = _detect_bom(input)
encoding = bom_encoding or fallback_encoding
return encoding.codec_info.decode(input, errors)[0], encoding
def _detect_bom(input):
"""Return (bom_encoding, input), with any BOM removed from the input."""
if input.startswith(b'\xFF\xFE'):
return _UTF16LE, input[2:]
if input.startswith(b'\xFE\xFF'):
return _UTF16BE, input[2:]
if input.startswith(b'\xEF\xBB\xBF'):
return UTF8, input[3:]
return None, input
def encode(input, encoding=UTF8, errors='strict'):
"""
Encode a single string.
:param input: An Unicode string.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:return: A byte string.
"""
return _get_encoding(encoding).codec_info.encode(input, errors)[0]
def iter_decode(input, fallback_encoding, errors='replace'):
"""
"Pull"-based decoder.
:param input:
An iterable of byte strings.
The input is first consumed just enough to determine the encoding
based on the precense of a BOM,
then consumed on demand when the return value is.
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:returns:
An ``(output, encoding)`` tuple.
:obj:`output` is an iterable of Unicode strings,
:obj:`encoding` is the :obj:`Encoding` that is being used.
"""
decoder = IncrementalDecoder(fallback_encoding, errors)
generator = _iter_decode_generator(input, decoder)
encoding = next(generator)
return generator, encoding
def _iter_decode_generator(input, decoder):
"""Return a generator that first yields the :obj:`Encoding`,
then yields output chukns as Unicode strings.
"""
decode = decoder.decode
input = iter(input)
for chunck in input:
output = decode(chunck)
if output:
assert decoder.encoding is not None
yield decoder.encoding
yield output
break
else:
# Input exhausted without determining the encoding
output = decode(b'', final=True)
assert decoder.encoding is not None
yield decoder.encoding
if output:
yield output
return
for chunck in input:
output = decode(chunck)
if output:
yield output
output = decode(b'', final=True)
if output:
yield output
def iter_encode(input, encoding=UTF8, errors='strict'):
"""
“Pull”-based encoder.
:param input: An iterable of Unicode strings.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:returns: An iterable of byte strings.
"""
# Fail early if `encoding` is an invalid label.
encode = IncrementalEncoder(encoding, errors).encode
return _iter_encode_generator(input, encode)
def _iter_encode_generator(input, encode):
for chunck in input:
output = encode(chunck)
if output:
yield output
output = encode('', final=True)
if output:
yield output
class IncrementalDecoder(object):
"""
“Push”-based decoder.
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
"""
def __init__(self, fallback_encoding, errors='replace'):
# Fail early if `encoding` is an invalid label.
self._fallback_encoding = _get_encoding(fallback_encoding)
self._errors = errors
self._buffer = b''
self._decoder = None
#: The actual :class:`Encoding` that is being used,
#: or :obj:`None` if that is not determined yet.
#: (Ie. if there is not enough input yet to determine
#: if there is a BOM.)
self.encoding = None # Not known yet.
def decode(self, input, final=False):
"""Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
"""
decoder = self._decoder
if decoder is not None:
return decoder(input, final)
input = self._buffer + input
encoding, input = _detect_bom(input)
if encoding is None:
if len(input) < 3 and not final: # Not enough data yet.
self._buffer = input
return ''
else: # No BOM
encoding = self._fallback_encoding
decoder = encoding.codec_info.incrementaldecoder(self._errors).decode
self._decoder = decoder
self.encoding = encoding
return decoder(input, final)
class IncrementalEncoder(object):
"""
“Push”-based encoder.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
.. method:: encode(input, final=False)
:param input: An Unicode string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: A byte string.
"""
def __init__(self, encoding=UTF8, errors='strict'):
encoding = _get_encoding(encoding)
self.encode = encoding.codec_info.incrementalencoder(errors).encode
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
import sys
import socket
import selectors
import types
sel = selectors.DefaultSelector()
messages = [b"Message 1 from client.", b"Message 2 from client."]
def start_connections(host, port, num_conns):
server_addr = (host, port)
for i in range(0, num_conns):
connid = i + 1
print("starting connection", connid, "to", server_addr)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
sock.connect_ex(server_addr)
events = selectors.EVENT_READ | selectors.EVENT_WRITE
data = types.SimpleNamespace(
connid=connid,
msg_total=sum(len(m) for m in messages),
recv_total=0,
messages=list(messages),
outb=b"",
)
sel.register(sock, events, data=data)
def service_connection(key, mask):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024) # Should be ready to read
if recv_data:
print("received", repr(recv_data), "from connection", data.connid)
data.recv_total += len(recv_data)
if not recv_data or data.recv_total == data.msg_total:
print("closing connection", data.connid)
sel.unregister(sock)
sock.close()
if mask & selectors.EVENT_WRITE:
if not data.outb and data.messages:
data.outb = data.messages.pop(0)
if data.outb:
print("sending", repr(data.outb), "to connection", data.connid)
sent = sock.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]
if len(sys.argv) != 4:
print("usage:", sys.argv[0], "<host> <port> <num_connections>")
sys.exit(1)
host, port, num_conns = sys.argv[1:4]
start_connections(host, int(port), int(num_conns))
try:
while True:
events = sel.select(timeout=1)
if events:
for key, mask in events:
service_connection(key, mask)
# Check for a socket being monitored to continue.
if not sel.get_map():
break
except KeyboardInterrupt:
print("caught keyboard interrupt, exiting")
finally:
sel.close()
| {
"pile_set_name": "Github"
} |
# Copyright 2019 Google LLC
#
# 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.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Api.RemarketingListShares do
@moduledoc """
API calls for all endpoints tagged `RemarketingListShares`.
"""
alias GoogleApi.DFAReporting.V34.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets one remarketing list share by remarketing list ID.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V34.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `remarketing_list_id` (*type:* `String.t`) - Remarketing list ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V34.Model.RemarketingListShare{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_remarketing_list_shares_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V34.Model.RemarketingListShare.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_remarketing_list_shares_get(
connection,
profile_id,
remarketing_list_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/dfareporting/v3.4/userprofiles/{profileId}/remarketingListShares/{remarketingListId}",
%{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1),
"remarketingListId" =>
URI.encode(remarketing_list_id, &(URI.char_unreserved?(&1) || &1 == ?/))
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V34.Model.RemarketingListShare{}])
end
@doc """
Updates an existing remarketing list share. This method supports patch semantics.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V34.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - RemarketingList ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DFAReporting.V34.Model.RemarketingListShare.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V34.Model.RemarketingListShare{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_remarketing_list_shares_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V34.Model.RemarketingListShare.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_remarketing_list_shares_patch(
connection,
profile_id,
id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/dfareporting/v3.4/userprofiles/{profileId}/remarketingListShares", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :id, id)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V34.Model.RemarketingListShare{}])
end
@doc """
Updates an existing remarketing list share.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V34.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DFAReporting.V34.Model.RemarketingListShare.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V34.Model.RemarketingListShare{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_remarketing_list_shares_update(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V34.Model.RemarketingListShare.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_remarketing_list_shares_update(
connection,
profile_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/dfareporting/v3.4/userprofiles/{profileId}/remarketingListShares", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V34.Model.RemarketingListShare{}])
end
end
| {
"pile_set_name": "Github"
} |
{-# OPTIONS --without-K --rewriting --confluence-check #-}
postulate
_↦_ : ∀ {i} {A : Set i} → A → A → Set i
idr : ∀ {i} {A : Set i} {a : A} → a ↦ a
{-# BUILTIN REWRITE _↦_ #-}
data _==_ {i} {A : Set i} (a : A) : A → Set i where
idp : a == a
PathOver : ∀ {i j} {A : Set i} (B : A → Set j)
{x y : A} (p : x == y) (u : B x) (v : B y) → Set j
PathOver B idp u v = (u == v)
syntax PathOver B p u v =
u == v [ B ↓ p ]
postulate
PathOver-rewr : ∀ {i j} {A : Set i} {B : Set j} {x y : A} (p : x == y) (u v : B) →
(PathOver (λ _ → B) p u v) ↦ (u == v)
{-# REWRITE PathOver-rewr #-}
ap : ∀ {i j} {A : Set i} {B : A → Set j} (f : (a : A) → B a) {x y : A}
→ (p : x == y) → PathOver B p (f x) (f y)
ap f idp = idp
postulate
Circle : Set
base : Circle
loop : base == base
module _ {i} {P : Circle → Set i} (base* : P base) (loop* : base* == base* [ P ↓ loop ])
where
postulate
Circle-elim : (x : Circle) → P x
Circle-base-β : Circle-elim base ↦ base*
{-# REWRITE Circle-base-β #-}
Circle-loop-β : ap Circle-elim loop ↦ loop*
{-# REWRITE Circle-loop-β #-}
idCircle : Circle → Circle
idCircle = Circle-elim base loop
| {
"pile_set_name": "Github"
} |
/* Instrument.java -- A MIDI Instrument
Copyright (C) 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.sound.midi;
/**
* The abstract base class for all MIDI instruments.
*
* @author Anthony Green ([email protected])
* @since 1.3
*
*/
public abstract class Instrument extends SoundbankResource
{
// The instrument patch.
private Patch patch;
/**
* Create a new Instrument.
*
* @param soundbank the Soundbank containing the instrument.
* @param patch the patch for this instrument
* @param name the name of this instrument
* @param dataClass the class used to represent sample data for this instrument
*/
protected Instrument(Soundbank soundbank, Patch patch,
String name, Class<?> dataClass)
{
super(soundbank, name, dataClass);
this.patch = patch;
}
/**
* Get the patch for this instrument.
*
* @return the patch for this instrument
*/
public Patch getPatch()
{
return patch;
}
}
| {
"pile_set_name": "Github"
} |
kind: Namespace
apiVersion: v1
metadata:
name: harbor
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 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.
*/
package com.google.maps.android.clustering;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.algo.StaticCluster;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame;
public class StaticClusterTest {
@Test
public void testEquality() {
StaticCluster<ClusterItem> cluster1 = new StaticCluster<>(new LatLng(0.1, 0.5));
StaticCluster<ClusterItem> cluster2 = new StaticCluster<>(new LatLng(0.1, 0.5));
assertEquals(cluster1, cluster2);
assertNotSame(cluster1, cluster2);
assertEquals(cluster1.hashCode(), cluster2.hashCode());
}
@Test
public void testUnequality() {
StaticCluster<ClusterItem> cluster1 = new StaticCluster<>(new LatLng(0.1, 0.5));
StaticCluster<ClusterItem> cluster2 = new StaticCluster<>(new LatLng(0.2, 0.3));
assertNotEquals(cluster1, cluster2);
assertNotEquals(cluster1.hashCode(), cluster2.hashCode());
}
}
| {
"pile_set_name": "Github"
} |
export default function isDate(input) {
return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}
| {
"pile_set_name": "Github"
} |
/*
* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL project
* 2006.
*/
/* ====================================================================
* Copyright (c) 2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include <openssl/dh.h>
#include <openssl/bn.h>
#include "asn1_locl.h"
#ifndef OPENSSL_NO_CMS
# include <openssl/cms.h>
#endif
extern const EVP_PKEY_ASN1_METHOD dhx_asn1_meth;
/*
* i2d/d2i like DH parameter functions which use the appropriate routine for
* PKCS#3 DH or X9.42 DH.
*/
static DH *d2i_dhp(const EVP_PKEY *pkey, const unsigned char **pp,
long length)
{
if (pkey->ameth == &dhx_asn1_meth)
return d2i_DHxparams(NULL, pp, length);
return d2i_DHparams(NULL, pp, length);
}
static int i2d_dhp(const EVP_PKEY *pkey, const DH *a, unsigned char **pp)
{
if (pkey->ameth == &dhx_asn1_meth)
return i2d_DHxparams(a, pp);
return i2d_DHparams(a, pp);
}
static void int_dh_free(EVP_PKEY *pkey)
{
DH_free(pkey->pkey.dh);
}
static int dh_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
{
const unsigned char *p, *pm;
int pklen, pmlen;
int ptype;
void *pval;
ASN1_STRING *pstr;
X509_ALGOR *palg;
ASN1_INTEGER *public_key = NULL;
DH *dh = NULL;
if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
return 0;
X509_ALGOR_get0(NULL, &ptype, &pval, palg);
if (ptype != V_ASN1_SEQUENCE) {
DHerr(DH_F_DH_PUB_DECODE, DH_R_PARAMETER_ENCODING_ERROR);
goto err;
}
pstr = pval;
pm = pstr->data;
pmlen = pstr->length;
if (!(dh = d2i_dhp(pkey, &pm, pmlen))) {
DHerr(DH_F_DH_PUB_DECODE, DH_R_DECODE_ERROR);
goto err;
}
if (!(public_key = d2i_ASN1_INTEGER(NULL, &p, pklen))) {
DHerr(DH_F_DH_PUB_DECODE, DH_R_DECODE_ERROR);
goto err;
}
/* We have parameters now set public key */
if (!(dh->pub_key = ASN1_INTEGER_to_BN(public_key, NULL))) {
DHerr(DH_F_DH_PUB_DECODE, DH_R_BN_DECODE_ERROR);
goto err;
}
ASN1_INTEGER_free(public_key);
EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh);
return 1;
err:
if (public_key)
ASN1_INTEGER_free(public_key);
if (dh)
DH_free(dh);
return 0;
}
static int dh_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
{
DH *dh;
int ptype;
unsigned char *penc = NULL;
int penclen;
ASN1_STRING *str;
ASN1_INTEGER *pub_key = NULL;
dh = pkey->pkey.dh;
str = ASN1_STRING_new();
if (!str) {
DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
goto err;
}
str->length = i2d_dhp(pkey, dh, &str->data);
if (str->length <= 0) {
DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
goto err;
}
ptype = V_ASN1_SEQUENCE;
pub_key = BN_to_ASN1_INTEGER(dh->pub_key, NULL);
if (!pub_key)
goto err;
penclen = i2d_ASN1_INTEGER(pub_key, &penc);
ASN1_INTEGER_free(pub_key);
if (penclen <= 0) {
DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
goto err;
}
if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id),
ptype, str, penc, penclen))
return 1;
err:
if (penc)
OPENSSL_free(penc);
if (str)
ASN1_STRING_free(str);
return 0;
}
/*
* PKCS#8 DH is defined in PKCS#11 of all places. It is similar to DH in that
* the AlgorithmIdentifier contains the paramaters, the private key is
* explcitly included and the pubkey must be recalculated.
*/
static int dh_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
{
const unsigned char *p, *pm;
int pklen, pmlen;
int ptype;
void *pval;
ASN1_STRING *pstr;
X509_ALGOR *palg;
ASN1_INTEGER *privkey = NULL;
DH *dh = NULL;
if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
return 0;
X509_ALGOR_get0(NULL, &ptype, &pval, palg);
if (ptype != V_ASN1_SEQUENCE)
goto decerr;
if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)))
goto decerr;
pstr = pval;
pm = pstr->data;
pmlen = pstr->length;
if (!(dh = d2i_dhp(pkey, &pm, pmlen)))
goto decerr;
/* We have parameters now set private key */
if (!(dh->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) {
DHerr(DH_F_DH_PRIV_DECODE, DH_R_BN_ERROR);
goto dherr;
}
/* Calculate public key */
if (!DH_generate_key(dh))
goto dherr;
EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh);
ASN1_STRING_clear_free(privkey);
return 1;
decerr:
DHerr(DH_F_DH_PRIV_DECODE, EVP_R_DECODE_ERROR);
dherr:
DH_free(dh);
ASN1_STRING_clear_free(privkey);
return 0;
}
static int dh_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
{
ASN1_STRING *params = NULL;
ASN1_INTEGER *prkey = NULL;
unsigned char *dp = NULL;
int dplen;
params = ASN1_STRING_new();
if (!params) {
DHerr(DH_F_DH_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
goto err;
}
params->length = i2d_dhp(pkey, pkey->pkey.dh, ¶ms->data);
if (params->length <= 0) {
DHerr(DH_F_DH_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
goto err;
}
params->type = V_ASN1_SEQUENCE;
/* Get private key into integer */
prkey = BN_to_ASN1_INTEGER(pkey->pkey.dh->priv_key, NULL);
if (!prkey) {
DHerr(DH_F_DH_PRIV_ENCODE, DH_R_BN_ERROR);
goto err;
}
dplen = i2d_ASN1_INTEGER(prkey, &dp);
ASN1_STRING_clear_free(prkey);
prkey = NULL;
if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0,
V_ASN1_SEQUENCE, params, dp, dplen))
goto err;
return 1;
err:
if (dp != NULL)
OPENSSL_free(dp);
if (params != NULL)
ASN1_STRING_free(params);
if (prkey != NULL)
ASN1_STRING_clear_free(prkey);
return 0;
}
static void update_buflen(const BIGNUM *b, size_t *pbuflen)
{
size_t i;
if (!b)
return;
if (*pbuflen < (i = (size_t)BN_num_bytes(b)))
*pbuflen = i;
}
static int dh_param_decode(EVP_PKEY *pkey,
const unsigned char **pder, int derlen)
{
DH *dh;
if (!(dh = d2i_dhp(pkey, pder, derlen))) {
DHerr(DH_F_DH_PARAM_DECODE, ERR_R_DH_LIB);
return 0;
}
EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh);
return 1;
}
static int dh_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
{
return i2d_dhp(pkey, pkey->pkey.dh, pder);
}
static int do_dh_print(BIO *bp, const DH *x, int indent,
ASN1_PCTX *ctx, int ptype)
{
unsigned char *m = NULL;
int reason = ERR_R_BUF_LIB, ret = 0;
size_t buf_len = 0;
const char *ktype = NULL;
BIGNUM *priv_key, *pub_key;
if (ptype == 2)
priv_key = x->priv_key;
else
priv_key = NULL;
if (ptype > 0)
pub_key = x->pub_key;
else
pub_key = NULL;
update_buflen(x->p, &buf_len);
if (buf_len == 0) {
reason = ERR_R_PASSED_NULL_PARAMETER;
goto err;
}
update_buflen(x->g, &buf_len);
update_buflen(x->q, &buf_len);
update_buflen(x->j, &buf_len);
update_buflen(x->counter, &buf_len);
update_buflen(pub_key, &buf_len);
update_buflen(priv_key, &buf_len);
if (ptype == 2)
ktype = "DH Private-Key";
else if (ptype == 1)
ktype = "DH Public-Key";
else
ktype = "DH Parameters";
m = OPENSSL_malloc(buf_len + 10);
if (m == NULL) {
reason = ERR_R_MALLOC_FAILURE;
goto err;
}
BIO_indent(bp, indent, 128);
if (BIO_printf(bp, "%s: (%d bit)\n", ktype, BN_num_bits(x->p)) <= 0)
goto err;
indent += 4;
if (!ASN1_bn_print(bp, "private-key:", priv_key, m, indent))
goto err;
if (!ASN1_bn_print(bp, "public-key:", pub_key, m, indent))
goto err;
if (!ASN1_bn_print(bp, "prime:", x->p, m, indent))
goto err;
if (!ASN1_bn_print(bp, "generator:", x->g, m, indent))
goto err;
if (x->q && !ASN1_bn_print(bp, "subgroup order:", x->q, m, indent))
goto err;
if (x->j && !ASN1_bn_print(bp, "subgroup factor:", x->j, m, indent))
goto err;
if (x->seed) {
int i;
BIO_indent(bp, indent, 128);
BIO_puts(bp, "seed:");
for (i = 0; i < x->seedlen; i++) {
if ((i % 15) == 0) {
if (BIO_puts(bp, "\n") <= 0
|| !BIO_indent(bp, indent + 4, 128))
goto err;
}
if (BIO_printf(bp, "%02x%s", x->seed[i],
((i + 1) == x->seedlen) ? "" : ":") <= 0)
goto err;
}
if (BIO_write(bp, "\n", 1) <= 0)
return (0);
}
if (x->counter && !ASN1_bn_print(bp, "counter:", x->counter, m, indent))
goto err;
if (x->length != 0) {
BIO_indent(bp, indent, 128);
if (BIO_printf(bp, "recommended-private-length: %d bits\n",
(int)x->length) <= 0)
goto err;
}
ret = 1;
if (0) {
err:
DHerr(DH_F_DO_DH_PRINT, reason);
}
if (m != NULL)
OPENSSL_free(m);
return (ret);
}
static int int_dh_size(const EVP_PKEY *pkey)
{
return (DH_size(pkey->pkey.dh));
}
static int dh_bits(const EVP_PKEY *pkey)
{
return BN_num_bits(pkey->pkey.dh->p);
}
static int dh_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
{
if (BN_cmp(a->pkey.dh->p, b->pkey.dh->p) ||
BN_cmp(a->pkey.dh->g, b->pkey.dh->g))
return 0;
else if (a->ameth == &dhx_asn1_meth) {
if (BN_cmp(a->pkey.dh->q, b->pkey.dh->q))
return 0;
}
return 1;
}
static int int_dh_bn_cpy(BIGNUM **dst, const BIGNUM *src)
{
BIGNUM *a;
if (src) {
a = BN_dup(src);
if (!a)
return 0;
} else
a = NULL;
if (*dst)
BN_free(*dst);
*dst = a;
return 1;
}
static int int_dh_param_copy(DH *to, const DH *from, int is_x942)
{
if (is_x942 == -1)
is_x942 = ! !from->q;
if (!int_dh_bn_cpy(&to->p, from->p))
return 0;
if (!int_dh_bn_cpy(&to->g, from->g))
return 0;
if (is_x942) {
if (!int_dh_bn_cpy(&to->q, from->q))
return 0;
if (!int_dh_bn_cpy(&to->j, from->j))
return 0;
if (to->seed) {
OPENSSL_free(to->seed);
to->seed = NULL;
to->seedlen = 0;
}
if (from->seed) {
to->seed = BUF_memdup(from->seed, from->seedlen);
if (!to->seed)
return 0;
to->seedlen = from->seedlen;
}
} else
to->length = from->length;
return 1;
}
DH *DHparams_dup(DH *dh)
{
DH *ret;
ret = DH_new();
if (!ret)
return NULL;
if (!int_dh_param_copy(ret, dh, -1)) {
DH_free(ret);
return NULL;
}
return ret;
}
static int dh_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
{
return int_dh_param_copy(to->pkey.dh, from->pkey.dh,
from->ameth == &dhx_asn1_meth);
}
static int dh_missing_parameters(const EVP_PKEY *a)
{
if (a->pkey.dh == NULL || a->pkey.dh->p == NULL || a->pkey.dh->g == NULL)
return 1;
return 0;
}
static int dh_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
{
if (dh_cmp_parameters(a, b) == 0)
return 0;
if (BN_cmp(b->pkey.dh->pub_key, a->pkey.dh->pub_key) != 0)
return 0;
else
return 1;
}
static int dh_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *ctx)
{
return do_dh_print(bp, pkey->pkey.dh, indent, ctx, 0);
}
static int dh_public_print(BIO *bp, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *ctx)
{
return do_dh_print(bp, pkey->pkey.dh, indent, ctx, 1);
}
static int dh_private_print(BIO *bp, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *ctx)
{
return do_dh_print(bp, pkey->pkey.dh, indent, ctx, 2);
}
int DHparams_print(BIO *bp, const DH *x)
{
return do_dh_print(bp, x, 4, NULL, 0);
}
#ifndef OPENSSL_NO_CMS
static int dh_cms_decrypt(CMS_RecipientInfo *ri);
static int dh_cms_encrypt(CMS_RecipientInfo *ri);
#endif
static int dh_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
{
switch (op) {
#ifndef OPENSSL_NO_CMS
case ASN1_PKEY_CTRL_CMS_ENVELOPE:
if (arg1 == 1)
return dh_cms_decrypt(arg2);
else if (arg1 == 0)
return dh_cms_encrypt(arg2);
return -2;
case ASN1_PKEY_CTRL_CMS_RI_TYPE:
*(int *)arg2 = CMS_RECIPINFO_AGREE;
return 1;
#endif
default:
return -2;
}
}
const EVP_PKEY_ASN1_METHOD dh_asn1_meth = {
EVP_PKEY_DH,
EVP_PKEY_DH,
0,
"DH",
"OpenSSL PKCS#3 DH method",
dh_pub_decode,
dh_pub_encode,
dh_pub_cmp,
dh_public_print,
dh_priv_decode,
dh_priv_encode,
dh_private_print,
int_dh_size,
dh_bits,
dh_param_decode,
dh_param_encode,
dh_missing_parameters,
dh_copy_parameters,
dh_cmp_parameters,
dh_param_print,
0,
int_dh_free,
0
};
const EVP_PKEY_ASN1_METHOD dhx_asn1_meth = {
EVP_PKEY_DHX,
EVP_PKEY_DHX,
0,
"X9.42 DH",
"OpenSSL X9.42 DH method",
dh_pub_decode,
dh_pub_encode,
dh_pub_cmp,
dh_public_print,
dh_priv_decode,
dh_priv_encode,
dh_private_print,
int_dh_size,
dh_bits,
dh_param_decode,
dh_param_encode,
dh_missing_parameters,
dh_copy_parameters,
dh_cmp_parameters,
dh_param_print,
0,
int_dh_free,
dh_pkey_ctrl
};
#ifndef OPENSSL_NO_CMS
static int dh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
{
ASN1_OBJECT *aoid;
int atype;
void *aval;
ASN1_INTEGER *public_key = NULL;
int rv = 0;
EVP_PKEY *pkpeer = NULL, *pk = NULL;
DH *dhpeer = NULL;
const unsigned char *p;
int plen;
X509_ALGOR_get0(&aoid, &atype, &aval, alg);
if (OBJ_obj2nid(aoid) != NID_dhpublicnumber)
goto err;
/* Only absent parameters allowed in RFC XXXX */
if (atype != V_ASN1_UNDEF && atype == V_ASN1_NULL)
goto err;
pk = EVP_PKEY_CTX_get0_pkey(pctx);
if (!pk)
goto err;
if (pk->type != EVP_PKEY_DHX)
goto err;
/* Get parameters from parent key */
dhpeer = DHparams_dup(pk->pkey.dh);
/* We have parameters now set public key */
plen = ASN1_STRING_length(pubkey);
p = ASN1_STRING_data(pubkey);
if (!p || !plen)
goto err;
if (!(public_key = d2i_ASN1_INTEGER(NULL, &p, plen))) {
DHerr(DH_F_DH_CMS_SET_PEERKEY, DH_R_DECODE_ERROR);
goto err;
}
/* We have parameters now set public key */
if (!(dhpeer->pub_key = ASN1_INTEGER_to_BN(public_key, NULL))) {
DHerr(DH_F_DH_CMS_SET_PEERKEY, DH_R_BN_DECODE_ERROR);
goto err;
}
pkpeer = EVP_PKEY_new();
if (!pkpeer)
goto err;
EVP_PKEY_assign(pkpeer, pk->ameth->pkey_id, dhpeer);
dhpeer = NULL;
if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
rv = 1;
err:
if (public_key)
ASN1_INTEGER_free(public_key);
if (pkpeer)
EVP_PKEY_free(pkpeer);
if (dhpeer)
DH_free(dhpeer);
return rv;
}
static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
{
int rv = 0;
X509_ALGOR *alg, *kekalg = NULL;
ASN1_OCTET_STRING *ukm;
const unsigned char *p;
unsigned char *dukm = NULL;
size_t dukmlen = 0;
int keylen, plen;
const EVP_CIPHER *kekcipher;
EVP_CIPHER_CTX *kekctx;
if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
goto err;
/*
* For DH we only have one OID permissible. If ever any more get defined
* we will need something cleverer.
*/
if (OBJ_obj2nid(alg->algorithm) != NID_id_smime_alg_ESDH) {
DHerr(DH_F_DH_CMS_SET_SHARED_INFO, DH_R_KDF_PARAMETER_ERROR);
goto err;
}
if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, EVP_PKEY_DH_KDF_X9_42) <= 0)
goto err;
if (EVP_PKEY_CTX_set_dh_kdf_md(pctx, EVP_sha1()) <= 0)
goto err;
if (alg->parameter->type != V_ASN1_SEQUENCE)
goto err;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
kekalg = d2i_X509_ALGOR(NULL, &p, plen);
if (!kekalg)
goto err;
kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
if (!kekctx)
goto err;
kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
goto err;
if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
goto err;
if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
goto err;
keylen = EVP_CIPHER_CTX_key_length(kekctx);
if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0)
goto err;
/* Use OBJ_nid2obj to ensure we use built in OID that isn't freed */
if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx,
OBJ_nid2obj(EVP_CIPHER_type(kekcipher)))
<= 0)
goto err;
if (ukm) {
dukmlen = ASN1_STRING_length(ukm);
dukm = BUF_memdup(ASN1_STRING_data(ukm), dukmlen);
if (!dukm)
goto err;
}
if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
goto err;
dukm = NULL;
rv = 1;
err:
if (kekalg)
X509_ALGOR_free(kekalg);
if (dukm)
OPENSSL_free(dukm);
return rv;
}
static int dh_cms_decrypt(CMS_RecipientInfo *ri)
{
EVP_PKEY_CTX *pctx;
pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
if (!pctx)
return 0;
/* See if we need to set peer key */
if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
X509_ALGOR *alg;
ASN1_BIT_STRING *pubkey;
if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
NULL, NULL, NULL))
return 0;
if (!alg || !pubkey)
return 0;
if (!dh_cms_set_peerkey(pctx, alg, pubkey)) {
DHerr(DH_F_DH_CMS_DECRYPT, DH_R_PEER_KEY_ERROR);
return 0;
}
}
/* Set DH derivation parameters and initialise unwrap context */
if (!dh_cms_set_shared_info(pctx, ri)) {
DHerr(DH_F_DH_CMS_DECRYPT, DH_R_SHARED_INFO_ERROR);
return 0;
}
return 1;
}
static int dh_cms_encrypt(CMS_RecipientInfo *ri)
{
EVP_PKEY_CTX *pctx;
EVP_PKEY *pkey;
EVP_CIPHER_CTX *ctx;
int keylen;
X509_ALGOR *talg, *wrap_alg = NULL;
ASN1_OBJECT *aoid;
ASN1_BIT_STRING *pubkey;
ASN1_STRING *wrap_str;
ASN1_OCTET_STRING *ukm;
unsigned char *penc = NULL, *dukm = NULL;
int penclen;
size_t dukmlen = 0;
int rv = 0;
int kdf_type, wrap_nid;
const EVP_MD *kdf_md;
pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
if (!pctx)
return 0;
/* Get ephemeral key */
pkey = EVP_PKEY_CTX_get0_pkey(pctx);
if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
NULL, NULL, NULL))
goto err;
X509_ALGOR_get0(&aoid, NULL, NULL, talg);
/* Is everything uninitialised? */
if (aoid == OBJ_nid2obj(NID_undef)) {
ASN1_INTEGER *pubk;
pubk = BN_to_ASN1_INTEGER(pkey->pkey.dh->pub_key, NULL);
if (!pubk)
goto err;
/* Set the key */
penclen = i2d_ASN1_INTEGER(pubk, &penc);
ASN1_INTEGER_free(pubk);
if (penclen <= 0)
goto err;
ASN1_STRING_set0(pubkey, penc, penclen);
pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
penc = NULL;
X509_ALGOR_set0(talg, OBJ_nid2obj(NID_dhpublicnumber),
V_ASN1_UNDEF, NULL);
}
/* See if custom paraneters set */
kdf_type = EVP_PKEY_CTX_get_dh_kdf_type(pctx);
if (kdf_type <= 0)
goto err;
if (!EVP_PKEY_CTX_get_dh_kdf_md(pctx, &kdf_md))
goto err;
if (kdf_type == EVP_PKEY_DH_KDF_NONE) {
kdf_type = EVP_PKEY_DH_KDF_X9_42;
if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, kdf_type) <= 0)
goto err;
} else if (kdf_type != EVP_PKEY_DH_KDF_X9_42)
/* Unknown KDF */
goto err;
if (kdf_md == NULL) {
/* Only SHA1 supported */
kdf_md = EVP_sha1();
if (EVP_PKEY_CTX_set_dh_kdf_md(pctx, kdf_md) <= 0)
goto err;
} else if (EVP_MD_type(kdf_md) != NID_sha1)
/* Unsupported digest */
goto err;
if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
goto err;
/* Get wrap NID */
ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
wrap_nid = EVP_CIPHER_CTX_type(ctx);
if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx, OBJ_nid2obj(wrap_nid)) <= 0)
goto err;
keylen = EVP_CIPHER_CTX_key_length(ctx);
/* Package wrap algorithm in an AlgorithmIdentifier */
wrap_alg = X509_ALGOR_new();
if (!wrap_alg)
goto err;
wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
wrap_alg->parameter = ASN1_TYPE_new();
if (!wrap_alg->parameter)
goto err;
if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
goto err;
if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
ASN1_TYPE_free(wrap_alg->parameter);
wrap_alg->parameter = NULL;
}
if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0)
goto err;
if (ukm) {
dukmlen = ASN1_STRING_length(ukm);
dukm = BUF_memdup(ASN1_STRING_data(ukm), dukmlen);
if (!dukm)
goto err;
}
if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
goto err;
dukm = NULL;
/*
* Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
* of another AlgorithmIdentifier.
*/
penc = NULL;
penclen = i2d_X509_ALGOR(wrap_alg, &penc);
if (!penc || !penclen)
goto err;
wrap_str = ASN1_STRING_new();
if (!wrap_str)
goto err;
ASN1_STRING_set0(wrap_str, penc, penclen);
penc = NULL;
X509_ALGOR_set0(talg, OBJ_nid2obj(NID_id_smime_alg_ESDH),
V_ASN1_SEQUENCE, wrap_str);
rv = 1;
err:
if (penc)
OPENSSL_free(penc);
if (wrap_alg)
X509_ALGOR_free(wrap_alg);
return rv;
}
#endif
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* (C) Copyright 2013-2016, Freescale Semiconductor, Inc.
*/
#ifndef __ASM_ARCH_IMX_REGS_H__
#define __ASM_ARCH_IMX_REGS_H__
#define ARCH_MXC
#define IRAM_BASE_ADDR 0x3E800000 /* internal ram */
#define IRAM_SIZE 0x00400000 /* 4MB */
#define AIPS0_BASE_ADDR (0x40000000UL)
#define AIPS1_BASE_ADDR (0x40080000UL)
/* AIPS 0 */
#define AXBS_BASE_ADDR (AIPS0_BASE_ADDR + 0x00000000)
#define CSE3_BASE_ADDR (AIPS0_BASE_ADDR + 0x00001000)
#define EDMA_BASE_ADDR (AIPS0_BASE_ADDR + 0x00002000)
#define XRDC_BASE_ADDR (AIPS0_BASE_ADDR + 0x00004000)
#define SWT0_BASE_ADDR (AIPS0_BASE_ADDR + 0x0000A000)
#define SWT1_BASE_ADDR (AIPS0_BASE_ADDR + 0x0000B000)
#define STM0_BASE_ADDR (AIPS0_BASE_ADDR + 0x0000D000)
#define NIC301_BASE_ADDR (AIPS0_BASE_ADDR + 0x00010000)
#define GC3000_BASE_ADDR (AIPS0_BASE_ADDR + 0x00020000)
#define DEC200_DECODER_BASE_ADDR (AIPS0_BASE_ADDR + 0x00026000)
#define DEC200_ENCODER_BASE_ADDR (AIPS0_BASE_ADDR + 0x00027000)
#define TWOD_ACE_BASE_ADDR (AIPS0_BASE_ADDR + 0x00028000)
#define MIPI_CSI0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00030000)
#define DMAMUX0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00031000)
#define ENET_BASE_ADDR (AIPS0_BASE_ADDR + 0x00032000)
#define FLEXRAY_BASE_ADDR (AIPS0_BASE_ADDR + 0x00034000)
#define MMDC0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00036000)
#define MEW0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00037000)
#define MONITOR_DDR0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00038000)
#define MONITOR_CCI0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00039000)
#define PIT0_BASE_ADDR (AIPS0_BASE_ADDR + 0x0003A000)
#define MC_CGM0_BASE_ADDR (AIPS0_BASE_ADDR + 0x0003C000)
#define MC_CGM1_BASE_ADDR (AIPS0_BASE_ADDR + 0x0003F000)
#define MC_CGM2_BASE_ADDR (AIPS0_BASE_ADDR + 0x00042000)
#define MC_CGM3_BASE_ADDR (AIPS0_BASE_ADDR + 0x00045000)
#define MC_RGM_BASE_ADDR (AIPS0_BASE_ADDR + 0x00048000)
#define MC_ME_BASE_ADDR (AIPS0_BASE_ADDR + 0x0004A000)
#define MC_PCU_BASE_ADDR (AIPS0_BASE_ADDR + 0x0004B000)
#define ADC0_BASE_ADDR (AIPS0_BASE_ADDR + 0x0004D000)
#define FLEXTIMER_BASE_ADDR (AIPS0_BASE_ADDR + 0x0004F000)
#define I2C0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00051000)
#define LINFLEXD0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00053000)
#define FLEXCAN0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00055000)
#define SPI0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00057000)
#define SPI2_BASE_ADDR (AIPS0_BASE_ADDR + 0x00059000)
#define CRC0_BASE_ADDR (AIPS0_BASE_ADDR + 0x0005B000)
#define USDHC_BASE_ADDR (AIPS0_BASE_ADDR + 0x0005D000)
#define OCOTP_CONTROLLER_BASE_ADDR (AIPS0_BASE_ADDR + 0x0005F000)
#define WKPU_BASE_ADDR (AIPS0_BASE_ADDR + 0x00063000)
#define VIU0_BASE_ADDR (AIPS0_BASE_ADDR + 0x00064000)
#define HPSMI_SRAM_CONTROLLER_BASE_ADDR (AIPS0_BASE_ADDR + 0x00068000)
#define SIUL2_BASE_ADDR (AIPS0_BASE_ADDR + 0x0006C000)
#define SIPI_BASE_ADDR (AIPS0_BASE_ADDR + 0x00074000)
#define LFAST_BASE_ADDR (AIPS0_BASE_ADDR + 0x00078000)
#define SSE_BASE_ADDR (AIPS0_BASE_ADDR + 0x00079000)
#define SRC_SOC_BASE_ADDR (AIPS0_BASE_ADDR + 0x0007C000)
/* AIPS 1 */
#define ERM_BASE_ADDR (AIPS1_BASE_ADDR + 0X000000000)
#define MSCM_BASE_ADDR (AIPS1_BASE_ADDR + 0X000001000)
#define SEMA42_BASE_ADDR (AIPS1_BASE_ADDR + 0X000002000)
#define INTC_MON_BASE_ADDR (AIPS1_BASE_ADDR + 0X000003000)
#define SWT2_BASE_ADDR (AIPS1_BASE_ADDR + 0X000004000)
#define SWT3_BASE_ADDR (AIPS1_BASE_ADDR + 0X000005000)
#define SWT4_BASE_ADDR (AIPS1_BASE_ADDR + 0X000006000)
#define STM1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000007000)
#define EIM_BASE_ADDR (AIPS1_BASE_ADDR + 0X000008000)
#define APB_BASE_ADDR (AIPS1_BASE_ADDR + 0X000009000)
#define XBIC_BASE_ADDR (AIPS1_BASE_ADDR + 0X000012000)
#define MIPI_BASE_ADDR (AIPS1_BASE_ADDR + 0X000020000)
#define DMAMUX1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000021000)
#define MMDC1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000022000)
#define MEW1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000023000)
#define DDR1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000024000)
#define CCI1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000025000)
#define QUADSPI0_BASE_ADDR (AIPS1_BASE_ADDR + 0X000026000)
#define PIT1_BASE_ADDR (AIPS1_BASE_ADDR + 0X00002A000)
#define FCCU_BASE_ADDR (AIPS1_BASE_ADDR + 0X000030000)
#define FLEXTIMER_FTM1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000036000)
#define I2C1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000038000)
#define I2C2_BASE_ADDR (AIPS1_BASE_ADDR + 0X00003A000)
#define LINFLEXD1_BASE_ADDR (AIPS1_BASE_ADDR + 0X00003C000)
#define FLEXCAN1_BASE_ADDR (AIPS1_BASE_ADDR + 0X00003E000)
#define SPI1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000040000)
#define SPI3_BASE_ADDR (AIPS1_BASE_ADDR + 0X000042000)
#define IPL_BASE_ADDR (AIPS1_BASE_ADDR + 0X000043000)
#define CGM_CMU_BASE_ADDR (AIPS1_BASE_ADDR + 0X000044000)
#define PMC_BASE_ADDR (AIPS1_BASE_ADDR + 0X000048000)
#define CRC1_BASE_ADDR (AIPS1_BASE_ADDR + 0X00004C000)
#define TMU_BASE_ADDR (AIPS1_BASE_ADDR + 0X00004E000)
#define VIU1_BASE_ADDR (AIPS1_BASE_ADDR + 0X000050000)
#define JPEG_BASE_ADDR (AIPS1_BASE_ADDR + 0X000054000)
#define H264_DEC_BASE_ADDR (AIPS1_BASE_ADDR + 0X000058000)
#define H264_ENC_BASE_ADDR (AIPS1_BASE_ADDR + 0X00005C000)
#define MEMU_BASE_ADDR (AIPS1_BASE_ADDR + 0X000060000)
#define STCU_BASE_ADDR (AIPS1_BASE_ADDR + 0X000064000)
#define SLFTST_CTRL_BASE_ADDR (AIPS1_BASE_ADDR + 0X000066000)
#define MCT_BASE_ADDR (AIPS1_BASE_ADDR + 0X000068000)
#define REP_BASE_ADDR (AIPS1_BASE_ADDR + 0X00006A000)
#define MBIST_CONTROLLER_BASE_ADDR (AIPS1_BASE_ADDR + 0X00006C000)
#define BOOT_LOADER_BASE_ADDR (AIPS1_BASE_ADDR + 0X00006F000)
/* TODO Remove this after the IOMUX framework is implemented */
#define IOMUXC_BASE_ADDR SIUL2_BASE_ADDR
/* MUX mode and PAD ctrl are in one register */
#define CONFIG_IOMUX_SHARE_CONF_REG
#define FEC_QUIRK_ENET_MAC
#define I2C_QUIRK_REG
/* MSCM interrupt router */
#define MSCM_IRSPRC_CPn_EN 3
#define MSCM_IRSPRC_NUM 176
#define MSCM_CPXTYPE_RYPZ_MASK 0xFF
#define MSCM_CPXTYPE_RYPZ_OFFSET 0
#define MSCM_CPXTYPE_PERS_MASK 0xFFFFFF00
#define MSCM_CPXTYPE_PERS_OFFSET 8
#define MSCM_CPXTYPE_PERS_A53 0x413533
#define MSCM_CPXTYPE_PERS_CM4 0x434d34
#if !(defined(__KERNEL_STRICT_NAMES) || defined(__ASSEMBLY__))
#include <asm/types.h>
/* System Reset Controller (SRC) */
struct src {
u32 bmr1;
u32 bmr2;
u32 gpr1_boot;
u32 reserved_0x00C[61];
u32 gpr1;
u32 gpr2;
u32 gpr3;
u32 gpr4;
u32 gpr5;
u32 gpr6;
u32 gpr7;
u32 reserved_0x11C[1];
u32 gpr9;
u32 gpr10;
u32 gpr11;
u32 gpr12;
u32 gpr13;
u32 gpr14;
u32 gpr15;
u32 gpr16;
u32 reserved_0x140[1];
u32 gpr17;
u32 gpr18;
u32 gpr19;
u32 gpr20;
u32 gpr21;
u32 gpr22;
u32 gpr23;
u32 gpr24;
u32 gpr25;
u32 gpr26;
u32 gpr27;
u32 reserved_0x16C[5];
u32 pcie_config1;
u32 ddr_self_ref_ctrl;
u32 pcie_config0;
u32 reserved_0x18C[4];
u32 soc_misc_config2;
};
/* SRC registers definitions */
/* SRC_GPR1 */
#define SRC_GPR1_PLL_SOURCE(pll,val)( ((val) & SRC_GPR1_PLL_SOURCE_MASK) << \
(SRC_GPR1_PLL_OFFSET + (pll)) )
#define SRC_GPR1_PLL_SOURCE_MASK (0x1)
#define SRC_GPR1_PLL_OFFSET (27)
#define SRC_GPR1_FIRC_CLK_SOURCE (0x0)
#define SRC_GPR1_XOSC_CLK_SOURCE (0x1)
/* Periodic Interrupt Timer (PIT) */
struct pit_reg {
u32 mcr;
u32 recv0[55];
u32 ltmr64h;
u32 ltmr64l;
u32 recv1[6];
u32 ldval0;
u32 cval0;
u32 tctrl0;
u32 tflg0;
u32 ldval1;
u32 cval1;
u32 tctrl1;
u32 tflg1;
u32 ldval2;
u32 cval2;
u32 tctrl2;
u32 tflg2;
u32 ldval3;
u32 cval3;
u32 tctrl3;
u32 tflg3;
u32 ldval4;
u32 cval4;
u32 tctrl4;
u32 tflg4;
u32 ldval5;
u32 cval5;
u32 tctrl5;
u32 tflg5;
};
/* Watchdog Timer (WDOG) */
struct wdog_regs {
u32 cr;
u32 ir;
u32 to;
u32 wn;
u32 sr;
u32 co;
u32 sk;
};
/* UART */
struct linflex_fsl {
u32 lincr1;
u32 linier;
u32 linsr;
u32 linesr;
u32 uartcr;
u32 uartsr;
u32 lintcsr;
u32 linocr;
u32 lintocr;
u32 linfbrr;
u32 linibrr;
u32 lincfr;
u32 lincr2;
u32 bidr;
u32 bdrl;
u32 bdrm;
u32 ifer;
u32 ifmi;
u32 ifmr;
u32 ifcr0;
u32 ifcr1;
u32 ifcr2;
u32 ifcr3;
u32 ifcr4;
u32 ifcr5;
u32 ifcr6;
u32 ifcr7;
u32 ifcr8;
u32 ifcr9;
u32 ifcr10;
u32 ifcr11;
u32 ifcr12;
u32 ifcr13;
u32 ifcr14;
u32 ifcr15;
u32 gcr;
u32 uartpto;
u32 uartcto;
u32 dmatxe;
u32 dmarxe;
};
/* MSCM Interrupt Router */
struct mscm_ir {
u32 cpxtype; /* Processor x Type Register */
u32 cpxnum; /* Processor x Number Register */
u32 cpxmaster; /* Processor x Master Number Register */
u32 cpxcount; /* Processor x Count Register */
u32 cpxcfg0; /* Processor x Configuration 0 Register */
u32 cpxcfg1; /* Processor x Configuration 1 Register */
u32 cpxcfg2; /* Processor x Configuration 2 Register */
u32 cpxcfg3; /* Processor x Configuration 3 Register */
u32 cp0type; /* Processor 0 Type Register */
u32 cp0num; /* Processor 0 Number Register */
u32 cp0master; /* Processor 0 Master Number Register */
u32 cp0count; /* Processor 0 Count Register */
u32 cp0cfg0; /* Processor 0 Configuration 0 Register */
u32 cp0cfg1; /* Processor 0 Configuration 1 Register */
u32 cp0cfg2; /* Processor 0 Configuration 2 Register */
u32 cp0cfg3; /* Processor 0 Configuration 3 Register */
u32 cp1type; /* Processor 1 Type Register */
u32 cp1num; /* Processor 1 Number Register */
u32 cp1master; /* Processor 1 Master Number Register */
u32 cp1count; /* Processor 1 Count Register */
u32 cp1cfg0; /* Processor 1 Configuration 0 Register */
u32 cp1cfg1; /* Processor 1 Configuration 1 Register */
u32 cp1cfg2; /* Processor 1 Configuration 2 Register */
u32 cp1cfg3; /* Processor 1 Configuration 3 Register */
u32 reserved_0x060[232];
u32 ocmdr0; /* On-Chip Memory Descriptor Register */
u32 reserved_0x404[2];
u32 ocmdr3; /* On-Chip Memory Descriptor Register */
u32 reserved_0x410[28];
u32 tcmdr[4]; /* Generic Tightly Coupled Memory Descriptor Register */
u32 reserved_0x490[28];
u32 cpce0; /* Core Parity Checking Enable Register 0 */
u32 reserved_0x504[191];
u32 ircp0ir; /* Interrupt Router CP0 Interrupt Register */
u32 ircp1ir; /* Interrupt Router CP1 Interrupt Register */
u32 reserved_0x808[6];
u32 ircpgir; /* Interrupt Router CPU Generate Interrupt Register */
u32 reserved_0x824[23];
u16 irsprc[176]; /* Interrupt Router Shared Peripheral Routing Control Register */
u32 reserved_0x9e0[136];
u32 iahbbe0; /* Gasket Burst Enable Register */
u32 reserved_0xc04[63];
u32 ipcge; /* Interconnect Parity Checking Global Enable Register */
u32 reserved_0xd04[3];
u32 ipce[4]; /* Interconnect Parity Checking Enable Register */
u32 reserved_0xd20[8];
u32 ipcgie; /* Interconnect Parity Checking Global Injection Enable Register */
u32 reserved_0xd44[3];
u32 ipcie[4]; /* Interconnect Parity Checking Injection Enable Register */
};
#endif /* __ASSEMBLY__ */
#endif /* __ASM_ARCH_IMX_REGS_H__ */
| {
"pile_set_name": "Github"
} |
//
// UIWindow+Hierarchy.m
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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.
#import "IQUIWindow+Hierarchy.h"
#import <UIKit/UINavigationController.h>
@implementation UIWindow (IQ_UIWindow_Hierarchy)
- (UIViewController*)topMostController
{
UIViewController *topController = [self rootViewController];
// Getting topMost ViewController
while ([topController presentedViewController]) topController = [topController presentedViewController];
// Returning topMost ViewController
return topController;
}
- (UIViewController*)currentViewController;
{
UIViewController *currentViewController = [self topMostController];
while ([currentViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)currentViewController topViewController])
currentViewController = [(UINavigationController*)currentViewController topViewController];
return currentViewController;
}
@end
| {
"pile_set_name": "Github"
} |
##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
#
# frozen_string_literal: true
module Twilio
module REST
class Voice < Domain
class V1 < Version
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class DialingPermissionsList < ListResource
##
# Initialize the DialingPermissionsList
# @param [Version] version Version that contains the resource
# @return [DialingPermissionsList] DialingPermissionsList
def initialize(version)
super(version)
# Path Solution
@solution = {}
# Components
@countries = nil
@settings = nil
@bulk_country_updates = nil
end
##
# Access the countries
# @param [String] iso_code The {ISO country
# code}[https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2] of the
# DialingPermissions Country resource to fetch
# @return [CountryList]
# @return [CountryContext] if iso_code was passed.
def countries(iso_code=:unset)
raise ArgumentError, 'iso_code cannot be nil' if iso_code.nil?
if iso_code != :unset
return CountryContext.new(@version, iso_code, )
end
@countries ||= CountryList.new(@version, )
end
##
# Access the settings
# @return [SettingsContext] SettingsContext
def settings
return SettingsContext.new(@version, )
end
##
# Access the bulk_country_updates
# @return [BulkCountryUpdateList]
# @return [BulkCountryUpdateContext]
def bulk_country_updates
@bulk_country_updates ||= BulkCountryUpdateList.new(@version, )
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Voice.V1.DialingPermissionsList>'
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class DialingPermissionsPage < Page
##
# Initialize the DialingPermissionsPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [DialingPermissionsPage] DialingPermissionsPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of DialingPermissionsInstance
# @param [Hash] payload Payload response from the API
# @return [DialingPermissionsInstance] DialingPermissionsInstance
def get_instance(payload)
DialingPermissionsInstance.new(@version, payload, )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Voice.V1.DialingPermissionsPage>'
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class DialingPermissionsInstance < InstanceResource
##
# Initialize the DialingPermissionsInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @return [DialingPermissionsInstance] DialingPermissionsInstance
def initialize(version, payload)
super(version)
end
##
# Provide a user friendly representation
def to_s
"<Twilio.Voice.V1.DialingPermissionsInstance>"
end
##
# Provide a detailed, user friendly representation
def inspect
"<Twilio.Voice.V1.DialingPermissionsInstance>"
end
end
end
end
end
end | {
"pile_set_name": "Github"
} |
package com.yibao.music.adapter;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.yibao.music.MusicApplication;
import com.yibao.music.R;
import com.yibao.music.base.BaseRvAdapter;
import com.yibao.music.model.AddAndDeleteListBean;
import com.yibao.music.model.MusicBean;
import com.yibao.music.util.Constants;
import com.yibao.music.util.LogUtil;
import com.yibao.music.util.RxBus;
import com.yibao.music.util.StringUtil;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Des:${快速列表的Adapter}
* Time:2017/8/22 14:31
*
* @author Stran
*/
public class BottomSheetAdapter
extends BaseRvAdapter<MusicBean> {
public BottomSheetAdapter(List<MusicBean> list) {
super(list);
}
@Override
protected String getLastItemDes() {
return " 首歌";
}
@Override
protected void bindView(RecyclerView.ViewHolder holder, MusicBean musicItem) {
if (holder instanceof MusicHolder) {
MusicHolder musicHolder = (MusicHolder) holder;
musicHolder.mMusicName.setText(musicItem.getTitle());
String unknownName = "<unknown>";
musicHolder.mMusicSinger.setText(unknownName.equals(musicItem.getArtist()) ? "Smartisan" : musicItem.getArtist());
musicHolder.mFavoriteTime.setText(StringUtil.getFormatDate(Long.valueOf(musicItem.getTime())));
int position = musicHolder.getAdapterPosition();
// 侧滑删除收藏歌曲
musicHolder.mDeleteLayout.setOnClickListener(v -> {
musicItem.setFavorite(false);
MusicApplication.getIntstance().getMusicDao().update(musicItem);
RxBus.getInstance().post(new AddAndDeleteListBean(Constants.NUMBER_FIVE, position, musicItem.getTitle()));
});
// MusicBottomSheetDialog页面接收,用于播放收藏列表中点击Position的音乐
musicHolder.mRootBottomSheet.setOnClickListener(view -> RxBus.getInstance().post(Constants.FAVORITE_POSITION, position));
}
}
@Override
protected RecyclerView.ViewHolder getViewHolder(View view) {
return new MusicHolder(view);
}
@Override
protected int getLayoutId() {
return R.layout.bottom_sheet_music_item;
}
@Override
public int getPositionForSection(int i) {
return 0;
}
@Override
public int getSectionForPosition(int i) {
return 0;
}
static class MusicHolder
extends RecyclerView.ViewHolder {
@BindView(R.id.favorite_music_name)
TextView mMusicName;
@BindView(R.id.favorite_artist_name)
TextView mMusicSinger;
@BindView(R.id.favorite_time)
TextView mFavoriteTime;
@BindView(R.id.delete_item)
LinearLayout mDeleteLayout;
@BindView(R.id.root_favorite_bottom_sheet)
RelativeLayout mRootBottomSheet;
MusicHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
| {
"pile_set_name": "Github"
} |
1.1.0 / 2014-04-12
==================
* add non-array values support
* expose internal utilities:
- `.is()`
- `.hasBody()`
- `.normalize()`
- `.match()`
1.0.1 / 2014-03-30
==================
* add `multipart` as a shorthand
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*-
nemo-directory.c: Nemo directory model.
Copyright (C) 1999, 2000, 2001 Eazel, Inc.
This program 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 2 of the
License, or (at your option) any later version.
This program 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 this program; if not, write to the
Free Software Foundation, Inc., 51 Franklin Street - Suite 500,
Boston, MA 02110-1335, USA.
Author: Darin Adler <[email protected]>
*/
#include <config.h>
#include "nemo-directory-private.h"
#include "nemo-directory-notify.h"
#include "nemo-file-attributes.h"
#include "nemo-file-private.h"
#include "nemo-file-utilities.h"
#include "nemo-search-directory.h"
#include "nemo-global-preferences.h"
#include "nemo-lib-self-check-functions.h"
#include "nemo-metadata.h"
#include "nemo-desktop-directory.h"
#include "nemo-vfs-directory.h"
#include <eel/eel-glib-extensions.h>
#include <eel/eel-string.h>
#include <gtk/gtk.h>
enum {
FILES_ADDED,
FILES_CHANGED,
DONE_LOADING,
LOAD_ERROR,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
static GHashTable *directories;
static void nemo_directory_finalize (GObject *object);
static NemoDirectory *nemo_directory_new (GFile *location);
static GList * real_get_file_list (NemoDirectory *directory);
static gboolean real_is_editable (NemoDirectory *directory);
static void set_directory_location (NemoDirectory *directory,
GFile *location);
G_DEFINE_TYPE (NemoDirectory, nemo_directory, G_TYPE_OBJECT);
static void
nemo_directory_class_init (NemoDirectoryClass *klass)
{
GObjectClass *object_class;
object_class = G_OBJECT_CLASS (klass);
object_class->finalize = nemo_directory_finalize;
signals[FILES_ADDED] =
g_signal_new ("files_added",
G_TYPE_FROM_CLASS (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NemoDirectoryClass, files_added),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER);
signals[FILES_CHANGED] =
g_signal_new ("files_changed",
G_TYPE_FROM_CLASS (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NemoDirectoryClass, files_changed),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER);
signals[DONE_LOADING] =
g_signal_new ("done_loading",
G_TYPE_FROM_CLASS (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NemoDirectoryClass, done_loading),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals[LOAD_ERROR] =
g_signal_new ("load_error",
G_TYPE_FROM_CLASS (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NemoDirectoryClass, load_error),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER);
klass->get_file_list = real_get_file_list;
klass->is_editable = real_is_editable;
g_type_class_add_private (klass, sizeof (NemoDirectoryDetails));
}
static void
nemo_directory_init (NemoDirectory *directory)
{
directory->details = G_TYPE_INSTANCE_GET_PRIVATE ((directory), NEMO_TYPE_DIRECTORY, NemoDirectoryDetails);
directory->details->file_hash = g_hash_table_new (g_str_hash, g_str_equal);
directory->details->high_priority_queue = nemo_file_queue_new ();
directory->details->low_priority_queue = nemo_file_queue_new ();
directory->details->extension_queue = nemo_file_queue_new ();
directory->details->max_deferred_file_count = g_settings_get_int (nemo_preferences,
NEMO_PREFERENCES_DEFERRED_ATTR_PRELOAD_LIMIT);
}
NemoDirectory *
nemo_directory_ref (NemoDirectory *directory)
{
if (directory == NULL) {
return directory;
}
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), NULL);
g_object_ref (directory);
return directory;
}
void
nemo_directory_unref (NemoDirectory *directory)
{
if (directory == NULL) {
return;
}
g_return_if_fail (NEMO_IS_DIRECTORY (directory));
g_object_unref (directory);
}
static void
nemo_directory_finalize (GObject *object)
{
NemoDirectory *directory;
directory = NEMO_DIRECTORY (object);
g_hash_table_remove (directories, directory->details->location);
nemo_directory_cancel (directory);
g_assert (directory->details->count_in_progress == NULL);
if (directory->details->monitor_list != NULL) {
g_warning ("destroying a NemoDirectory while it's being monitored");
g_list_free_full (directory->details->monitor_list, g_free);
}
if (directory->details->monitor != NULL) {
nemo_monitor_cancel (directory->details->monitor);
}
if (directory->details->dequeue_pending_idle_id != 0) {
g_source_remove (directory->details->dequeue_pending_idle_id);
}
if (directory->details->call_ready_idle_id != 0) {
g_source_remove (directory->details->call_ready_idle_id);
}
if (directory->details->location) {
g_object_unref (directory->details->location);
}
g_assert (directory->details->file_list == NULL);
g_hash_table_destroy (directory->details->file_hash);
nemo_file_queue_destroy (directory->details->high_priority_queue);
nemo_file_queue_destroy (directory->details->low_priority_queue);
nemo_file_queue_destroy (directory->details->extension_queue);
g_assert (directory->details->directory_load_in_progress == NULL);
g_assert (directory->details->count_in_progress == NULL);
g_assert (directory->details->dequeue_pending_idle_id == 0);
g_list_free_full (directory->details->pending_file_info, g_object_unref);
G_OBJECT_CLASS (nemo_directory_parent_class)->finalize (object);
}
static void
invalidate_one_count (gpointer key, gpointer value, gpointer user_data)
{
NemoDirectory *directory;
g_assert (key != NULL);
g_assert (NEMO_IS_DIRECTORY (value));
g_assert (user_data == NULL);
directory = NEMO_DIRECTORY (value);
nemo_directory_invalidate_count_and_mime_list (directory);
}
static void
filtering_changed_callback (gpointer callback_data)
{
g_assert (callback_data == NULL);
/* Preference about which items to show has changed, so we
* can't trust any of our precomputed directory counts.
*/
g_hash_table_foreach (directories, invalidate_one_count, NULL);
}
void
emit_change_signals_for_all_files (NemoDirectory *directory)
{
GList *files;
files = g_list_copy (directory->details->file_list);
if (directory->details->as_file != NULL) {
files = g_list_prepend (files, directory->details->as_file);
}
nemo_file_list_ref (files);
nemo_directory_emit_change_signals (directory, files);
nemo_file_list_free (files);
}
static void
collect_all_directories (gpointer key, gpointer value, gpointer callback_data)
{
NemoDirectory *directory;
GList **dirs;
directory = NEMO_DIRECTORY (value);
dirs = callback_data;
*dirs = g_list_prepend (*dirs, nemo_directory_ref (directory));
}
void
emit_change_signals_for_all_files_in_all_directories (void)
{
GList *dirs, *l;
NemoDirectory *directory;
dirs = NULL;
g_hash_table_foreach (directories,
collect_all_directories,
&dirs);
for (l = dirs; l != NULL; l = l->next) {
directory = NEMO_DIRECTORY (l->data);
emit_change_signals_for_all_files (directory);
nemo_directory_unref (directory);
}
g_list_free (dirs);
}
static void
async_state_changed_one (gpointer key, gpointer value, gpointer user_data)
{
NemoDirectory *directory;
g_assert (key != NULL);
g_assert (NEMO_IS_DIRECTORY (value));
g_assert (user_data == NULL);
directory = NEMO_DIRECTORY (value);
nemo_directory_async_state_changed (directory);
emit_change_signals_for_all_files (directory);
}
static void
async_data_preference_changed_callback (gpointer callback_data)
{
g_assert (callback_data == NULL);
/* Preference involving fetched async data has changed, so
* we have to kick off refetching all async data, and tell
* each file that it (might have) changed.
*/
g_hash_table_foreach (directories, async_state_changed_one, NULL);
}
static void
add_preferences_callbacks (void)
{
nemo_global_preferences_init ();
g_signal_connect_swapped (nemo_preferences,
"changed::" NEMO_PREFERENCES_SHOW_HIDDEN_FILES,
G_CALLBACK(filtering_changed_callback),
NULL);
g_signal_connect_swapped (nemo_preferences,
"changed::" NEMO_PREFERENCES_SHOW_DIRECTORY_ITEM_COUNTS,
G_CALLBACK (async_data_preference_changed_callback),
NULL);
g_signal_connect_swapped (nemo_preferences,
"changed::" NEMO_PREFERENCES_DATE_FORMAT,
G_CALLBACK(async_data_preference_changed_callback),
NULL);
}
/**
* nemo_directory_get_by_uri:
* @uri: URI of directory to get.
*
* Get a directory given a uri.
* Creates the appropriate subclass given the uri mappings.
* Returns a referenced object, not a floating one. Unref when finished.
* If two windows are viewing the same uri, the directory object is shared.
*/
NemoDirectory *
nemo_directory_get_internal (GFile *location, gboolean create)
{
NemoDirectory *directory;
/* Create the hash table first time through. */
if (directories == NULL) {
directories = g_hash_table_new (g_file_hash, (GCompareFunc) g_file_equal);
add_preferences_callbacks ();
}
/* If the object is already in the hash table, look it up. */
directory = g_hash_table_lookup (directories,
location);
if (directory != NULL) {
nemo_directory_ref (directory);
} else if (create) {
/* Create a new directory object instead. */
directory = nemo_directory_new (location);
if (directory == NULL) {
return NULL;
}
/* Put it in the hash table. */
g_hash_table_insert (directories,
directory->details->location,
directory);
}
return directory;
}
NemoDirectory *
nemo_directory_get (GFile *location)
{
if (location == NULL) {
return NULL;
}
return nemo_directory_get_internal (location, TRUE);
}
NemoDirectory *
nemo_directory_get_existing (GFile *location)
{
if (location == NULL) {
return NULL;
}
return nemo_directory_get_internal (location, FALSE);
}
NemoDirectory *
nemo_directory_get_by_uri (const char *uri)
{
NemoDirectory *directory;
GFile *location;
if (uri == NULL) {
return NULL;
}
location = g_file_new_for_uri (uri);
directory = nemo_directory_get_internal (location, TRUE);
g_object_unref (location);
return directory;
}
NemoDirectory *
nemo_directory_get_for_file (NemoFile *file)
{
char *uri;
NemoDirectory *directory;
g_return_val_if_fail (NEMO_IS_FILE (file), NULL);
uri = nemo_file_get_uri (file);
directory = nemo_directory_get_by_uri (uri);
g_free (uri);
return directory;
}
/* Returns a reffed NemoFile object for this directory.
*/
NemoFile *
nemo_directory_get_corresponding_file (NemoDirectory *directory)
{
NemoFile *file;
char *uri;
file = nemo_directory_get_existing_corresponding_file (directory);
if (file == NULL) {
uri = nemo_directory_get_uri (directory);
file = nemo_file_get_by_uri (uri);
g_free (uri);
}
return file;
}
/* Returns a reffed NemoFile object for this directory, but only if the
* NemoFile object has already been created.
*/
NemoFile *
nemo_directory_get_existing_corresponding_file (NemoDirectory *directory)
{
NemoFile *file;
char *uri;
file = directory->details->as_file;
if (file != NULL) {
nemo_file_ref (file);
return file;
}
uri = nemo_directory_get_uri (directory);
file = nemo_file_get_existing_by_uri (uri);
g_free (uri);
return file;
}
/* nemo_directory_get_name_for_self_as_new_file:
*
* Get a name to display for the file representing this
* directory. This is called only when there's no VFS
* directory for this NemoDirectory.
*/
char *
nemo_directory_get_name_for_self_as_new_file (NemoDirectory *directory)
{
char *directory_uri;
char *name, *colon;
directory_uri = nemo_directory_get_uri (directory);
colon = strchr (directory_uri, ':');
if (colon == NULL || colon == directory_uri) {
name = g_strdup (directory_uri);
} else {
name = g_strndup (directory_uri, colon - directory_uri);
}
g_free (directory_uri);
return name;
}
char *
nemo_directory_get_uri (NemoDirectory *directory)
{
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), NULL);
return g_file_get_uri (directory->details->location);
}
GFile *
nemo_directory_get_location (NemoDirectory *directory)
{
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), NULL);
return g_object_ref (directory->details->location);
}
static NemoDirectory *
nemo_directory_new (GFile *location)
{
NemoDirectory *directory;
char *uri;
uri = g_file_get_uri (location);
if (eel_uri_is_desktop (uri)) {
directory = NEMO_DIRECTORY (g_object_new (NEMO_TYPE_DESKTOP_DIRECTORY, NULL));
} else if (eel_uri_is_search (uri)) {
directory = NEMO_DIRECTORY (g_object_new (NEMO_TYPE_SEARCH_DIRECTORY, NULL));
} else if (g_str_has_suffix (uri, NEMO_SAVED_SEARCH_EXTENSION)) {
directory = NEMO_DIRECTORY (nemo_search_directory_new_from_saved_search (uri));
} else {
directory = NEMO_DIRECTORY (g_object_new (NEMO_TYPE_VFS_DIRECTORY, NULL));
}
set_directory_location (directory, location);
g_free (uri);
return directory;
}
gboolean
nemo_directory_is_local (NemoDirectory *directory)
{
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), FALSE);
if (directory->details->location == NULL) {
return TRUE;
}
return nemo_directory_is_in_trash (directory) ||
g_file_is_native (directory->details->location);
}
gboolean
nemo_directory_is_in_trash (NemoDirectory *directory)
{
g_assert (NEMO_IS_DIRECTORY (directory));
if (directory->details->location == NULL) {
return FALSE;
}
return g_file_has_uri_scheme (directory->details->location, "trash");
}
gboolean
nemo_directory_is_in_recent (NemoDirectory *directory)
{
g_assert (NEMO_IS_DIRECTORY (directory));
if (directory->details->location == NULL) {
return FALSE;
}
return g_file_has_uri_scheme (directory->details->location, "recent");
}
gboolean
nemo_directory_is_in_admin (NemoDirectory *directory)
{
g_assert (NEMO_IS_DIRECTORY (directory));
if (directory->details->location == NULL)
{
return FALSE;
}
return g_file_has_uri_scheme (directory->details->location, "admin");
}
gboolean
nemo_directory_are_all_files_seen (NemoDirectory *directory)
{
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), FALSE);
return NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->are_all_files_seen (directory);
}
static void
add_to_hash_table (NemoDirectory *directory, NemoFile *file, GList *node)
{
const char *name;
name = eel_ref_str_peek (file->details->name);
g_assert (node != NULL);
g_assert (g_hash_table_lookup (directory->details->file_hash,
name) == NULL);
g_hash_table_insert (directory->details->file_hash, (char *) name, node);
}
static GList *
extract_from_hash_table (NemoDirectory *directory, NemoFile *file)
{
const char *name;
GList *node;
name = eel_ref_str_peek (file->details->name);
if (name == NULL) {
return NULL;
}
/* Find the list node in the hash table. */
node = g_hash_table_lookup (directory->details->file_hash, name);
g_hash_table_remove (directory->details->file_hash, name);
return node;
}
void
nemo_directory_add_file (NemoDirectory *directory, NemoFile *file)
{
GList *node;
gboolean add_to_work_queue;
g_assert (NEMO_IS_DIRECTORY (directory));
g_assert (NEMO_IS_FILE (file));
g_assert (file->details->name != NULL);
/* Add to list. */
node = g_list_prepend (directory->details->file_list, file);
directory->details->file_list = node;
/* Add to hash table. */
add_to_hash_table (directory, file, node);
directory->details->confirmed_file_count++;
if (directory->details->early_load_file_count++ < directory->details->max_deferred_file_count) {
file->details->load_deferred_attrs = NEMO_FILE_LOAD_DEFERRED_ATTRS_PRELOAD;
}
add_to_work_queue = FALSE;
if (nemo_directory_is_file_list_monitored (directory)) {
/* Ref if we are monitoring, since monitoring owns the file list. */
nemo_file_ref (file);
add_to_work_queue = TRUE;
} else if (nemo_directory_has_active_request_for_file (directory, file)) {
/* We're waiting for the file in a call_when_ready. Make sure
we add the file to the work queue so that said waiter won't
wait forever for e.g. all files in the directory to be done */
add_to_work_queue = TRUE;
}
if (add_to_work_queue) {
nemo_directory_add_file_to_work_queue (directory, file);
}
}
void
nemo_directory_remove_file (NemoDirectory *directory, NemoFile *file)
{
GList *node;
g_assert (NEMO_IS_DIRECTORY (directory));
g_assert (NEMO_IS_FILE (file));
g_assert (file->details->name != NULL);
/* Find the list node in the hash table. */
node = extract_from_hash_table (directory, file);
g_assert (node != NULL);
g_assert (node->data == file);
/* Remove the item from the list. */
directory->details->file_list = g_list_remove_link
(directory->details->file_list, node);
g_list_free_1 (node);
nemo_directory_remove_file_from_work_queue (directory, file);
if (!file->details->unconfirmed) {
directory->details->confirmed_file_count--;
}
/* Unref if we are monitoring. */
if (nemo_directory_is_file_list_monitored (directory)) {
nemo_file_unref (file);
}
}
GList *
nemo_directory_begin_file_name_change (NemoDirectory *directory,
NemoFile *file)
{
/* Find the list node in the hash table. */
return extract_from_hash_table (directory, file);
}
void
nemo_directory_end_file_name_change (NemoDirectory *directory,
NemoFile *file,
GList *node)
{
/* Add the list node to the hash table. */
if (node != NULL) {
add_to_hash_table (directory, file, node);
}
}
NemoFile *
nemo_directory_find_file_by_name (NemoDirectory *directory,
const char *name)
{
GList *node;
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), NULL);
g_return_val_if_fail (name != NULL, NULL);
node = g_hash_table_lookup (directory->details->file_hash,
name);
return node == NULL ? NULL : NEMO_FILE (node->data);
}
/* "." for the directory-as-file, otherwise the filename */
NemoFile *
nemo_directory_find_file_by_internal_filename (NemoDirectory *directory,
const char *internal_filename)
{
NemoFile *result;
if (g_strcmp0 (internal_filename, ".") == 0) {
result = nemo_directory_get_existing_corresponding_file (directory);
if (result != NULL) {
nemo_file_unref (result);
}
} else {
result = nemo_directory_find_file_by_name (directory, internal_filename);
}
return result;
}
void
nemo_directory_emit_files_added (NemoDirectory *directory,
GList *added_files)
{
if (added_files != NULL) {
g_signal_emit (directory,
signals[FILES_ADDED], 0,
added_files);
}
}
void
nemo_directory_emit_files_changed (NemoDirectory *directory,
GList *changed_files)
{
if (changed_files != NULL) {
g_signal_emit (directory,
signals[FILES_CHANGED], 0,
changed_files);
}
}
void
nemo_directory_emit_change_signals (NemoDirectory *directory,
GList *changed_files)
{
GList *p;
for (p = changed_files; p != NULL; p = p->next) {
nemo_file_emit_changed (p->data);
}
nemo_directory_emit_files_changed (directory, changed_files);
}
void
nemo_directory_emit_done_loading (NemoDirectory *directory)
{
directory->details->early_load_file_count = 0;
g_signal_emit (directory,
signals[DONE_LOADING], 0);
}
void
nemo_directory_emit_load_error (NemoDirectory *directory,
GError *error)
{
g_signal_emit (directory,
signals[LOAD_ERROR], 0,
error);
}
/* Return a directory object for this one's parent. */
static NemoDirectory *
get_parent_directory (GFile *location)
{
NemoDirectory *directory;
GFile *parent;
parent = g_file_get_parent (location);
if (parent) {
directory = nemo_directory_get_internal (parent, TRUE);
g_object_unref (parent);
return directory;
}
return NULL;
}
/* If a directory object exists for this one's parent, then
* return it, otherwise return NULL.
*/
static NemoDirectory *
get_parent_directory_if_exists (GFile *location)
{
NemoDirectory *directory;
GFile *parent;
parent = g_file_get_parent (location);
if (parent) {
directory = nemo_directory_get_internal (parent, FALSE);
g_object_unref (parent);
return directory;
}
return NULL;
}
static void
hash_table_list_prepend (GHashTable *table, gconstpointer key, gpointer data)
{
GList *list;
list = g_hash_table_lookup (table, key);
list = g_list_prepend (list, data);
g_hash_table_insert (table, (gpointer) key, list);
}
static void
call_files_added_free_list (gpointer key, gpointer value, gpointer user_data)
{
g_assert (NEMO_IS_DIRECTORY (key));
g_assert (value != NULL);
g_assert (user_data == NULL);
g_signal_emit (key,
signals[FILES_ADDED], 0,
value);
g_list_free (value);
}
static void
call_files_changed_common (NemoDirectory *directory, GList *file_list)
{
GList *node;
NemoFile *file;
for (node = file_list; node != NULL; node = node->next) {
file = node->data;
if (file->details->directory == directory) {
nemo_directory_add_file_to_work_queue (directory,
file);
}
}
nemo_directory_async_state_changed (directory);
nemo_directory_emit_change_signals (directory, file_list);
}
static void
call_files_changed_free_list (gpointer key, gpointer value, gpointer user_data)
{
g_assert (value != NULL);
g_assert (user_data == NULL);
call_files_changed_common (NEMO_DIRECTORY (key), value);
g_list_free (value);
}
static void
call_files_changed_unref_free_list (gpointer key, gpointer value, gpointer user_data)
{
g_assert (value != NULL);
g_assert (user_data == NULL);
call_files_changed_common (NEMO_DIRECTORY (key), value);
nemo_file_list_free (value);
}
static void
call_get_file_info_free_list (gpointer key, gpointer value, gpointer user_data)
{
NemoDirectory *directory;
GList *files;
g_assert (NEMO_IS_DIRECTORY (key));
g_assert (value != NULL);
g_assert (user_data == NULL);
directory = key;
files = value;
nemo_directory_get_info_for_new_files (directory, files);
g_list_foreach (files, (GFunc) g_object_unref, NULL);
g_list_free (files);
}
static void
invalidate_count_and_unref (gpointer key, gpointer value, gpointer user_data)
{
g_assert (NEMO_IS_DIRECTORY (key));
g_assert (value == key);
g_assert (user_data == NULL);
nemo_directory_invalidate_count_and_mime_list (key);
nemo_directory_unref (key);
}
static void
collect_parent_directories (GHashTable *hash_table, NemoDirectory *directory)
{
g_assert (hash_table != NULL);
g_assert (NEMO_IS_DIRECTORY (directory));
if (g_hash_table_lookup (hash_table, directory) == NULL) {
nemo_directory_ref (directory);
g_hash_table_insert (hash_table, directory, directory);
}
}
void
nemo_directory_notify_files_added (GList *files)
{
GHashTable *added_lists;
GList *p;
NemoDirectory *directory;
GHashTable *parent_directories;
NemoFile *file;
GFile *location, *parent;
/* Make a list of added files in each directory. */
added_lists = g_hash_table_new (NULL, NULL);
/* Make a list of parent directories that will need their counts updated. */
parent_directories = g_hash_table_new (NULL, NULL);
for (p = files; p != NULL; p = p->next) {
location = p->data;
/* See if the directory is already known. */
directory = get_parent_directory_if_exists (location);
if (directory == NULL) {
/* In case the directory is not being
* monitored, but the corresponding file is,
* we must invalidate it's item count.
*/
file = NULL;
parent = g_file_get_parent (location);
if (parent) {
file = nemo_file_get_existing (parent);
g_object_unref (parent);
}
if (file != NULL) {
nemo_file_invalidate_count_and_mime_list (file);
nemo_file_unref (file);
}
continue;
}
collect_parent_directories (parent_directories, directory);
/* If no one is monitoring files in the directory, nothing to do. */
if (!nemo_directory_is_file_list_monitored (directory)) {
nemo_directory_unref (directory);
continue;
}
file = nemo_file_get_existing (location);
/* We check is_added here, because the file could have been added
* to the directory by a nemo_file_get() but not gotten
* files_added emitted
*/
if (file && file->details->is_added) {
/* A file already exists, it was probably renamed.
* If it was renamed this could be ignored, but
* queue a change just in case */
nemo_file_changed (file);
nemo_file_unref (file);
} else {
hash_table_list_prepend (added_lists,
directory,
g_object_ref (location));
}
nemo_directory_unref (directory);
}
/* Now get file info for the new files. This creates NemoFile
* objects for the new files, and sends out a files_added signal.
*/
g_hash_table_foreach (added_lists, call_get_file_info_free_list, NULL);
g_hash_table_destroy (added_lists);
/* Invalidate count for each parent directory. */
g_hash_table_foreach (parent_directories, invalidate_count_and_unref, NULL);
g_hash_table_destroy (parent_directories);
}
static void
g_file_pair_free (GFilePair *pair)
{
g_object_unref (pair->to);
g_object_unref (pair->from);
g_free (pair);
}
static GList *
uri_pairs_to_file_pairs (GList *uri_pairs)
{
GList *l, *file_pair_list;
GFilePair *file_pair;
URIPair *uri_pair;
file_pair_list = NULL;
for (l = uri_pairs; l != NULL; l = l->next) {
uri_pair = l->data;
file_pair = g_new (GFilePair, 1);
file_pair->from = g_file_new_for_uri (uri_pair->from_uri);
file_pair->to = g_file_new_for_uri (uri_pair->to_uri);
file_pair_list = g_list_prepend (file_pair_list, file_pair);
}
return g_list_reverse (file_pair_list);
}
void
nemo_directory_notify_files_added_by_uri (GList *uris)
{
GList *files;
files = nemo_file_list_from_uris (uris);
nemo_directory_notify_files_added (files);
g_list_free_full (files, g_object_unref);
}
void
nemo_directory_notify_files_changed (GList *files)
{
GHashTable *changed_lists;
GList *node;
GFile *location;
GFile *parent;
NemoDirectory *dir;
NemoFile *file;
/* Make a list of changed files in each directory. */
changed_lists = g_hash_table_new (NULL, NULL);
/* Go through all the notifications. */
for (node = files; node != NULL; node = node->next) {
location = node->data;
/* Find the file. */
file = nemo_file_get_existing (location);
if (file != NULL) {
/* Tell it to re-get info now, and later emit
* a changed signal.
*/
file->details->file_info_is_up_to_date = FALSE;
file->details->link_info_is_up_to_date = FALSE;
nemo_file_invalidate_extension_info_internal (file);
hash_table_list_prepend (changed_lists,
file->details->directory,
file);
} else {
parent = g_file_get_parent (location);
dir = nemo_directory_get_existing (parent);
if (dir != NULL && dir->details->new_files_in_progress != NULL &&
files != dir->details->new_files_in_progress_changes) {
dir->details->new_files_in_progress_changes = g_list_prepend (dir->details->new_files_in_progress_changes,
g_object_ref (location));
}
if (dir != NULL) {
nemo_directory_unref (dir);
}
if (parent != NULL) {
g_object_unref (parent);
}
}
}
/* Now send out the changed signals. */
g_hash_table_foreach (changed_lists, call_files_changed_unref_free_list, NULL);
g_hash_table_destroy (changed_lists);
}
void
nemo_directory_notify_files_changed_by_uri (GList *uris)
{
GList *files;
files = nemo_file_list_from_uris (uris);
nemo_directory_notify_files_changed (files);
g_list_free_full (files, g_object_unref);
}
void
nemo_directory_notify_files_removed (GList *files)
{
GHashTable *changed_lists;
GList *p;
NemoDirectory *directory;
GHashTable *parent_directories;
NemoFile *file;
GFile *location;
/* Make a list of changed files in each directory. */
changed_lists = g_hash_table_new (NULL, NULL);
/* Make a list of parent directories that will need their counts updated. */
parent_directories = g_hash_table_new (NULL, NULL);
/* Go through all the notifications. */
for (p = files; p != NULL; p = p->next) {
location = p->data;
/* Update file count for parent directory if anyone might care. */
directory = get_parent_directory_if_exists (location);
if (directory != NULL) {
collect_parent_directories (parent_directories, directory);
nemo_directory_unref (directory);
}
/* Find the file. */
file = nemo_file_get_existing (location);
if (file != NULL && !nemo_file_rename_in_progress (file)) {
/* Mark it gone and prepare to send the changed signal. */
nemo_file_mark_gone (file);
hash_table_list_prepend (changed_lists,
file->details->directory,
nemo_file_ref (file));
}
nemo_file_unref (file);
}
/* Now send out the changed signals. */
g_hash_table_foreach (changed_lists, call_files_changed_unref_free_list, NULL);
g_hash_table_destroy (changed_lists);
/* Invalidate count for each parent directory. */
g_hash_table_foreach (parent_directories, invalidate_count_and_unref, NULL);
g_hash_table_destroy (parent_directories);
}
void
nemo_directory_notify_files_removed_by_uri (GList *uris)
{
GList *files;
files = nemo_file_list_from_uris (uris);
nemo_directory_notify_files_changed (files);
g_list_free_full (files, g_object_unref);
}
static void
set_directory_location (NemoDirectory *directory,
GFile *location)
{
if (directory->details->location) {
g_object_unref (directory->details->location);
}
directory->details->location = g_object_ref (location);
}
static void
change_directory_location (NemoDirectory *directory,
GFile *new_location)
{
/* I believe it's impossible for a self-owned file/directory
* to be moved. But if that did somehow happen, this function
* wouldn't do enough to handle it.
*/
g_assert (directory->details->as_file == NULL);
g_hash_table_remove (directories,
directory->details->location);
set_directory_location (directory, new_location);
g_hash_table_insert (directories,
directory->details->location,
directory);
}
typedef struct {
GFile *container;
GList *directories;
} CollectData;
static void
collect_directories_by_container (gpointer key, gpointer value, gpointer callback_data)
{
NemoDirectory *directory;
CollectData *collect_data;
GFile *location;
location = (GFile *) key;
directory = NEMO_DIRECTORY (value);
collect_data = (CollectData *) callback_data;
if (g_file_has_prefix (location, collect_data->container) ||
g_file_equal (collect_data->container, location)) {
nemo_directory_ref (directory);
collect_data->directories =
g_list_prepend (collect_data->directories,
directory);
}
}
static GList *
nemo_directory_moved_internal (GFile *old_location,
GFile *new_location)
{
CollectData collection;
NemoDirectory *directory;
GList *node, *affected_files;
GFile *new_directory_location;
char *relative_path;
collection.container = old_location;
collection.directories = NULL;
g_hash_table_foreach (directories,
collect_directories_by_container,
&collection);
affected_files = NULL;
for (node = collection.directories; node != NULL; node = node->next) {
directory = NEMO_DIRECTORY (node->data);
new_directory_location = NULL;
if (g_file_equal (directory->details->location, old_location)) {
new_directory_location = g_object_ref (new_location);
} else {
relative_path = g_file_get_relative_path (old_location,
directory->details->location);
if (relative_path != NULL) {
new_directory_location = g_file_resolve_relative_path (new_location, relative_path);
g_free (relative_path);
}
}
if (new_directory_location) {
change_directory_location (directory, new_directory_location);
g_object_unref (new_directory_location);
/* Collect affected files. */
if (directory->details->as_file != NULL) {
affected_files = g_list_prepend
(affected_files,
nemo_file_ref (directory->details->as_file));
}
affected_files = g_list_concat
(affected_files,
nemo_file_list_copy (directory->details->file_list));
}
nemo_directory_unref (directory);
}
g_list_free (collection.directories);
return affected_files;
}
void
nemo_directory_moved (const char *old_uri,
const char *new_uri)
{
GList *list, *node;
GHashTable *hash;
NemoFile *file;
GFile *old_location;
GFile *new_location;
hash = g_hash_table_new (NULL, NULL);
old_location = g_file_new_for_uri (old_uri);
new_location = g_file_new_for_uri (new_uri);
list = nemo_directory_moved_internal (old_location, new_location);
for (node = list; node != NULL; node = node->next) {
file = NEMO_FILE (node->data);
hash_table_list_prepend (hash,
file->details->directory,
nemo_file_ref (file));
}
nemo_file_list_free (list);
g_object_unref (old_location);
g_object_unref (new_location);
g_hash_table_foreach (hash, call_files_changed_unref_free_list, NULL);
g_hash_table_destroy (hash);
}
void
nemo_directory_notify_files_moved (GList *file_pairs)
{
GList *p, *affected_files, *node;
GFilePair *pair;
NemoFile *file;
NemoDirectory *old_directory, *new_directory;
GHashTable *parent_directories;
GList *new_files_list, *unref_list;
GHashTable *added_lists, *changed_lists;
char *name;
NemoFileAttributes cancel_attributes;
GFile *to_location, *from_location;
/* Make a list of added and changed files in each directory. */
new_files_list = NULL;
added_lists = g_hash_table_new (NULL, NULL);
changed_lists = g_hash_table_new (NULL, NULL);
unref_list = NULL;
/* Make a list of parent directories that will need their counts updated. */
parent_directories = g_hash_table_new (NULL, NULL);
cancel_attributes = nemo_file_get_all_attributes ();
for (p = file_pairs; p != NULL; p = p->next) {
pair = p->data;
from_location = pair->from;
to_location = pair->to;
/* Handle overwriting a file. */
file = nemo_file_get_existing (to_location);
if (file != NULL) {
/* Mark it gone and prepare to send the changed signal. */
nemo_file_mark_gone (file);
new_directory = file->details->directory;
hash_table_list_prepend (changed_lists,
new_directory,
file);
collect_parent_directories (parent_directories,
new_directory);
}
/* Update any directory objects that are affected. */
affected_files = nemo_directory_moved_internal (from_location,
to_location);
for (node = affected_files; node != NULL; node = node->next) {
file = NEMO_FILE (node->data);
hash_table_list_prepend (changed_lists,
file->details->directory,
file);
}
unref_list = g_list_concat (unref_list, affected_files);
/* Move an existing file. */
file = nemo_file_get_existing (from_location);
if (file == NULL) {
/* Handle this as if it was a new file. */
new_files_list = g_list_prepend (new_files_list,
to_location);
} else {
/* Handle notification in the old directory. */
old_directory = file->details->directory;
collect_parent_directories (parent_directories, old_directory);
/* Cancel loading of attributes in the old directory */
nemo_directory_cancel_loading_file_attributes
(old_directory, file, cancel_attributes);
/* Locate the new directory. */
new_directory = get_parent_directory (to_location);
collect_parent_directories (parent_directories, new_directory);
/* We can unref now -- new_directory is in the
* parent directories list so it will be
* around until the end of this function
* anyway.
*/
nemo_directory_unref (new_directory);
/* Update the file's name and directory. */
name = g_file_get_basename (to_location);
nemo_file_update_name_and_directory
(file, name, new_directory);
g_free (name);
/* Update file attributes */
nemo_file_invalidate_attributes (file, NEMO_FILE_ATTRIBUTE_INFO);
hash_table_list_prepend (changed_lists,
old_directory,
file);
if (old_directory != new_directory) {
hash_table_list_prepend (added_lists,
new_directory,
file);
}
/* Unref each file once to balance out nemo_file_get_by_uri. */
unref_list = g_list_prepend (unref_list, file);
}
}
/* Now send out the changed and added signals for existing file objects. */
g_hash_table_foreach (changed_lists, call_files_changed_free_list, NULL);
g_hash_table_destroy (changed_lists);
g_hash_table_foreach (added_lists, call_files_added_free_list, NULL);
g_hash_table_destroy (added_lists);
/* Let the file objects go. */
nemo_file_list_free (unref_list);
/* Invalidate count for each parent directory. */
g_hash_table_foreach (parent_directories, invalidate_count_and_unref, NULL);
g_hash_table_destroy (parent_directories);
/* Separate handling for brand new file objects. */
nemo_directory_notify_files_added (new_files_list);
g_list_free (new_files_list);
}
void
nemo_directory_notify_files_moved_by_uri (GList *uri_pairs)
{
GList *file_pairs;
file_pairs = uri_pairs_to_file_pairs (uri_pairs);
nemo_directory_notify_files_moved (file_pairs);
g_list_foreach (file_pairs, (GFunc)g_file_pair_free, NULL);
g_list_free (file_pairs);
}
void
nemo_directory_schedule_position_set (GList *position_setting_list)
{
GList *p;
const NemoFileChangesQueuePosition *item;
NemoFile *file;
time_t now;
time (&now);
for (p = position_setting_list; p != NULL; p = p->next) {
item = (NemoFileChangesQueuePosition *) p->data;
file = nemo_file_get (item->location);
if (item->set) {
nemo_file_set_position (file, item->point.x, item->point.y);
} else {
nemo_file_set_position (file, -1, -1);
}
if (item->set) {
nemo_file_set_monitor_number (file, item->monitor);
} else {
nemo_file_set_monitor_number (file, -1);
}
nemo_file_set_time_metadata (file, NEMO_METADATA_KEY_ICON_POSITION_TIMESTAMP, UNDEFINED_TIME);
nemo_file_unref (file);
}
}
gboolean
nemo_directory_contains_file (NemoDirectory *directory,
NemoFile *file)
{
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), FALSE);
g_return_val_if_fail (NEMO_IS_FILE (file), FALSE);
if (nemo_file_is_gone (file)) {
return FALSE;
}
return NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->contains_file (directory, file);
}
char *
nemo_directory_get_file_uri (NemoDirectory *directory,
const char *file_name)
{
GFile *child;
char *result;
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), NULL);
g_return_val_if_fail (file_name != NULL, NULL);
result = NULL;
child = g_file_get_child (directory->details->location, file_name);
result = g_file_get_uri (child);
g_object_unref (child);
return result;
}
void
nemo_directory_call_when_ready (NemoDirectory *directory,
NemoFileAttributes file_attributes,
gboolean wait_for_all_files,
NemoDirectoryCallback callback,
gpointer callback_data)
{
g_return_if_fail (NEMO_IS_DIRECTORY (directory));
g_return_if_fail (callback != NULL);
NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->call_when_ready
(directory, file_attributes, wait_for_all_files,
callback, callback_data);
}
void
nemo_directory_cancel_callback (NemoDirectory *directory,
NemoDirectoryCallback callback,
gpointer callback_data)
{
g_return_if_fail (NEMO_IS_DIRECTORY (directory));
g_return_if_fail (callback != NULL);
NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->cancel_callback
(directory, callback, callback_data);
}
void
nemo_directory_file_monitor_add (NemoDirectory *directory,
gconstpointer client,
gboolean monitor_hidden_files,
NemoFileAttributes file_attributes,
NemoDirectoryCallback callback,
gpointer callback_data)
{
g_return_if_fail (NEMO_IS_DIRECTORY (directory));
g_return_if_fail (client != NULL);
NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->file_monitor_add
(directory, client,
monitor_hidden_files,
file_attributes,
callback, callback_data);
}
void
nemo_directory_file_monitor_remove (NemoDirectory *directory,
gconstpointer client)
{
g_return_if_fail (NEMO_IS_DIRECTORY (directory));
g_return_if_fail (client != NULL);
NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->file_monitor_remove
(directory, client);
}
void
nemo_directory_force_reload (NemoDirectory *directory)
{
g_return_if_fail (NEMO_IS_DIRECTORY (directory));
NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->force_reload (directory);
}
gboolean
nemo_directory_is_not_empty (NemoDirectory *directory)
{
g_return_val_if_fail (NEMO_IS_DIRECTORY (directory), FALSE);
return NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->is_not_empty (directory);
}
static gboolean
is_tentative (gpointer data, gpointer callback_data)
{
NemoFile *file;
g_assert (callback_data == NULL);
file = NEMO_FILE (data);
/* Avoid returning files with !is_added, because these
* will later be sent with the files_added signal, and a
* user doing get_file_list + files_added monitoring will
* then see the file twice */
return !file->details->got_file_info || !file->details->is_added;
}
GList *
nemo_directory_get_file_list (NemoDirectory *directory)
{
return NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->get_file_list (directory);
}
static GList *
real_get_file_list (NemoDirectory *directory)
{
GList *tentative_files, *non_tentative_files;
tentative_files = eel_g_list_partition
(g_list_copy (directory->details->file_list),
is_tentative, NULL, &non_tentative_files);
g_list_free (tentative_files);
nemo_file_list_ref (non_tentative_files);
return non_tentative_files;
}
static gboolean
real_is_editable (NemoDirectory *directory)
{
return TRUE;
}
gboolean
nemo_directory_is_editable (NemoDirectory *directory)
{
return NEMO_DIRECTORY_CLASS (G_OBJECT_GET_CLASS (directory))->is_editable (directory);
}
GList *
nemo_directory_match_pattern (NemoDirectory *directory, const char *pattern)
{
GList *files, *l, *ret;
GPatternSpec *spec;
ret = NULL;
spec = g_pattern_spec_new (pattern);
files = nemo_directory_get_file_list (directory);
for (l = files; l; l = l->next) {
NemoFile *file;
char *name;
file = NEMO_FILE (l->data);
name = nemo_file_get_display_name (file);
if (g_pattern_match_string (spec, name)) {
ret = g_list_prepend(ret, nemo_file_ref (file));
}
g_free (name);
}
g_pattern_spec_free (spec);
nemo_file_list_free (files);
return ret;
}
/**
* nemo_directory_list_ref
*
* Ref all the directories in a list.
* @list: GList of directories.
**/
GList *
nemo_directory_list_ref (GList *list)
{
g_list_foreach (list, (GFunc) nemo_directory_ref, NULL);
return list;
}
/**
* nemo_directory_list_unref
*
* Unref all the directories in a list.
* @list: GList of directories.
**/
void
nemo_directory_list_unref (GList *list)
{
g_list_foreach (list, (GFunc) nemo_directory_unref, NULL);
}
/**
* nemo_directory_list_free
*
* Free a list of directories after unrefing them.
* @list: GList of directories.
**/
void
nemo_directory_list_free (GList *list)
{
nemo_directory_list_unref (list);
g_list_free (list);
}
/**
* nemo_directory_list_copy
*
* Copy the list of directories, making a new ref of each,
* @list: GList of directories.
**/
GList *
nemo_directory_list_copy (GList *list)
{
return g_list_copy (nemo_directory_list_ref (list));
}
static int
compare_by_uri (NemoDirectory *a, NemoDirectory *b)
{
char *uri_a, *uri_b;
int res;
uri_a = g_file_get_uri (a->details->location);
uri_b = g_file_get_uri (b->details->location);
res = strcmp (uri_a, uri_b);
g_free (uri_a);
g_free (uri_b);
return res;
}
static int
compare_by_uri_cover (gconstpointer a, gconstpointer b)
{
return compare_by_uri (NEMO_DIRECTORY (a), NEMO_DIRECTORY (b));
}
/**
* nemo_directory_list_sort_by_uri
*
* Sort the list of directories by directory uri.
* @list: GList of directories.
**/
GList *
nemo_directory_list_sort_by_uri (GList *list)
{
return g_list_sort (list, compare_by_uri_cover);
}
gboolean
nemo_directory_is_desktop_directory (NemoDirectory *directory)
{
if (directory->details->location == NULL) {
return FALSE;
}
return nemo_is_desktop_directory (directory->details->location);
}
void
nemo_directory_set_show_thumbnails (NemoDirectory *directory,
gboolean show_thumbnails)
{
NemoFile *file;
file = nemo_file_get(directory->details->location);
nemo_file_set_boolean_metadata (file, NEMO_METADATA_KEY_SHOW_THUMBNAILS, FALSE, show_thumbnails);
nemo_directory_force_reload (directory);
}
#if !defined (NEMO_OMIT_SELF_CHECK)
#include <eel/eel-debug.h>
#include "nemo-file-attributes.h"
static int data_dummy;
static gboolean got_files_flag;
static void
got_files_callback (NemoDirectory *directory, GList *files, gpointer callback_data)
{
g_assert (NEMO_IS_DIRECTORY (directory));
g_assert (g_list_length (files) > 10);
g_assert (callback_data == &data_dummy);
got_files_flag = TRUE;
}
/* Return the number of extant NemoDirectories */
int
nemo_directory_number_outstanding (void)
{
return directories ? g_hash_table_size (directories) : 0;
}
void
nemo_self_check_directory (void)
{
NemoDirectory *directory;
NemoFile *file;
directory = nemo_directory_get_by_uri ("file:///etc");
file = nemo_file_get_by_uri ("file:///etc/passwd");
EEL_CHECK_INTEGER_RESULT (g_hash_table_size (directories), 1);
nemo_directory_file_monitor_add
(directory, &data_dummy,
TRUE, 0, NULL, NULL);
/* FIXME: these need to be updated to the new metadata infrastructure
* as make check doesn't pass.
nemo_file_set_metadata (file, "test", "default", "value");
EEL_CHECK_STRING_RESULT (nemo_file_get_metadata (file, "test", "default"), "value");
nemo_file_set_boolean_metadata (file, "test_boolean", TRUE, TRUE);
EEL_CHECK_BOOLEAN_RESULT (nemo_file_get_boolean_metadata (file, "test_boolean", TRUE), TRUE);
nemo_file_set_boolean_metadata (file, "test_boolean", TRUE, FALSE);
EEL_CHECK_BOOLEAN_RESULT (nemo_file_get_boolean_metadata (file, "test_boolean", TRUE), FALSE);
EEL_CHECK_BOOLEAN_RESULT (nemo_file_get_boolean_metadata (NULL, "test_boolean", TRUE), TRUE);
nemo_file_set_integer_metadata (file, "test_integer", 0, 17);
EEL_CHECK_INTEGER_RESULT (nemo_file_get_integer_metadata (file, "test_integer", 0), 17);
nemo_file_set_integer_metadata (file, "test_integer", 0, -1);
EEL_CHECK_INTEGER_RESULT (nemo_file_get_integer_metadata (file, "test_integer", 0), -1);
nemo_file_set_integer_metadata (file, "test_integer", 42, 42);
EEL_CHECK_INTEGER_RESULT (nemo_file_get_integer_metadata (file, "test_integer", 42), 42);
EEL_CHECK_INTEGER_RESULT (nemo_file_get_integer_metadata (NULL, "test_integer", 42), 42);
EEL_CHECK_INTEGER_RESULT (nemo_file_get_integer_metadata (file, "nonexistent_key", 42), 42);
*/
EEL_CHECK_BOOLEAN_RESULT (nemo_directory_get_by_uri ("file:///etc") == directory, TRUE);
nemo_directory_unref (directory);
EEL_CHECK_BOOLEAN_RESULT (nemo_directory_get_by_uri ("file:///etc/") == directory, TRUE);
nemo_directory_unref (directory);
EEL_CHECK_BOOLEAN_RESULT (nemo_directory_get_by_uri ("file:///etc////") == directory, TRUE);
nemo_directory_unref (directory);
nemo_file_unref (file);
nemo_directory_file_monitor_remove (directory, &data_dummy);
nemo_directory_unref (directory);
while (g_hash_table_size (directories) != 0) {
gtk_main_iteration ();
}
EEL_CHECK_INTEGER_RESULT (g_hash_table_size (directories), 0);
directory = nemo_directory_get_by_uri ("file:///etc");
got_files_flag = FALSE;
nemo_directory_call_when_ready (directory,
NEMO_FILE_ATTRIBUTE_INFO |
NEMO_FILE_ATTRIBUTE_DEEP_COUNTS,
TRUE,
got_files_callback, &data_dummy);
while (!got_files_flag) {
gtk_main_iteration ();
}
EEL_CHECK_BOOLEAN_RESULT (directory->details->file_list == NULL, TRUE);
EEL_CHECK_INTEGER_RESULT (g_hash_table_size (directories), 1);
file = nemo_file_get_by_uri ("file:///etc/passwd");
/* EEL_CHECK_STRING_RESULT (nemo_file_get_metadata (file, "test", "default"), "value"); */
nemo_file_unref (file);
nemo_directory_unref (directory);
EEL_CHECK_INTEGER_RESULT (g_hash_table_size (directories), 0);
}
#endif /* !NEMO_OMIT_SELF_CHECK */
| {
"pile_set_name": "Github"
} |
{
"index_name": "antv_g6",
"start_urls": [
{
"url": "https://g6.antv.vision/zh",
"tags": [
"zh"
]
},
{
"url": "https://g6.antv.vision/en",
"tags": [
"en"
]
},
{
"url": "https://g6.antv.vision/.*/en/",
"tags": [
"en"
]
},
{
"url": "https://g6.antv.vision/.*/zh",
"tags": [
"zh"
]
}
],
"stop_urls": [
"/demo/"
],
"selectors": {
"lvl0": {
"selector": "header h2",
"global": true,
"default_value": "Documentation"
},
"lvl1": "article h1, .banner-title",
"lvl2": "article h2",
"lvl3": "article h3",
"lvl4": "article h4",
"lvl5": "article h5",
"text": "article p, article li, article table td, .banner-description"
},
"strip_chars": "#",
"conversation_id": [
"1023340198"
],
"min_indexed_level": 1,
"nb_hits": 14301
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2010, Oracle America, Inc.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the "Oracle America, Inc." nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* fixincludes should not add extern "C" to this file */
/*
* Rpc additions to <sys/types.h>
*/
#ifndef _RPC_TYPES_H
#define _RPC_TYPES_H 1
typedef int bool_t;
typedef int enum_t;
/* This needs to be changed to uint32_t in the future */
typedef unsigned long rpcprog_t;
typedef unsigned long rpcvers_t;
typedef unsigned long rpcproc_t;
typedef unsigned long rpcprot_t;
typedef unsigned long rpcport_t;
#define __dontcare__ -1
#ifndef FALSE
# define FALSE (0)
#endif
#ifndef TRUE
# define TRUE (1)
#endif
#ifndef NULL
# define NULL 0
#endif
#include <stdlib.h> /* For malloc decl. */
#define mem_alloc(bsize) malloc(bsize)
/*
* XXX: This must not use the second argument, or code in xdr_array.c needs
* to be modified.
*/
#define mem_free(ptr, bsize) free(ptr)
#ifndef makedev /* ie, we haven't already included it */
#include <sys/types.h>
#endif
#if defined __APPLE_CC__ || defined __FreeBSD__
# define __u_char_defined
# define __daddr_t_defined
#endif
#ifndef __u_char_defined
typedef __u_char u_char;
typedef __u_short u_short;
typedef __u_int u_int;
typedef __u_long u_long;
typedef __quad_t quad_t;
typedef __u_quad_t u_quad_t;
typedef __fsid_t fsid_t;
# define __u_char_defined
#endif
#ifndef __daddr_t_defined
typedef __daddr_t daddr_t;
typedef __caddr_t caddr_t;
# define __daddr_t_defined
#endif
#include <sys/time.h>
#include <sys/param.h>
#include <netinet/in.h>
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK (u_long)0x7F000001
#endif
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif
#endif /* rpc/types.h */
| {
"pile_set_name": "Github"
} |
'use strict';
export interface ILyric {
songId: string;
chunks?: Array<{
/**
* type:
* c: origin lyric sentence
*/
type: string;
text: string;
point?: number;
translation?: string;
}>;
};
| {
"pile_set_name": "Github"
} |
_BASE_: "../Base-RetinaNet.yaml"
MODEL:
WEIGHTS: "detectron2://ImageNetPretrained/MSRA/R-50.pkl"
RESNETS:
DEPTH: 50
| {
"pile_set_name": "Github"
} |
# HOW TO ADD NEW TESTS
#
# There are three general cases when you need to add new test:
# 1) Add new test to existing test case class. It can be done by adding new test_xxx method
# to the existing child of unittest.TestCase.
# - If test is common for dual and single core modes add it to test iplementation class (e.g. DebuggerTemplateTestsImpl)
# - If test should be run only in dual or single core mode add it to the respective specialized test class (e.g. DebuggerBreakpointTests(Dual|Single)
# 2) Add new test which requires new test case class. It can be done by adding new test class inherited from DebuggerTestsBase or one of its childs
# 3) Add new test which requires new test module. The minimalistic template module is shown here. Create test module file. Use pattern 'test_*.py' for the name of file.
# Copy contents of this file to new module and follow items 1-2.
import logging
import unittest
import debug_backend as dbg
from debug_backend_tests import *
def get_logger():
return logging.getLogger(__name__)
########################################################################
# TESTS IMPLEMENTATION #
########################################################################
class DebuggerTemplateTestsImpl:
""" Test cases which are common for dual and single core modes
"""
def test_something(self):
pass
########################################################################
# TESTS DEFINITION WITH SPECIAL TESTS #
########################################################################
class DebuggerTemplateTestsDual(DebuggerGenericTestAppTestsDual, DebuggerTemplateTestsImpl):
""" Test cases in dual core mode
"""
def test_something_special_for_dual_core_mode(self):
pass
class DebuggerTemplateTestsSingle(DebuggerGenericTestAppTestsSingle, DebuggerTemplateTestsImpl):
""" Test cases in single core mode
"""
# no special tests for single core mode yet
pass
| {
"pile_set_name": "Github"
} |
//===-- HexagonELFObjectWriter.cpp - Hexagon Target Descriptions ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Hexagon.h"
#include "MCTargetDesc/HexagonFixupKinds.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "hexagon-elf-writer"
using namespace llvm;
using namespace Hexagon;
namespace {
class HexagonELFObjectWriter : public MCELFObjectTargetWriter {
private:
StringRef CPU;
public:
HexagonELFObjectWriter(uint8_t OSABI, StringRef C);
unsigned getRelocType(MCContext &Ctx, MCValue const &Target,
MCFixup const &Fixup, bool IsPCRel) const override;
};
}
HexagonELFObjectWriter::HexagonELFObjectWriter(uint8_t OSABI, StringRef C)
: MCELFObjectTargetWriter(/*Is64bit*/ false, OSABI, ELF::EM_HEXAGON,
/*HasRelocationAddend*/ true),
CPU(C) {}
unsigned HexagonELFObjectWriter::getRelocType(MCContext &Ctx,
MCValue const &Target,
MCFixup const &Fixup,
bool IsPCRel) const {
MCSymbolRefExpr::VariantKind Variant = Target.getAccessVariant();
switch ((unsigned)Fixup.getKind()) {
default:
report_fatal_error("Unrecognized relocation type");
break;
case FK_Data_4:
switch(Variant) {
case MCSymbolRefExpr::VariantKind::VK_DTPREL:
return ELF::R_HEX_DTPREL_32;
case MCSymbolRefExpr::VariantKind::VK_GOT:
return ELF::R_HEX_GOT_32;
case MCSymbolRefExpr::VariantKind::VK_GOTREL:
return ELF::R_HEX_GOTREL_32;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_GD_GOT:
return ELF::R_HEX_GD_GOT_32;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_IE:
return ELF::R_HEX_IE_32;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_IE_GOT:
return ELF::R_HEX_IE_GOT_32;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_LD_GOT:
return ELF::R_HEX_LD_GOT_32;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_PCREL:
return ELF::R_HEX_32_PCREL;
case MCSymbolRefExpr::VariantKind::VK_TPREL:
return ELF::R_HEX_TPREL_32;
case MCSymbolRefExpr::VariantKind::VK_None:
return IsPCRel ? ELF::R_HEX_32_PCREL : ELF::R_HEX_32;
default:
report_fatal_error("Unrecognized variant type");
};
case FK_PCRel_4:
return ELF::R_HEX_32_PCREL;
case FK_Data_2:
switch(Variant) {
case MCSymbolRefExpr::VariantKind::VK_DTPREL:
return ELF::R_HEX_DTPREL_16;
case MCSymbolRefExpr::VariantKind::VK_GOT:
return ELF::R_HEX_GOT_16;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_GD_GOT:
return ELF::R_HEX_GD_GOT_16;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_IE_GOT:
return ELF::R_HEX_IE_GOT_16;
case MCSymbolRefExpr::VariantKind::VK_Hexagon_LD_GOT:
return ELF::R_HEX_LD_GOT_16;
case MCSymbolRefExpr::VariantKind::VK_TPREL:
return ELF::R_HEX_TPREL_16;
case MCSymbolRefExpr::VariantKind::VK_None:
return ELF::R_HEX_16;
default:
report_fatal_error("Unrecognized variant type");
};
case FK_Data_1:
return ELF::R_HEX_8;
case fixup_Hexagon_B22_PCREL:
return ELF::R_HEX_B22_PCREL;
case fixup_Hexagon_B15_PCREL:
return ELF::R_HEX_B15_PCREL;
case fixup_Hexagon_B7_PCREL:
return ELF::R_HEX_B7_PCREL;
case fixup_Hexagon_LO16:
return ELF::R_HEX_LO16;
case fixup_Hexagon_HI16:
return ELF::R_HEX_HI16;
case fixup_Hexagon_32:
return ELF::R_HEX_32;
case fixup_Hexagon_16:
return ELF::R_HEX_16;
case fixup_Hexagon_8:
return ELF::R_HEX_8;
case fixup_Hexagon_GPREL16_0:
return ELF::R_HEX_GPREL16_0;
case fixup_Hexagon_GPREL16_1:
return ELF::R_HEX_GPREL16_1;
case fixup_Hexagon_GPREL16_2:
return ELF::R_HEX_GPREL16_2;
case fixup_Hexagon_GPREL16_3:
return ELF::R_HEX_GPREL16_3;
case fixup_Hexagon_HL16:
return ELF::R_HEX_HL16;
case fixup_Hexagon_B13_PCREL:
return ELF::R_HEX_B13_PCREL;
case fixup_Hexagon_B9_PCREL:
return ELF::R_HEX_B9_PCREL;
case fixup_Hexagon_B32_PCREL_X:
return ELF::R_HEX_B32_PCREL_X;
case fixup_Hexagon_32_6_X:
return ELF::R_HEX_32_6_X;
case fixup_Hexagon_B22_PCREL_X:
return ELF::R_HEX_B22_PCREL_X;
case fixup_Hexagon_B15_PCREL_X:
return ELF::R_HEX_B15_PCREL_X;
case fixup_Hexagon_B13_PCREL_X:
return ELF::R_HEX_B13_PCREL_X;
case fixup_Hexagon_B9_PCREL_X:
return ELF::R_HEX_B9_PCREL_X;
case fixup_Hexagon_B7_PCREL_X:
return ELF::R_HEX_B7_PCREL_X;
case fixup_Hexagon_16_X:
return ELF::R_HEX_16_X;
case fixup_Hexagon_12_X:
return ELF::R_HEX_12_X;
case fixup_Hexagon_11_X:
return ELF::R_HEX_11_X;
case fixup_Hexagon_10_X:
return ELF::R_HEX_10_X;
case fixup_Hexagon_9_X:
return ELF::R_HEX_9_X;
case fixup_Hexagon_8_X:
return ELF::R_HEX_8_X;
case fixup_Hexagon_7_X:
return ELF::R_HEX_7_X;
case fixup_Hexagon_6_X:
return ELF::R_HEX_6_X;
case fixup_Hexagon_32_PCREL:
return ELF::R_HEX_32_PCREL;
case fixup_Hexagon_COPY:
return ELF::R_HEX_COPY;
case fixup_Hexagon_GLOB_DAT:
return ELF::R_HEX_GLOB_DAT;
case fixup_Hexagon_JMP_SLOT:
return ELF::R_HEX_JMP_SLOT;
case fixup_Hexagon_RELATIVE:
return ELF::R_HEX_RELATIVE;
case fixup_Hexagon_PLT_B22_PCREL:
return ELF::R_HEX_PLT_B22_PCREL;
case fixup_Hexagon_GOTREL_LO16:
return ELF::R_HEX_GOTREL_LO16;
case fixup_Hexagon_GOTREL_HI16:
return ELF::R_HEX_GOTREL_HI16;
case fixup_Hexagon_GOTREL_32:
return ELF::R_HEX_GOTREL_32;
case fixup_Hexagon_GOT_LO16:
return ELF::R_HEX_GOT_LO16;
case fixup_Hexagon_GOT_HI16:
return ELF::R_HEX_GOT_HI16;
case fixup_Hexagon_GOT_32:
return ELF::R_HEX_GOT_32;
case fixup_Hexagon_GOT_16:
return ELF::R_HEX_GOT_16;
case fixup_Hexagon_DTPMOD_32:
return ELF::R_HEX_DTPMOD_32;
case fixup_Hexagon_DTPREL_LO16:
return ELF::R_HEX_DTPREL_LO16;
case fixup_Hexagon_DTPREL_HI16:
return ELF::R_HEX_DTPREL_HI16;
case fixup_Hexagon_DTPREL_32:
return ELF::R_HEX_DTPREL_32;
case fixup_Hexagon_DTPREL_16:
return ELF::R_HEX_DTPREL_16;
case fixup_Hexagon_GD_PLT_B22_PCREL:
return ELF::R_HEX_GD_PLT_B22_PCREL;
case fixup_Hexagon_LD_PLT_B22_PCREL:
return ELF::R_HEX_LD_PLT_B22_PCREL;
case fixup_Hexagon_GD_GOT_LO16:
return ELF::R_HEX_GD_GOT_LO16;
case fixup_Hexagon_GD_GOT_HI16:
return ELF::R_HEX_GD_GOT_HI16;
case fixup_Hexagon_GD_GOT_32:
return ELF::R_HEX_GD_GOT_32;
case fixup_Hexagon_GD_GOT_16:
return ELF::R_HEX_GD_GOT_16;
case fixup_Hexagon_LD_GOT_LO16:
return ELF::R_HEX_LD_GOT_LO16;
case fixup_Hexagon_LD_GOT_HI16:
return ELF::R_HEX_LD_GOT_HI16;
case fixup_Hexagon_LD_GOT_32:
return ELF::R_HEX_LD_GOT_32;
case fixup_Hexagon_LD_GOT_16:
return ELF::R_HEX_LD_GOT_16;
case fixup_Hexagon_IE_LO16:
return ELF::R_HEX_IE_LO16;
case fixup_Hexagon_IE_HI16:
return ELF::R_HEX_IE_HI16;
case fixup_Hexagon_IE_32:
return ELF::R_HEX_IE_32;
case fixup_Hexagon_IE_GOT_LO16:
return ELF::R_HEX_IE_GOT_LO16;
case fixup_Hexagon_IE_GOT_HI16:
return ELF::R_HEX_IE_GOT_HI16;
case fixup_Hexagon_IE_GOT_32:
return ELF::R_HEX_IE_GOT_32;
case fixup_Hexagon_IE_GOT_16:
return ELF::R_HEX_IE_GOT_16;
case fixup_Hexagon_TPREL_LO16:
return ELF::R_HEX_TPREL_LO16;
case fixup_Hexagon_TPREL_HI16:
return ELF::R_HEX_TPREL_HI16;
case fixup_Hexagon_TPREL_32:
return ELF::R_HEX_TPREL_32;
case fixup_Hexagon_TPREL_16:
return ELF::R_HEX_TPREL_16;
case fixup_Hexagon_6_PCREL_X:
return ELF::R_HEX_6_PCREL_X;
case fixup_Hexagon_GOTREL_32_6_X:
return ELF::R_HEX_GOTREL_32_6_X;
case fixup_Hexagon_GOTREL_16_X:
return ELF::R_HEX_GOTREL_16_X;
case fixup_Hexagon_GOTREL_11_X:
return ELF::R_HEX_GOTREL_11_X;
case fixup_Hexagon_GOT_32_6_X:
return ELF::R_HEX_GOT_32_6_X;
case fixup_Hexagon_GOT_16_X:
return ELF::R_HEX_GOT_16_X;
case fixup_Hexagon_GOT_11_X:
return ELF::R_HEX_GOT_11_X;
case fixup_Hexagon_DTPREL_32_6_X:
return ELF::R_HEX_DTPREL_32_6_X;
case fixup_Hexagon_DTPREL_16_X:
return ELF::R_HEX_DTPREL_16_X;
case fixup_Hexagon_DTPREL_11_X:
return ELF::R_HEX_DTPREL_11_X;
case fixup_Hexagon_GD_GOT_32_6_X:
return ELF::R_HEX_GD_GOT_32_6_X;
case fixup_Hexagon_GD_GOT_16_X:
return ELF::R_HEX_GD_GOT_16_X;
case fixup_Hexagon_GD_GOT_11_X:
return ELF::R_HEX_GD_GOT_11_X;
case fixup_Hexagon_LD_GOT_32_6_X:
return ELF::R_HEX_LD_GOT_32_6_X;
case fixup_Hexagon_LD_GOT_16_X:
return ELF::R_HEX_LD_GOT_16_X;
case fixup_Hexagon_LD_GOT_11_X:
return ELF::R_HEX_LD_GOT_11_X;
case fixup_Hexagon_IE_32_6_X:
return ELF::R_HEX_IE_32_6_X;
case fixup_Hexagon_IE_16_X:
return ELF::R_HEX_IE_16_X;
case fixup_Hexagon_IE_GOT_32_6_X:
return ELF::R_HEX_IE_GOT_32_6_X;
case fixup_Hexagon_IE_GOT_16_X:
return ELF::R_HEX_IE_GOT_16_X;
case fixup_Hexagon_IE_GOT_11_X:
return ELF::R_HEX_IE_GOT_11_X;
case fixup_Hexagon_TPREL_32_6_X:
return ELF::R_HEX_TPREL_32_6_X;
case fixup_Hexagon_TPREL_16_X:
return ELF::R_HEX_TPREL_16_X;
case fixup_Hexagon_TPREL_11_X:
return ELF::R_HEX_TPREL_11_X;
case fixup_Hexagon_23_REG:
return ELF::R_HEX_23_REG;
}
}
MCObjectWriter *llvm::createHexagonELFObjectWriter(raw_pwrite_stream &OS,
uint8_t OSABI,
StringRef CPU) {
MCELFObjectTargetWriter *MOTW = new HexagonELFObjectWriter(OSABI, CPU);
return createELFObjectWriter(MOTW, OS, /*IsLittleEndian*/ true);
}
| {
"pile_set_name": "Github"
} |
#
# Copyright 2014 Facebook
#
# 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.
from __future__ import absolute_import, division, print_function
from contextlib import closing
import os
import socket
from tornado.concurrent import Future
from tornado.netutil import bind_sockets, Resolver
from tornado.queues import Queue
from tornado.tcpclient import TCPClient, _Connector
from tornado.tcpserver import TCPServer
from tornado.testing import AsyncTestCase, gen_test
from tornado.test.util import skipIfNoIPv6, unittest, refusing_port, skipIfNonUnix
from tornado.gen import TimeoutError
# Fake address families for testing. Used in place of AF_INET
# and AF_INET6 because some installations do not have AF_INET6.
AF1, AF2 = 1, 2
class TestTCPServer(TCPServer):
def __init__(self, family):
super(TestTCPServer, self).__init__()
self.streams = []
self.queue = Queue()
sockets = bind_sockets(None, 'localhost', family)
self.add_sockets(sockets)
self.port = sockets[0].getsockname()[1]
def handle_stream(self, stream, address):
self.streams.append(stream)
self.queue.put(stream)
def stop(self):
super(TestTCPServer, self).stop()
for stream in self.streams:
stream.close()
class TCPClientTest(AsyncTestCase):
def setUp(self):
super(TCPClientTest, self).setUp()
self.server = None
self.client = TCPClient()
def start_server(self, family):
if family == socket.AF_UNSPEC and 'TRAVIS' in os.environ:
self.skipTest("dual-stack servers often have port conflicts on travis")
self.server = TestTCPServer(family)
return self.server.port
def stop_server(self):
if self.server is not None:
self.server.stop()
self.server = None
def tearDown(self):
self.client.close()
self.stop_server()
super(TCPClientTest, self).tearDown()
def skipIfLocalhostV4(self):
# The port used here doesn't matter, but some systems require it
# to be non-zero if we do not also pass AI_PASSIVE.
addrinfo = self.io_loop.run_sync(lambda: Resolver().resolve('localhost', 80))
families = set(addr[0] for addr in addrinfo)
if socket.AF_INET6 not in families:
self.skipTest("localhost does not resolve to ipv6")
@gen_test
def do_test_connect(self, family, host, source_ip=None, source_port=None):
port = self.start_server(family)
stream = yield self.client.connect(host, port,
source_ip=source_ip,
source_port=source_port)
server_stream = yield self.server.queue.get()
with closing(stream):
stream.write(b"hello")
data = yield server_stream.read_bytes(5)
self.assertEqual(data, b"hello")
def test_connect_ipv4_ipv4(self):
self.do_test_connect(socket.AF_INET, '127.0.0.1')
def test_connect_ipv4_dual(self):
self.do_test_connect(socket.AF_INET, 'localhost')
@skipIfNoIPv6
def test_connect_ipv6_ipv6(self):
self.skipIfLocalhostV4()
self.do_test_connect(socket.AF_INET6, '::1')
@skipIfNoIPv6
def test_connect_ipv6_dual(self):
self.skipIfLocalhostV4()
if Resolver.configured_class().__name__.endswith('TwistedResolver'):
self.skipTest('TwistedResolver does not support multiple addresses')
self.do_test_connect(socket.AF_INET6, 'localhost')
def test_connect_unspec_ipv4(self):
self.do_test_connect(socket.AF_UNSPEC, '127.0.0.1')
@skipIfNoIPv6
def test_connect_unspec_ipv6(self):
self.skipIfLocalhostV4()
self.do_test_connect(socket.AF_UNSPEC, '::1')
def test_connect_unspec_dual(self):
self.do_test_connect(socket.AF_UNSPEC, 'localhost')
@gen_test
def test_refused_ipv4(self):
cleanup_func, port = refusing_port()
self.addCleanup(cleanup_func)
with self.assertRaises(IOError):
yield self.client.connect('127.0.0.1', port)
def test_source_ip_fail(self):
'''
Fail when trying to use the source IP Address '8.8.8.8'.
'''
self.assertRaises(socket.error,
self.do_test_connect,
socket.AF_INET,
'127.0.0.1',
source_ip='8.8.8.8')
def test_source_ip_success(self):
'''
Success when trying to use the source IP Address '127.0.0.1'
'''
self.do_test_connect(socket.AF_INET, '127.0.0.1', source_ip='127.0.0.1')
@skipIfNonUnix
def test_source_port_fail(self):
'''
Fail when trying to use source port 1.
'''
self.assertRaises(socket.error,
self.do_test_connect,
socket.AF_INET,
'127.0.0.1',
source_port=1)
@gen_test
def test_connect_timeout(self):
timeout = 0.05
class TimeoutResolver(Resolver):
def resolve(self, *args, **kwargs):
return Future() # never completes
with self.assertRaises(TimeoutError):
yield TCPClient(resolver=TimeoutResolver()).connect(
'1.2.3.4', 12345, timeout=timeout)
class TestConnectorSplit(unittest.TestCase):
def test_one_family(self):
# These addresses aren't in the right format, but split doesn't care.
primary, secondary = _Connector.split(
[(AF1, 'a'),
(AF1, 'b')])
self.assertEqual(primary, [(AF1, 'a'),
(AF1, 'b')])
self.assertEqual(secondary, [])
def test_mixed(self):
primary, secondary = _Connector.split(
[(AF1, 'a'),
(AF2, 'b'),
(AF1, 'c'),
(AF2, 'd')])
self.assertEqual(primary, [(AF1, 'a'), (AF1, 'c')])
self.assertEqual(secondary, [(AF2, 'b'), (AF2, 'd')])
class ConnectorTest(AsyncTestCase):
class FakeStream(object):
def __init__(self):
self.closed = False
def close(self):
self.closed = True
def setUp(self):
super(ConnectorTest, self).setUp()
self.connect_futures = {}
self.streams = {}
self.addrinfo = [(AF1, 'a'), (AF1, 'b'),
(AF2, 'c'), (AF2, 'd')]
def tearDown(self):
# Unless explicitly checked (and popped) in the test, we shouldn't
# be closing any streams
for stream in self.streams.values():
self.assertFalse(stream.closed)
super(ConnectorTest, self).tearDown()
def create_stream(self, af, addr):
stream = ConnectorTest.FakeStream()
self.streams[addr] = stream
future = Future()
self.connect_futures[(af, addr)] = future
return stream, future
def assert_pending(self, *keys):
self.assertEqual(sorted(self.connect_futures.keys()), sorted(keys))
def resolve_connect(self, af, addr, success):
future = self.connect_futures.pop((af, addr))
if success:
future.set_result(self.streams[addr])
else:
self.streams.pop(addr)
future.set_exception(IOError())
# Run the loop to allow callbacks to be run.
self.io_loop.add_callback(self.stop)
self.wait()
def assert_connector_streams_closed(self, conn):
for stream in conn.streams:
self.assertTrue(stream.closed)
def start_connect(self, addrinfo):
conn = _Connector(addrinfo, self.create_stream)
# Give it a huge timeout; we'll trigger timeouts manually.
future = conn.start(3600, connect_timeout=self.io_loop.time() + 3600)
return conn, future
def test_immediate_success(self):
conn, future = self.start_connect(self.addrinfo)
self.assertEqual(list(self.connect_futures.keys()),
[(AF1, 'a')])
self.resolve_connect(AF1, 'a', True)
self.assertEqual(future.result(), (AF1, 'a', self.streams['a']))
def test_immediate_failure(self):
# Fail with just one address.
conn, future = self.start_connect([(AF1, 'a')])
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assertRaises(IOError, future.result)
def test_one_family_second_try(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'))
self.resolve_connect(AF1, 'b', True)
self.assertEqual(future.result(), (AF1, 'b', self.streams['b']))
def test_one_family_second_try_failure(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'))
self.resolve_connect(AF1, 'b', False)
self.assertRaises(IOError, future.result)
def test_one_family_second_try_timeout(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
# trigger the timeout while the first lookup is pending;
# nothing happens.
conn.on_timeout()
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'))
self.resolve_connect(AF1, 'b', True)
self.assertEqual(future.result(), (AF1, 'b', self.streams['b']))
def test_two_families_immediate_failure(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'), (AF2, 'c'))
self.resolve_connect(AF1, 'b', False)
self.resolve_connect(AF2, 'c', True)
self.assertEqual(future.result(), (AF2, 'c', self.streams['c']))
def test_two_families_timeout(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
conn.on_timeout()
self.assert_pending((AF1, 'a'), (AF2, 'c'))
self.resolve_connect(AF2, 'c', True)
self.assertEqual(future.result(), (AF2, 'c', self.streams['c']))
# resolving 'a' after the connection has completed doesn't start 'b'
self.resolve_connect(AF1, 'a', False)
self.assert_pending()
def test_success_after_timeout(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
conn.on_timeout()
self.assert_pending((AF1, 'a'), (AF2, 'c'))
self.resolve_connect(AF1, 'a', True)
self.assertEqual(future.result(), (AF1, 'a', self.streams['a']))
# resolving 'c' after completion closes the connection.
self.resolve_connect(AF2, 'c', True)
self.assertTrue(self.streams.pop('c').closed)
def test_all_fail(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
conn.on_timeout()
self.assert_pending((AF1, 'a'), (AF2, 'c'))
self.resolve_connect(AF2, 'c', False)
self.assert_pending((AF1, 'a'), (AF2, 'd'))
self.resolve_connect(AF2, 'd', False)
# one queue is now empty
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'))
self.assertFalse(future.done())
self.resolve_connect(AF1, 'b', False)
self.assertRaises(IOError, future.result)
def test_one_family_timeout_after_connect_timeout(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
conn.on_connect_timeout()
# the connector will close all streams on connect timeout, we
# should explicitly pop the connect_future.
self.connect_futures.pop((AF1, 'a'))
self.assertTrue(self.streams.pop('a').closed)
conn.on_timeout()
# if the future is set with TimeoutError, we will not iterate next
# possible address.
self.assert_pending()
self.assertEqual(len(conn.streams), 1)
self.assert_connector_streams_closed(conn)
self.assertRaises(TimeoutError, future.result)
def test_one_family_success_before_connect_timeout(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', True)
conn.on_connect_timeout()
self.assert_pending()
self.assertEqual(self.streams['a'].closed, False)
# success stream will be pop
self.assertEqual(len(conn.streams), 0)
# streams in connector should be closed after connect timeout
self.assert_connector_streams_closed(conn)
self.assertEqual(future.result(), (AF1, 'a', self.streams['a']))
def test_one_family_second_try_after_connect_timeout(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'))
conn.on_connect_timeout()
self.connect_futures.pop((AF1, 'b'))
self.assertTrue(self.streams.pop('b').closed)
self.assert_pending()
self.assertEqual(len(conn.streams), 2)
self.assert_connector_streams_closed(conn)
self.assertRaises(TimeoutError, future.result)
def test_one_family_second_try_failure_before_connect_timeout(self):
conn, future = self.start_connect([(AF1, 'a'), (AF1, 'b')])
self.assert_pending((AF1, 'a'))
self.resolve_connect(AF1, 'a', False)
self.assert_pending((AF1, 'b'))
self.resolve_connect(AF1, 'b', False)
conn.on_connect_timeout()
self.assert_pending()
self.assertEqual(len(conn.streams), 2)
self.assert_connector_streams_closed(conn)
self.assertRaises(IOError, future.result)
def test_two_family_timeout_before_connect_timeout(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
conn.on_timeout()
self.assert_pending((AF1, 'a'), (AF2, 'c'))
conn.on_connect_timeout()
self.connect_futures.pop((AF1, 'a'))
self.assertTrue(self.streams.pop('a').closed)
self.connect_futures.pop((AF2, 'c'))
self.assertTrue(self.streams.pop('c').closed)
self.assert_pending()
self.assertEqual(len(conn.streams), 2)
self.assert_connector_streams_closed(conn)
self.assertRaises(TimeoutError, future.result)
def test_two_family_success_after_timeout(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
conn.on_timeout()
self.assert_pending((AF1, 'a'), (AF2, 'c'))
self.resolve_connect(AF1, 'a', True)
# if one of streams succeed, connector will close all other streams
self.connect_futures.pop((AF2, 'c'))
self.assertTrue(self.streams.pop('c').closed)
self.assert_pending()
self.assertEqual(len(conn.streams), 1)
self.assert_connector_streams_closed(conn)
self.assertEqual(future.result(), (AF1, 'a', self.streams['a']))
def test_two_family_timeout_after_connect_timeout(self):
conn, future = self.start_connect(self.addrinfo)
self.assert_pending((AF1, 'a'))
conn.on_connect_timeout()
self.connect_futures.pop((AF1, 'a'))
self.assertTrue(self.streams.pop('a').closed)
self.assert_pending()
conn.on_timeout()
# if the future is set with TimeoutError, connector will not
# trigger secondary address.
self.assert_pending()
self.assertEqual(len(conn.streams), 1)
self.assert_connector_streams_closed(conn)
self.assertRaises(TimeoutError, future.result)
| {
"pile_set_name": "Github"
} |
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Part of Injectable Generic Camera System
// Copyright(c) 2017, Frans Bouma
// All rights reserved.
// https://github.com/FransBouma/InjectableGenericCameraSystem
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and / or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
#include "Gamepad.h"
namespace IGCS
{
// System defaults
#define FRAME_SLEEP 8 // in milliseconds
#define IGCS_OVERLAY_INI_FILENAME "IGCS_overlay.ini"
#define IGCS_SETTINGS_INI_FILENAME "IGCS_settings.ini"
#define IGCS_SETTINGS_SAVE_DELAY 5.0f // in seconds
#define IGCS_SPLASH_DURATION 2.0f // in seconds
// Keyboard system control
#define IGCS_KEY_TOGGLE_OVERLAY VK_INSERT // With control
#define IGCS_KEY_CAMERA_ENABLE VK_INSERT
#define IGCS_KEY_CAMERA_LOCK VK_HOME
#define IGCS_KEY_ROTATE_RIGHT VK_RIGHT // yaw
#define IGCS_KEY_ROTATE_LEFT VK_LEFT
#define IGCS_KEY_ROTATE_UP VK_UP // pitch
#define IGCS_KEY_ROTATE_DOWN VK_DOWN
#define IGCS_KEY_MOVE_FORWARD VK_NUMPAD8
#define IGCS_KEY_MOVE_BACKWARD VK_NUMPAD5
#define IGCS_KEY_MOVE_LEFT VK_NUMPAD4
#define IGCS_KEY_MOVE_RIGHT VK_NUMPAD6
#define IGCS_KEY_MOVE_UP VK_NUMPAD7
#define IGCS_KEY_MOVE_DOWN VK_NUMPAD9
#define IGCS_KEY_TILT_LEFT VK_NUMPAD1 // roll
#define IGCS_KEY_TILT_RIGHT VK_NUMPAD3
#define IGCS_KEY_FOV_RESET VK_MULTIPLY
#define IGCS_KEY_FOV_INCREASE VK_ADD
#define IGCS_KEY_FOV_DECREASE VK_SUBTRACT
#define IGCS_KEY_BLOCK_INPUT VK_DECIMAL
#define IGCS_KEY_TIMESTOP VK_NUMPAD0
#define IGCS_KEY_DECREASE_HOTSAMPLE_FACTOR VK_OEM_4 // [{
#define IGCS_KEY_INCREASE_HOTSAMPLE_FACTOR VK_OEM_6 // ]}
#define IGCS_KEY_HOTSAMPLE_ENABLE VK_DELETE
#define IGCS_BUTTON_FOV_DECREASE Gamepad::button_t::UP
#define IGCS_BUTTON_FOV_INCREASE Gamepad::button_t::DOWN
#define IGCS_BUTTON_RESET_FOV Gamepad::button_t::B
#define IGCS_BUTTON_TILT_LEFT Gamepad::button_t::LEFT
#define IGCS_BUTTON_TILT_RIGHT Gamepad::button_t::RIGHT
#define IGCS_BUTTON_FASTER Gamepad::button_t::Y
#define IGCS_BUTTON_SLOWER Gamepad::button_t::X
#define IGCS_BUTTON_BLOCK_INPUT Gamepad::button_t::RB
static const byte jmpFarInstructionBytes[6] = { 0xff, 0x25, 0, 0, 0, 0 }; // instruction bytes for jmp qword ptr [0000]
} | {
"pile_set_name": "Github"
} |
/* P動作--企圖進入一關鍵區 */
void semaphore_P(int sem_id)
{
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1; /* P動作-訊號量值減少 */
sb.sem_flg = SEM_UNDO; /* 若果死亡,解除訊號量請求*/
if (semop(sem_id, &sb, 1) == -1){
fprintf(stderr,”semaphore_P failed\n”);
return(0);
}
return(1);
}
/* V動作--離開關鍵區 */
void semaphore_V(int sem_id)
{
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = 1; /* V動作-訊號量值增加 */
sb.sem_flg = SEM_UNDO; /* 若果死亡,解除訊號量請求*/
if (semop(sem_id, &sb, 1) == -1){
fprintf(stderr,”semaphore_V failed\n”);
return(0);
}
return(1);
}
| {
"pile_set_name": "Github"
} |
sequenceDiagram
participant Initiating
participant Responding
Initiating->>Responding: M1
Responding->>Initiating: M2
Initiating->>Responding: M3
Responding->>Initiating: M4
Initiating->>Responding: M5
| {
"pile_set_name": "Github"
} |
// Scintilla source code edit control
/** @file LexMaxima.cxx
** Lexer for Maxima (http://maxima.sourceforge.net).
** Written by Gunter Königsmann based on the lisp lexer by Alexey Yutkin and Neil Hodgson .
**/
// Copyright 2018 by Gunter Königsmann <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
static inline bool isMaximaoperator(char ch) {
return (ch == '\'' || ch == '`' || ch == '(' ||
ch == ')' || ch == '[' || ch == ']' ||
ch == '{' || ch == '}' || ch == '!' ||
ch == '*' || ch == '/' || ch == '^' ||
ch == ',' || ch == ':' || ch == '+' ||
ch == '-');
}
static void ColouriseMaximaDoc(Sci_PositionU startPos, Sci_Position length, int lastStyle,
WordList *[],
Accessor &styler) {
styler.StartAt(startPos);
Sci_PositionU lengthDoc = startPos + length;
styler.StartSegment(startPos);
Sci_PositionU i = startPos;
// If we are in the middle of a comment we go back to its start before highlighting
if(lastStyle == SCE_MAXIMA_COMMENT)
{
while((i>0) &&
!((styler.SafeGetCharAt(i+1) == '*') && (styler.SafeGetCharAt(i) == '/')))
i--;
}
for (; i < lengthDoc; i++) {
char ch = styler.SafeGetCharAt(i);
char chNext = styler.SafeGetCharAt(i + 1);
if (styler.IsLeadByte(ch))
continue;
// Handle comments.
// Comments start with /* and end with */
if((ch == '/') && (chNext == '*'))
{
i++;i++;
chNext = styler.SafeGetCharAt(i);
for (; i < lengthDoc; i++)
{
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if((ch == '*') && (chNext == '/'))
{
i++;
i++;
break;
}
}
if(i > lengthDoc)
i = lengthDoc;
i--;
styler.ColourTo(i, SCE_MAXIMA_COMMENT);
continue;
}
// Handle Operators
if(isMaximaoperator(ch))
{
styler.ColourTo(i, SCE_MAXIMA_OPERATOR);
continue;
}
// Handle command endings.
if((ch == '$') || (ch == ';'))
{
styler.ColourTo(i, SCE_MAXIMA_COMMANDENDING);
continue;
}
// Handle numbers. Numbers always begin with a digit.
if(IsASCII(ch) && isdigit(ch))
{
i++;
for (; i < lengthDoc; i++)
{
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if(ch == '.')
continue;
// A "e" or similar can be followed by a "+" or a "-"
if(((ch == 'e') || (ch == 'b') || (ch == 'g') || (ch == 'f')) &&
((chNext == '+') || (chNext == '-')))
{
i++;
chNext = styler.SafeGetCharAt(i + 1);
continue;
}
if(!IsASCII(ch) || !(isdigit(ch) || islower(ch) || isupper(ch)))
{
i--;
break;
}
}
styler.ColourTo(i, SCE_MAXIMA_NUMBER);
continue;
}
// Handle strings
if(ch == '\"')
{
i++;
for (; i < lengthDoc; i++)
{
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if(ch == '\\')
i++;
else
{
if(ch == '\"')
break;
}
}
styler.ColourTo(i, SCE_MAXIMA_STRING);
continue;
}
// Handle keywords. Maxima treats Non-ASCII chars as ordinary letters.
if(((!IsASCII(ch))) || isalpha(ch) || (ch == '_'))
{
char cmd[100];
int cmdidx = 0;
memset(cmd,0,100);
cmd[cmdidx++] = ch;
i++;
for (; i < lengthDoc; i++)
{
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if(ch == '\\')
{
if(cmdidx < 99)
cmd[cmdidx++] = ch;
i++;
if(cmdidx < 99)
cmd[cmdidx++] = ch;
continue;
}
if(isMaximaoperator(ch) || ((IsASCII(ch) && !isalpha(ch) && !isdigit(ch) && (ch != '_'))))
{
i--;
break;
}
if(cmdidx < 99)
cmd[cmdidx++] = ch;
}
// A few known keywords
if(
(strncmp(cmd,"if",99) == 0) ||
(strncmp(cmd,"then",99) == 0) ||
(strncmp(cmd,"else",99) == 0) ||
(strncmp(cmd,"thru",99) == 0) ||
(strncmp(cmd,"for",99) == 0) ||
(strncmp(cmd,"while",99) == 0) ||
(strncmp(cmd,"do",99) == 0)
)
{
styler.ColourTo(i, SCE_MAXIMA_COMMAND);
continue;
}
// All other keywords are functions if they are followed
// by an opening parenthesis
char nextNonwhitespace = ' ';
for (Sci_PositionU o = i + 1; o < lengthDoc; o++)
{
nextNonwhitespace = styler.SafeGetCharAt(o);
if(!IsASCII(nextNonwhitespace) || !isspacechar(nextNonwhitespace))
break;
}
if(nextNonwhitespace == '(')
{
styler.ColourTo(i, SCE_MAXIMA_COMMAND);
}
else
{
styler.ColourTo(i, SCE_MAXIMA_VARIABLE);
}
continue;
}
styler.ColourTo(i-1, SCE_MAXIMA_UNKNOWN);
}
}
LexerModule lmMaxima(SCLEX_MAXIMA, ColouriseMaximaDoc, "maxima", 0, 0);
| {
"pile_set_name": "Github"
} |
/**
* @file
* Styles used by the Update Manager module.
*/
.checked .button {
margin: 1em;
vertical-align: middle;
}
table.update {
width: 100%;
margin-top: .5em;
}
.update tr {
position: relative;
}
.update .project {
font-weight: bold;
font-size: 110%;
}
@media all and (min-width: 550px) {
.update .project {
float: left; /* LTR */
}
[dir="rtl"] .update .project {
float: right;
}
.update .version-status {
float: right; /* LTR */
}
[dir="rtl"] .update .version-status {
float: left;
}
.update .versions,
.update .project-info {
clear: both;
}
}
@media all and (min-width: 550px) {
.update .version-status {
text-align: right;
font-size: 110%;
position: static;
float: right; /* LTR */
padding-left: 10px;
}
[dir="rtl"] .update .version-status {
float: left;
padding-left: 0;
padding-right: 10px;
}
}
.update .version-date {
white-space: nowrap;
display: none;
}
@media all and (min-width: 550px) {
.update .version-date {
display: inline-block;
}
}
.current-version,
.new-version {
direction: ltr; /* Note: version numbers should always be LTR. */
}
.update .version {
padding-top: 5px;
}
.update .version div {
box-sizing: border-box;
padding: 0;
margin: 0;
}
@media all and (min-width: 550px) {
.update .version-info {
width: 66%;
display: inline-block;
vertical-align: top;
}
.update .version-links {
width: 33%;
display: inline-block;
vertical-align: top;
}
.update .version-details {
display: inline-block;
}
}
.update .version-links ul {
font-size: .9em;
list-style-type: none;
padding: 0;
margin: 5px 0 0 0;
}
@media all and (min-width: 550px) {
.update .version-links ul {
text-align: right; /* LTR */
}
[dir="rtl"] .update .version-links {
text-align: left;
}
}
.update .security-error,
.update .version-recommended-strong .version-title {
font-weight: bold;
}
.update .version-security .version-title {
color: #EC351C;
}
.update .check-manually {
padding-left: 1em; /* LTR */
}
[dir="rtl"] .update .check-manually {
padding-left: 0;
padding-right: 1em;
}
.update .project-info {
display: none;
}
@media all and (min-width: 768px) {
.update .project-info {
display: block;
}
}
.update-major-version-warning {
color: #ff0000;
}
| {
"pile_set_name": "Github"
} |
---
title: Quebec Province of Canada
homepage: https://www.donneesquebec.ca/en/
category: Government
description:
version:
keywords:
image:
temporal:
spatial:
access_level:
copyrights:
accrual_periodicity:
specification:
data_quality: false
data_dictionary:
language: en
license:
publisher:
organization:
issued_time:
sources: []
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
/*
**
** Author: Jishnu Mohan <[email protected]>
** Copyright © 2013-2014 Jishnu Mohan, Swathanthra Malayalam Computing (SMC), International Centre for Free and Open Source Software (ICFOSS)
**
** 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.
*/
-->
<merge
xmlns:latin="http://schemas.android.com/apk/res-auto"
>
<include latin:keyboardLayout="@xml/key_styles_common" />
<Row latin:keyWidth="7.692%p" >
<include latin:keyboardLayout="@xml/rowkeys_tamil_inscript1" />
</Row>
<Row latin:keyWidth="7.692%p" >
<include latin:keyboardLayout="@xml/rowkeys_tamil_inscript2" />
</Row>
<Row latin:keyWidth="7.692%p" >
<include
latin:keyboardLayout="@xml/rowkeys_tamil_inscript3"
latin:keyXPos="3.846%p" />
<Key
latin:keyStyle="deleteKeyStyle"
latin:keyWidth="fillRight"
latin:visualInsetsLeft="1%p" />
</Row>
<Row latin:keyWidth="7.692%p" >
<Key
latin:keyStyle="shiftKeyStyle"
latin:keyWidth="11.538%p"
latin:visualInsetsRight="1%p" />
<include latin:keyboardLayout="@xml/rowkeys_tamil_inscript4" />
<Key
latin:keyStyle="shiftKeyStyle"
latin:keyWidth="fillRight"
latin:visualInsetsLeft="1%p" />
</Row>
<include latin:keyboardLayout="@xml/row_pcqwerty5" />
</merge>
| {
"pile_set_name": "Github"
} |
Symfony Debug Extension for PHP 5
=================================
This extension publishes several functions to help building powerful debugging tools.
It is compatible with PHP 5.3, 5.4, 5.5 and 5.6; with ZTS and non-ZTS modes.
It is not required thus not provided for PHP 7.
symfony_zval_info()
-------------------
- exposes zval_hash/refcounts, allowing e.g. efficient exploration of arbitrary structures in PHP,
- does work with references, preventing memory copying.
Its behavior is about the same as:
```php
<?php
function symfony_zval_info($key, $array, $options = 0)
{
// $options is currently not used, but could be in future version.
if (!array_key_exists($key, $array)) {
return null;
}
$info = array(
'type' => gettype($array[$key]),
'zval_hash' => /* hashed memory address of $array[$key] */,
'zval_refcount' => /* internal zval refcount of $array[$key] */,
'zval_isref' => /* is_ref status of $array[$key] */,
);
switch ($info['type']) {
case 'object':
$info += array(
'object_class' => get_class($array[$key]),
'object_refcount' => /* internal object refcount of $array[$key] */,
'object_hash' => spl_object_hash($array[$key]),
'object_handle' => /* internal object handle $array[$key] */,
);
break;
case 'resource':
$info += array(
'resource_handle' => (int) $array[$key],
'resource_type' => get_resource_type($array[$key]),
'resource_refcount' => /* internal resource refcount of $array[$key] */,
);
break;
case 'array':
$info += array(
'array_count' => count($array[$key]),
);
break;
case 'string':
$info += array(
'strlen' => strlen($array[$key]),
);
break;
}
return $info;
}
```
symfony_debug_backtrace()
-------------------------
This function works like debug_backtrace(), except that it can fetch the full backtrace in case of fatal errors:
```php
function foo() { fatal(); }
function bar() { foo(); }
function sd() { var_dump(symfony_debug_backtrace()); }
register_shutdown_function('sd');
bar();
/* Will output
Fatal error: Call to undefined function fatal() in foo.php on line 42
array(3) {
[0]=>
array(2) {
["function"]=>
string(2) "sd"
["args"]=>
array(0) {
}
}
[1]=>
array(4) {
["file"]=>
string(7) "foo.php"
["line"]=>
int(1)
["function"]=>
string(3) "foo"
["args"]=>
array(0) {
}
}
[2]=>
array(4) {
["file"]=>
string(102) "foo.php"
["line"]=>
int(2)
["function"]=>
string(3) "bar"
["args"]=>
array(0) {
}
}
}
*/
```
Usage
-----
To enable the extension from source, run:
```
phpize
./configure
make
sudo make install
```
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
{% extends "base.html" %}
{% block title %}{{ SITENAME }} - Authors{% endblock %}
{% block content %}
<h1>Authors on {{ SITENAME }}</h1>
<ul>
{%- for author, articles in authors|sort %}
<li><a href="{{ SITEURL }}/{{ author.url }}">{{ author }}</a> ({{ articles|count }})</li>
{% endfor %}
</ul>
{% endblock %}
| {
"pile_set_name": "Github"
} |
/**
* @fileoverview Tests the common tags file.
*
* @author Pete LePage <[email protected]>
*/
'use strict';
/**
* Tests and validates a commonTags.json file.
* Note: The returned promise always resolves, it will never reject.
*
* @param {string} filename The name of the file to be tested.
* @param {Object} tags The parsed contents of the tags file.
* @return {Promise} A promise with the result of the test.
*/
function test(filename, tags) {
if (Array.isArray(tags) === true) {
return Promise.resolve(true);
}
return Promise.reject({
level: 'ERROR',
filename: filename,
message: `Common tags file must be an array, was ${typeof tags}`,
});
}
exports.test = test;
| {
"pile_set_name": "Github"
} |
#include <libjrpc/jrpc.h>
struct jrpc_mapper *a6o_get_rpcbe_mapper(void);
| {
"pile_set_name": "Github"
} |
//TODO: Осталось сделать только список цветов с перебором по букве диска
//TODO: И аналогично для цвета фона градусника/картинок/текста и самого градусника
/*
Copyright (c) 2010-present Maximus5
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef _DEBUG
// Раскомментировать, чтобы сразу после загрузки плагина показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
// #define SHOW_WRITING_RECTS
#endif
#include "../common/Common.h"
#include "../common/CEStr.h"
#ifdef _DEBUG
#pragma warning( disable : 4995 )
#endif
#include "../common/pluginW1761.hpp" // Отличается от 995 наличием SynchoApi
#ifdef _DEBUG
#pragma warning( default : 4995 )
#endif
#define GDIPVER 0x0110
#include "../common/GdiPlusLt.h"
#include "../common/xmllite.h"
#include "../common/MStrDup.h"
#include "../common/MStream.h"
#include "../common/UnicodeChars.h"
#include "../common/FarVersion.h"
#include "../common/MSectionSimple.h"
#include "../common/WThreads.h"
#include "ConEmuBg.h"
#define MAKEFARVERSION(major,minor,build) ( ((major)<<8) | (minor) | ((build)<<16))
#define DBGSTR(s) OutputDebugString(s);
#if defined(__GNUC__)
extern "C" {
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved);
void WINAPI SetStartupInfoW(void *aInfo);
void WINAPI OnConEmuLoaded(struct ConEmuLoadedArg* pConEmuInfo);
void WINAPI GetPluginInfoWcmn(void *piv);
};
#endif
#ifndef DT_HIDEPREFIX
#define DT_HIDEPREFIX 0x00100000
#endif
HMODULE ghPluginModule = NULL; // ConEmuBg.dll - сам плагин
//wchar_t* gszRootKey = NULL;
FarVersion gFarVersion = {};
static RegisterBackground_t gfRegisterBackground = NULL;
bool gbInStartPlugin = false;
bool gbSetStartupInfoOk = false;
ConEmuBgSettings gSettings[] = {
{L"PluginEnabled", (LPBYTE)&gbBackgroundEnabled, REG_BINARY, 1},
{L"XmlConfigFile", (LPBYTE)gsXmlConfigFile, REG_SZ, countof(gsXmlConfigFile)},
//{L"LinesColor", (LPBYTE)&gcrLinesColor, REG_DWORD, 4},
//{L"HilightType", (LPBYTE)&giHilightType, REG_DWORD, 4},
//{L"HilightPlugins", (LPBYTE)&gbHilightPlugins, REG_BINARY, 1},
//{L"HilightPlugBack", (LPBYTE)&gcrHilightPlugBack, REG_DWORD, 4},
{NULL}
};
BOOL gbBackgroundEnabled = FALSE;
wchar_t gsXmlConfigFile[MAX_PATH] = {};
BOOL gbMonitorFileChange = FALSE;
//COLORREF gcrLinesColor = RGB(0,0,0xA8); // чуть светлее синего
//int giHilightType = 0; // 0 - линии, 1 - полосы
//BOOL gbHilightPlugins = FALSE;
//COLORREF gcrHilightPlugBack = RGB(0xA8,0,0); // чуть светлее красного
// minimal(?) FAR version 2.0 alpha build FAR_X_VER
int WINAPI GetMinFarVersionW(void)
{
// ACTL_SYNCHRO required
return MAKEFARVERSION(2,0,std::max(1007,FAR_X_VER));
}
void WINAPI GetPluginInfoWcmn(void *piv)
{
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(GetPluginInfoW)(piv);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(GetPluginInfoW)(piv);
else
FUNC_X(GetPluginInfoW)(piv);
}
BOOL gbInfoW_OK = FALSE;
void WINAPI ExitFARW(void);
void WINAPI ExitFARW3(void*);
int WINAPI ConfigureW(int ItemNumber);
int WINAPI ConfigureW3(void*);
bool FMatch(LPCWSTR asMask, LPWSTR asPath);
#include "../common/SetExport.h"
ExportFunc Far3Func[] =
{
{"ExitFARW", (void*)ExitFARW, (void*)ExitFARW3},
{"ConfigureW", (void*)ConfigureW, (void*)ConfigureW3},
{NULL}
};
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
ghPluginModule = (HMODULE)hModule;
//ghWorkingModule = hModule;
HeapInitialize();
#ifdef SHOW_STARTED_MSGBOX
if (!IsDebuggerPresent())
MessageBoxA(NULL, "ConEmuBg*.dll loaded", "ConEmuBg plugin", 0);
#endif
bool lbExportsChanged = false;
if (LoadFarVersion())
{
if (gFarVersion.dwVerMajor == 3)
{
lbExportsChanged = ChangeExports( Far3Func, ghPluginModule );
if (!lbExportsChanged)
{
_ASSERTE(lbExportsChanged);
}
}
}
}
break;
case DLL_PROCESS_DETACH:
HeapDeinitialize();
break;
}
return TRUE;
}
#if defined(CRTSTARTUP)
extern "C" {
BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
};
BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
{
DllMain(hDll, dwReason, lpReserved);
return TRUE;
}
#endif
BOOL LoadFarVersion()
{
wchar_t ErrText[512]; ErrText[0] = 0;
BOOL lbRc = LoadFarVersion(gFarVersion, ErrText);
if (!lbRc)
{
gFarVersion.dwVerMajor = 2;
gFarVersion.dwVerMinor = 0;
gFarVersion.dwBuild = FAR_X_VER;
}
return lbRc;
}
void WINAPI SetStartupInfoW(void *aInfo)
{
gbSetStartupInfoOk = true;
if (!gFarVersion.dwVerMajor) LoadFarVersion();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(SetStartupInfoW)(aInfo);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(SetStartupInfoW)(aInfo);
else
FUNC_X(SetStartupInfoW)(aInfo);
//_ASSERTE(gszRootKey!=NULL && *gszRootKey!=0);
gbInfoW_OK = TRUE;
StartPlugin(FALSE);
}
struct DrawInfo
{
LPCWSTR szVolume, szVolumeRoot, szVolumeSize, szVolumeFree;
DWORD nDriveType;
enum {
dib_Small = 0, dib_Large = 1, dib_Off = 2
} nSpaceBar;
wchar_t szPic[MAX_PATH]; // Это относительный путь! считая от папки с плагином ("img/plugin.png")
wchar_t szText[MAX_PATH]; // Текст, который отображается под картинкой ("G: 128Gb")
COLORREF crBack[32]; // Цвет фона
int nBackCount;
COLORREF crDark[32]; // Цвет спрайтов, текста, фона градусника
int nDarkCount;
COLORREF crLight[32]; // Цвет градусника
int nLightCount;
enum DrawInfoFlags
{
dif_PicFilled = 0x0000001,
dif_TextFilled = 0x0000002,
dif_BackFilled = 0x0000004,
dif_DarkFilled = 0x0000008,
dif_LightFilled = 0x0000010,
dif_ShiftBackColor = 0x0000020,
dif_Disabled = 0x8000000,
};
DWORD Flags; // of DrawInfoFlags
};
bool gbGdiPlusInitialized = false;
typedef HRESULT (WINAPI* CreateXmlReader_t)(REFIID riid, void** ppvObject, void* pMalloc);
CreateXmlReader_t gfCreateXmlReader = NULL;
HMODULE ghXmlLite = NULL;
struct XmlConfigFile
{
MSectionSimple* cr;
FILETIME FileTime;
LPBYTE FileData;
DWORD FileSize;
};
XmlConfigFile XmlFile = {};
wchar_t* gpszXmlFile = NULL;
wchar_t* gpszXmlFolder = NULL;
HANDLE ghXmlNotification = NULL;
const wchar_t* szDefaultXmlName = L"Background.xml";
void ReportFail(LPCWSTR asInfo)
{
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuBg, PID=%u", GetCurrentProcessId());
wchar_t* pszErr = lstrmerge(asInfo,
L"\n" L"Config value: ", gsXmlConfigFile[0] ? gsXmlConfigFile : szDefaultXmlName,
L"\n" L"Expanded: ", gpszXmlFile ? gpszXmlFile : L"<NULL>");
MessageBox(NULL, pszErr, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
free(pszErr);
}
bool WasXmlLoaded()
{
return (XmlFile.FileData != NULL);
}
// Возвращает TRUE, если файл изменился
bool CheckXmlFile(bool abUpdateName /*= false*/)
{
bool lbChanged = false, lbNeedCheck = false;
DWORD nNotify = 0;
wchar_t szErr[128];
_ASSERTE(XmlFile.cr && XmlFile.cr->IsInitialized());
MSectionLockSimple CS; CS.Lock(XmlFile.cr);
if (abUpdateName)
{
bool lbNameOk = false;
size_t cchMax = MAX_PATH+1;
if (!gpszXmlFile)
gpszXmlFile = (wchar_t*)malloc(cchMax*sizeof(*gpszXmlFile));
if (gpszXmlFile)
{
gpszXmlFile[0] = 0;
// If config file has full path or environment variable (supposing full path with %FARHOME% or %ConEmuDir%)
if (*gsXmlConfigFile && (wcschr(gsXmlConfigFile, L'\\') || wcschr(gsXmlConfigFile, L'%')))
{
DWORD nRc = ExpandEnvironmentStrings(gsXmlConfigFile, gpszXmlFile, MAX_PATH+1);
if (!nRc || nRc > MAX_PATH)
{
gpszXmlFile[0] = 0;
ReportFail(L"Too long xml path after ExpandEnvironmentStrings");
}
else
{
lbNameOk = true;
}
}
if (!lbNameOk && !*gpszXmlFile)
{
LPCWSTR pszXmlName = *gsXmlConfigFile ? gsXmlConfigFile : szDefaultXmlName;
int nNameLen = lstrlen(pszXmlName);
if (GetModuleFileName(ghPluginModule, gpszXmlFile, MAX_PATH-nNameLen))
{
wchar_t* pszSlash = wcsrchr(gpszXmlFile, L'\\');
if (pszSlash) pszSlash++; else pszSlash = gpszXmlFile;
_wcscpy_c(pszSlash, cchMax-(pszSlash-gpszXmlFile), pszXmlName);
lbNameOk = true;
}
}
}
if (!lbNameOk)
{
if (gpszXmlFile)
{
free(gpszXmlFile);
gpszXmlFile = NULL;
};
ReportFail(L"Can't initialize name of xml file");
lbChanged = false;
goto wrap;
}
// Notification - мониторинг изменения файла
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
FindCloseChangeNotification(ghXmlNotification);
ghXmlNotification = NULL;
}
if (gpszXmlFolder)
free(gpszXmlFolder);
gpszXmlFolder = lstrdup(gpszXmlFile);
if (gpszXmlFolder)
{
wchar_t* pszSlash = wcsrchr(gpszXmlFolder, L'\\');
if (pszSlash)
{
if (wcschr(gpszXmlFolder, L'\\') < pszSlash)
pszSlash[0] = 0;
else
pszSlash[1] = 0;
}
//Issue 1230
if (gbMonitorFileChange)
{
ghXmlNotification = FindFirstChangeNotification(gpszXmlFolder, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE);
}
else
{
_ASSERTE(ghXmlNotification==NULL);
lbNeedCheck = true;
}
}
}
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
nNotify = WaitForSingleObject(ghXmlNotification, 0);
if (nNotify == WAIT_OBJECT_0)
{
lbNeedCheck = true;
//FindNextChangeNotification(ghXmlNotification); -- в конце позовем
}
}
// в первый раз - выставляем строго
if (!lbNeedCheck && !XmlFile.FileData)
lbNeedCheck = true;
if (gpszXmlFile && *gpszXmlFile && lbNeedCheck)
{
HANDLE hFile = CreateFile(gpszXmlFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL);
if (hFile && hFile != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION inf = {};
GetFileInformationByHandle(hFile, &inf);
if (!inf.nFileSizeLow)
{
ReportFail(L"Configuration xml file is empty");
}
else if (!XmlFile.FileData)
{
lbChanged = true;
}
else
{
if ((memcmp(&inf.ftLastWriteTime, &XmlFile.FileTime, sizeof(XmlFile.FileTime)) != 0)
|| (inf.nFileSizeLow != XmlFile.FileSize))
{
lbChanged = true;
}
}
if (lbChanged)
{
DWORD dwRead = 0;
LPBYTE ptrData = (LPBYTE)calloc(inf.nFileSizeLow+1, sizeof(*ptrData));
if (!ptrData)
{
swprintf_c(szErr, L"Can't allocate %u bytes for xml configuration", inf.nFileSizeLow+1);
ReportFail(szErr);
}
else if (!ReadFile(hFile, ptrData, inf.nFileSizeLow, &dwRead, NULL) || (dwRead != inf.nFileSizeLow))
{
swprintf_c(szErr, L"Can't read %u bytes from xml configuration file", inf.nFileSizeLow);
ReportFail(szErr);
}
else
{
if (XmlFile.FileData)
free(XmlFile.FileData);
XmlFile.FileData = ptrData;
ptrData = NULL;
XmlFile.FileSize = dwRead;
}
if (ptrData) // Если ошибка, освободить память
free(ptrData);
}
// Done
CloseHandle(hFile);
}
else
{
// В первый раз - на отсутствие файла ругнемся
if (!XmlFile.FileData)
{
ReportFail(L"Configuration xml file was not found in the plugin folder");
}
}
}
// Если файла нет, или его не удалось прочитать - подсунем пустышку
if (!XmlFile.FileData)
{
XmlFile.FileSize = 0;
XmlFile.FileData = (LPBYTE)calloc(1,sizeof(*XmlFile.FileData));
}
wrap:
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE) && (nNotify == WAIT_OBJECT_0))
{
FindNextChangeNotification(ghXmlNotification);
}
return lbChanged;
}
#define DllGetFunction(hModule, FunctionName) FunctionName = (FunctionName##_t)GetProcAddress(hModule, #FunctionName)
enum tag_GdiStrMagics
{
eGdiStr_Decoder = 0x2001,
eGdiStr_Image = 0x2002,
};
struct CachedImage
{
DWORD nMagic;
BOOL bUsed;
// Имя картинки
wchar_t sImgName[MAX_PATH]; // i.e. L"img/plugin.png"
// Хэндлы. CompatibleDC & Bitmap
HDC hDc;
HBITMAP hBmp, hOldBmp;
int nWidth, nHeight;
// Next pointer
CachedImage *pNextImage;
bool Init(LPCWSTR apszName, HDC ahDc, UINT anWidth, UINT anHeight, const HDC hScreenDC)
{
_ASSERTE(hDc==NULL && hBmp==NULL && hOldBmp==NULL);
nMagic = eGdiStr_Image;
bUsed = TRUE;
wcscpy_c(sImgName, apszName);
//hDc = ahDc; ahDc = NULL;
//hBmp = ahBmp; ahBmp = NULL;
//hOldBmp = ahOldBmp; ahOldBmp = NULL;
nWidth = anWidth;
nHeight = anHeight;
hDc = CreateCompatibleDC(hScreenDC);
hBmp = CreateCompatibleBitmap(hScreenDC, nWidth, nHeight);
if (!hDc || !hBmp)
{
ReportFail(L"CreateCompatible[DC|Bitmap] failed in CachedImage::Init");
if (hDc)
{
DeleteDC(hDc);
hDc = NULL;
}
if (hBmp)
{
DeleteObject(hBmp);
hBmp = NULL;
}
return false;
}
hOldBmp = (HBITMAP)SelectObject(hDc, hBmp);
//BitBlt, MaskBlt, AlphaBlend, TransparentBlt
BitBlt(hDc, 0, 0, nWidth, nHeight, ahDc, 0, 0, SRCCOPY); // PATINVERT/PATPAINT?
return true;
};
// Деструктор
void Close()
{
sImgName[0] = 0;
if (hOldBmp && hDc)
{
SelectObject(hDc, hOldBmp);
hOldBmp = NULL;
}
if (hDc)
{
DeleteDC(hDc);
hDc = NULL;
}
if (hBmp)
{
DeleteObject(hBmp);
hBmp = NULL;
}
if (pNextImage)
{
pNextImage->Close();
}
free(this);
};
};
struct GDIPlusDecoder
{
DWORD nMagic;
HMODULE hGDIPlus;
ULONG_PTR gdiplusToken; bool bTokenInitialized;
HRESULT nLastError;
BOOL bCoInitialized;
wchar_t sModulePath[MAX_PATH];
CachedImage *pImages;
typedef Gdiplus::Status(WINAPI *GdiplusStartup_t)(ULONG_PTR *token, const Gdiplus::GdiplusStartupInput *input, void /*Gdiplus::GdiplusStartupOutput*/ *output);
typedef VOID (WINAPI *GdiplusShutdown_t)(ULONG_PTR token);
typedef Gdiplus::Status(WINAPI *GdipCreateBitmapFromFile_t)(GDIPCONST WCHAR* filename, Gdiplus::GpBitmap **bitmap);
typedef Gdiplus::Status(WINAPI *GdipGetImageWidth_t)(Gdiplus::GpImage *image, UINT *width);
typedef Gdiplus::Status(WINAPI *GdipGetImageHeight_t)(Gdiplus::GpImage *image, UINT *height);
typedef Gdiplus::Status(WINAPI *GdipDisposeImage_t)(Gdiplus::GpImage *image);
//typedef Gdiplus::Status(WINAPI *GdipCreateHBITMAPFromBitmap_t)(Gdiplus::GpBitmap* bitmap, HBITMAP* hbmReturn, ARGB background);
typedef Gdiplus::Status(WINAPI *GdipDrawImageI_t)(Gdiplus::GpGraphics *graphics, Gdiplus::GpImage *image, INT x, INT y);
typedef Gdiplus::Status(WINAPI *GdipCreateFromHDC_t)(HDC hdc, Gdiplus::GpGraphics **graphics);
typedef Gdiplus::Status(WINAPI *GdipDeleteGraphics_t)(Gdiplus::GpGraphics *graphics);
typedef Gdiplus::Status(WINAPI *GdipGetDC_t)(Gdiplus::GpGraphics* graphics, HDC * hdc);
typedef Gdiplus::Status(WINAPI *GdipReleaseDC_t)(Gdiplus::GpGraphics* graphics, HDC hdc);
typedef Gdiplus::Status(WINAPI *GdipGetImageGraphicsContext_t)(Gdiplus::GpImage *image, Gdiplus::GpGraphics **graphics);
typedef Gdiplus::Status(WINAPI *GdipBitmapConvertFormat_t)(Gdiplus::GpBitmap *pInputBitmap, Gdiplus::PixelFormat format, Gdiplus::DitherType dithertype, Gdiplus::PaletteType palettetype, Gdiplus::ColorPalette *palette, DWORD alphaThresholdPercent);
GdiplusStartup_t GdiplusStartup;
GdiplusShutdown_t GdiplusShutdown;
GdipCreateBitmapFromFile_t GdipCreateBitmapFromFile;
GdipGetImageWidth_t GdipGetImageWidth;
GdipGetImageHeight_t GdipGetImageHeight;
GdipDisposeImage_t GdipDisposeImage;
//GdipCreateHBITMAPFromBitmap_t GdipCreateHBITMAPFromBitmap;
GdipDrawImageI_t GdipDrawImageI;
GdipCreateFromHDC_t GdipCreateFromHDC;
GdipDeleteGraphics_t GdipDeleteGraphics;
GdipGetDC_t GdipGetDC;
GdipReleaseDC_t GdipReleaseDC;
GdipGetImageGraphicsContext_t GdipGetImageGraphicsContext;
GdipBitmapConvertFormat_t GdipBitmapConvertFormat;
bool Init()
{
nMagic = eGdiStr_Decoder;
hGDIPlus = NULL; gdiplusToken = 0; bTokenInitialized = false;
nLastError = 0;
if (!GetModuleFileName(ghPluginModule, sModulePath, countof(sModulePath)))
{
ReportFail(L"GetModuleFileName failed in GDIPlusDecoder::Init");
sModulePath[0] = 0;
}
else
{
wchar_t* pszSlash = wcsrchr(sModulePath, L'\\');
if (pszSlash)
pszSlash[1] = 0; // Оставить слеш.
else
sModulePath[0] = 0; // Ошибка?
}
bool result = false;
HRESULT hrCoInitialized = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
bCoInitialized = SUCCEEDED(hrCoInitialized);
_ASSERTE(bCoInitialized);
//wchar_t FullPath[MAX_PATH*2+15]; FullPath[0] = 0;
hGDIPlus = LoadLibraryW(L"GdiPlus.dll");
if (!hGDIPlus)
{
ReportFail(L"GdiPlus.dll not found!");
}
else
{
DllGetFunction(hGDIPlus, GdiplusStartup);
DllGetFunction(hGDIPlus, GdiplusShutdown);
DllGetFunction(hGDIPlus, GdipCreateBitmapFromFile);
DllGetFunction(hGDIPlus, GdipGetImageWidth);
DllGetFunction(hGDIPlus, GdipGetImageHeight);
DllGetFunction(hGDIPlus, GdipDisposeImage);
//DllGetFunction(hGDIPlus, GdipCreateHBITMAPFromBitmap);
DllGetFunction(hGDIPlus, GdipDrawImageI);
DllGetFunction(hGDIPlus, GdipCreateFromHDC);
DllGetFunction(hGDIPlus, GdipDeleteGraphics);
DllGetFunction(hGDIPlus, GdipGetDC);
DllGetFunction(hGDIPlus, GdipReleaseDC);
DllGetFunction(hGDIPlus, GdipGetImageGraphicsContext);
DllGetFunction(hGDIPlus, GdipBitmapConvertFormat); // may be absent in old versions of GdiPlus.dll
if (GdiplusStartup && GdiplusShutdown && GdipCreateBitmapFromFile
&& GdipGetImageWidth && GdipGetImageHeight
&& GdipDisposeImage //&& GdipCreateHBITMAPFromBitmap
&& GdipDrawImageI && GdipCreateFromHDC && GdipDeleteGraphics
&& GdipGetDC && GdipReleaseDC && GdipGetImageGraphicsContext
)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::Status lRc = GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
result = (lRc == Gdiplus::Ok);
if (!result)
{
nLastError = GetLastError();
GdiplusShutdown(gdiplusToken); bTokenInitialized = false;
ReportFail(L"GdiplusStartup failed");
}
else
{
bTokenInitialized = true;
}
}
else
{
ReportFail(L"Functions not found in GdiPlus.dll");
}
if (!result)
FreeLibrary(hGDIPlus);
}
return result;
};
// При использовании в фаре GdiPlus иногда может зависать на FreeLibrary.
// Причины пока не выяснены
static DWORD WINAPI FreeThreadProc(LPVOID lpParameter)
{
struct GDIPlusDecoder* p = (struct GDIPlusDecoder*)lpParameter;
if (p && p->hGDIPlus)
{
FreeLibrary(p->hGDIPlus);
}
return 0;
}
void Close()
{
if (pImages)
{
pImages->Close();
pImages = NULL;
}
if (bTokenInitialized)
{
GdiplusShutdown(gdiplusToken);
bTokenInitialized = false;
}
if (hGDIPlus)
{
//FreeLibrary(hGDIPlus);
DWORD nFreeTID = 0, nWait = 0, nErr = 0;
HANDLE hFree = apiCreateThread(FreeThreadProc, this, &nFreeTID, "Bg::FreeThreadProc");
if (!hFree)
{
nErr = GetLastError();
FreeLibrary(hGDIPlus);
}
else
{
nWait = WaitForSingleObject(hFree, 5000);
if (nWait != WAIT_OBJECT_0)
apiTerminateThread(hFree, 100);
CloseHandle(hFree);
}
UNREFERENCED_PARAMETER(nErr);
hGDIPlus = NULL;
}
if (bCoInitialized)
{
bCoInitialized = FALSE;
CoUninitialize();
}
free(this);
};
CachedImage* GetImage(LPCWSTR asRelativeName)
{
if (!asRelativeName || !*asRelativeName)
return NULL;
size_t cchFullName = MAX_PATH*2;
wchar_t* szFullName = (wchar_t*)malloc(cchFullName*sizeof(*szFullName));
size_t cchName = MAX_PATH;
wchar_t* szName = (wchar_t*)malloc(cchName*sizeof(*szName));
size_t cchError = MAX_PATH*3;
wchar_t* szError = (wchar_t*)malloc(cchError*sizeof(*szError));
wchar_t* psz = NULL;
Gdiplus::Status lRc;
Gdiplus::GpBitmap *bmp = NULL;
Gdiplus::GpGraphics *gr = NULL;
CachedImage *pI = NULL, *pLast = NULL;
UINT nW = 0, nH = 0;
HDC hDc = NULL, hCompDc = NULL;
HBITMAP hBmp = NULL, hOldBmp = NULL;
const HDC hScreenDC = GetDC(0);
if (!szFullName || !szName || !szError)
{
ReportFail(L"Can't allocate memory for szFullName");
goto wrap;
}
if (*asRelativeName == L'\\' || *asRelativeName == L'/')
asRelativeName++;
// Заменить "/" на "\"
_wcscpy_c(szName, cchName, asRelativeName);
psz = wcschr(szName, L'/');
while (psz)
{
*psz = L'\\';
psz = wcschr(psz+1, L'/');
}
// Lowercase, для сравнения
CharLowerBuff(szName, lstrlen(szName));
// Может уже есть?
pI = pImages;
while (pI != NULL)
{
pLast = pI;
if (pI->bUsed && lstrcmp(pI->sImgName, szName) == 0)
{
goto wrap;
}
pI = pI->pNextImage;
}
// Загрузить из файла
_ASSERTE(pI == NULL);
pI = NULL;
_wcscpy_c(szFullName, cchFullName, sModulePath);
_wcscat_c(szFullName, cchFullName, szName);
lRc = GdipCreateBitmapFromFile(szFullName, &bmp);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"Can't load image, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
_ASSERTE(bmp == NULL);
bmp = NULL;
goto wrap;
}
if (GdipBitmapConvertFormat)
{
Gdiplus::ColorPalette pal[2];
pal[0].Flags = Gdiplus::PaletteFlagsGrayScale;
pal[0].Count = 2;
pal[0].Entries[0] = (DWORD)0;
pal[0].Entries[1] = (DWORD)-1;
GdipBitmapConvertFormat(bmp, PixelFormat1bppIndexed, Gdiplus::DitherTypeSolid, Gdiplus::PaletteTypeFixedBW, pal, 0);
}
if (((lRc = GdipGetImageWidth(bmp, &nW)) != Gdiplus::Ok) || (GdipGetImageHeight(bmp, &nH) != Gdiplus::Ok)
|| (nW < 1) || (nH < 1))
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GetImageSize failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
hCompDc = CreateCompatibleDC(hScreenDC);
hBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
if (!hCompDc || !hBmp)
{
ReportFail(L"CreateCompatible[DC|Bitmap] failed");
goto wrap;
}
hOldBmp = (HBITMAP)SelectObject(hCompDc, hBmp);
lRc = GdipCreateFromHDC(hCompDc, &gr);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipCreateFromHDC failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
lRc = GdipDrawImageI(gr, bmp, 0, 0);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipDrawImageI failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
//lRc = GdipGetImageGraphicsContext(bmp, &gr);
//if (lRc != Gdiplus::Ok || !gr)
//{
// swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipGetImageGraphicsContext failed, Err=%i\n%s", (int)lRc, szFullName);
// ReportFail(szError);
// goto wrap;
//}
lRc = GdipGetDC(gr, &hDc);
if (lRc != Gdiplus::Ok || !hDc)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipGetDC failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
#ifdef _DEBUG
//SelectObject(hDc, (HPEN)GetStockObject(WHITE_PEN));
//MoveToEx(hDc, 0,0, NULL);
//LineTo(hDc, nW, nH);
/*{
RECT rcDbg = {nW/2,nH/2, nW, nH};
FillRect(hDc, &rcDbg, (HBRUSH)GetStockObject(WHITE_BRUSH));
//BitBlt(hScreenDC, 0, 0, nW, nH, hDc, 0, 0, SRCCOPY); // PATINVERT/PATPAINT?
}*/
#endif
// OK, теперь можно запомнить в кеше
if (!pLast)
{
_ASSERTE(pImages == NULL);
pImages = (CachedImage*)calloc(1,sizeof(CachedImage));
pI = pImages;
}
else
{
pI = (CachedImage*)calloc(1,sizeof(CachedImage));
pLast->pNextImage = pI;
}
if (!pI)
{
ReportFail(L"Can't allocate memory for CachedImage");
goto wrap;
}
// Done
if (!pI->Init(szName, hDc, nW, nH, hScreenDC))
{
if (pLast)
pLast->pNextImage = NULL;
if (pI == pImages)
pImages = NULL;
pI->Close();
pI = NULL;
goto wrap;
}
wrap:
if (szFullName)
free(szFullName);
if (szName)
free(szName);
if (szError)
free(szError);
if (hDc && gr)
GdipReleaseDC(gr, hDc);
if (gr)
GdipDeleteGraphics(gr);
if (hCompDc && hOldBmp)
SelectObject(hCompDc, hOldBmp);
if (hCompDc)
DeleteDC(hCompDc);
if (hBmp)
DeleteObject(hBmp);
if (bmp)
GdipDisposeImage(bmp);
if (hScreenDC)
ReleaseDC(0, hScreenDC);
return pI;
}
};
GDIPlusDecoder* gpDecoder = NULL;
bool GdipInit()
{
if (gbGdiPlusInitialized)
return true; // уже
_ASSERTE(XmlFile.cr && XmlFile.cr->IsInitialized());
// Загрузить его содержимое
CheckXmlFile(true);
// Инициализация XMLLite
ghXmlLite = LoadLibrary(L"xmllite.dll");
if (!ghXmlLite)
{
ReportFail(L"xmllite.dll not found");
}
else
{
gfCreateXmlReader = (CreateXmlReader_t)GetProcAddress(ghXmlLite, "CreateXmlReader");
if (!gfCreateXmlReader)
{
ReportFail(L"function CreateXmlReader in the xmllite.dll not found");
FreeLibrary(ghXmlLite);
ghXmlLite = NULL;
}
}
gpDecoder = (GDIPlusDecoder*)calloc(1,sizeof(*gpDecoder));
if (!gpDecoder->Init())
{
gpDecoder->Close();
gpDecoder = NULL;
}
gbGdiPlusInitialized = true;
return true;
}
void GdipDone()
{
if (!gbGdiPlusInitialized)
return; // Не выполнялось
MSectionLockSimple CS;
if (XmlFile.cr)
{
CS.Lock(XmlFile.cr);
}
if (ghXmlLite)
{
FreeLibrary(ghXmlLite);
ghXmlLite = NULL;
}
gfCreateXmlReader = NULL;
if (gpszXmlFile)
{
free(gpszXmlFile);
gpszXmlFile = NULL;
}
if (gpszXmlFolder)
{
free(gpszXmlFolder);
gpszXmlFolder = NULL;
}
if (XmlFile.FileData)
{
free(XmlFile.FileData);
XmlFile.FileData = NULL;
}
XmlFile.FileSize = 0;
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
FindCloseChangeNotification(ghXmlNotification);
ghXmlNotification = NULL;
}
if (XmlFile.cr)
{
CS.Unlock();
SafeDelete(XmlFile.cr);
}
if (gpDecoder)
{
gpDecoder->Close();
gpDecoder = NULL;
}
gbGdiPlusInitialized = false;
}
bool CompareNames(LPCWSTR asMaskList, LPWSTR asPath)
{
if (!asMaskList || !asPath)
return false;
if ((*asMaskList && !*asPath) || (*asPath && !*asMaskList))
return false;
wchar_t szMask[MAX_PATH];
while (*asMaskList)
{
LPCWSTR pszSep = wcschr(asMaskList, L'|');
if (pszSep)
{
int nLen = (int)std::min((INT_PTR)countof(szMask)-1,(INT_PTR)(pszSep-asMaskList));
lstrcpyn(szMask, asMaskList, nLen+1);
szMask[nLen] = 0;
}
else
{
lstrcpyn(szMask, asMaskList, countof(szMask));
}
wchar_t* pszSlash = wcschr(szMask, L'/');
while (pszSlash)
{
*pszSlash = L'\\';
pszSlash = wcschr(pszSlash+1, L'/');
}
if (FMatch(szMask, asPath))
return true;
if (!pszSep)
break;
asMaskList = pszSep+1;
}
return false;
}
struct RGBColor
{
union
{
COLORREF clr;
struct
{
BYTE R, G, B, Dummy;
};
};
};
void ParseColors(LPCWSTR asColors, BOOL abSwap/*RGB->COLORREF*/, COLORREF (&crValues)[32], int &nCount)
{
int i = 0;
wchar_t* pszEnd = NULL;
while (asColors && *asColors)
{
if (abSwap)
{
// Нам нужен COLORREF - это перевернутые R&B
RGBColor rgb = {}, bgr;
if (*asColors == L'#')
bgr.clr = wcstoul(asColors+1, &pszEnd, 16) & 0xFFFFFF;
else
bgr.clr = wcstoul(asColors, &pszEnd, 10) & 0xFFFFFF;
rgb.R = bgr.B;
rgb.G = bgr.G;
rgb.B = bgr.R;
crValues[i++] = rgb.clr;
}
else
{
RGBColor rgb;
if (*asColors == L'#')
rgb.clr = wcstoul(asColors+1, &pszEnd, 16) & 0xFFFFFF;
else
rgb.clr = wcstoul(asColors, &pszEnd, 10) & 0xFFFFFF;
crValues[i++] = rgb.clr;
}
if (pszEnd && *pszEnd == L'|')
asColors = pszEnd + 1;
else
break;
}
nCount = i;
//while (i < countof(crValues))
//{
// crValues[i++] = (COLORREF)-1;
//}
}
int FillPanelParams(PaintBackgroundArg* pBk, BkPanelInfo *pPanel, DrawInfo *pDraw)
{
int iFound = 0;
MStream strm;
IXmlReader* pXmlReader = NULL;
HRESULT hr = S_OK;
//int WindowType = -1;
struct ChunkInfo
{
enum {
ci_WindowNone = 0,
ci_WindowPanels = 1,
ci_WindowEditor = 2,
ci_WindowViewer = 3,
} WindowType;
enum {
ci_PanelNone = 0,
ci_PanelDrive = 1,
ci_PanelPlugin = 2,
ci_PanelTree = 3,
ci_PanelQView = 4,
ci_PanelInfo = 5,
} PanelType;
BOOL CondFailed;
bool Valid()
{
if (WindowType == ci_WindowNone)
return false;
if (WindowType == ci_WindowPanels)
{
if (PanelType == ci_PanelNone)
return false;
}
return true;
}
bool Equal(ChunkInfo* pTest)
{
if (pTest->WindowType == ci_WindowNone || pTest->WindowType != this->WindowType)
return false;
if (pTest->WindowType == ci_WindowPanels)
{
if (pTest->PanelType == ci_PanelNone || pTest->PanelType != this->PanelType)
return false;
}
if (CondFailed)
return false;
return true;
}
};
bool bFound = false;
ChunkInfo Test = {ChunkInfo::ci_WindowPanels, ChunkInfo::ci_PanelNone};
ChunkInfo Panel = {ChunkInfo::ci_WindowPanels, ChunkInfo::ci_PanelNone};
MSectionLockSimple CS;
LPWSTR pszFormat = lstrdup(pPanel->szFormat ? pPanel->szFormat : L"");
size_t nMaxLen = lstrlen(pPanel->szCurDir ? pPanel->szCurDir : L"");
LPWSTR pszPath = (wchar_t*)malloc((nMaxLen+2)*sizeof(*pszPath));
_wcscpy_c(pszPath, nMaxLen+1, pPanel->szCurDir ? pPanel->szCurDir : L"");
if (nMaxLen > 1 && pszPath[nMaxLen-1] != L'\\')
{
pszPath[nMaxLen] = L'\\';
pszPath[nMaxLen+1] = 0;
}
BOOL bTempPath = FALSE;
wchar_t szTemp[MAX_PATH+1];
// Проверка, путь - %TEMP%?
if (*pszPath)
{
if (!bTempPath)
{
lstrcpyn(szTemp, pszPath, countof(szTemp));
CharUpperBuff(szTemp, lstrlen(szTemp));
if (wcsstr(szTemp, L"\\TEMP\\") != NULL)
bTempPath = TRUE;
}
if (!bTempPath && GetTempPath(countof(szTemp)-1, szTemp))
{
szTemp[countof(szTemp)-1] = 0;
if (lstrcmpi(pszPath, szTemp) == 0)
bTempPath = TRUE;
}
}
pDraw->Flags = 0;
if (pBk->Place == pbp_Panels)
{
Panel.WindowType = ChunkInfo::ci_WindowPanels;
if (pPanel->bPlugin)
{
Panel.PanelType = ChunkInfo::ci_PanelPlugin;
}
else if (pPanel->nPanelType == PTYPE_FILEPANEL)
{
Panel.PanelType = ChunkInfo::ci_PanelDrive;
}
else
{
switch (pPanel->nPanelType)
{
case PTYPE_TREEPANEL:
Panel.PanelType = ChunkInfo::ci_PanelTree;
break;
case PTYPE_QVIEWPANEL:
Panel.PanelType = ChunkInfo::ci_PanelQView;
break;
case PTYPE_INFOPANEL:
Panel.PanelType = ChunkInfo::ci_PanelInfo;
break;
}
}
}
else if (pBk->Place == pbp_Editor || pBk->Place == pbp_Viewer)
{
Panel.WindowType = (pBk->Place == pbp_Editor) ? ChunkInfo::ci_WindowEditor : ChunkInfo::ci_WindowViewer;
}
else
{
_ASSERTE(pBk->Place == pbp_Panels || pBk->Place == pbp_Editor || pBk->Place == pbp_Viewer);
goto wrap;
}
CS.Lock(XmlFile.cr);
if (!XmlFile.FileData || !XmlFile.FileSize)
{
CS.Unlock();
goto wrap;
}
strm.SetData(XmlFile.FileData, XmlFile.FileSize);
CS.Unlock();
hr = gfCreateXmlReader(IID_IXmlReader, (void**)&pXmlReader, NULL);
if (SUCCEEDED(hr))
{
hr = pXmlReader->SetInput(&strm);
// read through the stream
XmlNodeType nodeType;
while (!iFound && (S_OK == (hr = pXmlReader->Read(&nodeType))))
{
PCWSTR pszName = NULL;
PCWSTR pszValue = NULL;
#ifdef _DEBUG
PCWSTR pszPrefix = NULL;
#endif
PCWSTR pszAttrName = NULL;
PCWSTR pszAttrValue = NULL;
switch (nodeType)
{
case XmlNodeType_EndElement:
hr = pXmlReader->GetLocalName(&pszName, NULL);
if (SUCCEEDED(hr))
{
bool bEndWindow = (lstrcmpi(pszName, L"window") == 0);
if (bEndWindow || (lstrcmpi(pszName, L"panel") == 0))
{
if (bEndWindow)
Test.WindowType = ChunkInfo::ci_WindowNone;
Test.PanelType = ChunkInfo::ci_PanelNone;
Test.CondFailed = FALSE;
if (bFound)
iFound = TRUE;
}
}
break;
case XmlNodeType_Element:
hr = pXmlReader->GetLocalName(&pszName, NULL);
if (FAILED(hr))
{
continue;
}
if (lstrcmpi(pszName, L"window") == 0)
{
// Сначала - сброс
Test.WindowType = ChunkInfo::ci_WindowNone;
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"PANELS") == 0 || lstrcmpi(pszAttrValue, L"PANEL") == 0)
Test.WindowType = ChunkInfo::ci_WindowPanels;
else if (lstrcmpi(pszAttrValue, L"EDITOR") == 0)
Test.WindowType = ChunkInfo::ci_WindowEditor;
else if (lstrcmpi(pszAttrValue, L"VIEWER") == 0)
Test.WindowType = ChunkInfo::ci_WindowViewer;
// Check
if (Test.WindowType != Panel.WindowType)
Test.CondFailed = TRUE;
}
}
}
} while (!Test.CondFailed && (hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"panel") == 0)
{
if ((Test.WindowType == ChunkInfo::ci_WindowNone) || (Test.WindowType != Panel.WindowType))
{
Test.CondFailed = TRUE;
}
else
{
// Сначала - сброс
Test.PanelType = ChunkInfo::ci_PanelNone;
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"DRIVE") == 0)
Test.PanelType = ChunkInfo::ci_PanelDrive;
else if (lstrcmpi(pszAttrValue, L"PLUGIN") == 0)
Test.PanelType = ChunkInfo::ci_PanelPlugin;
else if (lstrcmpi(pszAttrValue, L"TREE") == 0)
Test.PanelType = ChunkInfo::ci_PanelTree;
else if (lstrcmpi(pszAttrValue, L"QVIEW") == 0)
Test.PanelType = ChunkInfo::ci_PanelQView;
else if (lstrcmpi(pszAttrValue, L"INFO") == 0)
Test.PanelType = ChunkInfo::ci_PanelInfo;
else
Test.PanelType = ChunkInfo::ci_PanelNone;
// Check
if (Test.PanelType != Panel.PanelType)
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"drivetype") == 0)
{
DWORD nDriveType = DRIVE_UNKNOWN;
if (lstrcmpi(pszAttrValue, L"NO_ROOT_DIR") == 0)
nDriveType = DRIVE_NO_ROOT_DIR;
else if (lstrcmpi(pszAttrValue, L"REMOVABLE") == 0)
nDriveType = DRIVE_REMOVABLE;
else if (lstrcmpi(pszAttrValue, L"FIXED") == 0)
nDriveType = DRIVE_FIXED;
else if (lstrcmpi(pszAttrValue, L"REMOTE") == 0)
nDriveType = DRIVE_REMOTE;
else if (lstrcmpi(pszAttrValue, L"CDROM") == 0)
nDriveType = DRIVE_CDROM;
else if (lstrcmpi(pszAttrValue, L"RAMDISK") == 0)
nDriveType = DRIVE_RAMDISK;
else
nDriveType = DRIVE_UNKNOWN;
// Check
if (nDriveType != pDraw->nDriveType)
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"pathtype") == 0)
{
if (lstrcmpi(pszAttrValue, L"TEMP") == 0)
{
if (!bTempPath)
Test.CondFailed = TRUE;
}
}
else if (lstrcmpi(pszAttrName, L"pathmatch") == 0)
{
if (!CompareNames(pszAttrValue, pszPath))
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"format") == 0)
{
if (!CompareNames(pszAttrValue, pszFormat))
Test.CondFailed = TRUE;
}
}
}
} while (!Test.CondFailed && (hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
}
else if (Test.Valid() && Test.Equal(&Panel))
{
if (lstrcmpi(pszName, L"disabled") == 0)
{
pDraw->Flags |= DrawInfo::dif_Disabled;
iFound = TRUE;
break;
}
// Блок подошел, больше не проверяем
bFound = true;
// Смотрим, что там настроили
if (lstrcmpi(pszName, L"color") == 0)
{
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"rgb") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crBack, pDraw->nBackCount);
pDraw->Flags |= DrawInfo::dif_BackFilled;
}
else if (lstrcmpi(pszAttrName, L"rgb_dark") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crDark, pDraw->nDarkCount);
pDraw->Flags |= DrawInfo::dif_DarkFilled;
}
else if (lstrcmpi(pszAttrName, L"rgb_light") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crLight, pDraw->nLightCount);
pDraw->Flags |= DrawInfo::dif_LightFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crBack, pDraw->nBackCount);
pDraw->Flags |= DrawInfo::dif_BackFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr_dark") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crDark, pDraw->nDarkCount);
pDraw->Flags |= DrawInfo::dif_DarkFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr_light") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crLight, pDraw->nLightCount);
pDraw->Flags |= DrawInfo::dif_LightFilled;
}
else if (lstrcmpi(pszAttrName, L"shift") == 0)
{
if (lstrcmpi(pszAttrValue, L"yes") == 0)
pDraw->Flags |= DrawInfo::dif_ShiftBackColor;
}
}
}
} while ((hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"space") == 0)
{
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"large") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Large;
else if (lstrcmpi(pszAttrValue, L"off") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Off;
else //if (lstrcmpi(pszAttrValue, L"small") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Small;
}
}
}
} while ((hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"title") == 0)
{
//TODO: Обработка функций
hr = pXmlReader->Read(&nodeType);
if (SUCCEEDED(hr) && (nodeType == XmlNodeType_Text))
{
hr = pXmlReader->GetValue(&pszValue, NULL);
//lstrcpyn(pDraw->szText, pszValue, countof(pDraw->szPic));
// szTemp
pDraw->szText[0] = 0;
szTemp[0] = 0;
wchar_t* pszDst = pDraw->szText;
wchar_t* pszEnd = pDraw->szText+countof(pDraw->szText)-1;
wchar_t* pszTemp = szTemp;
wchar_t* pszTempEnd = szTemp+countof(szTemp)-1;
bool bPlain = false;
while (TRUE)
{
if (*pszValue == L'"')
{
if (!bPlain)
{
bPlain = true;
}
else if (pszValue[1] == L'"')
{
pszValue++;
*(pszDst++) = L'"';
}
else
{
bPlain = false;
}
pszValue++;
}
else if (bPlain)
{
*(pszDst++) = *(pszValue++);
if (pszDst >= pszEnd)
break;
}
else if (!*pszValue || wcschr(L" \t\r\n+", *pszValue))
{
if (*szTemp)
{
*pszTemp = 0;
LPCWSTR pszVar = szTemp;
if (lstrcmpi(szTemp, L"VOLUME") == 0)
lstrcpyn(szTemp, pDraw->szVolume, countof(szTemp));
else if (lstrcmpi(szTemp, L"VOLUMESIZE") == 0)
lstrcpyn(szTemp, pDraw->szVolumeSize, countof(szTemp));
else if (lstrcmpi(szTemp, L"VOLUMEFREE") == 0)
lstrcpyn(szTemp, pDraw->szVolumeFree, countof(szTemp));
else if (lstrcmpi(szTemp, L"PANELFORMAT") == 0)
lstrcpyn(szTemp, pPanel->szFormat ? pPanel->szFormat : L"", countof(szTemp));
int nTempLen = lstrlen(pszVar);
if ((pszDst + nTempLen) >= pszEnd)
break;
lstrcpyn(pszDst, pszVar, nTempLen+1);
pszDst += nTempLen;
pszTemp = szTemp;
*szTemp = 0;
}
if (!*pszValue)
break;
pszValue++;
}
else
{
*(pszTemp++) = *(pszValue++);
if (pszTemp >= pszTempEnd)
break;
}
}
while ((pszDst > pDraw->szText) && (*(pszDst-1) == L' '))
pszDst--;
*pszDst = 0; // ASCIIZ
pDraw->Flags |= DrawInfo::dif_TextFilled;
}
}
else if (lstrcmpi(pszName, L"img") == 0)
{
if (SUCCEEDED(hr = pXmlReader->MoveToAttributeByName(L"ref", NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
lstrcpyn(pDraw->szPic, pszAttrValue, countof(pDraw->szPic));
pDraw->Flags |= DrawInfo::dif_PicFilled;
}
}
}
}
break;
default:
; // GCC warning elimination
}
} // end - while (!iFound && (S_OK == (hr = pXmlReader->Read(&nodeType))))
pXmlReader->Release();
}
wrap:
if (pszPath)
free(pszPath);
if (pszFormat)
free(pszFormat);
return iFound;
}
// HSB
#if 0
struct HSBColor
{
double Hue, Saturnation, Brightness;
};
struct RGBColor
{
union
{
COLORREF clr;
struct
{
BYTE Red, Green, Blue, Dummy;
};
};
};
void COLORREF2HSB(COLORREF rgbclr, HSBColor& hsb)
{
double minRGB, maxRGB, Delta;
double H, s, b;
RGBColor rgb; rgb.clr = rgbclr;
H = 0.0;
minRGB = std::min(std::min(rgb.Red, rgb.Green), rgb.Blue);
maxRGB = std::max(std::max(rgb.Red, rgb.Green), rgb.Blue);
Delta = (maxRGB - minRGB);
b = maxRGB;
if (maxRGB != 0.0)
{
s = 255.0 * Delta / maxRGB;
}
else
{
s = 0.0;
}
if (s != 0.0)
{
if (rgb.Red == maxRGB)
{
H = (rgb.Green - rgb.Blue) / Delta;
}
else if (rgb.Green == maxRGB)
{
H = 2.0 + (rgb.Blue - rgb.Red) / Delta;
}
else if (rgb.Blue == maxRGB)
{
H = 4.0 + (rgb.Red - rgb.Green) / Delta;
}
}
else
{
H = -1.0;
}
H = H * 60 ;
if (H < 0.0)
{
H = H + 360.0;
}
hsb.Hue = H;
hsb.Saturnation = s * 100 / 255;
hsb.Brightness = b * 100 / 255;
}
inline BYTE ClrPart(double v)
{
return (v < 0) ? 0 : (v > 1) ? 255 : (int)(v*255);
}
inline double Abs(double v)
{
return (v < 0) ? (-v) : v;
}
void HSB2COLORREF(const HSBColor& hsb, COLORREF& rgbclr)
{
RGBColor rgb = {};
double C, H1, m, X;
//C = (1 - Abs(2*(hsb.Brightness/100.0) - 1)) * (hsb.Saturnation/100.0);
C = (hsb.Brightness/100.0) * (hsb.Saturnation/100.0);
H1 = (hsb.Hue / 60);
X = C*(1 - Abs((H1 - 2*(int)(H1 / 2)) - 1));
m = 0;// (hsb.Brightness/100.0) - (C / 2); -- пока без доп.яркости
if ((hsb.Brightness == 0) || (hsb.Hue < 0 || hsb.Hue >= 360))
{
rgb.clr = 0;
}
else if (hsb.Saturnation == 0)
{
rgb.Red = rgb.Green = rgb.Blue = ClrPart(hsb.Brightness/100);
}
else
{
// double r=0,g=0,b=0;
// double temp1,temp2;
// temp2 = (((hsb.Brightness/100)<=0.5)
// ? (hsb.Brightness/100)*(1.0+(hsb.Saturnation/100))
// : (hsb.Brightness/100)+(hsb.Saturnation/100)-((hsb.Brightness/100)*(hsb.Saturnation/100)));
// temp1 = 2.0*(hsb.Brightness/100)-temp2;
//
// double t3[]={hsb.Hue/360+1.0/3.0,hsb.Hue/360,(hsb.Hue/360)-1.0/3.0};
// double clr[]={0,0,0};
// for(int i=0;i<3;i++)
// {
// if(t3[i]<0)
// t3[i]+=1.0;
// if(t3[i]>1)
// t3[i]-=1.0;
//
// if(6.0*t3[i] < 1.0)
// clr[i]=temp1+(temp2-temp1)*t3[i]*6.0;
// else if(2.0*t3[i] < 1.0)
// clr[i]=temp2;
// else if(3.0*t3[i] < 2.0)
// clr[i]=(temp1+(temp2-temp1)*((2.0/3.0)-t3[i])*6.0);
// else
// clr[i]=temp1;
// }
// r=clr[0];
// g=clr[1];
// b=clr[2];
//rgb.Red = ClrPart(255*r); rgb.Green = ClrPart(255*g); rgb.Blue = ClrPart(255*b);
if (0 <= H1 && H1 < 1)
{
rgb.Red = ClrPart(C+m); rgb.Green = ClrPart(X+m); rgb.Blue = ClrPart(0+m);
}
else if (1 <= H1 && H1 < 2)
{
rgb.Red = ClrPart(X+m); rgb.Green = ClrPart(C+m); rgb.Blue = ClrPart(0+m);
}
else if (2 <= H1 && H1 < 3)
{
rgb.Red = ClrPart(0+m); rgb.Green = ClrPart(C+m); rgb.Blue = ClrPart(X+m);
}
else if (3 <= H1 && H1 < 4)
{
rgb.Red = ClrPart(0+m); rgb.Green = ClrPart(X+m); rgb.Blue = ClrPart(C+m);
}
else if (4 <= H1 && H1 < 5)
{
rgb.Red = ClrPart(X+m); rgb.Green = ClrPart(0+m); rgb.Blue = ClrPart(C+m);
}
else if (5 <= H1 && H1 < 6)
{
rgb.Red = ClrPart(C+m); rgb.Green = ClrPart(0+m); rgb.Blue = ClrPart(X+m);
}
}
rgbclr = rgb.clr;
}
#endif
//#define RETURN_HSV(h, s, v) {HSV.H = h; HSV.S = s; HSV.V = v; return
//HSV;}
//
//#define RETURN_RGB(r, g, b) {RGB.R = r; RGB.G = g; RGB.B = b; return
//RGB;}
#define UNDEFINED 0
// Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure
// red always maps to 6 in this implementation. Therefore UNDEFINED can be
// defined as 0 in situations where only unsigned numbers are desired.
//typedef struct {float R, G, B;} RGBType;
//
//typedef struct {float H, S, V;} HSVType;
struct HSVColor
{
int H; // (0..1)*360
int S; // (0..1)*100
int V; // (0..1)*100
};
void RGB2HSV(const RGBColor& rgb, HSVColor& HSV)
{
// rgb are each on [0, 1]. S and V are returned on [0, 1] and H is
// returned on [0, 1]. Exception: H is returned UNDEFINED if S==0.
int R = rgb.R, G = rgb.G, B = rgb.B, v, x, f;
int i;
x = std::min(R, G);
x = std::min(x, B);
v = std::max(R, G);
v = std::max(v, B);
if (v == x)
{
HSV.H = UNDEFINED;
HSV.S = 0;
HSV.V = v;
}
else if (v == 0)
{
_ASSERTE(v!=0);
HSV.H = UNDEFINED;
HSV.S = 0;
HSV.V = v;
}
else
{
f = (R == x) ? G - B : ((G == x) ? B - R : R - G); // -255 .. 255
i = (R == x) ? 3 : ((G == x) ? 5 : 1);
HSV.H = (((360*i) - ((360*f)/(v - x)))/6);
HSV.S = (100*(v - x))/v;
HSV.V = 100*v/255;
}
}
inline BYTE ClrPart(int v)
{
return (v < 0) ? 0 : (v > 100) ? 255 : (int)((v*255)/100);
}
void HSV2RGB(const HSVColor& HSV, RGBColor& rgb)
{
rgb.clr = 0;
// H is given on [0, 1] or UNDEFINED. S and V are given on [0, 1].
// rgb are each returned on [0, 1].
int h = HSV.H * 6, s = HSV.S, v = HSV.V, m, n, f;
int i;
//if (h == 0) h = 1;
if ((HSV.H < 0) /*== UNDEFINED*/ || (!HSV.H && !HSV.V))
{
rgb.R = rgb.G = rgb.B = ClrPart(v);
}
else
{
//i = floorf(h);
if (HSV.H < 60)
i = 0;
else if (HSV.H < 120)
i = 1;
else if (HSV.H < 180)
i = 2;
else if (HSV.H < 240)
i = 3;
else if (HSV.H < 300)
i = 4;
else if (HSV.H < 360)
i = 5;
else
i = 6;
//TODO:
f = h - i*360;
if(!(i & 1)) f = 360 - f; // if i is even
m = v * (100 - s) / 100;
n = v * (100 - s * f / 360) / 100;
#define RETURN_RGB(r,g,b) rgb.R = ClrPart(r); rgb.G = ClrPart(g); rgb.B = ClrPart(b);
switch (i)
{
case 6:
case 0: RETURN_RGB(v, n, m); break;
case 1: RETURN_RGB(n, v, m); break;
case 2: RETURN_RGB(m, v, n); break;
case 3: RETURN_RGB(m, n, v); break;
case 4: RETURN_RGB(n, m, v); break;
case 5: RETURN_RGB(v, m, n); break;
default: RETURN_RGB(0, 0, 0);
}
}
}
// Сколько линий в области статуса (без учета рамок)
int GetStatusLineCount(struct PaintBackgroundArg* pBk, BOOL bLeft)
{
if (!(pBk->FarPanelSettings.ShowStatusLine))
{
// Что-то при запуске (1.7x?) иногда картинки прыгают, как будто статус сразу не нашли
_ASSERTE(pBk->FarPanelSettings.ShowStatusLine);
return 0;
}
if ((bLeft ? pBk->LeftPanel.nPanelType : pBk->RightPanel.nPanelType) != PTYPE_FILEPANEL)
{
_ASSERTE(((UINT)(bLeft ? pBk->LeftPanel.nPanelType : pBk->RightPanel.nPanelType)) <= PTYPE_INFOPANEL);
return 0;
}
RECT rcPanel = bLeft ? pBk->LeftPanel.rcPanelRect : pBk->RightPanel.rcPanelRect;
if ((rcPanel.bottom-rcPanel.top) <= ((pBk->FarPanelSettings.ShowColumnTitles) ? 5 : 4))
return 1; // минимальная высота панели
COORD bufSize = {(SHORT)(rcPanel.right-rcPanel.left+1), std::min<SHORT>(10, (SHORT)(rcPanel.bottom-rcPanel.top))};
COORD bufCoord = {0,0};
HANDLE hStd = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
short nShiftX = 0, nShiftY = 0;
if (GetConsoleScreenBufferInfo(hStd, &csbi))
{
// Начиная с какой-то версии в фаре поменяли координаты :(
if (rcPanel.top <= 1)
{
nShiftY = csbi.dwSize.Y - (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
}
}
SMALL_RECT readRect = {
(SHORT)rcPanel.left + nShiftX,
(SHORT)(rcPanel.bottom-bufSize.Y)+nShiftY,
(SHORT)rcPanel.right+nShiftX,
(SHORT)rcPanel.bottom+nShiftY
};
PCHAR_INFO pChars = (PCHAR_INFO)malloc(bufSize.X*bufSize.Y*sizeof(*pChars));
if (!pChars)
{
_ASSERTE(pChars);
return 1;
}
int nLines = 0;
BOOL lbReadRc = ReadConsoleOutputW(hStd, pChars, bufSize, bufCoord, &readRect);
if (!lbReadRc)
{
_ASSERTE(lbReadRc);
}
else
{
for (int i = 2; i <= bufSize.Y; i++)
{
if ((pChars[bufSize.X*(bufSize.Y-i)].Char.UnicodeChar == ucBoxDblVertSinglRight)
|| (pChars[bufSize.X*(bufSize.Y-i)+bufSize.X-1].Char.UnicodeChar == ucBoxDblVertSinglLeft))
{
nLines = i - 1;
break;
}
}
}
// Что-то при запуске (1.7x?) иногда картинки прыгают, как будто статус сразу не нашли
#ifdef _DEBUG
int nArea = -1;
if (nLines<1)
{
static bool bWarnLines = false;
if (!bWarnLines)
{
nArea = GetMacroArea();
if (nArea == 1/*MACROAREA_SHELL*/ || nArea == 5/*MACROAREA_SEARCH*/)
{
bWarnLines = true;
// Far 3.0.3716. Assert при старте. Плагин активирован, а панелей на экране еще НЕТ.
_ASSERTE(nLines>0);
}
}
}
#endif
free(pChars);
return nLines;
}
void FormatSize(ULARGE_INTEGER size, wchar_t* out)
{
if (size.QuadPart)
{
// Сформатировать размер
uint64_t lSize = size.QuadPart, lDec = 0;
const wchar_t *SizeSymbol[]={L"B",L"KB",L"MB",L"GB",L"TB",L"PB"};
for (size_t n = 0; n < countof(SizeSymbol); n++)
{
if (lSize < 1000)
{
if (lDec > 0 && lDec < 10 && lSize < 10)
swprintf_c(out, MAX_PATH/*#SECURELEN*/, L"%u.%u %s", (UINT)lSize, (UINT)lDec, SizeSymbol[n]);
else
swprintf_c(out, MAX_PATH/*#SECURELEN*/, L"%u %s", (UINT)lSize, SizeSymbol[n]);
break;
}
uint64_t lNext = lSize >> 10;
lDec = (lSize % 1024) / 100;
lSize = lNext;
}
//if (!*szVolumeSize)
//{
// swprintf_c(szVolumeSize, MAX_PATH/*#SECURELEN*/, L"%u %s", (UINT)lSize, SizeSymbol[countof(SizeSymbol)-1]);
//}
}
}
int PaintPanel(struct PaintBackgroundArg* pBk, BOOL bLeft, COLORREF& crOtherColor, int& cOtherDrive)
{
DrawInfo* pDraw = (DrawInfo*)calloc(sizeof(*pDraw), 1);
if (!pDraw)
return FALSE;
wchar_t szDbg[128];
// Инициализация и начальное определение размеров и прочего...
int nStatusLines = GetStatusLineCount(pBk, bLeft);
RECT rcPanel = bLeft ? pBk->rcDcLeft : pBk->rcDcRight;
RECT rcConPanel = bLeft ? pBk->LeftPanel.rcPanelRect : pBk->RightPanel.rcPanelRect;
BkPanelInfo *bkInfo = bLeft ? &pBk->LeftPanel : &pBk->RightPanel;
// Не должен содержать рамки
int nPanelWidth = std::max<int>(1, rcConPanel.right - rcConPanel.left + 1); // ширина в символах
int nPanelHeight = std::max<int>(1, rcConPanel.bottom - rcConPanel.top + 1); // высота в символах
RECT rcWork = {}; //rcPanel;
rcWork.left = rcPanel.left + ((rcPanel.right - rcPanel.left + 1) / nPanelWidth);
rcWork.right = rcPanel.right - ((rcPanel.right - rcPanel.left + 1) / nPanelWidth);
rcWork.top = rcPanel.top + ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
rcWork.bottom = rcPanel.bottom - ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
RECT rcInt = rcWork;
if (nStatusLines > 0)
rcInt.bottom -= ((rcPanel.bottom - rcPanel.top + 1) * (nStatusLines + 1) / nPanelHeight);
int nMaxPicSize = (rcInt.bottom - rcInt.top) * 35 / 100;
ULARGE_INTEGER llTotalSize = {}, llFreeSize = {};
UINT nDriveType = DRIVE_UNKNOWN;
BOOL bProgressAllowed = FALSE; // Градусник свободного места
int nMaxVolumeLen = lstrlen(bkInfo->szCurDir ? bkInfo->szCurDir : L"");
wchar_t* szVolumeRoot = (wchar_t*)calloc(nMaxVolumeLen+2,sizeof(*szVolumeRoot));
wchar_t* szVolumeSize = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolumeSize));
wchar_t* szVolumeFree = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolumeFree));
wchar_t* szVolume = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolume));
if (bkInfo->szCurDir && *bkInfo->szCurDir)
{
if (!bkInfo->bPlugin)
{
// Определить размер свободного места на диске
bool lbSizeOk = false, lbTypeOk = false;
_wcscpy_c(szVolumeRoot, nMaxVolumeLen+2, bkInfo->szCurDir);
if (szVolumeRoot[nMaxVolumeLen-1] != L'\\')
{
szVolumeRoot[nMaxVolumeLen++] = L'\\';
szVolumeRoot[nMaxVolumeLen] = 0;
}
int nLen = lstrlen(szVolumeRoot);
while (!(lbSizeOk && lbTypeOk) && (nLen > 0))
{
// To determine whether a drive is a USB-type drive,
// call SetupDiGetDeviceRegistryProperty and specify the SPDRP_REMOVAL_POLICY property.
ULARGE_INTEGER llTotal = {}, llFree = {};
UINT nType = DRIVE_UNKNOWN;
if (!lbSizeOk && GetDiskFreeSpaceEx(szVolumeRoot, &llFree, &llTotal, NULL))
{
llTotalSize.QuadPart = llTotal.QuadPart;
llFreeSize.QuadPart = llFree.QuadPart;
lbSizeOk = TRUE;
}
if (!lbTypeOk && ((nType = GetDriveType(szVolumeRoot)) != DRIVE_UNKNOWN))
{
nDriveType = nType;
lbTypeOk = TRUE;
}
// Если не все определили - пробуем откусить папку
if (!lbSizeOk || !lbTypeOk)
{
if (szVolumeRoot[nLen-1] != L'\\')
{
_ASSERTE(szVolumeRoot[nLen-1] == L'\\');
break;
}
szVolumeRoot[--nLen] = 0;
// Найти следующий слеш
while ((nLen > 0) && (szVolumeRoot[nLen-1] != L'\\'))
nLen--;
// Пропустить все слеши
while ((nLen > 0) && (szVolumeRoot[nLen-1] == L'\\'))
nLen--;
// Откусить
szVolumeRoot[nLen] = 0;
}
}
FormatSize(llTotalSize, szVolumeSize);
FormatSize(llFreeSize, szVolumeFree);
}
// Извлечь "Букву" диска
LPCWSTR psz = bkInfo->szCurDir;
if (psz[0] == L'\\' && psz[1] == L'\\' && (psz[2] == L'.' || psz[2] == L'?') && psz[3] == L'\\')
{
psz += 4;
if (psz[0] == L'U' && psz[1] == L'N' && psz[2] == L'C' && psz[3] == L'\\')
psz += 4;
}
LPCWSTR pszSlash = wcschr(psz, L'\\');
if (!pszSlash)
pszSlash = wcschr(psz, L'/');
if (!pszSlash)
pszSlash = psz + lstrlen(psz);
if (pszSlash > psz)
lstrcpyn(szVolume, psz, (int)(pszSlash - psz + 1));
}
pDraw->szVolume = szVolume;
pDraw->szVolumeRoot = szVolumeRoot;
pDraw->szVolumeSize = szVolumeSize;
pDraw->szVolumeFree = szVolumeFree;
pDraw->nDriveType = nDriveType;
if (nDriveType != DRIVE_UNKNOWN && nDriveType != DRIVE_CDROM && nDriveType != DRIVE_NO_ROOT_DIR)
{
bProgressAllowed = TRUE;
}
else
{
bProgressAllowed = FALSE;
}
// Если есть xml - получить из него настройки для текущего случая
if (gfCreateXmlReader && XmlFile.FileData && XmlFile.FileSize)
{
FillPanelParams(pBk, bkInfo, pDraw);
}
if ((pDraw->Flags & DrawInfo::dif_Disabled))
{
if (pBk->dwLevel == 0)
{
DWORD nPanelBackIdx = CONBACKCOLOR(pBk->nFarColors[col_PanelText]);
COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
swprintf_c(szDbg, L"ConEmuBk: Disabled %s - {%i,%i,%i,%i) #%06X\n",
bLeft ? L"Left" : L"Right", rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom,
crPanel);
DBGSTR(szDbg);
HBRUSH hBr = CreateSolidBrush(crPanel);
FillRect(pBk->hdc, &rcPanel, hBr);
DeleteObject(hBr);
}
}
else
{
// Если не было задано - инициализируем умолчания
if (!(pDraw->Flags & DrawInfo::dif_BackFilled))
{
if (bkInfo->bPlugin)
{
pDraw->crBack[0] = RGB(128,128,128);
}
else
{
switch (nDriveType)
{
case DRIVE_REMOVABLE:
pDraw->crBack[0] = 0x00D98C; break;
case DRIVE_REMOTE:
pDraw->crBack[0] = 0xFF00E6; break;
case DRIVE_CDROM:
pDraw->crBack[0] = 0x7E00FF; break;
case DRIVE_RAMDISK:
pDraw->crBack[0] = 0x008080; break;
default:
pDraw->crBack[0] = 0xFF0000;
}
pDraw->Flags |= DrawInfo::dif_ShiftBackColor;
}
pDraw->nBackCount = 1;
}
int nLetter = 0;
if ((pDraw->Flags & DrawInfo::dif_ShiftBackColor) && pDraw->crBack && (szVolume[1] == L':'))
{
nLetter = (szVolume[0] >= L'a' && szVolume[0] <= L'b') ? (szVolume[0] - L'a' + 24) :
(szVolume[0] >= L'c' && szVolume[0] <= L'z') ? (szVolume[0] - L'c') :
(szVolume[0] >= L'A' && szVolume[0] <= L'B') ? (szVolume[0] - L'A' + 24) :
(szVolume[0] >= L'C' && szVolume[0] <= L'Z') ? (szVolume[0] - L'C') :
0;
if (pDraw->nBackCount > 0)
{
_ASSERTE(pDraw->nBackCount <= countof(pDraw->crBack));
pDraw->crBack[0] = pDraw->crBack[nLetter % pDraw->nBackCount];
}
else
{
// Сконвертить в HSV, сдвинуть, и обратно в COLORREF
int nShift = (nLetter % 5) * 15;
HSVColor hsv = {};
RGBColor rgb; rgb.clr = *pDraw->crBack;
//COLORREF2HSB(pDraw->crBack, hsb);
RGB2HSV(rgb, hsv);
#ifdef _DEBUG
HSV2RGB(hsv, rgb);
#endif
//hsv.H += nShift;
hsv.S -= nShift;
if (hsv.S < 0) hsv.S += 100;
hsv.V = hsv.V / 2;
HSV2RGB(hsv, rgb);
//hsv.Brightness *= 0.7;
//HSB2COLORREF(hsb, clr);
if (bLeft)
{
crOtherColor = rgb.clr;
cOtherDrive = nLetter;
}
else if ((rgb.clr == crOtherColor) && (cOtherDrive != nLetter))
{
hsv.H += 15;
HSV2RGB(hsv, rgb);
}
pDraw->crBack[0] = rgb.clr;
}
}
// Цвет спрайтов, текста, фона градусника
if (!(pDraw->Flags & DrawInfo::dif_DarkFilled))
{
RGBColor rgb; rgb.clr = *pDraw->crBack;
rgb.R = (BYTE)((int)rgb.R * 2 / 3);
rgb.G = (BYTE)((int)rgb.G * 2 / 3);
rgb.B = (BYTE)((int)rgb.B * 2 / 3);
pDraw->crDark[0] = rgb.clr;
pDraw->nDarkCount = 1;
}
else if (pDraw->Flags & DrawInfo::dif_ShiftBackColor)
{
if (pDraw->nDarkCount > 0)
{
_ASSERTE(pDraw->nDarkCount <= countof(pDraw->crDark));
pDraw->crDark[0] = pDraw->crDark[nLetter % pDraw->nDarkCount];
}
}
// Цвет градусника
if (!(pDraw->Flags & DrawInfo::dif_LightFilled))
{
HSVColor hsv = {};
RGBColor rgb; rgb.clr = *pDraw->crBack;
RGB2HSV(rgb, hsv);
hsv.H += 20;
hsv.S = std::min(100,hsv.S+25);
hsv.V = std::min(100,hsv.V+25);
HSV2RGB(hsv, rgb);
pDraw->crLight[0] = rgb.clr;
pDraw->nLightCount = 1;
}
else if (pDraw->Flags & DrawInfo::dif_ShiftBackColor)
{
if (pDraw->nLightCount > 0)
{
_ASSERTE(pDraw->nLightCount <= countof(pDraw->crLight));
pDraw->crLight[0] = pDraw->crLight[nLetter % pDraw->nLightCount];
}
}
if (!(pDraw->Flags & DrawInfo::dif_PicFilled))
{
if (bkInfo->bPlugin)
{
wcscpy_c(pDraw->szPic, L"img/plugin.png");
}
else
{
switch (nDriveType)
{
case DRIVE_REMOVABLE:
wcscpy_c(pDraw->szPic, L"img/drive_removable.png"); break;
case DRIVE_REMOTE:
wcscpy_c(pDraw->szPic, L"img/drive_network.png"); break;
case DRIVE_CDROM:
wcscpy_c(pDraw->szPic, L"img/drive_cdrom.png"); break;
case DRIVE_RAMDISK:
wcscpy_c(pDraw->szPic, L"img/drive_ramdisk.png"); break;
default:
wcscpy_c(pDraw->szPic, L"img/drive_fixed.png");
}
}
}
if (!(pDraw->Flags & DrawInfo::dif_TextFilled))
{
TODO("Размер диска");
wcscpy_c(pDraw->szText, szVolume);
}
// Поехали рисовать
if (pBk->dwLevel == 0)
{
swprintf_c(szDbg, L"ConEmuBk: %s - {%i,%i,%i,%i) #%06X\n",
bLeft ? L"Left" : L"Right", rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom,
*pDraw->crBack);
DBGSTR(szDbg);
HBRUSH hBrush = CreateSolidBrush(*pDraw->crBack);
FillRect(pBk->hdc, &rcPanel, hBrush);
DeleteObject(hBrush);
}
LOGFONT lf = {};
lf.lfHeight = std::max<LONG>(20, (rcInt.bottom - rcInt.top) * 12 / 100);
lf.lfWeight = 700;
lstrcpy(lf.lfFaceName, L"Arial");
// GO
HFONT hText = CreateFontIndirect(&lf);
HFONT hOldFont = (HFONT)SelectObject(pBk->hdc, hText);
#define IMG_SHIFT_X 0
#define IMG_SHIFT_Y 0
#define LINE_SHIFT_Y (lf.lfHeight)
#define LINE_SHIFT_X (lf.lfHeight/6)
// Determine appropriate font size:
int nY = std::max(rcInt.top, rcInt.bottom - (LINE_SHIFT_Y));
RECT rcText = {rcInt.left+IMG_SHIFT_X, nY, rcInt.right-LINE_SHIFT_X, nY+LINE_SHIFT_Y};
RECT rcTemp = rcText;
DrawText(pBk->hdc, pDraw->szText, -1, &rcTemp, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP|DT_CALCRECT);
LONG width = rcText.right - rcText.left;
LONG actualWidth = rcTemp.right - rcTemp.left;
if (actualWidth > width)
{
// Delete current font:
SelectObject(pBk->hdc, hOldFont);
DeleteObject(hText);
// Create new font of appropriate size:
lf.lfHeight = lf.lfHeight * width / actualWidth;
hText = CreateFontIndirect(&lf);
hOldFont = (HFONT)SelectObject(pBk->hdc, hText);
}
CachedImage* pI = NULL;
if (gpDecoder && *pDraw->szPic)
{
pI = gpDecoder->GetImage(pDraw->szPic);
if (pI)
{
int nPicDim = std::max(pI->nWidth,pI->nHeight);
int nW = std::min(nMaxPicSize,nPicDim), nH = std::min(nMaxPicSize,nPicDim); //TODO: Пропорционально pI->nWidth/pI->nHeight
if (pI && (rcWork.top <= (rcText.top - nH - IMG_SHIFT_Y)) && (rcWork.left <= (rcWork.right - nW - IMG_SHIFT_X)))
{
// - картинки чисто черного цвета
#if 0
const HDC hScreenDC = GetDC(0);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
StretchBlt(hReadyDC, 0, 0, nW, nH, pI->hDc, 0,0, pI->nWidth, pI->nHeight, SRCCOPY);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCAND);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
ReleaseDC(0, hScreenDC);
#endif
// OK
#if 1
const HDC hScreenDC = GetDC(0);
HDC hMaskDC = CreateCompatibleDC(hScreenDC);
HBITMAP hMaskBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldMaskBmp = (HBITMAP)SelectObject(hMaskDC, hMaskBmp);
StretchBlt(hMaskDC, 0, 0, nW, nH, pI->hDc, 0,0, pI->nWidth, pI->nHeight, NOTSRCCOPY);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
HBRUSH hDarkBr = CreateSolidBrush(*pDraw->crDark);
HBRUSH hOldBr = (HBRUSH)SelectObject(hInvDC, hDarkBr);
BitBlt(hInvDC, 0, 0, nW, nH,
hMaskDC, 0,0, MERGECOPY);
SelectObject(hInvDC, hOldBr);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
HBRUSH hBackBr = CreateSolidBrush(*pDraw->crBack);
hOldBr = (HBRUSH)SelectObject(hReadyDC, hBackBr);
BitBlt(hMaskDC, 0, 0, nW, nH,
hMaskDC, 0,0, DSTINVERT);
BitBlt(hReadyDC, 0, 0, nW, nH,
hMaskDC, 0,0, MERGECOPY);
SelectObject(hReadyDC, hOldBr);
BitBlt(hReadyDC, 0, 0, nW, nH,
hInvDC, 0,0, SRCPAINT);
DeleteObject(hDarkBr);
DeleteObject(hBackBr);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
SelectObject(hInvDC, hOldInvBmp);
DeleteObject(hInvBmp);
DeleteDC(hInvDC);
SelectObject(hMaskDC, hOldMaskBmp);
DeleteObject(hMaskBmp);
DeleteDC(hMaskDC);
ReleaseDC(0, hScreenDC);
#endif
#if 0
const HDC hScreenDC = GetDC(0);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
RECT rcFill = {0,0,pI->nWidth, pI->nHeight};
HBRUSH hDarkBr = CreateSolidBrush(/*RGB(128,128,128)*/ *pDraw->crDark);
FillRect(hInvDC, &rcFill, hDarkBr);
DeleteObject(hDarkBr);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight,
pI->hDc, 0,0, SRCAND);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
//SetStretchBltMode(hReadyDC, HALFTONE);
rcFill.right = nW; rcFill.bottom = nH;
FillRect(hReadyDC, &rcFill, (HBRUSH)GetStockObject(BLACK_BRUSH));
StretchBlt(hReadyDC, 0, 0, nW, nH, hInvDC, 0,0, pI->nWidth, pI->nHeight, SRCINVERT);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
ReleaseDC(0, hScreenDC);
#endif
// - Черная окантовка вокруг плагиновой картинки
#if 0
const HDC hScreenDC = GetDC(0);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight, pI->hDc, 0,0, SRCCOPY); //NOTSRCCOPY
HDC hCompDC = CreateCompatibleDC(hScreenDC);
HBITMAP hCompBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldCompBmp = (HBITMAP)SelectObject(hCompDC, hCompBmp);
HDC hBackDC = CreateCompatibleDC(hScreenDC);
HBITMAP hBackBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldBackBmp = (HBITMAP)SelectObject(hBackDC, hBackBmp);
HBRUSH hPaintBr = CreateSolidBrush(*pDraw->crDark);
HBRUSH hBackBr = CreateSolidBrush(*pDraw->crBack);
RECT rcFill = {0,0,pI->nWidth, pI->nHeight};
HBRUSH hOldCompBr = (HBRUSH)SelectObject(hCompDC, hBackBr);
BitBlt(hCompDC, 0, 0, pI->nWidth, pI->nHeight, hInvDC, 0,0, MERGECOPY);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight, pI->hDc, 0,0, NOTSRCCOPY);
HBRUSH hOldBackBr = (HBRUSH)SelectObject(hBackDC, hPaintBr);
BitBlt(hBackDC, 0, 0, pI->nWidth, pI->nHeight, hInvDC, 0,0, MERGECOPY);
BitBlt(hCompDC, 0, 0, pI->nWidth, pI->nHeight, hBackDC, 0,0, SRCPAINT);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
StretchBlt(hReadyDC, 0, 0, nW, nH, hCompDC, 0,0, pI->nWidth, pI->nHeight, SRCCOPY); //NOTSRCCOPY
BOOL lbBitRc = BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
DeleteObject(hPaintBr);
SelectObject(hCompDC, hOldCompBr);
DeleteObject(hBackBr);
SelectObject(hInvDC, hOldInvBmp);
DeleteObject(hInvBmp);
DeleteDC(hInvDC);
SelectObject(hCompDC, hOldCompBmp);
DeleteObject(hCompBmp);
DeleteDC(hCompDC);
SelectObject(hBackDC, hOldBackBmp);
DeleteObject(hBackBmp);
DeleteDC(hBackDC);
ReleaseDC(0, hScreenDC);
#endif
}
}
}
SetBkMode(pBk->hdc, TRANSPARENT);
SetTextColor(pBk->hdc, *pDraw->crDark);
DrawText(pBk->hdc, pDraw->szText, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP);
/*
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
swprintf_c(szText, L"Volume: «%s» %s, Format: «%s»", szVolume, szVolumeSize, bkInfo->szFormat ? bkInfo->szFormat : L"");
DrawText(pBk->hdc, szText, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP);
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
if (bkInfo->szCurDir)
DrawText(pBk->hdc, bkInfo->szCurDir, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP|DT_PATH_ELLIPSIS);
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
*/
TODO("В Far3 можно и в плагинах свободное место получить");
if (bProgressAllowed && pDraw->nSpaceBar == DrawInfo::dib_Off)
bProgressAllowed = FALSE;
if (bProgressAllowed && (nStatusLines > 0) && !bkInfo->bPlugin && llTotalSize.QuadPart)
{
//llTotalSize = {},
HBRUSH hUsedBr = CreateSolidBrush(*pDraw->crLight);
HBRUSH hFreeBr = CreateSolidBrush(*pDraw->crDark);
RECT rcUsed = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? rcWork : rcPanel;
int iShift = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? 0 : 2;
rcUsed.top = rcUsed.bottom - (nStatusLines+iShift) * ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
rcUsed.right = rcUsed.right - (int)((uint64_t)(rcUsed.right - rcUsed.left + 1) * llFreeSize.QuadPart / llTotalSize.QuadPart);
if (rcUsed.right > rcWork.right)
{
_ASSERTE(rcUsed.right <= rcWork.right);
rcUsed.right = rcWork.right;
}
else if (rcUsed.right < rcWork.left)
{
_ASSERTE(rcUsed.right >= rcWork.left);
rcUsed.right = rcWork.left;
}
RECT rcFree = rcUsed;
rcFree.left = rcUsed.right;
rcFree.right = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? rcWork.right : rcPanel.right;
FillRect(pBk->hdc, &rcFree, hFreeBr);
FillRect(pBk->hdc, &rcUsed, hUsedBr);
DeleteObject(hUsedBr);
DeleteObject(hFreeBr);
}
SelectObject(pBk->hdc, hOldFont);
DeleteObject(hText);
}
// Free pointers
free(pDraw);
free(szVolume);
free(szVolumeSize);
free(szVolumeFree);
return TRUE;
}
int WINAPI PaintConEmuBackground(struct PaintBackgroundArg* pBk)
{
int iLeftRc = 0, iRightRc = 0;
if (pBk->Place == pbp_Finalize)
{
GdipDone();
return TRUE;
}
if (!gbGdiPlusInitialized)
{
if (!GdipInit())
{
return FALSE;
}
}
else
{
// Проверить, может содержимое xml-ки изменилось?
CheckXmlFile();
}
wchar_t szDbg[128];
COLORREF crOtherColor = (COLORREF)-1;
int cOtherDrive = -1;
if (pBk->LeftPanel.bVisible)
{
iLeftRc = PaintPanel(pBk, TRUE/*bLeft*/, crOtherColor, cOtherDrive);
}
else
{
RECT rcConPanel = pBk->LeftPanel.rcPanelRect;
swprintf_c(szDbg, L"ConEmuBk: Invisible Left - {%i,%i,%i,%i)\n",
rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom);
DBGSTR(szDbg);
}
if (pBk->RightPanel.bVisible)
{
iRightRc = PaintPanel(pBk, FALSE/*bLeft*/, crOtherColor, cOtherDrive);
}
else
{
RECT rcConPanel = pBk->RightPanel.rcPanelRect;
swprintf_c(szDbg, L"ConEmuBk: Invisible Right - {%i,%i,%i,%i)\n",
rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom);
DBGSTR(szDbg);
}
UNREFERENCED_PARAMETER(iLeftRc); UNREFERENCED_PARAMETER(iRightRc);
return TRUE;
//DWORD nPanelBackIdx = (pBk->nFarColors[col_PanelText] & 0xF0) >> 4;
//
//if (bDragBackground)
//{
// if (pBk->LeftPanel.bVisible)
// {
// COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
//
// if (pBk->LeftPanel.bPlugin && gbHilightPlugins)
// crPanel = gcrHilightPlugBack;
//
// HBRUSH hBr = CreateSolidBrush(crPanel);
// FillRect(pBk->hdc, &pBk->rcDcLeft, hBr);
// DeleteObject(hBr);
// }
//
// if (pBk->RightPanel.bVisible)
// {
// COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
//
// if (pBk->RightPanel.bPlugin && gbHilightPlugins)
// crPanel = gcrHilightPlugBack;
//
// HBRUSH hBr = CreateSolidBrush(crPanel);
// FillRect(pBk->hdc, &pBk->rcDcRight, hBr);
// DeleteObject(hBr);
// }
//}
//
//if ((pBk->LeftPanel.bVisible || pBk->RightPanel.bVisible) /*&& pBk->MainFont.nFontHeight>0*/)
//{
// HPEN hPen = CreatePen(PS_SOLID, 1, gcrLinesColor);
// HPEN hOldPen = (HPEN)SelectObject(pBk->hdc, hPen);
// HBRUSH hBrush = CreateSolidBrush(gcrLinesColor);
// int nCellHeight = 12;
//
// if (pBk->LeftPanel.bVisible)
// nCellHeight = pBk->rcDcLeft.bottom / (pBk->LeftPanel.rcPanelRect.bottom - pBk->LeftPanel.rcPanelRect.top + 1);
// else
// nCellHeight = pBk->rcDcRight.bottom / (pBk->RightPanel.rcPanelRect.bottom - pBk->RightPanel.rcPanelRect.top + 1);
//
// int nY1 = (pBk->LeftPanel.bVisible) ? pBk->rcDcLeft.top : pBk->rcDcRight.top;
// int nY2 = (pBk->rcDcLeft.bottom >= pBk->rcDcRight.bottom) ? pBk->rcDcLeft.bottom : pBk->rcDcRight.bottom;
// int nX1 = (pBk->LeftPanel.bVisible) ? 0 : pBk->rcDcRight.left;
// int nX2 = (pBk->RightPanel.bVisible) ? pBk->rcDcRight.right : pBk->rcDcLeft.right;
//
// bool bDrawStipe = true;
//
// for(int Y = nY1; Y < nY2; Y += nCellHeight)
// {
// if (giHilightType == 0)
// {
// MoveToEx(pBk->hdc, nX1, Y, NULL);
// LineTo(pBk->hdc, nX2, Y);
// }
// else if (giHilightType == 1)
// {
// if (bDrawStipe)
// {
// bDrawStipe = false;
// RECT rc = {nX1, Y - nCellHeight + 1, nX2, Y};
// FillRect(pBk->hdc, &rc, hBrush);
// }
// else
// {
// bDrawStipe = true;
// }
// }
// }
//
// SelectObject(pBk->hdc, hOldPen);
// DeleteObject(hPen);
// DeleteObject(hBrush);
//}
//
//return TRUE;
}
void WINAPI OnConEmuLoaded(struct ConEmuLoadedArg* pConEmuInfo)
{
gfRegisterBackground = pConEmuInfo->RegisterBackground;
ghPluginModule = pConEmuInfo->hPlugin;
if (gfRegisterBackground && gbBackgroundEnabled)
{
StartPlugin(FALSE/*считать параметры из реестра*/);
}
}
void SettingsLoad()
{
if (!gbSetStartupInfoOk)
{
_ASSERTE(gbSetStartupInfoOk);
return;
}
if (!*gsXmlConfigFile)
{
lstrcpyn(gsXmlConfigFile, szDefaultXmlName, countof(gsXmlConfigFile));
}
if (gFarVersion.dwVerMajor == 1)
SettingsLoadA();
else if (gFarVersion.dwBuild >= FAR_Y2_VER)
FUNC_Y2(SettingsLoadW)();
else if (gFarVersion.dwBuild >= FAR_Y1_VER)
FUNC_Y1(SettingsLoadW)();
else
FUNC_X(SettingsLoadW)();
}
void SettingsLoadReg(LPCWSTR pszRegKey)
{
HKEY hkey = NULL;
if (!RegOpenKeyExW(HKEY_CURRENT_USER, pszRegKey, 0, KEY_READ, &hkey))
{
DWORD nVal, nType, nSize; BYTE cVal;
for (ConEmuBgSettings *p = gSettings; p->pszValueName; p++)
{
if (p->nValueType == REG_BINARY)
{
_ASSERTE(p->nValueSize == 1);
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_BINARY), &cVal, &(nSize = sizeof(cVal))))
*((BOOL*)p->pValue) = (cVal != 0);
}
else if (p->nValueType == REG_DWORD)
{
_ASSERTE(p->nValueSize == 4);
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_DWORD), (LPBYTE)&nVal, &(nSize = sizeof(nVal))))
*((DWORD*)p->pValue) = nVal;
}
else if (p->nValueType == REG_SZ)
{
wchar_t szValue[MAX_PATH] = {};
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_SZ), (LPBYTE)szValue, &(nSize = sizeof(szValue))))
lstrcpyn((wchar_t*)p->pValue, szValue, p->nValueSize);
}
}
RegCloseKey(hkey);
}
}
void SettingsSave()
{
if (gFarVersion.dwVerMajor == 1)
SettingsSaveA();
else if (gFarVersion.dwBuild >= FAR_Y2_VER)
FUNC_Y2(SettingsSaveW)();
else if (gFarVersion.dwBuild >= FAR_Y1_VER)
FUNC_Y1(SettingsSaveW)();
else
FUNC_X(SettingsSaveW)();
}
void SettingsSaveReg(LPCWSTR pszRegKey)
{
HKEY hkey = NULL;
if (!RegCreateKeyExW(HKEY_CURRENT_USER, pszRegKey, 0, 0, 0, KEY_ALL_ACCESS, 0, &hkey, NULL))
{
BYTE cVal;
for (ConEmuBgSettings *p = gSettings; p->pszValueName; p++)
{
if (p->nValueType == REG_BINARY)
{
_ASSERTE(p->nValueSize == 1);
cVal = (BYTE)*(BOOL*)p->pValue;
RegSetValueExW(hkey, p->pszValueName, 0, REG_BINARY, &cVal, sizeof(cVal));
}
else if (p->nValueType == REG_DWORD)
{
_ASSERTE(p->nValueSize == 4);
RegSetValueExW(hkey, p->pszValueName, 0, REG_DWORD, p->pValue, p->nValueSize);
}
else if (p->nValueType == REG_SZ)
{
RegSetValueExW(hkey, p->pszValueName, 0, REG_SZ, p->pValue, sizeof(wchar_t)*(1+lstrlenW((wchar_t*)p->pValue)));
}
}
RegCloseKey(hkey);
}
}
void StartPlugin(BOOL bConfigure)
{
if (gbInStartPlugin)
{
// Вложенных вызовов быть не должно
_ASSERTE(gbInStartPlugin==false);
return;
}
gbInStartPlugin = true;
if (!XmlFile.cr)
{
XmlFile.cr = new MSectionSimple(true);
}
if (!bConfigure)
{
SettingsLoad();
}
static bool bWasRegistered = false;
if (gfRegisterBackground)
{
if (gbBackgroundEnabled)
{
if (bConfigure && bWasRegistered)
{
RegisterBackgroundArg upd = {sizeof(RegisterBackgroundArg), rbc_Redraw};
gfRegisterBackground(&upd);
}
else
{
RegisterBackgroundArg reg = {sizeof(RegisterBackgroundArg), rbc_Register, ghPluginModule};
reg.PaintConEmuBackground = ::PaintConEmuBackground;
reg.dwPlaces = pbp_Panels;
reg.dwSuggestedLevel = 0;
gfRegisterBackground(®);
bWasRegistered = true;
}
}
else
{
RegisterBackgroundArg unreg = {sizeof(RegisterBackgroundArg), rbc_Unregister, ghPluginModule};
gfRegisterBackground(&unreg);
bWasRegistered = false;
}
}
else
{
bWasRegistered = false;
}
// Вернуть флаг обратно
gbInStartPlugin = false;
}
void ExitPlugin(void)
{
if (gfRegisterBackground != NULL)
{
RegisterBackgroundArg inf = {sizeof(RegisterBackgroundArg), rbc_Unregister, ghPluginModule};
gfRegisterBackground(&inf);
}
// Вообще-то это нужно делать в нити отрисовки, но на всякий случай, дернем здесь (LastChance)
GdipDone();
gbSetStartupInfoOk = false;
}
void WINAPI ExitFARW(void)
{
ExitPlugin();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(ExitFARW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(ExitFARW)();
else
FUNC_X(ExitFARW)();
}
void WINAPI ExitFARW3(void*)
{
ExitPlugin();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(ExitFARW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(ExitFARW)();
else
FUNC_X(ExitFARW)();
}
LPCWSTR GetMsgW(int aiMsg)
{
if (gFarVersion.dwVerMajor==1)
return L"";
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(GetMsgW)(aiMsg);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(GetMsgW)(aiMsg);
else
return FUNC_X(GetMsgW)(aiMsg);
}
HANDLE WINAPI OpenW(const void* Info)
{
HANDLE hResult = NULL;
if (gFarVersion.dwBuild>=FAR_Y2_VER)
hResult = FUNC_Y2(OpenW)(Info);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
hResult = FUNC_Y1(OpenW)(Info);
else
{
_ASSERTE(FALSE && "Must not called in Far2");
}
return hResult;
}
int WINAPI ConfigureW(int ItemNumber)
{
if (gFarVersion.dwVerMajor==1)
return false;
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(ConfigureW)(ItemNumber);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(ConfigureW)(ItemNumber);
else
return FUNC_X(ConfigureW)(ItemNumber);
}
int WINAPI ConfigureW3(void*)
{
if (gFarVersion.dwVerMajor==1)
return false;
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(ConfigureW)(0);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(ConfigureW)(0);
else
return FUNC_X(ConfigureW)(0);
}
HANDLE OpenPluginWcmn(int OpenFrom,INT_PTR Item)
{
HANDLE hResult = (gFarVersion.dwVerMajor >= 3) ? NULL : INVALID_HANDLE_VALUE;
if (!gbInfoW_OK)
return hResult;
ConfigureW(0);
return hResult;
}
bool FMatch(LPCWSTR asMask, LPWSTR asPath)
{
if (!asMask || !asPath)
return false;
if ((*asMask && !*asPath) || (*asPath && !*asMask))
return false;
if (gFarVersion.dwVerMajor==1)
{
bool lbRc = false;
int nMaskLen = lstrlenW(asMask);
char* pszMask = (char*)malloc(nMaskLen+1);
int nPathLen = lstrlenW(asPath);
char* pszPath = (char*)malloc(nPathLen+1);
if (pszMask && pszPath)
{
WideCharToMultiByte(CP_ACP, 0, asMask, nMaskLen+1, pszMask, nMaskLen+1, 0,0);
WideCharToMultiByte(CP_ACP, 0, asPath, nPathLen+1, pszPath, nPathLen+1, 0,0);
lbRc = FMatchA(pszMask, pszPath);
}
if (pszMask)
free(pszMask);
if (pszPath)
free(pszPath);
return lbRc;
}
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(FMatchW)(asMask, asPath);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(FMatchW)(asMask, asPath);
else
return FUNC_X(FMatchW)(asMask, asPath);
}
int GetMacroArea()
{
int nMacroArea = 0/*MACROAREA_OTHER*/;
if (gFarVersion.dwVerMajor==1)
{
_ASSERTE(gFarVersion.dwVerMajor>1);
nMacroArea = 1; // в Far 1.7x не поддерживается
}
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
nMacroArea = FUNC_Y2(GetMacroAreaW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
nMacroArea = FUNC_Y1(GetMacroAreaW)();
else
nMacroArea = FUNC_X(GetMacroAreaW)();
return nMacroArea;
}
| {
"pile_set_name": "Github"
} |
{
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
package com.example.service;
import com.example.domain.Customer;
import com.example.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CustomerService {
@Autowired
CustomerRepository customerRepository;
public Customer save(Customer customer) {
return customerRepository.save(customer);
}
public List<Customer> findAll() {
return customerRepository.findAll();
}
// その他のメソッドは次章で定義します
}
| {
"pile_set_name": "Github"
} |
require 'rx'
source = Rx::Observable.repeat(42, 3)
subscription = source.subscribe(
lambda {|x|
puts 'Next: ' + x.to_s
},
lambda {|err|
puts 'Error: ' + err.to_s
},
lambda {
puts 'Completed'
})
#=> Next: 42
# => Next: 42
# => Next: 42
# => Completed
| {
"pile_set_name": "Github"
} |
package org.opencb.opencga.storage.core.metadata;
import org.opencb.biodata.models.variant.metadata.VariantMetadata;
import org.opencb.biodata.models.variant.metadata.VariantStudyMetadata;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.opencga.storage.core.exceptions.StorageEngineException;
import org.opencb.opencga.storage.core.metadata.adaptors.FileMetadataDBAdaptor;
import org.opencb.opencga.storage.core.metadata.models.StudyMetadata;
import org.opencb.opencga.storage.core.variant.query.projection.VariantQueryProjection;
import org.opencb.opencga.storage.core.variant.query.projection.VariantQueryProjectionParser;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Creates a VariantMetadata from other metadata information stored in the database.
*
* Created on 17/08/17.
*
* @author Jacobo Coll <[email protected]>
*/
public class VariantMetadataFactory {
protected final VariantStorageMetadataManager scm;
public VariantMetadataFactory(VariantStorageMetadataManager variantStorageMetadataManager) {
scm = variantStorageMetadataManager;
}
public VariantMetadata makeVariantMetadata() throws StorageEngineException {
return makeVariantMetadata(new Query(), new QueryOptions());
}
public VariantMetadata makeVariantMetadata(Query query, QueryOptions queryOptions) throws StorageEngineException {
VariantQueryProjection queryFields = VariantQueryProjectionParser.parseVariantQueryFields(query, queryOptions, scm);
return makeVariantMetadata(queryFields, queryOptions);
}
protected VariantMetadata makeVariantMetadata(VariantQueryProjection queryFields, QueryOptions queryOptions)
throws StorageEngineException {
VariantMetadata metadata = new VariantMetadataConverter(scm)
.toVariantMetadata(queryFields);
Map<String, StudyMetadata> studyConfigurationMap = queryFields.getStudies().values().stream()
.collect(Collectors.toMap(VariantQueryProjection.StudyVariantQueryProjection::getName,
VariantQueryProjection.StudyVariantQueryProjection::getStudyMetadata));
for (VariantStudyMetadata variantStudyMetadata : metadata.getStudies()) {
StudyMetadata studyMetadata = studyConfigurationMap.get(variantStudyMetadata.getId());
List<Integer> fileIds = queryFields.getStudy(studyMetadata.getId()).getFiles();
if (fileIds != null && !fileIds.isEmpty()) {
Query query = new Query()
.append(FileMetadataDBAdaptor.VariantFileMetadataQueryParam.STUDY_ID.key(), studyMetadata.getId())
.append(FileMetadataDBAdaptor.VariantFileMetadataQueryParam.FILE_ID.key(), fileIds);
scm.variantFileMetadataIterator(query, new QueryOptions()).forEachRemaining(fileMetadata -> {
variantStudyMetadata.getFiles().removeIf(file -> file.getId().equals(fileMetadata.getId()));
variantStudyMetadata.getFiles().add(fileMetadata.getImpl());
});
}
}
return metadata;
}
}
| {
"pile_set_name": "Github"
} |
// Pingus - A free Lemmings clone
// Copyright (C) 2000 Ingo Ruhnke <[email protected]>
//
// This program 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.
//
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef HEADER_PINGUS_PINGUS_ACTIONS_FALLER_HPP
#define HEADER_PINGUS_PINGUS_ACTIONS_FALLER_HPP
#include "pingus/pingu_action.hpp"
#include "pingus/state_sprite.hpp"
namespace Actions {
class Faller : public PinguAction
{
private:
StateSprite faller;
StateSprite tumbler;
public:
Faller(Pingu*);
virtual ~Faller();
void draw (SceneContext& gc);
void update();
bool change_allowed (ActionName::Enum new_action);
ActionName::Enum get_type() const { return ActionName::FALLER; }
bool is_tumbling () const;
private:
Faller (const Faller&);
Faller& operator= (const Faller&);
};
} // namespace Actions
#endif
/* EOF */
| {
"pile_set_name": "Github"
} |
/***************************************************************************
*
* truncate.c-释放指定i节点在设备上占用的所有逻辑块
* 包括直接块、一次间接块和二次间接块,从而将文件对应的
* 长度截为零,并释放占用的设备空间
*
* Copyright (C) 2010 杨习辉
***************************************************************************/
#include "type.h"
#include "blk.h"
#include "process.h"
#include "fs.h"
/*释放一次间接块,block是间接块的块号*/
private void free_level1(int dev,int block)
{
struct_mem_buffer *mbuffer;
int i;
u16 *p;
/*块号不能为零*/
if(!block)
{
return;
}
/*下面释放一次间接块中指向的数据块号*/
if(mbuffer = bread(dev,block))
{
p = (u16 *)mbuffer->data;
for(i = 0 ; i < (BLOCK_SIZE / sizeof(u16)) ; i ++)
{
if(*p)
{
free_block(dev,*p);
}
}
brelease(mbuffer);
}
/*最后释放一次间接块*/
free_block(dev,block);
}
/*释放二次间接块,block是二次间接块的块号*/
private void free_level2(int dev,int block)
{
struct_mem_buffer *mbuffer;
int i;
u16 *p;
/*块号不能为零*/
if(!block)
{
return;
}
if(mbuffer = bread(dev,block))
{
p = (u16 *)mbuffer->data;
/*下面循环释放多个可以看作为一次间接块的块*/
for(i = 0 ; i <= BLOCK_SIZE / sizeof(u16) ; i ++)
{
if(*p)
{
free_level1(dev,*p);
}
}
brelease(mbuffer);
}
/*最后再释放二次间接块本身*/
free_block(dev,block);
}
/*将文件截断为零,并释放占用的空间*/
/*由于此函数供文件系统本身调用,所以不考虑竞争条件*/
public void truncate(struct_mem_inode *inode)
{
int i;
/*参数合法性检查*/
if(!inode)
{
return;
}
/*判断是不是目录文件或普通文件,只有这两种文件才可以进行操作*/
if(IS_DIR(inode->mode) || IS_NORMAL(inode->mode))
{
/*首先释放直接块号*/
for(i = 0 ; i < INDEX_LEVEL1 ; i ++)
{
free_block(inode->dev,inode->data[i]);
inode->data[i] = 0;
}
/*一次间接块*/
free_level1(inode->dev,inode->data[INDEX_LEVEL1]);
free_level2(inode->dev,inode->data[INDEX_LEVEL2]);
inode->data[INDEX_LEVEL1] = 0;
inode->data[INDEX_LEVEL2] = 0;
/*文件长度为0*/
inode->size = 0;
/*已修改inode*/
inode->dirty = TRUE;
/*时间*/
inode->modify_time = CURRENT_TIME;
inode->last_access = CURRENT_TIME;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* WordPress Administration Scheme API
*
* Here we keep the DB structure and option values.
*
* @package WordPress
* @subpackage Administration
*/
/**
* Declare these as global in case schema.php is included from a function.
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global array $wp_queries
* @global string $charset_collate
*/
global $wpdb, $wp_queries, $charset_collate;
/**
* The database character collate.
*/
$charset_collate = $wpdb->get_charset_collate();
/**
* Retrieve the SQL for creating database tables.
*
* @since 3.3.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $scope Optional. The tables for which to retrieve SQL. Can be all, global, ms_global, or blog tables. Defaults to all.
* @param int $blog_id Optional. The site ID for which to retrieve SQL. Default is the current site ID.
* @return string The SQL needed to create the requested tables.
*/
function wp_get_db_schema( $scope = 'all', $blog_id = null ) {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
if ( $blog_id && $blog_id != $wpdb->blogid ) {
$old_blog_id = $wpdb->set_blog_id( $blog_id );
}
// Engage multisite if in the middle of turning it on from network.php.
$is_multisite = is_multisite() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK );
/*
* Indexes have a maximum size of 767 bytes. Historically, we haven't need to be concerned about that.
* As of 4.2, however, we moved to utf8mb4, which uses 4 bytes per character. This means that an index which
* used to have room for floor(767/3) = 255 characters, now only has room for floor(767/4) = 191 characters.
*/
$max_index_length = 191;
// Blog-specific tables.
$blog_tables = "CREATE TABLE $wpdb->termmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
term_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY term_id (term_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->terms (
term_id bigint(20) unsigned NOT NULL auto_increment,
name varchar(200) NOT NULL default '',
slug varchar(200) NOT NULL default '',
term_group bigint(10) NOT NULL default 0,
PRIMARY KEY (term_id),
KEY slug (slug($max_index_length)),
KEY name (name($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->term_taxonomy (
term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment,
term_id bigint(20) unsigned NOT NULL default 0,
taxonomy varchar(32) NOT NULL default '',
description longtext NOT NULL,
parent bigint(20) unsigned NOT NULL default 0,
count bigint(20) NOT NULL default 0,
PRIMARY KEY (term_taxonomy_id),
UNIQUE KEY term_id_taxonomy (term_id,taxonomy),
KEY taxonomy (taxonomy)
) $charset_collate;
CREATE TABLE $wpdb->term_relationships (
object_id bigint(20) unsigned NOT NULL default 0,
term_taxonomy_id bigint(20) unsigned NOT NULL default 0,
term_order int(11) NOT NULL default 0,
PRIMARY KEY (object_id,term_taxonomy_id),
KEY term_taxonomy_id (term_taxonomy_id)
) $charset_collate;
CREATE TABLE $wpdb->commentmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
comment_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY comment_id (comment_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->comments (
comment_ID bigint(20) unsigned NOT NULL auto_increment,
comment_post_ID bigint(20) unsigned NOT NULL default '0',
comment_author tinytext NOT NULL,
comment_author_email varchar(100) NOT NULL default '',
comment_author_url varchar(200) NOT NULL default '',
comment_author_IP varchar(100) NOT NULL default '',
comment_date datetime NOT NULL default '0000-00-00 00:00:00',
comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
comment_content text NOT NULL,
comment_karma int(11) NOT NULL default '0',
comment_approved varchar(20) NOT NULL default '1',
comment_agent varchar(255) NOT NULL default '',
comment_type varchar(20) NOT NULL default 'comment',
comment_parent bigint(20) unsigned NOT NULL default '0',
user_id bigint(20) unsigned NOT NULL default '0',
PRIMARY KEY (comment_ID),
KEY comment_post_ID (comment_post_ID),
KEY comment_approved_date_gmt (comment_approved,comment_date_gmt),
KEY comment_date_gmt (comment_date_gmt),
KEY comment_parent (comment_parent),
KEY comment_author_email (comment_author_email(10))
) $charset_collate;
CREATE TABLE $wpdb->links (
link_id bigint(20) unsigned NOT NULL auto_increment,
link_url varchar(255) NOT NULL default '',
link_name varchar(255) NOT NULL default '',
link_image varchar(255) NOT NULL default '',
link_target varchar(25) NOT NULL default '',
link_description varchar(255) NOT NULL default '',
link_visible varchar(20) NOT NULL default 'Y',
link_owner bigint(20) unsigned NOT NULL default '1',
link_rating int(11) NOT NULL default '0',
link_updated datetime NOT NULL default '0000-00-00 00:00:00',
link_rel varchar(255) NOT NULL default '',
link_notes mediumtext NOT NULL,
link_rss varchar(255) NOT NULL default '',
PRIMARY KEY (link_id),
KEY link_visible (link_visible)
) $charset_collate;
CREATE TABLE $wpdb->options (
option_id bigint(20) unsigned NOT NULL auto_increment,
option_name varchar(191) NOT NULL default '',
option_value longtext NOT NULL,
autoload varchar(20) NOT NULL default 'yes',
PRIMARY KEY (option_id),
UNIQUE KEY option_name (option_name),
KEY autoload (autoload)
) $charset_collate;
CREATE TABLE $wpdb->postmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
post_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY post_id (post_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->posts (
ID bigint(20) unsigned NOT NULL auto_increment,
post_author bigint(20) unsigned NOT NULL default '0',
post_date datetime NOT NULL default '0000-00-00 00:00:00',
post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
post_content longtext NOT NULL,
post_title text NOT NULL,
post_excerpt text NOT NULL,
post_status varchar(20) NOT NULL default 'publish',
comment_status varchar(20) NOT NULL default 'open',
ping_status varchar(20) NOT NULL default 'open',
post_password varchar(255) NOT NULL default '',
post_name varchar(200) NOT NULL default '',
to_ping text NOT NULL,
pinged text NOT NULL,
post_modified datetime NOT NULL default '0000-00-00 00:00:00',
post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00',
post_content_filtered longtext NOT NULL,
post_parent bigint(20) unsigned NOT NULL default '0',
guid varchar(255) NOT NULL default '',
menu_order int(11) NOT NULL default '0',
post_type varchar(20) NOT NULL default 'post',
post_mime_type varchar(100) NOT NULL default '',
comment_count bigint(20) NOT NULL default '0',
PRIMARY KEY (ID),
KEY post_name (post_name($max_index_length)),
KEY type_status_date (post_type,post_status,post_date,ID),
KEY post_parent (post_parent),
KEY post_author (post_author)
) $charset_collate;\n";
// Single site users table. The multisite flavor of the users table is handled below.
$users_single_table = "CREATE TABLE $wpdb->users (
ID bigint(20) unsigned NOT NULL auto_increment,
user_login varchar(60) NOT NULL default '',
user_pass varchar(255) NOT NULL default '',
user_nicename varchar(50) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
user_url varchar(100) NOT NULL default '',
user_registered datetime NOT NULL default '0000-00-00 00:00:00',
user_activation_key varchar(255) NOT NULL default '',
user_status int(11) NOT NULL default '0',
display_name varchar(250) NOT NULL default '',
PRIMARY KEY (ID),
KEY user_login_key (user_login),
KEY user_nicename (user_nicename),
KEY user_email (user_email)
) $charset_collate;\n";
// Multisite users table.
$users_multi_table = "CREATE TABLE $wpdb->users (
ID bigint(20) unsigned NOT NULL auto_increment,
user_login varchar(60) NOT NULL default '',
user_pass varchar(255) NOT NULL default '',
user_nicename varchar(50) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
user_url varchar(100) NOT NULL default '',
user_registered datetime NOT NULL default '0000-00-00 00:00:00',
user_activation_key varchar(255) NOT NULL default '',
user_status int(11) NOT NULL default '0',
display_name varchar(250) NOT NULL default '',
spam tinyint(2) NOT NULL default '0',
deleted tinyint(2) NOT NULL default '0',
PRIMARY KEY (ID),
KEY user_login_key (user_login),
KEY user_nicename (user_nicename),
KEY user_email (user_email)
) $charset_collate;\n";
// Usermeta.
$usermeta_table = "CREATE TABLE $wpdb->usermeta (
umeta_id bigint(20) unsigned NOT NULL auto_increment,
user_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (umeta_id),
KEY user_id (user_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;\n";
// Global tables.
if ( $is_multisite ) {
$global_tables = $users_multi_table . $usermeta_table;
} else {
$global_tables = $users_single_table . $usermeta_table;
}
// Multisite global tables.
$ms_global_tables = "CREATE TABLE $wpdb->blogs (
blog_id bigint(20) NOT NULL auto_increment,
site_id bigint(20) NOT NULL default '0',
domain varchar(200) NOT NULL default '',
path varchar(100) NOT NULL default '',
registered datetime NOT NULL default '0000-00-00 00:00:00',
last_updated datetime NOT NULL default '0000-00-00 00:00:00',
public tinyint(2) NOT NULL default '1',
archived tinyint(2) NOT NULL default '0',
mature tinyint(2) NOT NULL default '0',
spam tinyint(2) NOT NULL default '0',
deleted tinyint(2) NOT NULL default '0',
lang_id int(11) NOT NULL default '0',
PRIMARY KEY (blog_id),
KEY domain (domain(50),path(5)),
KEY lang_id (lang_id)
) $charset_collate;
CREATE TABLE $wpdb->blogmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
blog_id bigint(20) NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY meta_key (meta_key($max_index_length)),
KEY blog_id (blog_id)
) $charset_collate;
CREATE TABLE $wpdb->registration_log (
ID bigint(20) NOT NULL auto_increment,
email varchar(255) NOT NULL default '',
IP varchar(30) NOT NULL default '',
blog_id bigint(20) NOT NULL default '0',
date_registered datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (ID),
KEY IP (IP)
) $charset_collate;
CREATE TABLE $wpdb->site (
id bigint(20) NOT NULL auto_increment,
domain varchar(200) NOT NULL default '',
path varchar(100) NOT NULL default '',
PRIMARY KEY (id),
KEY domain (domain(140),path(51))
) $charset_collate;
CREATE TABLE $wpdb->sitemeta (
meta_id bigint(20) NOT NULL auto_increment,
site_id bigint(20) NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY meta_key (meta_key($max_index_length)),
KEY site_id (site_id)
) $charset_collate;
CREATE TABLE $wpdb->signups (
signup_id bigint(20) NOT NULL auto_increment,
domain varchar(200) NOT NULL default '',
path varchar(100) NOT NULL default '',
title longtext NOT NULL,
user_login varchar(60) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
registered datetime NOT NULL default '0000-00-00 00:00:00',
activated datetime NOT NULL default '0000-00-00 00:00:00',
active tinyint(1) NOT NULL default '0',
activation_key varchar(50) NOT NULL default '',
meta longtext,
PRIMARY KEY (signup_id),
KEY activation_key (activation_key),
KEY user_email (user_email),
KEY user_login_email (user_login,user_email),
KEY domain_path (domain(140),path(51))
) $charset_collate;";
switch ( $scope ) {
case 'blog':
$queries = $blog_tables;
break;
case 'global':
$queries = $global_tables;
if ( $is_multisite ) {
$queries .= $ms_global_tables;
}
break;
case 'ms_global':
$queries = $ms_global_tables;
break;
case 'all':
default:
$queries = $global_tables . $blog_tables;
if ( $is_multisite ) {
$queries .= $ms_global_tables;
}
break;
}
if ( isset( $old_blog_id ) ) {
$wpdb->set_blog_id( $old_blog_id );
}
return $queries;
}
// Populate for back compat.
$wp_queries = wp_get_db_schema( 'all' );
/**
* Create WordPress options and set the default values.
*
* @since 1.5.0
* @since 5.1.0 The $options parameter has been added.
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $wp_db_version WordPress database version.
* @global int $wp_current_db_version The old (current) database version.
*
* @param array $options Optional. Custom option $key => $value pairs to use. Default empty array.
*/
function populate_options( array $options = array() ) {
global $wpdb, $wp_db_version, $wp_current_db_version;
$guessurl = wp_guess_url();
/**
* Fires before creating WordPress options and populating their default values.
*
* @since 2.6.0
*/
do_action( 'populate_options' );
// If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
$stylesheet = WP_DEFAULT_THEME;
$template = WP_DEFAULT_THEME;
$theme = wp_get_theme( WP_DEFAULT_THEME );
if ( ! $theme->exists() ) {
$theme = WP_Theme::get_core_default_theme();
}
// If we can't find a core default theme, WP_DEFAULT_THEME is the best we can do.
if ( $theme ) {
$stylesheet = $theme->get_stylesheet();
$template = $theme->get_template();
}
$timezone_string = '';
$gmt_offset = 0;
/*
* translators: default GMT offset or timezone string. Must be either a valid offset (-12 to 14)
* or a valid timezone string (America/New_York). See https://www.php.net/manual/en/timezones.php
* for all timezone strings supported by PHP.
*/
$offset_or_tz = _x( '0', 'default GMT offset or timezone string' ); // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings
if ( is_numeric( $offset_or_tz ) ) {
$gmt_offset = $offset_or_tz;
} elseif ( $offset_or_tz && in_array( $offset_or_tz, timezone_identifiers_list(), true ) ) {
$timezone_string = $offset_or_tz;
}
$defaults = array(
'siteurl' => $guessurl,
'home' => $guessurl,
'blogname' => __( 'My Site' ),
/* translators: Site tagline. */
'blogdescription' => __( 'Just another WordPress site' ),
'users_can_register' => 0,
'admin_email' => '[email protected]',
/* translators: Default start of the week. 0 = Sunday, 1 = Monday. */
'start_of_week' => _x( '1', 'start of week' ),
'use_balanceTags' => 0,
'use_smilies' => 1,
'require_name_email' => 1,
'comments_notify' => 1,
'posts_per_rss' => 10,
'rss_use_excerpt' => 0,
'mailserver_url' => 'mail.example.com',
'mailserver_login' => '[email protected]',
'mailserver_pass' => 'password',
'mailserver_port' => 110,
'default_category' => 1,
'default_comment_status' => 'open',
'default_ping_status' => 'open',
'default_pingback_flag' => 1,
'posts_per_page' => 10,
/* translators: Default date format, see https://www.php.net/manual/datetime.format.php */
'date_format' => __( 'F j, Y' ),
/* translators: Default time format, see https://www.php.net/manual/datetime.format.php */
'time_format' => __( 'g:i a' ),
/* translators: Links last updated date format, see https://www.php.net/manual/datetime.format.php */
'links_updated_date_format' => __( 'F j, Y g:i a' ),
'comment_moderation' => 0,
'moderation_notify' => 1,
'permalink_structure' => '',
'rewrite_rules' => '',
'hack_file' => 0,
'blog_charset' => 'UTF-8',
'moderation_keys' => '',
'active_plugins' => array(),
'category_base' => '',
'ping_sites' => 'http://rpc.pingomatic.com/',
'comment_max_links' => 2,
'gmt_offset' => $gmt_offset,
// 1.5.0
'default_email_category' => 1,
'recently_edited' => '',
'template' => $template,
'stylesheet' => $stylesheet,
'comment_registration' => 0,
'html_type' => 'text/html',
// 1.5.1
'use_trackback' => 0,
// 2.0.0
'default_role' => 'subscriber',
'db_version' => $wp_db_version,
// 2.0.1
'uploads_use_yearmonth_folders' => 1,
'upload_path' => '',
// 2.1.0
'blog_public' => '1',
'default_link_category' => 2,
'show_on_front' => 'posts',
// 2.2.0
'tag_base' => '',
// 2.5.0
'show_avatars' => '1',
'avatar_rating' => 'G',
'upload_url_path' => '',
'thumbnail_size_w' => 150,
'thumbnail_size_h' => 150,
'thumbnail_crop' => 1,
'medium_size_w' => 300,
'medium_size_h' => 300,
// 2.6.0
'avatar_default' => 'mystery',
// 2.7.0
'large_size_w' => 1024,
'large_size_h' => 1024,
'image_default_link_type' => 'none',
'image_default_size' => '',
'image_default_align' => '',
'close_comments_for_old_posts' => 0,
'close_comments_days_old' => 14,
'thread_comments' => 1,
'thread_comments_depth' => 5,
'page_comments' => 0,
'comments_per_page' => 50,
'default_comments_page' => 'newest',
'comment_order' => 'asc',
'sticky_posts' => array(),
'widget_categories' => array(),
'widget_text' => array(),
'widget_rss' => array(),
'uninstall_plugins' => array(),
// 2.8.0
'timezone_string' => $timezone_string,
// 3.0.0
'page_for_posts' => 0,
'page_on_front' => 0,
// 3.1.0
'default_post_format' => 0,
// 3.5.0
'link_manager_enabled' => 0,
// 4.3.0
'finished_splitting_shared_terms' => 1,
'site_icon' => 0,
// 4.4.0
'medium_large_size_w' => 768,
'medium_large_size_h' => 0,
// 4.9.6
'wp_page_for_privacy_policy' => 0,
// 4.9.8
'show_comments_cookies_opt_in' => 1,
// 5.3.0
'admin_email_lifespan' => ( time() + 6 * MONTH_IN_SECONDS ),
// 5.5.0
'disallowed_keys' => '',
'comment_previously_approved' => 1,
'auto_plugin_theme_update_emails' => array(),
);
// 3.3.0
if ( ! is_multisite() ) {
$defaults['initial_db_version'] = ! empty( $wp_current_db_version ) && $wp_current_db_version < $wp_db_version
? $wp_current_db_version : $wp_db_version;
}
// 3.0.0 multisite.
if ( is_multisite() ) {
/* translators: %s: Network title. */
$defaults['blogdescription'] = sprintf( __( 'Just another %s site' ), get_network()->site_name );
$defaults['permalink_structure'] = '/%year%/%monthnum%/%day%/%postname%/';
}
$options = wp_parse_args( $options, $defaults );
// Set autoload to no for these options.
$fat_options = array(
'moderation_keys',
'recently_edited',
'disallowed_keys',
'uninstall_plugins',
'auto_plugin_theme_update_emails',
);
$keys = "'" . implode( "', '", array_keys( $options ) ) . "'";
$existing_options = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name in ( $keys )" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$insert = '';
foreach ( $options as $option => $value ) {
if ( in_array( $option, $existing_options, true ) ) {
continue;
}
if ( in_array( $option, $fat_options, true ) ) {
$autoload = 'no';
} else {
$autoload = 'yes';
}
if ( is_array( $value ) ) {
$value = serialize( $value );
}
if ( ! empty( $insert ) ) {
$insert .= ', ';
}
$insert .= $wpdb->prepare( '(%s, %s, %s)', $option, $value, $autoload );
}
if ( ! empty( $insert ) ) {
$wpdb->query( "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
// In case it is set, but blank, update "home".
if ( ! __get_option( 'home' ) ) {
update_option( 'home', $guessurl );
}
// Delete unused options.
$unusedoptions = array(
'blodotgsping_url',
'bodyterminator',
'emailtestonly',
'phoneemail_separator',
'smilies_directory',
'subjectprefix',
'use_bbcode',
'use_blodotgsping',
'use_phoneemail',
'use_quicktags',
'use_weblogsping',
'weblogs_cache_file',
'use_preview',
'use_htmltrans',
'smilies_directory',
'fileupload_allowedusers',
'use_phoneemail',
'default_post_status',
'default_post_category',
'archive_mode',
'time_difference',
'links_minadminlevel',
'links_use_adminlevels',
'links_rating_type',
'links_rating_char',
'links_rating_ignore_zero',
'links_rating_single_image',
'links_rating_image0',
'links_rating_image1',
'links_rating_image2',
'links_rating_image3',
'links_rating_image4',
'links_rating_image5',
'links_rating_image6',
'links_rating_image7',
'links_rating_image8',
'links_rating_image9',
'links_recently_updated_time',
'links_recently_updated_prepend',
'links_recently_updated_append',
'weblogs_cacheminutes',
'comment_allowed_tags',
'search_engine_friendly_urls',
'default_geourl_lat',
'default_geourl_lon',
'use_default_geourl',
'weblogs_xml_url',
'new_users_can_blog',
'_wpnonce',
'_wp_http_referer',
'Update',
'action',
'rich_editing',
'autosave_interval',
'deactivated_plugins',
'can_compress_scripts',
'page_uris',
'update_core',
'update_plugins',
'update_themes',
'doing_cron',
'random_seed',
'rss_excerpt_length',
'secret',
'use_linksupdate',
'default_comment_status_page',
'wporg_popular_tags',
'what_to_show',
'rss_language',
'language',
'enable_xmlrpc',
'enable_app',
'embed_autourls',
'default_post_edit_rows',
'gzipcompression',
'advanced_edit',
);
foreach ( $unusedoptions as $option ) {
delete_option( $option );
}
// Delete obsolete magpie stuff.
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name REGEXP '^rss_[0-9a-f]{32}(_ts)?$'" );
// Clear expired transients.
delete_expired_transients( true );
}
/**
* Execute WordPress role creation for the various WordPress versions.
*
* @since 2.0.0
*/
function populate_roles() {
populate_roles_160();
populate_roles_210();
populate_roles_230();
populate_roles_250();
populate_roles_260();
populate_roles_270();
populate_roles_280();
populate_roles_300();
}
/**
* Create the roles for WordPress 2.0
*
* @since 2.0.0
*/
function populate_roles_160() {
// Add roles.
add_role( 'administrator', 'Administrator' );
add_role( 'editor', 'Editor' );
add_role( 'author', 'Author' );
add_role( 'contributor', 'Contributor' );
add_role( 'subscriber', 'Subscriber' );
// Add caps for Administrator role.
$role = get_role( 'administrator' );
$role->add_cap( 'switch_themes' );
$role->add_cap( 'edit_themes' );
$role->add_cap( 'activate_plugins' );
$role->add_cap( 'edit_plugins' );
$role->add_cap( 'edit_users' );
$role->add_cap( 'edit_files' );
$role->add_cap( 'manage_options' );
$role->add_cap( 'moderate_comments' );
$role->add_cap( 'manage_categories' );
$role->add_cap( 'manage_links' );
$role->add_cap( 'upload_files' );
$role->add_cap( 'import' );
$role->add_cap( 'unfiltered_html' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_others_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'edit_pages' );
$role->add_cap( 'read' );
$role->add_cap( 'level_10' );
$role->add_cap( 'level_9' );
$role->add_cap( 'level_8' );
$role->add_cap( 'level_7' );
$role->add_cap( 'level_6' );
$role->add_cap( 'level_5' );
$role->add_cap( 'level_4' );
$role->add_cap( 'level_3' );
$role->add_cap( 'level_2' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Editor role.
$role = get_role( 'editor' );
$role->add_cap( 'moderate_comments' );
$role->add_cap( 'manage_categories' );
$role->add_cap( 'manage_links' );
$role->add_cap( 'upload_files' );
$role->add_cap( 'unfiltered_html' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_others_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'edit_pages' );
$role->add_cap( 'read' );
$role->add_cap( 'level_7' );
$role->add_cap( 'level_6' );
$role->add_cap( 'level_5' );
$role->add_cap( 'level_4' );
$role->add_cap( 'level_3' );
$role->add_cap( 'level_2' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Author role.
$role = get_role( 'author' );
$role->add_cap( 'upload_files' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'read' );
$role->add_cap( 'level_2' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Contributor role.
$role = get_role( 'contributor' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'read' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Subscriber role.
$role = get_role( 'subscriber' );
$role->add_cap( 'read' );
$role->add_cap( 'level_0' );
}
/**
* Create and modify WordPress roles for WordPress 2.1.
*
* @since 2.1.0
*/
function populate_roles_210() {
$roles = array( 'administrator', 'editor' );
foreach ( $roles as $role ) {
$role = get_role( $role );
if ( empty( $role ) ) {
continue;
}
$role->add_cap( 'edit_others_pages' );
$role->add_cap( 'edit_published_pages' );
$role->add_cap( 'publish_pages' );
$role->add_cap( 'delete_pages' );
$role->add_cap( 'delete_others_pages' );
$role->add_cap( 'delete_published_pages' );
$role->add_cap( 'delete_posts' );
$role->add_cap( 'delete_others_posts' );
$role->add_cap( 'delete_published_posts' );
$role->add_cap( 'delete_private_posts' );
$role->add_cap( 'edit_private_posts' );
$role->add_cap( 'read_private_posts' );
$role->add_cap( 'delete_private_pages' );
$role->add_cap( 'edit_private_pages' );
$role->add_cap( 'read_private_pages' );
}
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'delete_users' );
$role->add_cap( 'create_users' );
}
$role = get_role( 'author' );
if ( ! empty( $role ) ) {
$role->add_cap( 'delete_posts' );
$role->add_cap( 'delete_published_posts' );
}
$role = get_role( 'contributor' );
if ( ! empty( $role ) ) {
$role->add_cap( 'delete_posts' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.3.
*
* @since 2.3.0
*/
function populate_roles_230() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'unfiltered_upload' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.5.
*
* @since 2.5.0
*/
function populate_roles_250() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'edit_dashboard' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.6.
*
* @since 2.6.0
*/
function populate_roles_260() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'update_plugins' );
$role->add_cap( 'delete_plugins' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.7.
*
* @since 2.7.0
*/
function populate_roles_270() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'install_plugins' );
$role->add_cap( 'update_themes' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.8.
*
* @since 2.8.0
*/
function populate_roles_280() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'install_themes' );
}
}
/**
* Create and modify WordPress roles for WordPress 3.0.
*
* @since 3.0.0
*/
function populate_roles_300() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'update_core' );
$role->add_cap( 'list_users' );
$role->add_cap( 'remove_users' );
$role->add_cap( 'promote_users' );
$role->add_cap( 'edit_theme_options' );
$role->add_cap( 'delete_themes' );
$role->add_cap( 'export' );
}
}
if ( ! function_exists( 'install_network' ) ) :
/**
* Install Network.
*
* @since 3.0.0
*/
function install_network() {
if ( ! defined( 'WP_INSTALLING_NETWORK' ) ) {
define( 'WP_INSTALLING_NETWORK', true );
}
dbDelta( wp_get_db_schema( 'global' ) );
}
endif;
/**
* Populate network settings.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global object $current_site
* @global WP_Rewrite $wp_rewrite WordPress rewrite component.
*
* @param int $network_id ID of network to populate.
* @param string $domain The domain name for the network (eg. "example.com").
* @param string $email Email address for the network administrator.
* @param string $site_name The name of the network.
* @param string $path Optional. The path to append to the network's domain name. Default '/'.
* @param bool $subdomain_install Optional. Whether the network is a subdomain installation or a subdirectory installation.
* Default false, meaning the network is a subdirectory installation.
* @return bool|WP_Error True on success, or WP_Error on warning (with the installation otherwise successful,
* so the error code must be checked) or failure.
*/
function populate_network( $network_id = 1, $domain = '', $email = '', $site_name = '', $path = '/', $subdomain_install = false ) {
global $wpdb, $current_site, $wp_rewrite;
$errors = new WP_Error();
if ( '' === $domain ) {
$errors->add( 'empty_domain', __( 'You must provide a domain name.' ) );
}
if ( '' === $site_name ) {
$errors->add( 'empty_sitename', __( 'You must provide a name for your network of sites.' ) );
}
// Check for network collision.
$network_exists = false;
if ( is_multisite() ) {
if ( get_network( (int) $network_id ) ) {
$errors->add( 'siteid_exists', __( 'The network already exists.' ) );
}
} else {
if ( $network_id == $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE id = %d", $network_id ) ) ) {
$errors->add( 'siteid_exists', __( 'The network already exists.' ) );
}
}
if ( ! is_email( $email ) ) {
$errors->add( 'invalid_email', __( 'You must provide a valid email address.' ) );
}
if ( $errors->has_errors() ) {
return $errors;
}
if ( 1 == $network_id ) {
$wpdb->insert(
$wpdb->site,
array(
'domain' => $domain,
'path' => $path,
)
);
$network_id = $wpdb->insert_id;
} else {
$wpdb->insert(
$wpdb->site,
array(
'domain' => $domain,
'path' => $path,
'id' => $network_id,
)
);
}
populate_network_meta(
$network_id,
array(
'admin_email' => $email,
'site_name' => $site_name,
'subdomain_install' => $subdomain_install,
)
);
$site_user = get_userdata( (int) $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", 'admin_user_id', $network_id ) ) );
/*
* When upgrading from single to multisite, assume the current site will
* become the main site of the network. When using populate_network()
* to create another network in an existing multisite environment, skip
* these steps since the main site of the new network has not yet been
* created.
*/
if ( ! is_multisite() ) {
$current_site = new stdClass;
$current_site->domain = $domain;
$current_site->path = $path;
$current_site->site_name = ucfirst( $domain );
$wpdb->insert(
$wpdb->blogs,
array(
'site_id' => $network_id,
'blog_id' => 1,
'domain' => $domain,
'path' => $path,
'registered' => current_time( 'mysql' ),
)
);
$current_site->blog_id = $wpdb->insert_id;
update_user_meta( $site_user->ID, 'source_domain', $domain );
update_user_meta( $site_user->ID, 'primary_blog', $current_site->blog_id );
if ( $subdomain_install ) {
$wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' );
} else {
$wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' );
}
flush_rewrite_rules();
if ( ! $subdomain_install ) {
return true;
}
$vhost_ok = false;
$errstr = '';
$hostname = substr( md5( time() ), 0, 6 ) . '.' . $domain; // Very random hostname!
$page = wp_remote_get(
'http://' . $hostname,
array(
'timeout' => 5,
'httpversion' => '1.1',
)
);
if ( is_wp_error( $page ) ) {
$errstr = $page->get_error_message();
} elseif ( 200 == wp_remote_retrieve_response_code( $page ) ) {
$vhost_ok = true;
}
if ( ! $vhost_ok ) {
$msg = '<p><strong>' . __( 'Warning! Wildcard DNS may not be configured correctly!' ) . '</strong></p>';
$msg .= '<p>' . sprintf(
/* translators: %s: Host name. */
__( 'The installer attempted to contact a random hostname (%s) on your domain.' ),
'<code>' . $hostname . '</code>'
);
if ( ! empty( $errstr ) ) {
/* translators: %s: Error message. */
$msg .= ' ' . sprintf( __( 'This resulted in an error message: %s' ), '<code>' . $errstr . '</code>' );
}
$msg .= '</p>';
$msg .= '<p>' . sprintf(
/* translators: %s: Asterisk symbol (*). */
__( 'To use a subdomain configuration, you must have a wildcard entry in your DNS. This usually means adding a %s hostname record pointing at your web server in your DNS configuration tool.' ),
'<code>*</code>'
) . '</p>';
$msg .= '<p>' . __( 'You can still use your site but any subdomain you create may not be accessible. If you know your DNS is correct, ignore this message.' ) . '</p>';
return new WP_Error( 'no_wildcard_dns', $msg );
}
}
return true;
}
/**
* Creates WordPress network meta and sets the default values.
*
* @since 5.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $wp_db_version WordPress database version.
*
* @param int $network_id Network ID to populate meta for.
* @param array $meta Optional. Custom meta $key => $value pairs to use. Default empty array.
*/
function populate_network_meta( $network_id, array $meta = array() ) {
global $wpdb, $wp_db_version;
$network_id = (int) $network_id;
$email = ! empty( $meta['admin_email'] ) ? $meta['admin_email'] : '';
$subdomain_install = isset( $meta['subdomain_install'] ) ? (int) $meta['subdomain_install'] : 0;
// If a user with the provided email does not exist, default to the current user as the new network admin.
$site_user = ! empty( $email ) ? get_user_by( 'email', $email ) : false;
if ( false === $site_user ) {
$site_user = wp_get_current_user();
}
if ( empty( $email ) ) {
$email = $site_user->user_email;
}
$template = get_option( 'template' );
$stylesheet = get_option( 'stylesheet' );
$allowed_themes = array( $stylesheet => true );
if ( $template != $stylesheet ) {
$allowed_themes[ $template ] = true;
}
if ( WP_DEFAULT_THEME != $stylesheet && WP_DEFAULT_THEME != $template ) {
$allowed_themes[ WP_DEFAULT_THEME ] = true;
}
// If WP_DEFAULT_THEME doesn't exist, also include the latest core default theme.
if ( ! wp_get_theme( WP_DEFAULT_THEME )->exists() ) {
$core_default = WP_Theme::get_core_default_theme();
if ( $core_default ) {
$allowed_themes[ $core_default->get_stylesheet() ] = true;
}
}
if ( function_exists( 'clean_network_cache' ) ) {
clean_network_cache( $network_id );
} else {
wp_cache_delete( $network_id, 'networks' );
}
wp_cache_delete( 'networks_have_paths', 'site-options' );
if ( ! is_multisite() ) {
$site_admins = array( $site_user->user_login );
$users = get_users(
array(
'fields' => array( 'user_login' ),
'role' => 'administrator',
)
);
if ( $users ) {
foreach ( $users as $user ) {
$site_admins[] = $user->user_login;
}
$site_admins = array_unique( $site_admins );
}
} else {
$site_admins = get_site_option( 'site_admins' );
}
/* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */
$welcome_email = __(
'Howdy USERNAME,
Your new SITE_NAME site has been successfully set up at:
BLOG_URL
You can log in to the administrator account with the following information:
Username: USERNAME
Password: PASSWORD
Log in here: BLOG_URLwp-login.php
We hope you enjoy your new site. Thanks!
--The Team @ SITE_NAME'
);
$misc_exts = array(
// Images.
'jpg',
'jpeg',
'png',
'gif',
// Video.
'mov',
'avi',
'mpg',
'3gp',
'3g2',
// "audio".
'midi',
'mid',
// Miscellaneous.
'pdf',
'doc',
'ppt',
'odt',
'pptx',
'docx',
'pps',
'ppsx',
'xls',
'xlsx',
'key',
);
$audio_exts = wp_get_audio_extensions();
$video_exts = wp_get_video_extensions();
$upload_filetypes = array_unique( array_merge( $misc_exts, $audio_exts, $video_exts ) );
$sitemeta = array(
'site_name' => __( 'My Network' ),
'admin_email' => $email,
'admin_user_id' => $site_user->ID,
'registration' => 'none',
'upload_filetypes' => implode( ' ', $upload_filetypes ),
'blog_upload_space' => 100,
'fileupload_maxk' => 1500,
'site_admins' => $site_admins,
'allowedthemes' => $allowed_themes,
'illegal_names' => array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator', 'files' ),
'wpmu_upgrade_site' => $wp_db_version,
'welcome_email' => $welcome_email,
/* translators: %s: Site link. */
'first_post' => __( 'Welcome to %s. This is your first post. Edit or delete it, then start writing!' ),
// @todo - Network admins should have a method of editing the network siteurl (used for cookie hash).
'siteurl' => get_option( 'siteurl' ) . '/',
'add_new_users' => '0',
'upload_space_check_disabled' => is_multisite() ? get_site_option( 'upload_space_check_disabled' ) : '1',
'subdomain_install' => $subdomain_install,
'global_terms_enabled' => global_terms_enabled() ? '1' : '0',
'ms_files_rewriting' => is_multisite() ? get_site_option( 'ms_files_rewriting' ) : '0',
'initial_db_version' => get_option( 'initial_db_version' ),
'active_sitewide_plugins' => array(),
'WPLANG' => get_locale(),
);
if ( ! $subdomain_install ) {
$sitemeta['illegal_names'][] = 'blog';
}
$sitemeta = wp_parse_args( $meta, $sitemeta );
/**
* Filters meta for a network on creation.
*
* @since 3.7.0
*
* @param array $sitemeta Associative array of network meta keys and values to be inserted.
* @param int $network_id ID of network to populate.
*/
$sitemeta = apply_filters( 'populate_network_meta', $sitemeta, $network_id );
$insert = '';
foreach ( $sitemeta as $meta_key => $meta_value ) {
if ( is_array( $meta_value ) ) {
$meta_value = serialize( $meta_value );
}
if ( ! empty( $insert ) ) {
$insert .= ', ';
}
$insert .= $wpdb->prepare( '( %d, %s, %s)', $network_id, $meta_key, $meta_value );
}
$wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id, meta_key, meta_value ) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
/**
* Creates WordPress site meta and sets the default values.
*
* @since 5.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $site_id Site ID to populate meta for.
* @param array $meta Optional. Custom meta $key => $value pairs to use. Default empty array.
*/
function populate_site_meta( $site_id, array $meta = array() ) {
global $wpdb;
$site_id = (int) $site_id;
if ( ! is_site_meta_supported() ) {
return;
}
if ( empty( $meta ) ) {
return;
}
/**
* Filters meta for a site on creation.
*
* @since 5.2.0
*
* @param array $meta Associative array of site meta keys and values to be inserted.
* @param int $site_id ID of site to populate.
*/
$site_meta = apply_filters( 'populate_site_meta', $meta, $site_id );
$insert = '';
foreach ( $site_meta as $meta_key => $meta_value ) {
if ( is_array( $meta_value ) ) {
$meta_value = serialize( $meta_value );
}
if ( ! empty( $insert ) ) {
$insert .= ', ';
}
$insert .= $wpdb->prepare( '( %d, %s, %s)', $site_id, $meta_key, $meta_value );
}
$wpdb->query( "INSERT INTO $wpdb->blogmeta ( blog_id, meta_key, meta_value ) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
wp_cache_delete( $site_id, 'blog_meta' );
wp_cache_set_sites_last_changed();
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 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.
// Functions to access/create device major and minor numbers matching the
// encoding used in Darwin's sys/types.h header.
package unix
// Major returns the major component of a Darwin device number.
func Major(dev uint64) uint32 {
return uint32((dev >> 24) & 0xff)
}
// Minor returns the minor component of a Darwin device number.
func Minor(dev uint64) uint32 {
return uint32(dev & 0xffffff)
}
// Mkdev returns a Darwin device number generated from the given major and minor
// components.
func Mkdev(major, minor uint32) uint64 {
return (uint64(major) << 24) | uint64(minor)
}
| {
"pile_set_name": "Github"
} |
``odd``
=======
``odd`` returns ``true`` if the given number is odd:
.. code-block:: twig
{{ var is odd }}
.. seealso:: :doc:`even<../tests/even>`
| {
"pile_set_name": "Github"
} |
{
"private": true,
"main": "index.js"
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 org.jetbrains.android;
import static com.android.SdkConstants.ANDROID_URI;
import static com.android.SdkConstants.ATTR_DRAWABLE;
import static com.android.SdkConstants.ATTR_SRC;
import static com.android.SdkConstants.DOT_XML;
import static com.android.SdkConstants.FD_RES_LAYOUT;
import com.android.ide.common.rendering.api.ResourceReference;
import com.android.ide.common.rendering.api.ResourceValue;
import com.android.ide.common.resources.ResourceItem;
import com.android.ide.common.resources.ResourceResolver;
import com.android.ide.common.resources.configuration.DensityQualifier;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.resources.Density;
import com.android.tools.adtui.LightCalloutPopup;
import com.android.tools.idea.configurations.Configuration;
import com.android.tools.idea.configurations.ConfigurationManager;
import com.android.tools.idea.flags.StudioFlags;
import com.android.tools.idea.res.FileResourceReader;
import com.android.tools.idea.res.LocalResourceRepository;
import com.android.tools.idea.res.ResourceHelper;
import com.android.tools.idea.res.ResourceRepositoryManager;
import com.android.tools.idea.ui.resourcechooser.ColorResourcePicker;
import com.android.tools.idea.ui.resourcechooser.HorizontalTabbedPanelBuilder;
import com.android.tools.idea.ui.resourcechooser.colorpicker2.ColorPickerBuilder;
import com.android.tools.idea.ui.resourcechooser.colorpicker2.internal.MaterialColorPaletteProvider;
import com.android.tools.idea.ui.resourcechooser.colorpicker2.internal.MaterialGraphicalColorPipetteProvider;
import com.android.utils.HashCodes;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.UnknownFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTagValue;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.Consumer;
import com.intellij.util.EmptyConsumer;
import com.intellij.util.ui.ColorIcon;
import com.intellij.util.ui.EmptyIcon;
import java.awt.*;
import java.util.List;
import java.util.Objects;
import javax.swing.*;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xmlpull.v1.XmlPullParser;
/**
* Static methods to be used by Android annotators.
*/
public class AndroidAnnotatorUtil {
static final int MAX_ICON_SIZE = 5000;
private static final String SET_COLOR_COMMAND_NAME = "Change Color";
private static final int ICON_SIZE = 8;
/**
* Returns a bitmap to be used as an icon to annotate an Android resource reference in an XML file.
*
* @param resourceValue the resource value defining the resource being referenced
* @param resourceResolver the resource resolver to use
* @param facet the android facet
* @return the bitmap for the annotation icon, or null to have no annotation icon
*/
@Nullable
public static VirtualFile resolveDrawableFile(@NotNull ResourceValue resourceValue,
@NotNull ResourceResolver resourceResolver,
@NotNull AndroidFacet facet) {
Project project = facet.getModule().getProject();
VirtualFile file = ResourceHelper.resolveDrawable(resourceResolver, resourceValue, project);
if (file != null && file.getPath().endsWith(DOT_XML)) {
file = pickBitmapFromXml(file, resourceResolver, project, facet, resourceValue);
}
return pickBestBitmap(file);
}
@Nullable
private static VirtualFile pickBitmapFromXml(@NotNull VirtualFile file,
@NotNull ResourceResolver resourceResolver,
@NotNull Project project,
@NotNull AndroidFacet facet,
@NotNull ResourceValue resourceValue) {
try {
XmlPullParser parser = FileResourceReader.createXmlPullParser(file);
if (parser == null) {
return null;
}
if (parser.nextTag() != XmlPullParser.START_TAG) {
return null;
}
String source;
String tagName = parser.getName();
switch (tagName) {
case "vector": {
// Take a look and see if we have a bitmap we can fall back to.
LocalResourceRepository resourceRepository = ResourceRepositoryManager.getAppResources(facet);
List<ResourceItem> items =
resourceRepository.getResources(resourceValue.getNamespace(), resourceValue.getResourceType(), resourceValue.getName());
for (ResourceItem item : items) {
FolderConfiguration configuration = item.getConfiguration();
DensityQualifier densityQualifier = configuration.getDensityQualifier();
if (densityQualifier != null) {
Density density = densityQualifier.getValue();
if (density != null && density.isValidValueForDevice()) {
return ResourceHelper.getSourceAsVirtualFile(item);
}
}
}
// Vectors are handled in the icon cache.
return file;
}
case "bitmap":
case "nine-patch":
source = parser.getAttributeValue(ANDROID_URI, ATTR_SRC);
break;
case "clip":
case "inset":
case "scale":
source = parser.getAttributeValue(ANDROID_URI, ATTR_DRAWABLE);
break;
case "layer-list":
case "level-list":
case "selector":
case "shape":
case "transition":
return file;
default:
// <set>, <drawable> etc - no bitmap to be found.
return null;
}
if (source == null) {
return null;
}
ResourceValue resValue = resourceResolver.findResValue(source, resourceValue.isFramework());
return resValue == null ? null : ResourceHelper.resolveDrawable(resourceResolver, resValue, project);
}
catch (Throwable ignore) {
// Not logging for now; afraid to risk unexpected crashes in upcoming preview. TODO: Re-enable.
//Logger.getInstance(AndroidColorAnnotator.class).warn(String.format("Could not read/render icon image %1$s", file), e);
return null;
}
}
@Nullable
public static VirtualFile pickBestBitmap(@Nullable VirtualFile bitmap) {
if (bitmap != null && bitmap.exists()) {
// Pick the smallest resolution, if possible! E.g. if the theme resolver located
// drawable-hdpi/foo.png, and drawable-mdpi/foo.png pick that one instead (and ditto
// for -ldpi etc)
VirtualFile smallest = findSmallestDpiVersion(bitmap);
if (smallest != null) {
return smallest;
}
// TODO: For XML drawables, look in the rendered output to see if there's a DPI version we can use:
// These are found in ${module}/build/generated/res/pngs/debug/drawable-*dpi
long length = bitmap.getLength();
if (length < MAX_ICON_SIZE) {
return bitmap;
}
}
return null;
}
@Nullable
private static VirtualFile findSmallestDpiVersion(@NotNull VirtualFile bitmap) {
VirtualFile parentFile = bitmap.getParent();
if (parentFile == null) {
return null;
}
VirtualFile resFolder = parentFile.getParent();
if (resFolder == null) {
return null;
}
String parentName = parentFile.getName();
FolderConfiguration config = FolderConfiguration.getConfigForFolder(parentName);
if (config == null) {
return null;
}
DensityQualifier qualifier = config.getDensityQualifier();
if (qualifier == null) {
return null;
}
Density density = qualifier.getValue();
if (density != null && density.isValidValueForDevice()) {
String fileName = bitmap.getName();
Density[] densities = Density.values();
// Iterate in reverse, since the Density enum is in descending order.
for (int i = densities.length; --i >= 0;) {
Density d = densities[i];
if (d.isValidValueForDevice()) {
String folderName = parentName.replace(density.getResourceValue(), d.getResourceValue());
VirtualFile folder = resFolder.findChild(folderName);
if (folder != null) {
bitmap = folder.findChild(fileName);
if (bitmap != null) {
if (bitmap.getLength() > MAX_ICON_SIZE) {
// No point continuing the loop; the other densities will be too big too.
return null;
}
return bitmap;
}
}
}
}
}
return null;
}
/**
* Picks a suitable configuration to use for resource resolution within a given file.
*
* @param file the file to determine a configuration for
* @param facet {@link AndroidFacet} of the {@code file}
*/
@Nullable
public static Configuration pickConfiguration(@NotNull PsiFile file, @NotNull AndroidFacet facet) {
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) {
return null;
}
VirtualFile parent = virtualFile.getParent();
if (parent == null) {
return null;
}
VirtualFile layout;
String parentName = parent.getName();
if (!parentName.startsWith(FD_RES_LAYOUT)) {
layout = ResourceHelper.pickAnyLayoutFile(facet);
if (layout == null) {
return null;
}
} else {
layout = virtualFile;
}
return ConfigurationManager.getOrCreateInstance(facet.getModule()).getConfiguration(layout);
}
/**
* Return {@link FileType} if found, or {@link UnknownFileType#INSTANCE} otherwise.
*/
@NotNull
public static FileType getFileType(@NotNull PsiElement element) {
return ApplicationManager.getApplication().runReadAction((Computable<FileType>)() -> {
PsiFile file = element.getContainingFile();
if (file != null) {
return file.getFileType();
}
return UnknownFileType.INSTANCE;
});
}
public static class ColorRenderer extends GutterIconRenderer {
private final PsiElement myElement;
private final Color myColor;
private final ResourceReference myResourceReference;
private final Consumer<String> mySetColorTask;
private final boolean myIncludeClickAction;
@Nullable private final Configuration myConfiguration;
public ColorRenderer(@NotNull PsiElement element,
@Nullable Color color,
@Nullable ResourceReference resourceReference,
boolean includeClickAction,
@Nullable Configuration configuration) {
myElement = element;
myColor = color;
myResourceReference = resourceReference;
myIncludeClickAction = includeClickAction;
mySetColorTask = createSetColorTask(myElement);
myConfiguration = configuration;
}
@NotNull
@Override
public Icon getIcon() {
Color color = getCurrentColor();
return color == null ? JBUIScale.scaleIcon(EmptyIcon.create(ICON_SIZE)) : JBUIScale.scaleIcon(new ColorIcon(ICON_SIZE, color));
}
@Nullable
private Color getCurrentColor() {
if (myColor != null) {
return myColor;
} else if (myElement instanceof XmlTag) {
return ResourceHelper.parseColor(((XmlTag)myElement).getValue().getText());
} else if (myElement instanceof XmlAttributeValue) {
return ResourceHelper.parseColor(((XmlAttributeValue)myElement).getValue());
} else {
return null;
}
}
@Override
public AnAction getClickAction() {
if (!myIncludeClickAction) { // Cannot set colors that were derived.
return null;
}
return new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (editor != null) {
openColorPicker(getCurrentColor());
}
}
};
}
private void openColorPicker(@Nullable Color currentColor) {
LightCalloutPopup dialog = new LightCalloutPopup();
JComponent colorPicker = new ColorPickerBuilder()
.setOriginalColor(currentColor)
.addSaturationBrightnessComponent()
.addColorAdjustPanel(new MaterialGraphicalColorPipetteProvider())
.addColorValuePanel().withFocus()
.addSeparator()
.addCustomComponent(MaterialColorPaletteProvider.INSTANCE)
.addColorPickerListener((color, source) -> setColorToAttribute(color))
.focusWhenDisplay(true)
.setFocusCycleRoot(true)
.build();
JComponent popupContent;
if (StudioFlags.NELE_RESOURCE_POPUP_PICKER.get() && myConfiguration != null) {
// Use tabbed panel instead.
ColorResourcePicker resourcePicker = new ColorResourcePicker(myConfiguration, myResourceReference);
// TODO: Use relative resource url instead.
resourcePicker.addColorResourcePickerListener(resource -> setColorStringAttribute(resource.getResourceUrl().toString()));
popupContent = new HorizontalTabbedPanelBuilder()
.addTab("Resources", resourcePicker)
.addTab("Custom", colorPicker)
.setDefaultPage(myResourceReference != null ? 0 : 1)
.build();
}
else {
popupContent = colorPicker;
}
dialog.show(popupContent, null, MouseInfo.getPointerInfo().getLocation());
}
private void setColorToAttribute(@NotNull Color color) {
setColorStringAttribute(ResourceHelper.colorToString(color));
}
private void setColorStringAttribute(@NotNull String colorString) {
Project project = myElement.getProject();
TransactionGuard.submitTransaction(project, () ->
WriteCommandAction.runWriteCommandAction(project, SET_COLOR_COMMAND_NAME, null, () -> mySetColorTask.consume(colorString))
);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ColorRenderer that = (ColorRenderer)o;
// TODO: Compare with modification count in app resources (if not framework).
if (!Objects.equals(myColor, that.myColor)) return false;
if (!myElement.equals(that.myElement)) return false;
return true;
}
@Override
public int hashCode() {
return HashCodes.mix(myElement.hashCode(), Objects.hashCode(myColor));
}
@VisibleForTesting
public static Consumer<String> createSetColorTask(@NotNull PsiElement element) {
if (element instanceof XmlTag) {
XmlTagValue xmlTagValue = ((XmlTag)element).getValue();
return colorString -> xmlTagValue.setText(colorString);
}
else if (element instanceof XmlAttributeValue) {
XmlAttribute xmlAttribute = PsiTreeUtil.getParentOfType(element, XmlAttribute.class);
if (xmlAttribute != null) {
return colorString -> xmlAttribute.setValue(colorString);
}
}
// Unknown case, do nothing.
return EmptyConsumer.getInstance();
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* FreeRTOS Kernel V10.1.0
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/******************************************************************************
* >>>>>> NOTE 1: <<<<<<
*
* main() can be configured to create either a very simple LED flasher demo, or
* a more comprehensive test/demo application.
*
* To create a very simple LED flasher example, set the
* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY constant (defined below) to 1. When
* this is done, only the standard demo flash tasks are created. The standard
* demo flash example creates three tasks, each of which toggle an LED at a
* fixed but different frequency.
*
* To create a more comprehensive test and demo application, set
* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY to 0.
******************************************************************************
*
* main() creates all the demo application tasks and software timers, then starts
* the scheduler. The web documentation provides more details of the standard
* demo application tasks, which provide no particular functionality, but do
* provide a good example of how to use the FreeRTOS API.
*
* In addition to the standard demo tasks, the following tasks and tests are
* defined and/or created within this file:
*
* "Reg test" tasks - These fill both the core and floating point registers with
* known values, then check that each register maintains its expected value for
* the lifetime of the task. Each task uses a different set of values. The reg
* test tasks execute with a very low priority, so get preempted very
* frequently. A register containing an unexpected value is indicative of an
* error in the context switching mechanism.
*
* "Check" timer - The check software timer period is initially set to three
* seconds. The callback function associated with the check software timer
* checks that all the standard demo tasks, and the register check tasks, are
* not only still executing, but are executing without reporting any errors. If
* the check software timer discovers that a task has either stalled, or
* reported an error, then it changes its own execution period from the initial
* three seconds, to just 200ms. The check software timer callback function
* also toggles an LED each time it is called. This provides a visual
* indication of the system status: If the LED toggles every three seconds,
* then no issues have been discovered. If the LED toggles every 200ms, then
* an issue has been discovered with at least one task.
*/
/* Standard includes. */
#include <stdio.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "semphr.h"
/* Demo application includes. */
#include "partest.h"
#include "flash.h"
#include "flop.h"
#include "integer.h"
#include "PollQ.h"
#include "semtest.h"
#include "dynamic.h"
#include "BlockQ.h"
#include "blocktim.h"
#include "countsem.h"
#include "GenQTest.h"
#include "recmutex.h"
#include "death.h"
/* Hardware includes. */
#include "platform_config.h"
/* Priorities for the demo application tasks. */
#define mainFLASH_TASK_PRIORITY ( tskIDLE_PRIORITY + 1UL )
#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 2UL )
#define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1UL )
#define mainBLOCK_Q_PRIORITY ( tskIDLE_PRIORITY + 2UL )
#define mainCREATOR_TASK_PRIORITY ( tskIDLE_PRIORITY + 3UL )
#define mainFLOP_TASK_PRIORITY ( tskIDLE_PRIORITY )
/* The LED used by the check timer. */
#define mainCHECK_LED ( 3UL )
/* A block time of zero simply means "don't block". */
#define mainDONT_BLOCK ( 0UL )
/* The period after which the check timer will expire, in ms, provided no errors
have been reported by any of the standard demo tasks. ms are converted to the
equivalent in ticks using the portTICK_PERIOD_MS constant. */
#define mainCHECK_TIMER_PERIOD_MS ( 3000UL / portTICK_PERIOD_MS )
/* The period at which the check timer will expire, in ms, if an error has been
reported in one of the standard demo tasks. ms are converted to the equivalent
in ticks using the portTICK_PERIOD_MS constant. */
#define mainERROR_CHECK_TIMER_PERIOD_MS ( 200UL / portTICK_PERIOD_MS )
/* Set mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY to 1 to create a simple demo.
Set mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY to 0 to create a much more
comprehensive test application. See the comments at the top of this file, and
the documentation page on the http://www.FreeRTOS.org web site for more
information. */
#define mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY 0
/*-----------------------------------------------------------*/
/*
* Set up the hardware ready to run this demo.
*/
static void prvSetupHardware( void );
/*
* The check timer callback function, as described at the top of this file.
*/
static void prvCheckTimerCallback( TimerHandle_t xTimer );
/*
* Register check tasks, and the tasks used to write over and check the contents
* of the FPU registers, as described at the top of this file. The nature of
* these files necessitates that they are written in an assembly file.
*/
extern void vRegTest1Task( void *pvParameters );
extern void vRegTest2Task( void *pvParameters );
extern void vRegTestClearFlopRegistersToParameterValue( unsigned long ulValue );
extern unsigned long ulRegTestCheckFlopRegistersContainParameterValue( unsigned long ulValue );
/*
* This file can be used to create either a simple LED flasher example, or a
* comprehensive test/demo application - depending on the setting of the
* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY constant defined above. If
* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY is set to 1, then the following
* function will create a lot of additional tasks and a software timer. If
* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY is set to 0, then the following
* function will do nothing.
*/
static void prvOptionallyCreateComprehensveTestApplication( void );
/*-----------------------------------------------------------*/
/* The following two variables are used to communicate the status of the
register check tasks to the check software timer. If the variables keep
incrementing, then the register check tasks have not discovered any errors. If
a variable stops incrementing, then an error has been found. */
volatile unsigned long ulRegTest1LoopCounter = 0UL, ulRegTest2LoopCounter = 0UL;
/*-----------------------------------------------------------*/
int main( void )
{
/* Configure the hardware ready to run the test. */
prvSetupHardware();
/* Start standard demo/test application flash tasks. See the comments at
the top of this file. The LED flash tasks are always created. The other
tasks are only created if mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY is set to
0 (at the top of this file). See the comments at the top of this file for
more information. */
vStartLEDFlashTasks( mainFLASH_TASK_PRIORITY );
/* The following function will only create more tasks and timers if
mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY is set to 0 (at the top of this
file). See the comments at the top of this file for more information. */
prvOptionallyCreateComprehensveTestApplication();
/* Start the scheduler. */
vTaskStartScheduler();
/* Infinite loop */
for( ;; );
}
/*-----------------------------------------------------------*/
static void prvCheckTimerCallback( TimerHandle_t xTimer )
{
static long lChangedTimerPeriodAlready = pdFALSE;
static unsigned long ulLastRegTest1Value = 0, ulLastRegTest2Value = 0;
unsigned long ulErrorFound = pdFALSE;
/* Check all the demo tasks (other than the flash tasks) to ensure
that they are all still running, and that none have detected an error. */
if( xAreMathsTaskStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 0UL;
}
if( xAreIntegerMathsTaskStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 1UL;
}
if( xAreDynamicPriorityTasksStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 2UL;
}
if( xAreBlockingQueuesStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 3UL;
}
if ( xAreBlockTimeTestTasksStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 4UL;
}
if ( xAreGenericQueueTasksStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 5UL;
}
if ( xAreRecursiveMutexTasksStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 6UL;
}
if( xIsCreateTaskStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 7UL;
}
if( xArePollingQueuesStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 8UL;
}
if( xAreSemaphoreTasksStillRunning() != pdTRUE )
{
ulErrorFound |= 0x01UL << 9UL;
}
/* Check that the register test 1 task is still running. */
if( ulLastRegTest1Value == ulRegTest1LoopCounter )
{
ulErrorFound |= 0x01UL << 10UL;
}
ulLastRegTest1Value = ulRegTest1LoopCounter;
/* Check that the register test 2 task is still running. */
if( ulLastRegTest2Value == ulRegTest2LoopCounter )
{
ulErrorFound |= 0x01UL << 11UL;
}
ulLastRegTest2Value = ulRegTest2LoopCounter;
/* Toggle the check LED to give an indication of the system status. If
the LED toggles every mainCHECK_TIMER_PERIOD_MS milliseconds then
everything is ok. A faster toggle indicates an error. */
vParTestToggleLED( mainCHECK_LED );
/* Have any errors been latch in ulErrorFound? If so, shorten the
period of the check timer to mainERROR_CHECK_TIMER_PERIOD_MS milliseconds.
This will result in an increase in the rate at which mainCHECK_LED
toggles. */
if( ulErrorFound != pdFALSE )
{
if( lChangedTimerPeriodAlready == pdFALSE )
{
lChangedTimerPeriodAlready = pdTRUE;
/* This call to xTimerChangePeriod() uses a zero block time.
Functions called from inside of a timer callback function must
*never* attempt to block. */
xTimerChangePeriod( xTimer, ( mainERROR_CHECK_TIMER_PERIOD_MS ), mainDONT_BLOCK );
}
}
}
/*-----------------------------------------------------------*/
static void prvSetupHardware( void )
{
extern void Hitex_CGU_Init( void );
/* Setup system (clock, PLL and Flash configuration) */
platformInit();
/* Wind the clock speed up in steps to its maximum. */
Hitex_CGU_Init();
/* Ensure all priority bits are assigned as preemption priority bits. */
NVIC_SetPriorityGrouping( 0 );
/* Setup the LED outputs. */
vParTestInitialise();
}
/*-----------------------------------------------------------*/
static void prvOptionallyCreateComprehensveTestApplication( void )
{
#if ( mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY == 0 )
{
TimerHandle_t xCheckTimer = NULL;
/* Start all the other standard demo/test tasks. */
vStartIntegerMathTasks( tskIDLE_PRIORITY );
vStartDynamicPriorityTasks();
vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY );
vCreateBlockTimeTasks();
vStartCountingSemaphoreTasks();
vStartGenericQueueTasks( tskIDLE_PRIORITY );
vStartRecursiveMutexTasks();
vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY );
vStartSemaphoreTasks( mainSEM_TEST_PRIORITY );
/* Most importantly, start the tasks that use the FPU. */
vStartMathTasks( mainFLOP_TASK_PRIORITY );
/* Create the register check tasks, as described at the top of this
file */
xTaskCreate( vRegTest1Task, "Reg1", configMINIMAL_STACK_SIZE, ( void * ) NULL, tskIDLE_PRIORITY, NULL );
xTaskCreate( vRegTest2Task, "Reg2", configMINIMAL_STACK_SIZE, ( void * ) NULL, tskIDLE_PRIORITY, NULL );
/* Create the software timer that performs the 'check' functionality,
as described at the top of this file. */
xCheckTimer = xTimerCreate( "CheckTimer", /* A text name, purely to help debugging. */
( mainCHECK_TIMER_PERIOD_MS ), /* The timer period, in this case 3000ms (3s). */
pdTRUE, /* This is an auto-reload timer, so xAutoReload is set to pdTRUE. */
( void * ) 0, /* The ID is not used, so can be set to anything. */
prvCheckTimerCallback /* The callback function that inspects the status of all the other tasks. */
);
if( xCheckTimer != NULL )
{
xTimerStart( xCheckTimer, mainDONT_BLOCK );
}
/* This task has to be created last as it keeps account of the number of
tasks it expects to see running. */
vCreateSuicidalTasks( mainCREATOR_TASK_PRIORITY );
}
#else /* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY */
{
/* Just to prevent compiler warnings when the configuration options are
set such that these static functions are not used. */
( void ) vRegTest1Task;
( void ) vRegTest2Task;
( void ) prvCheckTimerCallback;
( void ) prvSetupNestedFPUInterruptsTest;
}
#endif /* mainCREATE_SIMPLE_LED_FLASHER_DEMO_ONLY */
}
/*-----------------------------------------------------------*/
void vApplicationMallocFailedHook( void )
{
/* vApplicationMallocFailedHook() will only be called if
configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook
function that will get called if a call to pvPortMalloc() fails.
pvPortMalloc() is called internally by the kernel whenever a task, queue,
timer or semaphore is created. It is also called by various parts of the
demo application. If heap_1.c or heap_2.c are used, then the size of the
heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
to query the size of free heap space that remains (although it does not
provide information on how the remaining heap might be fragmented). */
taskDISABLE_INTERRUPTS();
for( ;; );
}
/*-----------------------------------------------------------*/
void vApplicationIdleHook( void )
{
/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
to 1 in FreeRTOSConfig.h. It will be called on each iteration of the idle
task. It is essential that code added to this hook function never attempts
to block in any way (for example, call xQueueReceive() with a block time
specified, or call vTaskDelay()). If the application makes use of the
vTaskDelete() API function (as this demo application does) then it is also
important that vApplicationIdleHook() is permitted to return to its calling
function, because it is the responsibility of the idle task to clean up
memory allocated by the kernel to any task that has since been deleted. */
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
( void ) pcTaskName;
( void ) pxTask;
/* Run time stack overflow checking is performed if
configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
function is called if a stack overflow is detected. */
taskDISABLE_INTERRUPTS();
for( ;; );
}
/*-----------------------------------------------------------*/
void vApplicationTickHook( void )
{
/* This function will be called by each tick interrupt if
configUSE_TICK_HOOK is set to 1 in FreeRTOSConfig.h. User code can be
added here, but the tick hook is called from an interrupt context, so
code must not attempt to block, and only the interrupt safe FreeRTOS API
functions can be used (those that end in FromISR()). */
}
/*-----------------------------------------------------------*/
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 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.
*/
class Google_Service_AndroidEnterprise_GroupLicenseUsersListResponse extends Google_Collection
{
protected $collection_key = 'user';
public $kind;
protected $userType = 'Google_Service_AndroidEnterprise_User';
protected $userDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
/**
* @param Google_Service_AndroidEnterprise_User
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* @return Google_Service_AndroidEnterprise_User
*/
public function getUser()
{
return $this->user;
}
}
| {
"pile_set_name": "Github"
} |
/*
931004-13.c from the execute part of the gcc torture suite.
*/
#include <testfwk.h>
#ifdef __SDCC
#pragma std_c99
#endif
// Todo: Enable when sdcc supports struct!
#if 0
struct tiny
{
char c;
char d;
char e;
char f;
};
f (int n, struct tiny x, struct tiny y, struct tiny z, long l)
{
if (x.c != 10)
ASSERT (0);
if (x.d != 20)
ASSERT (0);
if (x.e != 30)
ASSERT (0);
if (x.f != 40)
ASSERT (0);
if (y.c != 11)
ASSERT (0);
if (y.d != 21)
ASSERT (0);
if (y.e != 31)
ASSERT (0);
if (y.f != 41)
ASSERT (0);
if (z.c != 12)
ASSERT (0);
if (z.d != 22)
ASSERT (0);
if (z.e != 32)
ASSERT (0);
if (z.f != 42)
ASSERT (0);
if (l != 123)
ASSERT (0);
}
#endif
void
testTortureExecute (void)
{
#if 0
struct tiny x[3];
x[0].c = 10;
x[1].c = 11;
x[2].c = 12;
x[0].d = 20;
x[1].d = 21;
x[2].d = 22;
x[0].e = 30;
x[1].e = 31;
x[2].e = 32;
x[0].f = 40;
x[1].f = 41;
x[2].f = 42;
f (3, x[0], x[1], x[2], (long) 123);
return;
#endif
}
| {
"pile_set_name": "Github"
} |
import { expect } from "chai";
import "reflect-metadata";
import { IMock, Mock } from "typemoq";
import { IDirectoryManager, ISettingsManager } from "managers";
import { IDirectoryItem, IStatusNotifier } from "models";
import { DirectoryListModel } from "objects";
import { IDirectoryListProps } from "props/panels";
import applicationTheme from "settings/internal/themes/dark";
import { IDirectoryListState } from "states/panels";
import { DirectoryPaneSide } from "types";
describe("DirectoryListModel's", () => {
let directoryListModel: DirectoryListModel;
let directoryItem1: IDirectoryItem;
let settingsManager: IMock<ISettingsManager>;
before(() => {
directoryListModel = new DirectoryListModel();
settingsManager = Mock.ofType<ISettingsManager>();
});
beforeEach(() => {
directoryItem1 = {
accessible: true,
created: new Date(),
isDirectory: false,
isHidden: false,
lastModified: new Date(),
name: "Item 1",
path: "path/to/Item 1"
};
});
describe("stateChanged method", () => {
let prevState: IDirectoryListState;
let nextState: IDirectoryListState;
beforeEach(() => {
const commonState: IDirectoryListState = {
chosenItems: [],
creatingNewItem: false,
directoryItems: [],
isFocused: false,
isGotoOpen: false,
itemDeleted: false,
renamingItem: false,
selectedIndex: 0,
showHiddenItems: false
};
prevState = { ...commonState };
nextState = { ...commonState };
});
it("Returns false when nothing has changed", () => {
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.false;
});
it("detects changes in 'creatingNewItem'", () => {
nextState.creatingNewItem = "file";
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.true;
});
it("detects changes in 'itemDeleted'", () => {
nextState.itemDeleted = true;
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.true;
});
it("detects changes in 'renamingItem'", () => {
nextState.renamingItem = true;
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.true;
});
it("detects changes in 'selectedIndex'", () => {
nextState.selectedIndex = 1;
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.true;
});
it("detects changes in 'showHiddenItems'", () => {
nextState.showHiddenItems = true;
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.true;
});
it("detects changes in 'isGotoOpen'", () => {
nextState.isGotoOpen = true;
expect(directoryListModel.stateChanged(prevState, nextState))
.to.be.true;
});
});
describe("propsChanged method", () => {
let prevProps: IDirectoryListProps;
let nextProps: IDirectoryListProps;
let directoryManager: IMock<IDirectoryManager>;
const statusNotifier = {} as IStatusNotifier;
beforeEach(() => {
directoryManager = Mock.ofType<IDirectoryManager>();
const commonProps: IDirectoryListProps = {
columnSizes: {
createdOn: 0,
lastModified: 25,
name: 50,
size: 25
},
directoryManager: directoryManager.object,
id: "left",
isSelectedPane: false,
path: "/path/to/directory",
sendPathUp: (path: string) => { },
sendSelectedPaneUp: (paneToSelect: DirectoryPaneSide) => { },
settingsManager: settingsManager.object,
statusNotifier,
theme: applicationTheme
};
prevProps = JSON.parse(JSON.stringify(commonProps));
nextProps = JSON.parse(JSON.stringify(commonProps));
});
it("returns false when nothing has changed", () => {
const result = directoryListModel.propsChanged(prevProps, nextProps);
expect(result).to.be.false;
});
it("detects changes in 'isSelectedPane'", () => {
nextProps.isSelectedPane = true;
const result = directoryListModel.propsChanged(prevProps, nextProps);
expect(result).to.be.true;
});
it("detects changes in 'path'", () => {
nextProps.path = "some/other/path";
const result = directoryListModel.propsChanged(prevProps, nextProps);
expect(result).to.be.true;
});
it("detects changes in column sizes", () => {
nextProps.columnSizes.name = prevProps.columnSizes.name * 2;
const result = directoryListModel.propsChanged(prevProps, nextProps);
expect(result).to.be.true;
});
});
describe("chosenItemsChanged method", () => {
let prevItems: IDirectoryItem[];
let nextItems: IDirectoryItem[];
beforeEach(() => {
const commonItems: IDirectoryItem[] = [directoryItem1];
prevItems = [...commonItems];
nextItems = [...commonItems];
});
it("returns false when nothing has changed", () => {
const result = directoryListModel.chosenItemsChanged(prevItems, nextItems);
expect(result).to.be.false;
});
it("detects when a chosen item has been added or removed", () => {
nextItems.shift();
const result = directoryListModel.chosenItemsChanged(prevItems, nextItems);
expect(result).to.be.true;
});
});
describe("directoryItemsChanged method", () => {
let prevItems: IDirectoryItem[];
let nextItems: IDirectoryItem[];
beforeEach(() => {
const commonItems: IDirectoryItem[] = [directoryItem1];
prevItems = commonItems;
nextItems = commonItems;
});
it("returns false when nothing has changed", () => {
const result = directoryListModel.directoryItemsChanged(prevItems, nextItems);
expect(result).to.be.false;
});
it("detects when an item has been added or removed", () => {
nextItems = [];
const result = directoryListModel.directoryItemsChanged(prevItems, nextItems);
expect(result).to.be.true;
});
it("detects when an item's name has changed", () => {
const changedItem: IDirectoryItem = { ...directoryItem1 };
changedItem.name = "Different name";
nextItems = [changedItem];
const result = directoryListModel.directoryItemsChanged(prevItems, nextItems);
expect(result).to.be.true;
});
});
});
| {
"pile_set_name": "Github"
} |
# ngrep
> Filter network traffic packets using regular expressions.
> More information: <https://github.com/jpr5/ngrep>.
- Capture traffic of all interfaces:
`ngrep -d any`
- Capture traffic of a specific interface:
`ngrep -d {{eth0}}`
- Capture traffic crossing port 22 of interface eth0:
`ngrep -d {{eth0}} port {{22}}`
- Capture traffic from or to a host:
`ngrep host {{www.example.com}}`
- Filter keyword 'User-Agent:' of interface eth0:
`ngrep -d {{eth0}} '{{User-Agent:}}'`
| {
"pile_set_name": "Github"
} |
#include <u.h>
#include <libc.h>
/*
* In place, rewrite name to compress multiple /, eliminate ., and process ..
*/
#define SEP(x) ((x)=='/' || (x) == 0)
char*
cleanname(char *name)
{
char *p, *q, *dotdot;
int rooted;
rooted = name[0] == '/';
/*
* invariants:
* p points at beginning of path element we're considering.
* q points just past the last path element we wrote (no slash).
* dotdot points just past the point where .. cannot backtrack
* any further (no slash).
*/
p = q = dotdot = name+rooted;
while(*p) {
if(p[0] == '/') /* null element */
p++;
else if(p[0] == '.' && SEP(p[1]))
p += 1; /* don't count the separator in case it is nul */
else if(p[0] == '.' && p[1] == '.' && SEP(p[2])) {
p += 2;
if(q > dotdot) { /* can backtrack */
while(--q > dotdot && *q != '/')
;
} else if(!rooted) { /* /.. is / but ./../ is .. */
if(q != name)
*q++ = '/';
*q++ = '.';
*q++ = '.';
dotdot = q;
}
} else { /* real path element */
if(q != name+rooted)
*q++ = '/';
while((*q = *p) != '/' && *q != 0)
p++, q++;
}
}
if(q == name) /* empty string is really ``.'' */
*q++ = '.';
*q = '\0';
return name;
}
| {
"pile_set_name": "Github"
} |
---
layout: post
title: Space
date: 2016-09-13 16:08:00
homepage: https://github.com/victorvoid/space-jekyll-template/
download: https://github.com/victorvoid/space-jekyll-template/archive/master.zip
demo: http://victorvoid.github.io/space-jekyll-template/
author: Victor Igor
thumbnail: space-jekyll-template.png
license: MIT License
license_link: https://github.com/victorvoid/space-jekyll-template/blob/master/LICENSE
---
### Space Jekyll Template
<iframe
src="//ghbtns.com/github-btn.html?user=victorvoid&repo=space-jekyll-template&type=watch&count=true&size=small"
allowtransparency="true" frameborder="0" scrolling="0" width="110px"
height="20px"></iframe>
A simple and elegant Jekyll theme based on Spacemacs. The theme works well on mobile devices as well.
The [Space Jekyll Template](https://github.com/victorvoid/space-jekyll-template/) show the main Theme. Feel free to Fork, Star it and make a New Version of it.
### Contribute
<iframe
src="//ghbtns.com/github-btn.html?user=victorvoid&repo=space-jekyll-template&type=fork&count=true&size=small"
allowtransparency="true" frameborder="0" scrolling="0" width="95px"
height="20px"></iframe>
Start by [forking the repository](https://github.com/victorvoid/space-jekyll-template/).
### Contact
<iframe
src="//ghbtns.com/github-btn.html?user=victorvoid&type=follow&count=true&size=small"
allowtransparency="true" frameborder="0" scrolling="0" width="156px"
height="20px"></iframe>
If you have any questions or suggestions for improvements, don't
hesitate to [open an issue](https://github.com/victorvoid/space-jekyll-template/issues)
or making a pull request for your fork!
| {
"pile_set_name": "Github"
} |
syntax = "proto3";
package host;
option java_package = "com.imageworks.spcue.grpc.host";
option java_multiple_files = true;
import "comment.proto";
import "criterion.proto";
import "job.proto";
import "renderPartition.proto";
// -------- Services --------]
service DeedInterface {
// Remove the deed
rpc Delete(DeedDeleteRequest) returns (DeedDeleteResponse);
// Returns the full host for these settings.
rpc GetHost(DeedGetHostRequest) returns (DeedGetHostResponse);
// Returns the owner for these settings.
rpc GetOwner(DeedGetOwnerRequest) returns (DeedGetOwnerResponse);
// Sets a blackout time for the host.
rpc SetBlackoutTime(DeedSetBlackoutTimeRequest) returns (DeedSetBlackoutTimeResponse);
// Enable/Disable blackout time without changing the times.
rpc SetBlackoutTimeEnabled(DeedSetBlackoutTimeEnabledRequest) returns (DeedSetBlackoutTimeEnabledResponse);
}
service HostInterface {
// Add a comment on this host.
rpc AddComment(HostAddCommentRequest) returns (HostAddCommentResponse);
// Set a tag on this host.
rpc AddTags(HostAddTagsRequest) returns (HostAddTagsResponse);
// Delete host.
rpc Delete(HostDeleteRequest) returns (HostDeleteResponse);
// Find a host by its name
rpc FindHost(HostFindHostRequest) returns (HostFindHostResponse);
// Get the comments for this host.
rpc GetComments(HostGetCommentsRequest) returns (HostGetCommentsResponse);
// Return the deed for this host.
rpc GetDeed(HostGetDeedRequest) returns (HostGetDeedResponse);
// Return a host by its id
rpc GetHost(HostGetHostRequest) returns (HostGetHostResponse);
// Search for a number of hosts
rpc GetHosts(HostGetHostsRequest) returns (HostGetHostsResponse);
// Return the host whiteboard
rpc GetHostWhiteboard(HostGetHostWhiteboardRequest) returns (HostGetHostWhiteboardResponse);
// Get the owner settings of this particular host.
rpc GetOwner(HostGetOwnerRequest) returns (HostGetOwnerResponse);
// Returns the list of proc resources allocated from this host.
rpc GetProcs(HostGetProcsRequest) returns (HostGetProcsResponse);
// Return any render partitions that are setup on this host.
rpc GetRenderPartitions(HostGetRenderPartitionsRequest) returns (HostGetRenderPartitionsResponse);
// Locks the host. Its possible we'll need to pass in a show name here in the future
rpc Lock(HostLockRequest) returns (HostLockResponse);
// Issues an immediate reboot.
rpc Reboot(HostRebootRequest) returns (HostRebootResponse);
// Sets the reboot when idle state, nothing has to be locked to set this. When the host pings in idle a reboot
// command is sent to the host and the host will be put into the Rebooting state. If any locks are set they will
// be removed upon reboot.
rpc RebootWhenIdle(HostRebootWhenIdleRequest) returns (HostRebootWhenIdleResponse);
// Redirect the given procs to the specified job.
rpc RedirectToJob(HostRedirectToJobRequest) returns (HostRedirectToJobResponse);
// Remove a tag from this host.
rpc RemoveTags(HostRemoveTagsRequest) returns (HostRemoveTagsResponse);
// Rename tag.
rpc RenameTag(HostRenameTagRequest) returns (HostRenameTagResponse);
// Assign a host to an allocation.
rpc SetAllocation(HostSetAllocationRequest) returns (HostSetAllocationResponse);
// Manually set the hardware state for the host. The hardware state may be changed automatically if the host pings
// in. If the hardware state is set to "Reimage", the state will not automatically change with a host ping, and
// must be manually set back to Up.
rpc SetHardwareState(HostSetHardwareStateRequest) returns (HostSetHardwareStateResponse);
// Set the name of the host operating system.
rpc SetOs(HostSetOsRequest) returns (HostSetOsResponse);
// Changes the host's [ThreadMode]
rpc SetThreadMode(HostSetThreadModeRequest) returns (HostSetThreadModeResponse);
// Unlocks the host for booking if the proc is in the Locked state. You cannot unlock a NimbyLocked proc.
rpc Unlock(HostUnlockRequest) returns (HostUnlockResponse);
}
service OwnerInterface {
// Deletes the owner record.
rpc Delete(OwnerDeleteRequest) returns (OwnerDeleteResponse);
// Get a list of all deeds this owner has.
rpc GetDeeds(OwnerGetDeedsRequest) returns (OwnerGetDeedsResponse);
// Get a list of all hosts this owner is responsible for.
rpc GetHosts(OwnerGetHostsRequest) returns (OwnerGetHostsResponse);
// Return an Owner record by name, id, or email.
rpc GetOwner(OwnerGetOwnerRequest) returns (OwnerGetOwnerResponse);
//Sets the owners show.
rpc SetShow(OwnerSetShowRequest) returns (OwnerSetShowResponse);
// Set the hosts new owner settings. Any host may have an owner, not just desktops. This allows direct control of
// the cores. By default hosts have no owner settings.
rpc TakeOwnership(OwnerTakeOwnershipRequest) returns (OwnerTakeOwnershipResponse);
}
service ProcInterface {
// Clears the redirect off of the proc so it dispatches naturally.
rpc ClearRedirect(ProcClearRedirectRequest) returns (ProcClearRedirectResponse);
// Returns the [Frame] running on the [Proc]
rpc GetFrame(ProcGetFrameRequest) returns (ProcGetFrameResponse);
// Returns the [Host] this [Proc] was allocated from.
rpc GetHost(ProcGetHostRequest) returns (ProcGetHostResponse);
// Returns the [Job] the [Proc] has been assigned to.
rpc GetJob(ProcGetJobRequest) returns (ProcGetJobResponse);
// Returns the [Layer] the [Proc] has been assigned to.
rpc GetLayer(ProcGetLayerRequest) returns (ProcGetLayerResponse);
// Return a list of procs matching the search
rpc GetProcs(ProcGetProcsRequest) returns (ProcGetProcsResponse);
// Sends a kill signal to the running process.
rpc Kill(ProcKillRequest) returns (ProcKillResponse);
// Unbooks and redriects the proc to the specified group. Optionally kills the proc immediately. Will overwrite an
// existing redirect. Return true if the redirect was a success. The redirect would fail in the event that the
// specified group does not have a suitable frame for the proc.
rpc RedirectToGroup(ProcRedirectToGroupRequest) returns (ProcRedirectToGroupResponse);
// Unbooks and redriects the proc to the specified job. Optionally kills the proc immediately. Will overwrite an
// existing redirect. Return true if the redirect was a success. The redirect would fail in the event th
rpc RedirectToJob(ProcRedirectToJobRequest) returns (ProcRedirectToJobResponse);
// Unbooks this [Proc]. Unbooking means the [Proc] will automatically seek out a new [Job] when the current
// [Frame] is complete.
rpc Unbook(ProcUnbookRequest) returns (ProcUnbookResponse);
//Unbooks procs that match the ProcSearchCriteria. This request can span jobs, shows, allocations, hosts etc.
// Set kill to true if the running frames should immediately be killed.
rpc UnbookProcs(ProcUnbookProcsRequest) returns (ProcUnbookProcsResponse);
// Unbooks procs that match the ProcSearchCriteria and books them on the specified group, assuming the group has
// layers that can take the procs. If the kill boolean is set to true, the operation happens immediately. If false,
// the proc will move after it finishes its current frame.
rpc UnbookToGroup(ProcUnbookToGroupRequest) returns (ProcUnbookToGroupResponse);
// Unbooks procs that match the ProcSearchCriteria and books them on the specified list of jobs, assuming those jobs
// have layers that can take the procs. If the kill boolean is set to true, the operation happens immediately. If
// false, the proc will move after it finishes its current frame.
rpc UnbookToJob(ProcUnbookToJobRequest) returns (ProcUnbookToJobResponse);
}
// -------- Enums --------
enum HardwareState {
UP = 0;
DOWN = 1;
REBOOTING = 2;
REBOOT_WHEN_IDLE = 3;
REPAIR = 4;
}
enum HostTagType {
MANUAL = 0;
HARDWARE = 1;
ALLOC = 2;
HOSTNAME = 3;
}
enum LockState {
OPEN = 0;
LOCKED = 1;
NIMBY_LOCKED = 2;
}
// Proc redirects can have two different types of destinations, jobs and groups.
enum RedirectType {
JOB_REDIRECT = 0;
GROUP_REDIRECT = 1;
}
// Defines the possible states for a core or proc
enum RunState {
// Entity is idle, which means it can be booked.
IDLE = 0;
// Entity is booked, which means its in use on a render proc
BOOKED = 1;
}
enum ThreadMode {
// Auto determines the number of threads to use automatically
// based on the amount of memory used by the frame.
AUTO = 0;
// All always uses all of the cores available on the proc.
// These hosts are always booked on threadable layers.
ALL = 1;
// All mode during the day, auto-mode at night.
VARIABLE = 2;
}
// -------- Primary Message Types --------]
message Deed {
string id = 1;
string host = 2;
string owner = 3;
string show = 4;
bool blackout = 5;
int32 blackout_start_time = 6;
int32 blackout_stop_time = 7;
}
message DeedSeq {
repeated Deed deeds = 1;
}
message HardwareStateSeq {
repeated HardwareState state = 1;
}
message Host {
string id = 1;
string name = 2;
string alloc_name = 3;
bool nimby_enabled = 4;
bool has_comment = 5;
float cores = 6;
float idle_cores = 7;
int64 memory = 8;
int64 idle_memory = 9;
int64 gpu = 10;
int64 idle_gpu = 11;
int64 total_swap = 12;
int64 total_memory = 13;
int64 total_gpu = 14;
int64 total_mcp = 15;
int64 free_swap = 16;
int64 free_memory = 17;
int64 free_mcp = 18;
int64 free_gpu = 19;
int32 load = 20;
int32 boot_time = 21;
int32 ping_time = 22;
string os = 23;
repeated string tags = 24;
HardwareState state = 25;
LockState lock_state = 26;
ThreadMode thread_mode = 27;
}
message HostSearchCriteria {
repeated string hosts = 1;
repeated string regex = 2;
repeated string substr = 3;
repeated string ids = 4;
repeated string allocs = 5;
HardwareStateSeq states = 6;
}
message HostSeq {
repeated Host hosts = 1;
}
message NestedHost {
string id = 1;
string name = 2;
string alloc_name = 3;
bool nimby_enabled = 4;
bool has_comment = 5;
float cores = 6;
float idle_cores = 7;
int64 memory = 8;
int64 idle_memory = 9;
int64 gpu = 10;
int64 idle_gpu = 11;
int64 total_swap = 12;
int64 total_memory = 13;
int64 total_gpu = 14;
int64 total_mcp = 15;
int64 free_swap = 16;
int64 free_memory = 17;
int64 free_mcp = 18;
int64 free_gpu = 19;
int32 load = 20;
int32 boot_time = 21;
int32 ping_time = 22;
string os = 23;
repeated string tags = 24;
HardwareState state = 25;
LockState lock_state = 26;
ThreadMode thread_mode = 27;
NestedProcSeq procs = 28;
}
message NestedHostSeq {
repeated NestedHost nested_hosts = 1;
}
message NestedProc {
string id = 1;
string name = 2;
string show_name = 3;
string job_name = 4;
string frame_name = 5;
string group_name = 6;
int32 ping_time = 7;
int32 bookedTime = 8;
int32 dispatch_time = 9;
int64 reserved_memory = 10;
int64 reserverd_gpu = 11;
int64 used_memory = 12;
float reserved_cores = 13;
bool unbooked = 14;
string log_path = 15;
string redirect_target = 16;
repeated string services = 17;
NestedHost parent = 18;
}
message NestedProcSeq {
repeated NestedProc nested_procs = 1;
}
message Owner {
string id = 1;
string name = 2;
string show = 3;
int32 host_count = 4;
}
message Proc {
string id = 1;
string name = 2;
string show_name = 3;
string job_name = 4;
string frame_name = 5;
string group_name = 6;
int32 ping_time = 7;
int32 bookedTime = 8;
int32 dispatch_time = 9;
int64 reserved_memory = 10;
int64 reserved_gpu = 11;
int64 used_memory = 12;
float reserved_cores = 13;
bool unbooked = 14;
string log_path = 15;
string redirect_target = 16;
repeated string services = 17;
}
message ProcSearchCriteria {
// An array of host names to match.
repeated string hosts = 1;
// An array of job names to match.
repeated string jobs = 2;
// An arra of layer names to match.
repeated string layers = 3;
// An array of show names to match.
repeated string shows = 4;
// An array of allocation names to match.
repeated string allocs = 5;
// A range of memory usage. Values are in KB.
repeated criterion.InRangeIntegerSearchCriterion memory_range = 6;
// A duration range. Values are in seconds.
repeated criterion.InRangeIntegerSearchCriterion duration_range = 7;
//The maximum number of results.
repeated int32 max_results = 8;
//The offset of the first result.
int32 first_result = 9;
}
message ProcSeq {
repeated Proc procs = 1;
}
// -------- Requests & Responses --------]
// DEED ----
// Delete
message DeedDeleteRequest {
Deed deed = 1;
}
message DeedDeleteResponse {} // Empty
// GetHost
message DeedGetHostRequest {
Deed deed = 1;
}
message DeedGetHostResponse {
Host host = 1;
}
// GetOwner
message DeedGetOwnerRequest {
Deed deed = 1;
}
message DeedGetOwnerResponse {
Owner owner = 1;
}
// SetBlackoutTimeEnabled
message DeedSetBlackoutTimeEnabledRequest {
Deed deed = 1;
bool enabled = 2;
}
message DeedSetBlackoutTimeEnabledResponse {} // Empty
// SetBlackoutTime
message DeedSetBlackoutTimeRequest {
Deed deed = 1;
int32 start_time = 2;
int32 stop_time = 3;
}
message DeedSetBlackoutTimeResponse {} // Empty
// HOST ----
// AddComment
message HostAddCommentRequest {
Host host = 1;
comment.Comment new_comment = 2;
}
message HostAddCommentResponse {} // Empty
// AddTags
message HostAddTagsRequest {
Host host = 1;
repeated string tags = 2;
}
message HostAddTagsResponse {} // Empty
// Delete
message HostDeleteRequest {
Host host = 1;
}
message HostDeleteResponse {} // Empty
// FindHost
message HostFindHostRequest {
string name = 1;
}
message HostFindHostResponse {
Host host = 1;
}
// GetComments
message HostGetCommentsRequest {
Host host = 1;
}
message HostGetCommentsResponse {
comment.CommentSeq comments = 1;
}
// GetDeed
message HostGetDeedRequest {
Host host = 1;
}
message HostGetDeedResponse {
Deed deed = 1;
}
// GetHost
message HostGetHostRequest {
string id = 1;
}
message HostGetHostResponse {
Host host = 1;
}
// GetHosts
message HostGetHostsRequest {
HostSearchCriteria r = 1;
}
message HostGetHostsResponse {
HostSeq hosts = 1;
}
// GetHostWhiteboard
message HostGetHostWhiteboardRequest {} // Empty
message HostGetHostWhiteboardResponse {
NestedHostSeq nested_hosts = 1;
}
// GetOwner
message HostGetOwnerRequest {
Host host = 1;
}
message HostGetOwnerResponse {
Owner owner = 1;
}
// GetProcs
message HostGetProcsRequest {
Host host = 1;
}
message HostGetProcsResponse {
ProcSeq procs = 1;
}
// GetRenderPartitions
message HostGetRenderPartitionsRequest {
Host host = 1;
}
message HostGetRenderPartitionsResponse {
renderPartition.RenderPartitionSeq render_partitions = 1;
}
// Lock
message HostLockRequest {
Host host = 1;
}
message HostLockResponse {} // Empty
// Reboot
message HostRebootRequest {
Host host = 1;
}
message HostRebootResponse {} // Empty
// RebootWhenIdle
message HostRebootWhenIdleRequest {
Host host = 1;
}
message HostRebootWhenIdleResponse {} // Empty
// RedirectToJob
message HostRedirectToJobRequest {
Host host = 1;
repeated string proc_names = 2;
string job_id = 3;
}
message HostRedirectToJobResponse {
bool value = 1;
}
// RemoveTags
message HostRemoveTagsRequest {
Host host = 1;
repeated string tags = 2;
}
message HostRemoveTagsResponse {} // Empty
// RenameTag
message HostRenameTagRequest {
Host host = 1;
string old_tag = 2;
string new_tag = 3;
}
message HostRenameTagResponse {} // Empty
// SetAllocation
message HostSetAllocationRequest {
Host host = 1;
string allocation_id = 2;
}
message HostSetAllocationResponse {} // Empty
// SetHardwareState
message HostSetHardwareStateRequest {
Host host = 1;
HardwareState state = 2;
}
message HostSetHardwareStateResponse {} // Empty
// SetOs
message HostSetOsRequest {
Host host = 1;
string os = 2;
}
message HostSetOsResponse {} // Empty
// SetThreadMode
message HostSetThreadModeRequest {
Host host = 1;
ThreadMode mode = 2;
}
message HostSetThreadModeResponse {} // Empty
// Unlock
message HostUnlockRequest {
Host host = 1;
}
message HostUnlockResponse {} // Empty
// OWNER ----
// Delete
message OwnerDeleteRequest {
Owner owner = 1;
}
message OwnerDeleteResponse {} // Empty
// GetDeeds
message OwnerGetDeedsRequest {
Owner owner = 1;
}
message OwnerGetDeedsResponse {
DeedSeq deeds = 1;
}
// GetHosts
message OwnerGetHostsRequest {
Owner owner = 1;
}
message OwnerGetHostsResponse {
HostSeq hosts = 1;
}
// GetOwner
message OwnerGetOwnerRequest {
string name = 1;
}
message OwnerGetOwnerResponse {
Owner owner = 1;
}
// SetShow
message OwnerSetShowRequest {
Owner owner = 1;
string show = 2;
}
message OwnerSetShowResponse {} // Empty
// TakeOwnership
message OwnerTakeOwnershipRequest {
Owner owner = 1;
string host = 2;
}
message OwnerTakeOwnershipResponse {} // Empty
// PROC ---
// ClearRedirect
message ProcClearRedirectRequest {
Proc proc = 1;
}
message ProcClearRedirectResponse {
bool value = 1;
}
// GetFrame
message ProcGetFrameRequest {
Proc proc = 1;
}
message ProcGetFrameResponse {
job.Frame frame = 1;
}
// GetHost
message ProcGetHostRequest {
Proc proc = 1;
}
message ProcGetHostResponse {
Host host = 1;
}
// GetJob
message ProcGetJobRequest {
Proc proc = 1;
}
message ProcGetJobResponse {
job.Job job = 1;
}
// GetLayer
message ProcGetLayerRequest {
Proc proc = 1;
}
message ProcGetLayerResponse {
job.Layer layer = 1;
}
// GetProcs
message ProcGetProcsRequest {
ProcSearchCriteria r = 1;
}
message ProcGetProcsResponse {
ProcSeq procs = 1;
}
// Kill
message ProcKillRequest {
Proc proc = 1;
}
message ProcKillResponse {} // Empty
// RedirectToGroup
message ProcRedirectToGroupRequest {
Proc proc = 1;
string group_id = 2;
bool kill = 3;
}
message ProcRedirectToGroupResponse {
bool value = 1;
}
// RedirectToJob
message ProcRedirectToJobRequest {
Proc proc = 1;
string job_id = 2;
bool kill = 3;
}
message ProcRedirectToJobResponse {
bool value = 1;
}
// Unbook
message ProcUnbookRequest {
Proc proc = 1;
bool kill = 2;
}
message ProcUnbookResponse {} // Empty
// UnbookProcs
message ProcUnbookProcsRequest {
ProcSearchCriteria r = 1;
bool kill = 2;
}
message ProcUnbookProcsResponse {
int32 num_procs = 1;
}
// UnbookToJob
message ProcUnbookToJobRequest {
ProcSearchCriteria r = 1;
job.JobSeq jobs = 2;
bool kill = 3;
}
message ProcUnbookToJobResponse {
int32 num_procs = 1;
}
// UnbookToGroup
message ProcUnbookToGroupRequest {
ProcSearchCriteria r = 1;
job.Group group = 2;
bool kill = 3;
}
message ProcUnbookToGroupResponse {
int32 num_procs = 1;
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace Baskervilles.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| {
"pile_set_name": "Github"
} |
# Write a function to sort a list of numbers. What is the runtime of the
# algorithm that you have written? Can it be improved?
# This is insertion sort, it is acceptable answer for this question but not
# in many real-world circumstances.
def sort(ls):
for i in range(len(ls)):
for j in range(i-1,0, -1):
if list[j] > list[j-1]:
tmp = list[j]
list[j] = list[j-1]
list[j-1] = tml
| {
"pile_set_name": "Github"
} |
package ftp
// A scanner for fields delimited by one or more whitespace characters
type scanner struct {
bytes []byte
position int
}
// newScanner creates a new scanner
func newScanner(str string) *scanner {
return &scanner{
bytes: []byte(str),
}
}
// NextFields returns the next `count` fields
func (s *scanner) NextFields(count int) []string {
fields := make([]string, 0, count)
for i := 0; i < count; i++ {
if field := s.Next(); field != "" {
fields = append(fields, field)
} else {
break
}
}
return fields
}
// Next returns the next field
func (s *scanner) Next() string {
sLen := len(s.bytes)
// skip trailing whitespace
for s.position < sLen {
if s.bytes[s.position] != ' ' {
break
}
s.position++
}
start := s.position
// skip non-whitespace
for s.position < sLen {
if s.bytes[s.position] == ' ' {
s.position++
return string(s.bytes[start : s.position-1])
}
s.position++
}
return string(s.bytes[start:s.position])
}
// Remaining returns the remaining string
func (s *scanner) Remaining() string {
return string(s.bytes[s.position:len(s.bytes)])
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/cloudtrail/CloudTrail_EXPORTS.h>
#include <aws/cloudtrail/CloudTrailRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/cloudtrail/model/EventSelector.h>
#include <utility>
namespace Aws
{
namespace CloudTrail
{
namespace Model
{
/**
*/
class AWS_CLOUDTRAIL_API PutEventSelectorsRequest : public CloudTrailRequest
{
public:
PutEventSelectorsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "PutEventSelectors"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline const Aws::String& GetTrailName() const{ return m_trailName; }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline bool TrailNameHasBeenSet() const { return m_trailNameHasBeenSet; }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline void SetTrailName(const Aws::String& value) { m_trailNameHasBeenSet = true; m_trailName = value; }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline void SetTrailName(Aws::String&& value) { m_trailNameHasBeenSet = true; m_trailName = std::move(value); }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline void SetTrailName(const char* value) { m_trailNameHasBeenSet = true; m_trailName.assign(value); }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline PutEventSelectorsRequest& WithTrailName(const Aws::String& value) { SetTrailName(value); return *this;}
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline PutEventSelectorsRequest& WithTrailName(Aws::String&& value) { SetTrailName(std::move(value)); return *this;}
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail</code> </p>
*/
inline PutEventSelectorsRequest& WithTrailName(const char* value) { SetTrailName(value); return *this;}
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline const Aws::Vector<EventSelector>& GetEventSelectors() const{ return m_eventSelectors; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline bool EventSelectorsHasBeenSet() const { return m_eventSelectorsHasBeenSet; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline void SetEventSelectors(const Aws::Vector<EventSelector>& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors = value; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline void SetEventSelectors(Aws::Vector<EventSelector>&& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors = std::move(value); }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& WithEventSelectors(const Aws::Vector<EventSelector>& value) { SetEventSelectors(value); return *this;}
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& WithEventSelectors(Aws::Vector<EventSelector>&& value) { SetEventSelectors(std::move(value)); return *this;}
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& AddEventSelectors(const EventSelector& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors.push_back(value); return *this; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& AddEventSelectors(EventSelector&& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors.push_back(std::move(value)); return *this; }
private:
Aws::String m_trailName;
bool m_trailNameHasBeenSet;
Aws::Vector<EventSelector> m_eventSelectors;
bool m_eventSelectorsHasBeenSet;
};
} // namespace Model
} // namespace CloudTrail
} // namespace Aws
| {
"pile_set_name": "Github"
} |
defmodule Companies.Schema.CompanyTest do
@moduledoc """
This module holds the unit tests to the company changeset
"""
use Companies.DataCase
alias Companies.Schema.Company
@valid_company_params %{
blog: "Company blog",
description: "Description of the company",
github: "github account of the company",
location: "Amsterdam",
name: "Company name",
url: "link of the company",
industry_id: 12_346
}
describe "changeset/2" do
test "returns a valid changeset for correct parameters" do
changeset = Company.changeset(%Company{}, @valid_company_params)
assert changeset.valid?
end
test "returns an invalid changeset for incorrect parameteres" do
changeset = Company.changeset(%Company{}, %{})
refute changeset.valid?
end
end
end
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const { ActivityHandler, ActivityTypes } = require('botbuilder');
class RootBot extends ActivityHandler {
constructor(conversationState, skillsConfig, skillClient) {
super();
if (!conversationState) throw new Error('[RootBot]: Missing parameter. conversationState is required');
if (!skillsConfig) throw new Error('[RootBot]: Missing parameter. skillsConfig is required');
if (!skillClient) throw new Error('[RootBot]: Missing parameter. skillClient is required');
this.conversationState = conversationState;
this.skillsConfig = skillsConfig;
this.skillClient = skillClient;
this.botId = process.env.MicrosoftAppId;
if (!this.botId) {
throw new Error('[RootBot] MicrosoftAppId is not set in configuration');
}
// We use a single skill in this example.
const targetSkillId = 'EchoSkillBot';
this.targetSkill = skillsConfig.skills[targetSkillId];
if (!this.targetSkill) {
throw new Error(`[RootBot] Skill with ID "${ targetSkillId }" not found in configuration`);
}
// Create state property to track the active skill
this.activeSkillProperty = this.conversationState.createProperty(RootBot.ActiveSkillPropertyName);
this.onTurn(async (turnContext, next) => {
// Forward all activities except EndOfConversation to the active skill.
if (turnContext.activity.type !== ActivityTypes.EndOfConversation) {
// Try to get the active skill
const activeSkill = await this.activeSkillProperty.get(turnContext);
if (activeSkill) {
// Send the activity to the skill
await this.sendToSkill(turnContext, activeSkill);
return;
}
}
// Ensure next BotHandler is executed.
await next();
});
// See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
this.onMessage(async (context, next) => {
if (context.activity.text.toLowerCase() === 'skill') {
await context.sendActivity('Got it, connecting you to the skill...');
// Set active skill
await this.activeSkillProperty.set(context, this.targetSkill);
// Send the activity to the skill
await this.sendToSkill(context, this.targetSkill);
} else {
await context.sendActivity("Me no nothin'. Say 'skill' and I'll patch you through");
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
// Handle EndOfConversation returned by the skill.
this.onEndOfConversation(async (context, next) => {
// Stop forwarding activities to Skill.
await this.activeSkillProperty.set(context, undefined);
// Show status message, text and value returned by the skill
let eocActivityMessage = `Received ${ ActivityTypes.EndOfConversation }.\n\nCode: ${ context.activity.code }`;
if (context.activity.text) {
eocActivityMessage += `\n\nText: ${ context.activity.text }`;
}
if (context.activity.value) {
eocActivityMessage += `\n\nValue: ${ context.activity.value }`;
}
await context.sendActivity(eocActivityMessage);
// We are back at the root
await context.sendActivity('Back in the root bot. Say \'skill\' and I\'ll patch you through');
// Save conversation state
await this.conversationState.saveChanges(context, true);
// By calling next() you ensure that the next BotHandler is run.
await next();
});
this.onMembersAdded(async (context, next) => {
const membersAdded = context.activity.membersAdded;
for (let cnt = 0; cnt < membersAdded.length; ++cnt) {
if (membersAdded[cnt].id !== context.activity.recipient.id) {
await context.sendActivity('Hello and welcome!');
}
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
}
/**
* Override the ActivityHandler.run() method to save state changes after the bot logic completes.
*/
async run(context) {
await super.run(context);
// Save any state changes. The load happened during the execution of the Dialog.
await this.conversationState.saveChanges(context, false);
}
async sendToSkill(context, targetSkill) {
// NOTE: Always SaveChanges() before calling a skill so that any activity generated by the skill
// will have access to current accurate state.
await this.conversationState.saveChanges(context, true);
// route the activity to the skill
const response = await this.skillClient.postToSkill(this.botId, targetSkill, this.skillsConfig.skillHostEndpoint, context.activity);
// Check response status
if (!(response.status >= 200 && response.status <= 299)) {
throw new Error(`[RootBot]: Error invoking the skill id: "${ targetSkill.id }" at "${ targetSkill.skillEndpoint }" (status is ${ response.status }). \r\n ${ response.body }`);
}
}
}
module.exports.RootBot = RootBot;
RootBot.ActiveSkillPropertyName = 'activeSkillProperty';
| {
"pile_set_name": "Github"
} |
{% extends "appuser/base.html" %}
{% load widget_tweaks %}
{% block appusercontent %}
<h1>Change Password</h1>
{% if form.non_field_errors %}
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{% for error in form.non_field_errors %}
<p>{{ error }}</p>
{% endfor %}
</div><!-- /alert alert-danger -->
{% endif %}
<form method="post" action="{{ request.path }}">
{% csrf_token %}
{% for field in form.visible_fields %}
<div class="form_group">
{% if field.errors %}
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endif %}
{{ field.label_tag }}
{{ field|add_class:"form-control" }}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Change Password</button>
</form>
{% endblock %} | {
"pile_set_name": "Github"
} |
" MIT License. Copyright (c) 2013-2019 Bailey Ling et al.
" Plugin: https://github.com/wesQ3/vim-windowswap
" vim: et ts=2 sts=2 sw=2
scriptencoding utf-8
if !exists('g:loaded_windowswap')
finish
endif
let s:spc = g:airline_symbols.space
if !exists('g:airline#extensions#windowswap#indicator_text')
let g:airline#extensions#windowswap#indicator_text = 'WS'
endif
function! airline#extensions#windowswap#init(ext)
call airline#parts#define_function('windowswap', 'airline#extensions#windowswap#get_status')
endfunction
function! airline#extensions#windowswap#get_status()
" use new tab-aware api if WS is up to date
let s:mark = exists('*WindowSwap#IsCurrentWindowMarked') ?
\WindowSwap#IsCurrentWindowMarked() :
\(WindowSwap#HasMarkedWindow() && WindowSwap#GetMarkedWindowNum() == winnr())
if s:mark
return g:airline#extensions#windowswap#indicator_text.s:spc
endif
return ''
endfunction
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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 external.com.android.dx.rop.annotation;
import external.com.android.dx.rop.cst.Constant;
import external.com.android.dx.rop.cst.CstString;
/**
* A (name, value) pair. These are used as the contents of an annotation.
*/
public final class NameValuePair implements Comparable<NameValuePair> {
/** {@code non-null;} the name */
private final CstString name;
/** {@code non-null;} the value */
private final Constant value;
/**
* Construct an instance.
*
* @param name {@code non-null;} the name
* @param value {@code non-null;} the value
*/
public NameValuePair(CstString name, Constant value) {
if (name == null) {
throw new NullPointerException("name == null");
}
if (value == null) {
throw new NullPointerException("value == null");
}
this.name = name;
this.value = value;
}
/** {@inheritDoc} */
@Override
public String toString() {
return name.toHuman() + ":" + value;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return name.hashCode() * 31 + value.hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(Object other) {
if (! (other instanceof NameValuePair)) {
return false;
}
NameValuePair otherPair = (NameValuePair) other;
return name.equals(otherPair.name)
&& value.equals(otherPair.value);
}
/**
* {@inheritDoc}
*
* <p>Instances of this class compare in name-major and value-minor
* order.</p>
*/
@Override
public int compareTo(NameValuePair other) {
int result = name.compareTo(other.name);
if (result != 0) {
return result;
}
return value.compareTo(other.value);
}
/**
* Gets the name.
*
* @return {@code non-null;} the name
*/
public CstString getName() {
return name;
}
/**
* Gets the value.
*
* @return {@code non-null;} the value
*/
public Constant getValue() {
return value;
}
}
| {
"pile_set_name": "Github"
} |
package com.tencent.mm.d.a;
import com.tencent.mm.sdk.c.b;
public final class kn
extends b
{
public static boolean arQ = false;
public static boolean arR = false;
public kn()
{
id = "ScanBankcardEnd";
jUI = arR;
}
}
/* Location:
* Qualified Name: com.tencent.mm.d.a.kn
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | {
"pile_set_name": "Github"
} |
<!-- Generated by pkgdown: do not edit by hand -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>List Bookmarks from a Word Document — list_bookmarks • ReporteRs package</title>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha384-nrOSfDHtoPMzJHjVTdCopGqIqeYETSXhZDFyniQ8ZHcVy08QesyHcnOUpMpqnmWq" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Font Awesome icons -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<!-- pkgdown -->
<link href="../pkgdown.css" rel="stylesheet">
<script src="../jquery.sticky-kit.min.js"></script>
<script src="../pkgdown.js"></script>
<!-- mathjax -->
<script src='https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container template-reference-topic">
<header>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">ReporteRs</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Word
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="../articles/word.html">Overview</a>
</li>
<li>
<a href="../articles/bookmarks.html">Replace content</a>
</li>
</ul>
</li>
<li>
<a href="../articles/powerpoint.html">Powerpoint</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
FlexTable
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="../articles/FlexTable.html">Overview</a>
</li>
<li>
<a href="../articles/flextable_examples.html">Examples</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Formatting content
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="../articles/formatting_properties.html">Formatting properties</a>
</li>
<li>
<a href="../articles/pot.html">pot objects</a>
</li>
<li>
<a href="../articles/evg.html">Editable vector graphics</a>
</li>
</ul>
</li>
<li>
<a href="../articles/faq.html">FAQ</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="../reference/index.html">Function reference</a>
</li>
<li>
<a href="https://github.com/davidgohel/ReporteRs">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
</header>
<div class="row">
<div class="col-md-9 contents">
<div class="page-header">
<h1>List Bookmarks from a Word Document</h1>
</div>
<p>List all bookmarks available in a <code>docx</code> object.</p>
<pre class="usage"><span class='fu'>list_bookmarks</span>(<span class='no'>x</span>, <span class='kw'>body</span> <span class='kw'>=</span> <span class='fl'>TRUE</span>, <span class='kw'>header</span> <span class='kw'>=</span> <span class='fl'>TRUE</span>, <span class='kw'>footer</span> <span class='kw'>=</span> <span class='fl'>TRUE</span>)</pre>
<h2 class="hasAnchor" id="arguments"><a class="anchor" href="#arguments"></a> Arguments</h2>
<table class="ref-arguments">
<colgroup><col class="name" /><col class="desc" /></colgroup>
<tr>
<th>x</th>
<td><p>a <code>docx</code> object</p></td>
</tr>
<tr>
<th>body</th>
<td><p>specifies to scan document body</p></td>
</tr>
<tr>
<th>header</th>
<td><p>specifies to scan document header</p></td>
</tr>
<tr>
<th>footer</th>
<td><p>specifies to scan document footer</p></td>
</tr>
</table>
<h2 class="hasAnchor" id="value"><a class="anchor" href="#value"></a>Value</h2>
<p>a character vector</p>
<h2 class="hasAnchor" id="see-also"><a class="anchor" href="#see-also"></a>See also</h2>
<p><code><a href='docx.html'>docx</a></code>, <code><a href='text_extract.html'>text_extract</a></code></p>
<h2 class="hasAnchor" id="examples"><a class="anchor" href="#examples"></a>Examples</h2>
<pre class="examples"><div class='input'><span class='no'>doc</span> <span class='kw'><-</span> <span class='fu'><a href='docx.html'>docx</a></span>( <span class='kw'>title</span> <span class='kw'>=</span> <span class='st'>"My example"</span>, <span class='kw'>template</span> <span class='kw'>=</span> <span class='fu'>file.path</span>(
<span class='fu'>system.file</span>(<span class='kw'>package</span> <span class='kw'>=</span> <span class='st'>"ReporteRs"</span>), <span class='st'>"templates/bookmark_example.docx"</span>) )
<span class='fu'>list_bookmarks</span>( <span class='no'>doc</span> )</div><div class='output co'>#> [1] "PLOT" "DATA" "AUTHOR" "REVIEWER"</div></pre>
</div>
<div class="col-md-3 hidden-xs hidden-sm" id="sidebar">
<h2>Contents</h2>
<ul class="nav nav-pills nav-stacked">
<li><a href="#arguments">Arguments</a></li>
<li><a href="#value">Value</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#examples">Examples</a></li>
</ul>
</div>
</div>
<footer>
<div class="author">
<p>Version 0.8.9 - Developed by David Gohel - proudly brought to you by <a href="http://www.ardata.fr"><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAATYAAAA9CAYAAAAnDEXeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAABtISURBVHic7Z15nBzVde+/p3oWtCVIYIMEAeMNY8cGgu0EPhhLQghJGDCIaQGGYWY00zWSQDH2S2ycxDRe4gUeeWGRumpWBEiaHrGKzQZDvIBfnNiA/YId/IyRAEnIIAlbQpql6+SPmunZerlV3T0zQv39i+m+yxF1+1f33HvuuUKRSDp1m0CWmpXWb0ftzuuK1XcukmsaTiSij4xHX/lQlRuXNbcnQlVucpciuqnIJhWXSOp9rF35UsnajzlTgZ3ANKPyKp+kJfYfJbNnEDvxU5DKkvdTbJSnce2/LUnbjS3HYnlbATEo7WF5x5FY8Vqxuq8oRiObndjU/fQtMq8hUWBchI2IVwXy3nHpKw8iHD7RNhzUiC5CxUzU/PKXAKUXNpW/AqpK3k+xUXm9ZG1b3sWYiRqAhcrFwK1F674YjeyX/nMxfYv6vDfp1p1SjL7LHEKoXBSwRg2o6Y+rTDEJ+qxULilm90URNpSgA67o/5Ay73BiTiVwXsBaJxBzTy2FOWVysOq2IxA9M2CtM2lom1MsEwoWNseJVQKfCV5Tagrtu8whhMp8YGbger47WmY86a/4LMGXuSwq+oNPkLI2ViCHS9980OADDv1g0qn7aKH9lzlEEA036FWWFdmSMvkIvmQwiOHmY34Kd0XDuKHpumV3tIwB8bgFXBCy9nuxEycX05wyOWhomwGcHbL2p4k5s4thRkHCFo/HLUHDDjgQym/TMvnZNvsMIPyA96zyC3S8iKTOAw4LWdtC9MJimFGQsH149tYzQApR2BM3uVd9pBAbyhwChHdtfESjRbKkTD4sr7BnVSQvrrA4NuEitDAD1P+H/FdhrRSFXSC/D1l3BugHi2pNmSFEP1tgCx8k5nwU1/5VUewpk5lrbqmmRxYX2Mpcmte+m8SKnYU0UpiwacEDDkUuAW4otJ0i8FjUbv9cmIrda+vmqiVPFdugkDyPaxc3RjDmbKMQV7AQmteeikfhAdb+7miphO10PKvweDnL+wpwcd5yol8mFXmi4P5U3iq4jeH0Vi0EZhTYSoRU5EKgpZBGQgvbRqf+r6AIAw7+cmNL40mXNrX+ughtlXmnkYpcjBToFgCoRIHrC28oA679i6K0E3P+YFRO5SVam35elD6LS35RNsF/CRUkbKHX2EQK2A0dRSSVKto2b5l3GKLF+bHAh7ATHy5SW2VGU5OMoBIinjUj84k5RxbSQHhhKyTMYxQqlHetyozFTnwAKJ4YlXdHS8esXXOBgsRoGBWohI+2IKSwbXRrPwiY7GZuA6PthZM3Jeo+EMaWMu9g1DRbDGZZIcqnEEqH+c71uDyrUMIWIWI04BTuQtQou0JKKB+xKjMaMzdUdDVmL9CPEnM+VJBFZTKgApjEnyminzdsdAHLW2eFtSiUsClmu6GWpQ+p8oBJWWFynUJIOg1BD/GWKSaNLccCHzcouZPZO+5HMF3AL6/nFhvb+RvgWIOSz+HY92A2a6skkjo/rEmBhe2elsZjUfmEQdE3j3ztPT+NiBoJG3BqsnX5+4PaUzq0vcttKAd2ThSiSzHJ56WymXjcw/AFCuX13KJj7oY+iL/F/ZBR6QLc0cDC1u+ljBLIqfDwvHi8/5LYHf8F8qJJ29o/qXZHI6J6Z1eiLvRb4xBjD6nIH4vYnlmMpOjgj+R+w3ZPGdiUKFM8gj0rFbOXkMo5xJw/D2NQYGEzDfMQj83p/1Z90KztyeWOAlUisqnbbSg0mvqdzh4s71xc+42itBZzjjTM59VDRb8fqOqfKvitUfvl3dHi0djyMcDkRbEdx/Zj7w478CRg8hKsDrs7GkjY1juxI1FMBlxvb2/v9wf/UDFUaPj4PWsaJkUa72FUqeqmLqdh3kQbMknxRS2x4mdFbNM0n9cTrFm1N/2XyuYcZYewdDJ5Bgc3fgpwEwbdULh1dQ+ijxnWC/WsAglbRHovwGTACT+8YvXdaUV+Yftxz+BfwpEP9azUCUFsGiemCvpgt1t/xkQbMsnYjWctSIuan16oGAR1Q30sz9DF4RiuuaU6sFVlMmH2rFQeGvW32bMSDTXRCTQQxfQWKmWE6xmPxz1E871NVUSvrmm+4wdBbBpHpqvy6Ea3zmTj5FBgDyrnpo/22Ikv8fq731Nwq+b5vJRUZOSPZdesp4F8x5J2orKAW1f3hLSwzCCNLScAJrnu3kb0yVGfPQz05qn3Wywv1DKQsbA90NYwA2W+WauRh0d/pF7OXStf1GKda0ztmSD+zFL5frLlqtMm2pAJZg8qC9NX29mJL6Hy7aK0XNn3GUzyeQm/oLXp1RGfdUdT5N5xex2V+bTEJkM2mYMfyzNbq1R5HNd+e8Rnrv0WKj/MUeu3WN68sFfyGQtbb8ozTSD3q2hT65j0P/L2vieAfRnKewKxQVFLug0XTPJZ0eF41qPD88ipZfVPpEHjzJtY3vy0qMWc64smamAeOqBZBCx7eNEOYK4vairEnHj5BquCCbdkMPR5tmf1Iv0Vc0mseI14vIIm96tBDTMWNlUrwCLhWKJf6N4PYxYMFbi6xu5oBeh2GhaiutHCutTUrgniXZ5aT25saTwJoCbW/jSwdoJtGg92I7qIxIpnAX+mBvGitV7XcRhgej9t5p32qW9/n7Ev0NcRPRvX/g2oYDv/AlxPc6K8ZhoW/0apvzEo6VHRn1nYLO9+xp4YeZH+inm0L99GTTLC9qM7EY3TvPY9QcwzEraOjrrDQI0GnAXZ19JkhDuqqrIyanesBV/UFH0AmIJqVNX4stWJ4t2Wl3p8o3PV+0TQmljHKlEpKNXKJGc3nnUOTvN/AhBz4kWdqQFU95yLWT6vbbixZzN+8y9f2A88PuyT1xGdj9P8QlrUVPzbzz2rHIAdFv9GKRP9+A/WrNqR8ZvEitdGnRgZKWqzdt2ByucAwbMCHbk0ErbpPWI64Hb+v+3HZz8b6q+99TMgasua2xMAXW79uQOiNujqHruppf50E9smmGMsrKeSLY0niKA6608rRNgw0UaVgDfwrLnpjYKYE6cUuc2M3VAZCh3I/P3gC3SkqMXc/5MWNZ8oNclIeIMPaUxPG+TeNBw6MfLfI0Rt5u51A6I2SKCXkJkrapp7TXRzPB73sn0dbWzbBfwbIg3DRU2U+xm1fqdesH/IBPIXeKmn7mldfnw02p3Sw/deCdI90UYVFcu7gNamXwKlE7V4vALT+2mzrdmM/H4rKmcNE7VbgNWjSh7N4XvKZ4KD4h9OP8uobL5n5Z8Y+TUV/XNpX76NmFPJ4Xs2ApePKvdxYs77TE3MK2xPxeMVajjgNNuC7jD6qbwsGmvvBOhK1C0RX7HHbkoINfHixUWVmuNTKe9761saj4pGu1PTe6ZdCWIagDj5Sax4GQA7cQOlykK7/ehPA0cYlNzHtH2jQwdG4p+AOI2W2IsDonYrcHXGspZ3sLxAJw/+4fRKg5JbcJqfz1nCPzFyFmtW7SDmVAIbsp4R9bMgG5FXOHbO2ToXswG3v2dK6vF8hS633TcAkom6RSJyD5AtUHLOSUe/MmFvUxW5DkgFqHJihZf64fqWxqOWrL61h31/uhiYLPcgFI6/phZ4dyoApptTjw+so+XGtd8YNlNblbWcSs3AbLGMOabPyuwkiGu/MbAksI5cJw0C3DaWf0bkmfrS+mRt7Z2ZwjnG0O02LEbkPvKEj1iSmrC36bJYexKRRiCra52BEyu81Pfuva32iOgXuvdPofIzoD8qlY3jRilnagCoGJ8JND02NSRqmWdqQ7yLV48xc6vKwMrbpwPnGJY2e1Yxp5JZu7qBfNEQp9DYcpJJkzmFTRURMbsQWTAbcN1uw2JVvReDmDhFLkkmayZscTcaa+8UsDFLYjjIyf2VkcfvXnP5zPNt9+3enr7zAaNkm5MSO3FDiWdq0NRyOmb5vDwq+x7JXyyP+zmasjtqTl/lEmCKQcm9VPfkCsD1iTmViHYZbxwZBgXnFLZup8E0gZxaGU4bjGnPF7W8M7VhHKW7Z0zo27TG7mhF9NqA1U6tjFQ//EBbw4wrVt/9x8oqXQhkDk+YzIyHqIH5JbuiP8saOpAmLWrZ3c+xLC27o4aImu5cP5b32Jq/ppYMeCG20Usotysqxrc6P7u0qfXVXAWSbsMFqno/2dfUsmAWP1dKorHOfxXhKwGrnd6T0gc3O7GpF9V37um3IosR/rskBpaCJvfr4yJqACrhDlJnKEDMTRBM1ACOZNvsQ/2YXH78xAFLjMpaXm4PriZZhUo3pqcXhvjLgezKubvP/bUYLRIKufOtdSXqlqCaBKpM2hvGs5V9qe8GrFMSamId30L5WqBKytz99D3Q0VF32OVNra9HY+33lci84mInbkD0H8epr5MB08zJOcaZCrZzGxALbIPKzbj2vweud6jRU70A+DODkilUsi8Z1CSrmLm7C1GTexJGc92YM8IZyCpsGxMNJwNGcSOpHOtrSWf5eSJyL4Fnajxb0Zc65+Kr170ZsF7JiDZ3XK/KtwJWWzCtR+5/5JZrDo40OTHnG6FmaqL3kYq8Erie6WwNtgyEBowlHrewHQeVlYH7hxtpiX0xRL1DEdNn9dOsSUd9UdsUoK1BFJXP49pGp12yCltEPNOOX1sW68i4fpR0Gy4C7z6Ci9p/Vlbp/IuvXvdm8uaaKV1OXVA3sGQsa+74Csq/BqoknLu3au+Gpyb7Ok7M+QbwDyFq3ovKMly7L0TdwkIH4nGLbbMdVJpC9P1dXPvvAWhyP4KdWBaijUMDPxzDdIaV+Vldc0s1s3bdAwRNt6/A52mJ+b+7xpZPEXMW5qqQVdjUMPeaiG4WGbtr2J2ouxjVLswC+YbzCyLWuRfVd+5J3lwzhWnTHxTka+tbGo8K2E7JqLE7rlWVYCmWhIv+MPvljZNW3GLO1wgranBpKFFb3vp+4GNGZSXTcocK22bfBjQG7lv0Jlz7SwDEnA8h+gQqKwK3c6hwxJufAt5lWHrss6pJVtFTnQxxW7wvaq59CwAx50ws72FEa3NVyihsA7dFfdSkV88bq85dbsNSFdlIOFE7J9rYtmtQ1IAFQKTCv0RmUiCCRu32qwE3YM2lO+dsaZt0Jyp8UfunEDXvIayoAUSMn+leqnpHxQOq0NSyBgguRqI34TT/HcBAXNRTwNHAp2hee0zg9g4FPMt0I/F3fhaVYfjuZzcQ9P4CRfRvR4gaPALMQOUCrr05a9hJxh+YpIzzmO97u5oRx1u63IalorqBwKImPx8Utc1ObOowURv4enKdHRVBX9h+/AqBuwLVU2pPmr2lddKIW5P7dcKImsom4LLQogbmoQPw6MjQARVi7lpEm0P0euMIUbO8J/FFDcDCs8r3IYxBBfMU4CNzrA2tqYUTNaf5VmBQ1B5lKBnHDN6emjW7bsYfl6rpaQN5vL6+88DgX8lE/SVhRa0vdSAtavvpHylqAMpZG9oa5gRrt7TE43FPZ+6tU2RjkHoC9SfN3uJMeGqmJvfroXY/VTYhenlBota89hhU/tqwvyGvIB63iLkd+IHTQbkxvabW2PIxLO9HDInaIIHS4xwSNCc+ARxnVDaSGnpWQ6IWZk1tdVrUGls+hS9q00eWkqzPaoywbWhrmIPwSYPO+2RYcsVup64GP2VPMFFT/i9UnP25let3+6LW9xBoppz3ltVvnCpl3IhGu1N7qKglZyjCWAQak279jSUyKz924p9DiZpokmO2FTZTA0hFLsTkQmR4KZ2o0N8oaAeuCtHjN9OiZidOxvJ+AByZodwZZXd0FOY717/As54G/KShM3c/QDhRW4Vr3wZAzJmH5T3GaFHz+QwxZ2qmRsYI24B45HOTUiJaW2O3fx/8mZoi6zG7Mm04P+3t7T03artvbXZiU/dr32Yg6zV3wuQ8+mLbbh8z99aA5j19MRyBL3Y59TeVyq6s+MG314Wo2c3sHZ8jHi88Fbrlmbh8W/CsBaxduZuaZKQAUfsuru2LuJ04GZUnyCxq4Luj5VnbcNQonvU5KvsW4tp9XHNLNdU93ZhnQ073BFyDa/sTJjtxFv6EIaN4AdMRzRgwPEbAJH8CuZQqV9bEOjfCiJlacFHr6V10xeq7/5gWNcl3WYycmVxbOynfptFod+/0nhlL8afMxvji1hBm4T4cYd1P6GbO9suLImqrbjsClXxH5bbiWfNobfo9NckIh+8JJ2oq30nvfja5p+QRtUHKwjZIk/sR4MQ8pZ6jsm8Bt1/9JtfcUk1v1aaQu5/X4Nq3A76oqTxM5pnacDI+qxHClmxdPgv00zka6Ue5dFlzxwaAbrfu0pAztWcGRQ1gP/1X5Bc13161IpN2cXfJ6lt7Dkzpr0H5cZB6gn6t26n/+1LZlSbmfCvkmtoGds+8rCiiBtBbdT65x8zvSUXOSovazN2d+bb3s3ADLbEvp/+yvG+TX9QATmfl7X8Ror93HvnP8T5LKnI2t1/9JtfePIWe6gdDiZrQnBY1AD+cKp+ogcp5XLlu2hizh/8h/d6FZB9wKVVqo80dmwC63IaoqtyZo3w2nqmukEXDL1SOROR7GGbQkEn+Nq2tvXPfgan9i4OKm8J3kk7D35XKroHg2y/nLTcaf02tduBqu+Igmsu12YpnnU1b45YBUesArgjRSxzXjo/4RI2TfwqpyKQeZ+NGbjf0OSr7zqGtcRfX3jyFvdMfAHIGzmbqAZWrcezRoVOmz2oahx04b/SHI4RNJeuWbr+glw3O1JJO3eWiGmam9pPqCll04fL2Pw3/cGlj2xbMs1+ccU9Lo0nGkQmjtvbOfZXVegHIz4PV1O8MHGUrLuFPFHQVbU1tkNz5vLYO3K3w+2GidmWIXuK49g1jPk1F7sM8BVVZ2PyboU7J8u3zaffz2punsG/ag4ia5mkbxN8oaIllCna/P0A7Y55VWtiSt6+cTma1TYFeVWN3doM/UwO5AwiWJ03k6eoKWTJa1AZRxPQfYnme4UWtE8hF9Z17Kqu8BTDiFp58iCVGl+bkYmSyz5jzHcKJ2l3snllcUQPor1hM5rRVL2N5nx62pnYn4UTtqxlFDaCtcQuQO1X1ICp/zfLW40P0/87BD8rNtHP9HJV9vvsZc6ayb9pmRodnGbSOaFN6o2A0c7Y/A7xu1JLokoEXZpq0sGnlgSWMHXAp0Nqo3bkeIJmoXyaqdxN0pibydHWExdlEDUDwjBVa0YPibXpRfeceKlkEjNfN468AQ2tR/kwtzNrdRuZsry+q+zlEpjXSrURSZ5NY8fKwNbXLArescj2u/fU8pUzHmWB5B8U4Kxma8Vjl88A5aVGDB4BM4Vk5W0Z0FU5zW9YS8biX+RhdRqbSVzliXW/IFR0blJsSkasGRa3brbsU4S7CuJ95RA0ganf+CvitYZun39O6/KB4m0YbOv5Q4fXPB35d4q5eBebh2r8DIOZ8k3AztY3M2X5l0WdqMJjPa3S0+FYiqXmsXflS+i7JcGtqX6Ullj+tlKi5ixMgx/47jsaWoxAdfSHy88ACXPuNAVEbG0ifH0V0JU5zIn/JUacYcjEqC7IF8Mgt11QLI+JBUiJyVU2s/W4Y2P0Mt1Hwk1zu52jUPMhVvFSWm2wmIRevuHNnxIosBF4qURevAnOHidp3IXBiTIA7mLO9+O7nIGPzeW3Bs+ayduVLxOMVzNq1ftRdkqb8g8FMzce/Ncn0OXycxpYTQthz8GN5n2XkctNoUXuI4DM1D5UGI1EDqO55AjDSDlQW0dCWXsaxAPYdtvcchgZcJlELNVOjf0remdpwxHyd7aBxRwfxMwyn5gEvF7npHXjWwlEztTC7qx3M2d5Ajnthi8DwHbZXiKTmp9fUts2+I8j1amlE/wnX/udAddR4nAmRibtQaIIZ/qx+yXBRE80ZSJ8FD2igJdZpXOPW1T2ImsaFTiGSSp9H9V3RITc0pUrdoKh1JeovGxC1YBsFyo/pn7I4umrN3iDVXth+3DNAnpz2aT65YW3dewLZNcFE7XVbiVjnANuK1OTreNZ8Wpt8N9cXtTAztQ7mbG8sqaj5+bwGj9e8Agy5nzN3r2PsBbkm/CNO8zcC17I8cxeH7OcR37HUdRwOzB3465fA2SNETcUk5nQ4KaAB174jsC1B3NFhu6NWMlkTUX/ApVSpW9bccRdAd6K+Xvw1teCilpqyJKiowcChcvJfujyARKyD7+hLtLHt/3uSmoe5gGfjdUSLIWrtJRc1gJm7z8LP5+WLmmv/btjuZzhRc+1vhrJl9o6fYPr/XzltIG/coUNl3/n4afx/TUX/uSPczzCiJhpO1HweBnqNSoouIub8OYA1cAvUrNGipkIrJveODqcAUUvbhhUgfuXgckcHuTS27kXQhUDm9Mn58UXNaX4B8A+0hxe1ppKLGjBwE9FYUQuz++mvqYUTNfB33PzjOmYcaruj/mmD31DRP3/ghvbBNbWg7qcvak7zutC2uPZbiJpePF49eD+tJaoXDhe1LreuIZSooT8qVNQApvdMNV8whE9sdK4yupdhshG1O3/lqSwAdgWsunOMqIU70D5+ooYKoqcxKGoxp5KZu5MFiFqwNbVMBHFH5eB8gYYi5kwFOY6K/nmsWbVj4LhSOFFTqS9I1AYJ4o4OPCtLse4dFLVkomG5qLQQWNTkB1OoCrymloklq2/tAeOjL4jKQbM7OppLm9uft/zrzP6Yt7DPDjxrblrUYs5NoURNtGX8RA1oTswBatOiJtqF+V0Hw/lfRRE1gJ7qxwHT8XoqduIDRel38nMc4i1hzaodrLx9OlP2P0YYUYNaWmJ3FsWi/ooH8DcfTFhIXcfh1rLmth+BP1ND1CWwqPHDA1P6Ljzfdt8OWC8H5sG6IgffOttwLrE7/l2ExeT7kansHLVRcBMQ5nYlF8e2x03UABIrXhtwP6sIfkGuj+gXce3/XTSbOusPBDg7Sqgd24MR1/4NiRU7aWibQX/Fo8CZAVtIIXolrr2+aDa1L9+G6M8MS1dT1XuhBQXM1ITH2bd3cW3tnfvyFw5ClfmCIXrawB0NBy01sY5nQBYz+jjUcFqbfpwWNX9NLYyotTJn+woQ0/OSxWPwLsng164BXIfTfHOxTQq2O3oInR29ct00IqkHCSdqdTjNG4puU8Dd0Yp1666cpgc8S9QKdCmGoJ7u3Xt39Avd+wOamJeo7b7V5TZcLsoRJuU9ry+7IFfKDu1Vk6wWL5jaVwqidvtPutz6pYrXk7NgQ9sc6H8ZCZga25N9tDStnxBRA5i16/0gjxIwXx3Ka7h2oASexlT1Pkhvtfn/x5hTWXDm4Fx41t1EvPxni61UwOQKATnswIexdAMQTKDEe5HEin8riU1wB2K4Hu1J7/8AsD0b69uqADIAAAAASUVORK5CYII=' height="12pt" style="vertical-align:middle;"/></a>
</p>
</div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-48354045-1', 'auto');
ga('send', 'pageview');
</script>
</footer>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
-- Phone numbers
local lpeg = require "lpeg"
local P = lpeg.P
local R = lpeg.R
local S = lpeg.S
local digit = R"09"
local seperator = S"- ,."
local function optional_parens(patt)
return P"(" * patt * P")" + patt
end
local _M = {}
local extension = P"e" * (P"xt")^-1 * seperator^-1 * digit^1
local optional_extension = (seperator^-1 * extension)^-1
_M.Australia = (
-- Normal landlines
optional_parens((P"0")^-1*S"2378") * seperator^-1 * digit*digit*digit*digit * seperator^-1 * digit*digit*digit*digit
-- Mobile numbers
+ (optional_parens(P"0"*S"45"*digit*digit) + S"45"*digit*digit)
* seperator^-1 * digit*digit*digit * seperator^-1 * digit*digit*digit
-- Local rate calls
+ P"1300" * seperator^-1 * digit*digit*digit * seperator^-1 * digit*digit*digit
-- 1345 is only used for back-to-base monitored alarm systems
+ P"1345" * seperator^-1 * digit*digit * seperator^-1 * digit*digit
+ P"13" * seperator^-1 * digit*digit * seperator^-1 * digit*digit
+ (P"0")^-1*P"198" * seperator^-1 * digit*digit*digit * seperator^-1 * digit*digit*digit -- data calls
-- Free calls
+ P"1800" * seperator^-1 * digit*digit*digit * seperator^-1 * digit*digit*digit
+ P"180" * seperator^-1 * digit*digit*digit*digit
) * optional_extension
local NPA = (digit-S"01")*digit*digit
local NXX = ((digit-S"01")*(digit-P"9")-P"37"-P"96")*digit-P(1)*P"11"
local USSubscriber = digit*digit*digit*digit
_M.USA = ((P"1" * seperator^-1)^-1 * optional_parens(NPA) * seperator^-1)^-1
* NXX * seperator^-1 * USSubscriber * optional_extension
local international = (
P"1" * seperator^-1 * #(-P"1") * _M.USA
+ P"61" * seperator^-1 * #(digit-P"0") * _M.Australia
-- Other countries we haven't made specific patterns for yet
+(P"20"+P"212"+P"213"+P"216"+P"218"+P"220"+P"221"
+P"222"+P"223"+P"224"+P"225"+P"226"+P"227"+P"228"+P"229"
+P"230"+P"231"+P"232"+P"233"+P"234"+P"235"+P"236"+P"237"
+P"238"+P"239"+P"240"+P"241"+P"242"+P"243"+P"244"+P"245"
+P"246"+P"247"+P"248"+P"249"+P"250"+P"251"+P"252"+P"253"
+P"254"+P"255"+P"256"+P"257"+P"258"+P"260"+P"261"+P"262"
+P"263"+P"264"+P"265"+P"266"+P"267"+P"268"+P"269"+P"27"
+P"290"+P"291"+P"297"+P"298"+P"299"+P"30" +P"31" +P"32"
+P"33" +P"34" +P"350"+P"351"+P"352"+P"353"+P"354"+P"355"
+P"356"+P"357"+P"358"+P"359"+P"36" +P"370"+P"371"+P"372"
+P"373"+P"374"+P"375"+P"376"+P"377"+P"378"+P"380"+P"381"
+P"385"+P"386"+P"387"+P"389"+P"39" +P"40" +P"41" +P"420"
+P"421"+P"423"+P"43" +P"44" +P"45" +P"46" +P"47" +P"48"
+P"49" +P"500"+P"501"+P"502"+P"503"+P"504"+P"505"+P"506"
+P"507"+P"508"+P"509"+P"51" +P"52" +P"53" +P"54" +P"55"
+P"56" +P"57" +P"58" +P"590"+P"591"+P"592"+P"593"+P"594"
+P"595"+P"596"+P"597"+P"598"+P"599"+P"60" +P"62"
+P"63" +P"64" +P"65" +P"66" +P"670"+P"672"+P"673"+P"674"
+P"675"+P"676"+P"677"+P"678"+P"679"+P"680"+P"681"+P"682"
+P"683"+P"684"+P"685"+P"686"+P"687"+P"688"+P"689"+P"690"
+P"691"+P"692"+P"7" +P"808"+P"81" +P"82" +P"84" +P"850"
+P"852"+P"853"+P"855"+P"856"+P"86" +P"870"+P"871"+P"872"
+P"873"+P"874"+P"878"+P"880"+P"881"+P"886"+P"90" +P"91"
+P"92" +P"93" +P"94" +P"95" +P"960"+P"961"+P"962"+P"963"
+P"964"+P"965"+P"966"+P"967"+P"968"+P"970"+P"971"+P"972"
+P"973"+P"974"+P"975"+P"976"+P"977"+P"98" +P"992"+P"993"
+P"994"+P"995"+P"996"+P"998" ) * (seperator^-1*digit)^6 -- At least 6 digits
)
_M.phone = P"+" * seperator^-1 * international
return _M
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
# SOME DESCRIPTIVE TITLE.
# Copyright (C) Micah Lee, et al.
# This file is distributed under the same license as the OnionShare package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2020.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: OnionShare 2.3\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-09-03 11:46-0700\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.8.0\n"
#: ../../source/index.rst:2
msgid "OnionShare's documentation"
msgstr ""
#: ../../source/index.rst:6
msgid ""
"OnionShare is an open source tool that lets you securely and anonymously "
"share files, host websites, and chat with friends using the Tor network."
msgstr ""
| {
"pile_set_name": "Github"
} |
// Copyright 2020, Google Inc. All rights reserved.
//
// 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.
using System;
namespace FirebaseAdmin.Auth
{
/// <summary>
/// Options for the
/// <see cref="FirebaseAuth.CreateSessionCookieAsync(string, SessionCookieOptions)"/>
/// API.
/// </summary>
public sealed class SessionCookieOptions
{
/// <summary>
/// Gets or sets the duration until the cookie is expired. Must be between 5 minutes
/// and 14 days. The backend service uses seconds precision for this parameter.
/// </summary>
public TimeSpan ExpiresIn { get; set; }
internal SessionCookieOptions CopyAndValidate()
{
var copy = new SessionCookieOptions()
{
ExpiresIn = this.ExpiresIn,
};
if (copy.ExpiresIn < TimeSpan.FromMinutes(5))
{
throw new ArgumentException("ExpiresIn must be at least 5 minutes");
}
else if (copy.ExpiresIn > TimeSpan.FromDays(14))
{
throw new ArgumentException("ExpiresIn must be at most 14 days");
}
return copy;
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* addToFilter higher-order component.
*
* Site Kit by Google, Copyright 2019 Google LLC
*
* 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
*
* https://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.
*/
export const addToFilter = ( AddComponent, slug ) => {
return function( OriginalComponent ) {
const NewComponent = function( props ) {
if ( props.slug !== slug ) {
return <OriginalComponent
{ ...props }
/>;
}
return (
<AddComponent
{ ...props }
/>
);
};
return NewComponent;
};
};
| {
"pile_set_name": "Github"
} |
define([
"../core",
"../core/init",
"../deferred"
], function( jQuery ) {
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
});
| {
"pile_set_name": "Github"
} |
define( [
"../core"
], function( jQuery ) {
"use strict";
jQuery.readyException = function( error ) {
window.setTimeout( function() {
throw error;
} );
};
} );
| {
"pile_set_name": "Github"
} |
# Makefile.in generated by automake 1.11.6 from Makefile.am.
# @configure_input@
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
# Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
VPATH = @srcdir@
am__make_dryrun = \
{ \
am__dry=no; \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \
| grep '^AM OK$$' >/dev/null || am__dry=yes;; \
*) \
for am__flg in $$MAKEFLAGS; do \
case $$am__flg in \
*=*|--*) ;; \
*n*) am__dry=yes; break;; \
esac; \
done;; \
esac; \
test $$am__dry = yes; \
}
pkgdatadir = $(datadir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkglibexecdir = $(libexecdir)/@PACKAGE@
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
subdir = dist-build
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \
$(top_srcdir)/m4/ax_check_define.m4 \
$(top_srcdir)/m4/ax_check_link_flag.m4 \
$(top_srcdir)/m4/ld-output-def.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
AM_V_GEN = $(am__v_GEN_@AM_V@)
am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
am__v_GEN_0 = @echo " GEN " $@;
AM_V_at = $(am__v_at_@AM_V@)
am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
am__v_at_0 = @
SOURCES =
DIST_SOURCES =
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = @ACLOCAL@
AMTAR = @AMTAR@
AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
AR = @AR@
AS = @AS@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
CC = @CC@
CCAS = @CCAS@
CCASDEPMODE = @CCASDEPMODE@
CCASFLAGS = @CCASFLAGS@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CWFLAGS = @CWFLAGS@
CYGPATH_W = @CYGPATH_W@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
DLLTOOL = @DLLTOOL@
DLL_VERSION = @DLL_VERSION@
DSYMUTIL = @DSYMUTIL@
DUMPBIN = @DUMPBIN@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
FGREP = @FGREP@
GREP = @GREP@
HAVE_AMD64_ASM_V = @HAVE_AMD64_ASM_V@
HAVE_CPUID_V = @HAVE_CPUID_V@
HAVE_TI_MODE_V = @HAVE_TI_MODE_V@
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
ISODATE = @ISODATE@
LD = @LD@
LDFLAGS = @LDFLAGS@
LIBOBJS = @LIBOBJS@
LIBS = @LIBS@
LIBTOOL = @LIBTOOL@
LIBTOOL_DEPS = @LIBTOOL_DEPS@
LIBTOOL_EXTRA_FLAGS = @LIBTOOL_EXTRA_FLAGS@
LIPO = @LIPO@
LN_S = @LN_S@
LTLIBOBJS = @LTLIBOBJS@
MAINT = @MAINT@
MAKEINFO = @MAKEINFO@
MANIFEST_TOOL = @MANIFEST_TOOL@
MKDIR_P = @MKDIR_P@
NM = @NM@
NMEDIT = @NMEDIT@
OBJDUMP = @OBJDUMP@
OBJEXT = @OBJEXT@
OTOOL = @OTOOL@
OTOOL64 = @OTOOL64@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_URL = @PACKAGE_URL@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH_SEPARATOR = @PATH_SEPARATOR@
RANLIB = @RANLIB@
SAFECODE_HOME = @SAFECODE_HOME@
SED = @SED@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
SODIUM_LIBRARY_VERSION = @SODIUM_LIBRARY_VERSION@
SODIUM_LIBRARY_VERSION_MAJOR = @SODIUM_LIBRARY_VERSION_MAJOR@
SODIUM_LIBRARY_VERSION_MINOR = @SODIUM_LIBRARY_VERSION_MINOR@
STRIP = @STRIP@
VERSION = @VERSION@
abs_builddir = @abs_builddir@
abs_srcdir = @abs_srcdir@
abs_top_builddir = @abs_top_builddir@
abs_top_srcdir = @abs_top_srcdir@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
builddir = @builddir@
datadir = @datadir@
datarootdir = @datarootdir@
docdir = @docdir@
dvidir = @dvidir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
htmldir = @htmldir@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
localedir = @localedir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
oldincludedir = @oldincludedir@
pdfdir = @pdfdir@
prefix = @prefix@
program_transform_name = @program_transform_name@
psdir = @psdir@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
srcdir = @srcdir@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
top_build_prefix = @top_build_prefix@
top_builddir = @top_builddir@
top_srcdir = @top_srcdir@
EXTRA_DIST = \
android-build.sh \
android-arm.sh \
android-x86.sh \
android-mips.sh \
emscripten.sh \
ios.sh \
msys2-win32.sh \
msys2-win64.sh
all: all-am
.SUFFIXES:
$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign dist-build/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign dist-build/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
tags: TAGS
TAGS:
ctags: CTAGS
CTAGS:
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile
installdirs:
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am:
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am:
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am:
.MAKE: install-am install-strip
.PHONY: all all-am check check-am clean clean-generic clean-libtool \
distclean distclean-generic distclean-libtool distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
| {
"pile_set_name": "Github"
} |
@font-face {
font-family: 'AvenirNext LT Pro';
src: url('../fonts/avenir/AvenirNextLTPro-UltLt.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-UltLt.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-UltLt.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-UltLt.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-UltLt.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 200;
}
@font-face {
font-family: 'AvenirNext LT Pro';
src: url('../fonts/avenir/AvenirNextLTPro-Regular.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-Regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-Regular.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-Regular.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-Regular.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 300;
}
@font-face {
font-family: 'AvenirNext LT Pro';
src: url('../fonts/avenir/AvenirNextLTPro-Medium.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-Medium.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-Medium.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-Medium.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-Medium.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: 'AvenirNext LT Pro';
src: url('../fonts/avenir/AvenirNextLTPro-Demi.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-Demi.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-Demi.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-Demi.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-Demi.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 500;
}
@font-face {
font-family: 'AvenirNext LT Pro';
src: url('../fonts/avenir/AvenirNextLTPro-Bold.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-Bold.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-Bold.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-Bold.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-Bold.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 600;
}
@font-face {
font-family: 'AvenirNext LT Pro Cn';
src: url('../fonts/avenir/AvenirNextLTPro-UltLtCn.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-UltLtCn.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-UltLtCn.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-UltLtCn.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-UltLtCn.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 200;
}
@font-face {
font-family: 'AvenirNext LT Pro Cn';
src: url('../fonts/avenir/AvenirNextLTPro-Cn.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-Cn.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-Cn.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-Cn.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-Cn.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 300;
}
@font-face {
font-family: 'AvenirNext LT Pro Cn';
src: url('../fonts/avenir/AvenirNextLTPro-MediumCn.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-MediumCn.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-MediumCn.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-MediumCn.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-MediumCn.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: 'AvenirNext LT Pro Cn';
src: url('../fonts/avenir/AvenirNextLTPro-DemiCn.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-DemiCn.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-DemiCn.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-DemiCn.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-DemiCn.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 500;
}
@font-face {
font-family: 'AvenirNext LT Pro Cn';
src: url('../fonts/avenir/AvenirNextLTPro-BoldCn.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-BoldCn.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-BoldCn.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-BoldCn.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-BoldCn.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 600;
}
@font-face {
font-family: 'AvenirNext LT Pro Cn';
src: url('../fonts/avenir/AvenirNextLTPro-HeavyCn.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-HeavyCn.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-HeavyCn.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-HeavyCn.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-HeavyCn.svg#svg') format('svg'); /* Legacy iOS */
font-style: normal;
font-weight: 600;
}
@font-face {
font-family: 'AvenirNext LT Pro';
src: url('../fonts/avenir/AvenirNextLTPro-It.eot'); /* IE9 Compat Modes */
src: url('../fonts/avenir/AvenirNextLTPro-It.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/avenir/AvenirNextLTPro-It.woff') format('woff'), /* Modern Browsers */
url('../fonts/avenir/AvenirNextLTPro-It.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/avenir/AvenirNextLTPro-It.svg#svg') format('svg'); /* Legacy iOS */
font-style: italic;
font-weight: 300;
}
| {
"pile_set_name": "Github"
} |
/*
* Typelib for wbemdisp
*
* Copyright 2013 Hans Leidekker for CodeWeavers
*
* 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
*/
#pragma makedep regtypelib
#include "wbemdisp.idl"
| {
"pile_set_name": "Github"
} |
/*
* This file is part of "SnipSnap Radeox Rendering Engine".
*
* Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
* All Rights Reserved.
*
* Please visit http://radeox.org/ for updates and contact.
*
* --LICENSE NOTICE--
* 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.
* --LICENSE NOTICE--
*/
package org.radeox.filter.context;
/**
* InitialFilterContext is used to give the filter information after it's
* startup (e.g. locales)
*
* @author Stephan J. Schmidt
* @version $Id: InitialFilterContext.java 7707 2006-04-12 17:30:19Z
* [email protected] $
*/
public interface InitialFilterContext
{
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.util.generator.opencl.CLDeviceExtension;
@CLDeviceExtension
public interface KHR_3d_image_writes {
} | {
"pile_set_name": "Github"
} |
(* TEST
* toplevel
*)
(* Correct escapes and their encoding *)
let () =
assert ("\xF0\x9F\x90\xAB" = "\u{1F42B}");
assert ("\xF0\x9F\x90\xAB" = "\u{01F42B}");
assert ("\x00" = "\u{0}");
assert ("\x00" = "\u{00}");
assert ("\x00" = "\u{000}");
assert ("\x00" = "\u{0000}");
assert ("\x00" = "\u{00000}");
assert ("\x00" = "\u{000000}");
assert ("\xC3\xA9" = "\u{E9}");
assert ("\xC3\xA9" = "\u{0E9}");
assert ("\xC3\xA9" = "\u{00E9}");
assert ("\xC3\xA9" = "\u{000E9}");
assert ("\xC3\xA9" = "\u{0000E9}");
assert ("\xC3\xA9" = "\u{0000E9}");
assert ("\xF4\x8F\xBF\xBF" = "\u{10FFFF}");
()
;;
(* Errors *)
let invalid_sv = "\u{0D800}" ;;
let invalid_sv = "\u{D800}" ;;
let invalid_sv = "\u{D900}" ;;
let invalid_sv = "\u{DFFF}" ;;
let invalid_sv = "\u{110000} ;;
let too_many_digits = "\u{01234567}" ;;
let no_hex_digits = "\u{}" ;;
let illegal_hex_digit = "\u{u}" ;;
| {
"pile_set_name": "Github"
} |
@echo off
pyinstaller --noconfirm artisan-win.spec
rem #
rem # Don't make assumptions as to where the 'makensis.exe' is - look in the obvious places
rem #
if exist "C:\Program Files (x86)\NSIS\makensis.exe" set NSIS_EXE="C:\Program Files (x86)\NSIS\makensis.exe"
if exist "C:\Program Files\NSIS\makensis.exe" set NSIS_EXE="C:\Program Files\NSIS\makensis.exe"
if exist "%ProgramFiles%\NSIS\makensis.exe" set NSIS_EXE="%ProgramFiles%\NSIS\makensis.exe"
if exist "%ProgramFiles(x86)%\NSIS\makensis.exe" set NSIS_EXE="%ProgramFiles(x86)%\NSIS\makensis.exe"
rem #
rem #
rem #
%NSIS_EXE% setup-install3-pi.nsi
| {
"pile_set_name": "Github"
} |
require 'aws-sdk-apigateway'
require 'aws-sdk-cloudformation'
STAGE_NAME = "<%= @stage_name %>"
def lambda_handler(event:, context:)
puts("event['RequestType'] #{event['RequestType']}")
puts("event: #{JSON.dump(event)}")
puts("context: #{JSON.dump(context)}")
puts("context.log_stream_name #{context.log_stream_name.inspect}")
mimic = event['ResourceProperties']['Mimic']
physical_id = event['ResourceProperties']['PhysicalId'] || "PhysicalId"
puts "mimic: #{mimic}"
puts "physical_id: #{physical_id}"
if event['RequestType'] == 'Delete'
if mimic == 'FAILED'
send_response(event, context, "FAILED")
else
mapping = BasePathMapping.new(event)
mapping.delete(true) if mapping.should_delete?
send_response(event, context, "SUCCESS")
end
return # early return
end
mapping = BasePathMapping.new(event)
mapping.update
response_status = mimic == "FAILED" ? "FAILED" : "SUCCESS"
response_data = { "Hello" => "World" }
send_response(event, context, response_status, response_data, physical_id)
# We rescue all exceptions and send an message to CloudFormation so we dont have to
# wait for over an hour for the stack operation to timeout and rollback.
rescue Exception => e
puts e.message
puts e.backtrace
sleep 10 # provide delete to make sure that the log gets sent to CloudWatch
send_response(event, context, "FAILED")
end
def send_response(event, context, response_status, response_data={}, physical_id="PhysicalId")
response_body = JSON.dump(
Status: response_status,
Reason: "See the details in CloudWatch Log Stream: #{context.log_stream_name.inspect}",
PhysicalResourceId: physical_id,
StackId: event['StackId'],
RequestId: event['RequestId'],
LogicalResourceId: event['LogicalResourceId'],
Data: response_data
)
puts "RESPONSE BODY:\n"
puts response_body
url = event['ResponseURL']
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = http.read_timeout = 30
http.use_ssl = true if uri.scheme == 'https'
# must used url to include the AWSAccessKeyId and Signature
req = Net::HTTP::Put.new(url) # url includes query string and uri.path does not, must used url t
req.body = response_body
req.content_length = response_body.bytesize
# set headers
req['content-type'] = ''
req['content-length'] = response_body.bytesize
res = http.request(req)
puts "status code: #{res.code}"
puts "headers: #{res.each_header.to_h.inspect}"
puts "body: #{res.body}"
end
class BasePathMapping
def initialize(event)
@event = event
@rest_api_id = get_rest_api_id
@domain_name = get_domain_name
@base_path = ''
end
def update
# Cannot use update_base_path_mapping to update the base_mapping because it doesnt
# allow us to change the rest_api_id. So we delete and create.
delete(true)
create
end
# Dont delete the newly created base path mapping unless this is an operation
# where we're fully deleting the stack
def should_delete?
deleting_parent?
end
def delete(fail_silently=false)
apigateway.delete_base_path_mapping(
domain_name: @domain_name, # required
base_path: '(none)',
)
# https://github.com/tongueroo/jets/issues/255
# Used to return: Aws::APIGateway::Errors::NotFoundException
# Now returns: Aws::APIGateway::Errors::InternalFailure
# So we'll use a more generic error
rescue Aws::APIGateway::Errors::ServiceError => e
raise(e) unless fail_silently
end
def create
apigateway.create_base_path_mapping(
domain_name: @domain_name, # required
base_path: @base_path,
rest_api_id: @rest_api_id, # required
stage: STAGE_NAME,
)
end
def get_domain_name
param = deployment_stack[:parameters].find { |p| p.parameter_key == 'DomainName' }
param.parameter_value
end
def deployment_stack
@deployment_stack ||= cfn.describe_stacks(stack_name: @event['StackId']).stacks.first
end
def get_rest_api_id
param = deployment_stack[:parameters].find { |p| p.parameter_key == 'RestApi' }
param.parameter_value
end
def deleting_parent?
stack = cfn.describe_stacks(stack_name: parent_stack_name).stacks.first
stack.stack_status == 'DELETE_IN_PROGRESS'
end
def parent_stack_name
deployment_stack[:root_id]
end
private
def apigateway
@apigateway ||= Aws::APIGateway::Client.new
end
def cfn
@cfn ||= Aws::CloudFormation::Client.new
end
end
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.