answer
stringlengths
15
1.25M
#pragma once #include <drizzled/nested_join.h> #include <drizzled/table.h> namespace drizzled { /** * A Table referenced in the FROM clause. * * These table references can be of several types that correspond to * different SQL elements. Below we list all types of TableLists with * the necessary conditions to determine when a TableList instance * belongs to a certain type. * * 1) table (TableList::view == NULL) * - base table * (TableList::derived == NULL) * - subquery - TableList::table is a temp table * (TableList::derived != NULL) * * @note * * for schema tables TableList::field_translation may be != NULL * * 2) Was VIEW * 3) nested table reference (TableList::nested_join != NULL) * - table sequence - e.g. (t1, t2, t3) * @todo how to distinguish from a JOIN? * - general JOIN * @todo how to distinguish from a table sequence? * - NATURAL JOIN * (TableList::natural_join != NULL) * - JOIN ... USING * (TableList::join_using_fields != NULL) * - semi-join */ class TableList { public: TableList(): next_local(NULL), next_global(NULL), prev_global(NULL), schema(NULL), alias(NULL), table_name(NULL), option(NULL), on_expr(NULL), table(NULL), prep_on_expr(NULL), cond_equal(NULL), natural_join(NULL), is_natural_join(false), <API key>(false), straight(false), force_index(false), ignore_leaves(false), join_using_fields(NULL), join_columns(NULL), <API key>(NULL), index_hints(NULL), derived_result(NULL), derived(NULL), schema_select_lex(NULL), select_lex(NULL), next_leaf(NULL), outer_join(0), dep_tables(0), on_expr_dep_tables(0), nested_join(NULL), embedding(NULL), join_list(NULL), db_type(NULL), internal_tmp_table(false), is_alias(false), is_fqtn(false), create(false) { } /** * List of tables local to a subquery (used by SQL_LIST). Considers * views as leaves (unlike 'next_leaf' below). Created at parse time * in Select_Lex::add_table_to_list() -> table_list.link_in_list(). */ TableList *next_local; /** link in a global list of all queries tables */ TableList *next_global; TableList **prev_global; private: const char* schema; public: const char *getSchemaName() const { return schema; } void setSchemaName(const char* v) { schema= v; } const char *alias; private: const char* table_name; public: const char *getTableName() const { return table_name; } void setTableName(const char* v) { table_name= v; } const char *option; ///< Used by cache index Item *on_expr; ///< Used with outer join Table *table; ///< opened table /** * The structure of ON expression presented in the member above * can be changed during certain optimizations. This member * contains a snapshot of AND-OR structure of the ON expression * made after permanent transformations of the parse tree, and is * used to restore ON clause before every reexecution of a prepared * statement or stored procedure. */ Item *prep_on_expr; COND_EQUAL *cond_equal; ///< Used with outer join /** * During parsing - left operand of NATURAL/USING join where 'this' is * the right operand. After parsing (this->natural_join == this) iff * 'this' represents a NATURAL or USING join operation. Thus after * parsing 'this' is a NATURAL/USING join iff (natural_join != NULL). */ TableList *natural_join; /** * True if 'this' represents a nested join that is a NATURAL JOIN. * For one of the operands of 'this', the member 'natural_join' points * to the other operand of 'this'. */ bool is_natural_join; /** true if join_columns contains all columns of this table reference. */ bool <API key>; bool straight; ///< optimize with prev table bool force_index; ///< prefer index over table scan bool ignore_leaves; ///< preload only non-leaf nodes /* is the table a cartesian join, assumption is yes unless "solved" */ bool isCartesian() const; /** Field names in a USING clause for JOIN ... USING. */ List<String> *join_using_fields; /** * Explicitly store the result columns of either a NATURAL/USING join or * an operand of such a join. */ List<Natural_join_column> *join_columns; /** * List of nodes in a nested join tree, that should be considered as * leaves with respect to name resolution. The leaves are: views, * top-most nodes representing NATURAL/USING joins, subqueries, and * base tables. All of these TableList instances contain a * materialized list of columns. The list is local to a subquery. */ TableList *<API key>; /** Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */ List<Index_hint> *index_hints; /** * select_result for derived table to pass it from table creation to table * filling procedure */ select_union *derived_result; Select_Lex_Unit *derived; ///< Select_Lex_Unit of derived table */ Select_Lex *schema_select_lex; /** link to select_lex where this table was used */ Select_Lex *select_lex; /** * List of all base tables local to a subquery including all view * tables. Unlike 'next_local', this in this list views are *not* * leaves. Created in setup_tables() -> make_leaves_list(). */ TableList *next_leaf; thr_lock_type lock_type; uint32_t outer_join; ///< Which join type void <API key>(); bool setup_underlying(Session *session); /** * If you change placeholder(), please check the condition in * <API key>() too. */ bool placeholder(); /** * Print table as it should be in join list. * * @param str string where table should be printed */ void print(Session *session, String *str); /** * Sets insert_values buffer * * @param[in] memory pool for allocating * * @retval * false - OK * @retval * true - out of memory */ void set_insert_values(); /** * Find underlying base tables (TableList) which represent given * table_to_find (Table) * * @param[in] table to find * * @retval * NULL if table is not found * @retval * Pointer to found table reference */ TableList *<API key>(Table *table); /** * Retrieve the first (left-most) leaf in a nested join tree with * respect to name resolution. * * @details * * Given that 'this' is a nested table reference, recursively walk * down the left-most children of 'this' until we reach a leaf * table reference with respect to name resolution. * * @retval * If 'this' is a nested table reference - the left-most child of * the tree rooted in 'this', * else return 'this' */ TableList *<API key>(); /** * Retrieve the last (right-most) leaf in a nested join tree with * respect to name resolution. * * @details * * Given that 'this' is a nested table reference, recursively walk * down the right-most children of 'this' until we reach a leaf * table reference with respect to name resolution. * * @retval * If 'this' is a nested table reference - the right-most child of * the tree rooted in 'this', * else 'this' */ TableList *<API key>(); /** * Test if this is a leaf with respect to name resolution. * * @details * * A table reference is a leaf with respect to name resolution if * it is either a leaf node in a nested join tree (table, view, * schema table, subquery), or an inner node that represents a * NATURAL/USING join, or a nested join with materialized join * columns. * * @retval * true if a leaf, false otherwise. */ bool <API key>() const; inline TableList *top_table() { return this; } /** * Return subselect that contains the FROM list this table is taken from * * @retval * Subselect item for the subquery that contains the FROM list * this table is taken from if there is any * @retval * NULL otherwise */ Item_subselect *<API key>(); /** * Compiles the tagged hints list and fills up st_table::<API key>, * st_table::<API key>, st_table::<API key>, * st_table::force_index and st_table::covering_keys. * * @param the Table to operate on. * * @details * * The parser collects the index hints for each table in a "tagged list" * (TableList::index_hints). Using the information in this tagged list * this function sets the members Table::<API key>, * Table::<API key>, Table::<API key>, * Table::force_index and Table::covering_keys. * * Current implementation of the runtime does not allow mixing FORCE INDEX * and USE INDEX, so this is checked here. Then the FORCE INDEX list * (if non-empty) is appended to the USE INDEX list and a flag is set. * * Multiple hints of the same kind are processed so that each clause * is applied to what is computed in the previous clause. * * For example: * USE INDEX (i1) USE INDEX (i2) * is equivalent to * USE INDEX (i1,i2) * and means "consider only i1 and i2". * * Similarly * USE INDEX () USE INDEX (i1) * is equivalent to * USE INDEX (i1) * and means "consider only the index i1" * * It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is * not an error. * * Different kind of hints (USE/FORCE/IGNORE) are processed in the following * order: * 1. All indexes in USE (or FORCE) INDEX are added to the mask. * 2. All IGNORE INDEX * e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all * as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1". * As an optimization if there is a covering index, and we have * IGNORE INDEX FOR GROUP/order_st, and this index is used for the JOIN part, * then we have to ignore the IGNORE INDEX FROM GROUP/order_st. * * @retval * false no errors found * @retval * true found and reported an error. */ bool process_index_hints(Table *table); friend std::ostream& operator<<(std::ostream& output, const TableList &list) { output << "TableList:("; output << list.getSchemaName(); output << ", "; output << list.getTableName(); output << ", "; output << list.alias; output << ", "; output << "is_natural_join:" << list.is_natural_join; output << ", "; output << "<API key>:" << list.<API key>; output << ", "; output << "straight:" << list.straight; output << ", "; output << "force_index" << list.force_index; output << ", "; output << "ignore_leaves:" << list.ignore_leaves; output << ", "; output << "create:" << list.create; output << ", "; output << "outer_join:" << list.outer_join; output << ", "; output << "nested_join:" << list.nested_join; output << ")"; return output; // for multiple << operators. } void setIsAlias(bool in_is_alias) { is_alias= in_is_alias; } void setIsFqtn(bool in_is_fqtn) { is_fqtn= in_is_fqtn; } void setCreate(bool in_create) { create= in_create; } void setInternalTmpTable(bool <API key>) { internal_tmp_table= <API key>; } void setDbType(plugin::StorageEngine *in_db_type) { db_type= in_db_type; } void setJoinList(List<TableList> *in_join_list) { join_list= in_join_list; } void setEmbedding(TableList *in_embedding) { embedding= in_embedding; } void setNestedJoin(NestedJoin *in_nested_join) { nested_join= in_nested_join; } void setDepTables(table_map in_dep_tables) { dep_tables= in_dep_tables; } void setOnExprDepTables(table_map <API key>) { on_expr_dep_tables= <API key>; } bool getIsAlias() const { return is_alias; } bool getIsFqtn() const { return is_fqtn; } bool isCreate() const { return create; } bool getInternalTmpTable() const { return internal_tmp_table; } plugin::StorageEngine *getDbType() const { return db_type; } TableList *getEmbedding() const { return embedding; } List<TableList> *getJoinList() const { return join_list; } NestedJoin *getNestedJoin() const { return nested_join; } table_map getDepTables() const { return dep_tables; } table_map getOnExprDepTables() const { return on_expr_dep_tables; } void unlock_table_name(); void unlock_table_names(TableList *last_table= NULL); private: table_map dep_tables; ///< tables the table depends on table_map on_expr_dep_tables; ///< tables on expression depends on NestedJoin *nested_join; ///< if the element is a nested join TableList *embedding; ///< nested join containing the table List<TableList> *join_list; ///< join list the table belongs to plugin::StorageEngine *db_type; ///< table_type for handler bool internal_tmp_table; /** true if an alias for this table was specified in the SQL. */ bool is_alias; /** * true if the table is referred to in the statement using a fully * qualified name (<db_name>.<table_name>). */ bool is_fqtn; /** * This TableList object corresponds to the table to be created * so it is possible that it does not exist (used in CREATE TABLE * ... SELECT implementation). */ bool create; }; void close_thread_tables(Session *session); } /* namespace drizzled */
/** * @file * memory handling functions */ #ifndef AVUTIL_MEM_H #define AVUTIL_MEM_H #include <limits.h> #include <stdint.h> #include "attributes.h" #include "avutil.h" /** * @addtogroup lavu_mem * @{ */ #if defined(__ICC) && __ICC < 1200 || defined(__SUNPRO_C) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) const t __attribute__ ((aligned (n))) v #elif defined(<API key>) #define DECLARE_ALIGNED(n,t,v) \ AV_PRAGMA(DATA_ALIGN(v,n)) \ t __attribute__((aligned(n))) v #define DECLARE_ASM_CONST(n,t,v) \ AV_PRAGMA(DATA_ALIGN(v,n)) \ static const t __attribute__((aligned(n))) v #elif defined(__GNUC__) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (n))) v #elif defined(_MSC_VER) #define DECLARE_ALIGNED(n,t,v) __declspec(align(n)) t v #define DECLARE_ASM_CONST(n,t,v) __declspec(align(n)) static const t v #else #define DECLARE_ALIGNED(n,t,v) t v #define DECLARE_ASM_CONST(n,t,v) static const t v #endif #if <API key>(3,1) #define av_malloc_attrib __attribute__((__malloc__)) #else #define av_malloc_attrib #endif #if <API key>(4,3) #define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__))) #else #define av_alloc_size(...) #endif /** * Allocate a block of size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU). * @param size Size in bytes for the memory block to be allocated. * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_mallocz() */ void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1); /** * Allocate a block of size * nmemb bytes with av_malloc(). * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_malloc() */ av_alloc_size(1, 2) static inline void *av_malloc_array(size_t nmemb, size_t size) { if (size <= 0 || nmemb >= INT_MAX / size) return NULL; return av_malloc(nmemb * size); } /** * Allocate or reallocate a block of memory. * If ptr is NULL and size > 0, allocate a new block. If * size is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a memory block already allocated with * av_realloc() or NULL. * @param size Size in bytes of the memory block to be allocated or * reallocated. * @return Pointer to a newly-reallocated block or NULL if the block * cannot be reallocated or the function is used to free the memory block. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_realloc(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. * @see av_fast_realloc() */ void *av_realloc(void *ptr, size_t size) av_alloc_size(2); /** * Allocate or reallocate a block of memory. * If *ptr is NULL and size > 0, allocate a new block. If * size is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a pointer to a memory block already allocated * with av_realloc(), or pointer to a pointer to NULL. * The pointer is updated on success, or freed on failure. * @param size Size in bytes for the memory block to be allocated or * reallocated * @return Zero on success, an AVERROR error code on failure. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_reallocp(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. */ int av_reallocp(void *ptr, size_t size); /** * Allocate or reallocate an array. * If ptr is NULL and nmemb > 0, allocate a new block. If * nmemb is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a memory block already allocated with * av_realloc() or NULL. * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to a newly-reallocated block or NULL if the block * cannot be reallocated or the function is used to free the memory block. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_realloc(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. */ av_alloc_size(2, 3) void *av_realloc_array(void *ptr, size_t nmemb, size_t size); /** * Allocate or reallocate an array through a pointer to a pointer. * If *ptr is NULL and nmemb > 0, allocate a new block. If * nmemb is zero, free the memory block pointed to by ptr. * @param ptr Pointer to a pointer to a memory block already allocated * with av_realloc(), or pointer to a pointer to NULL. * The pointer is updated on success, or freed on failure. * @param nmemb Number of elements * @param size Size of the single element * @return Zero on success, an AVERROR error code on failure. * @warning Pointers originating from the av_malloc() family of functions must * not be passed to av_realloc(). The former can be implemented using * memalign() (or other functions), and there is no guarantee that * pointers from such functions can be passed to realloc() at all. * The situation is undefined according to POSIX and may crash with * some libc implementations. */ av_alloc_size(2, 3) int av_reallocp_array(void *ptr, size_t nmemb, size_t size); /** * Free a memory block which has been allocated with av_malloc(z)() or * av_realloc(). * @param ptr Pointer to the memory block which should be freed. * @note ptr = NULL is explicitly allowed. * @note It is recommended that you use av_freep() instead. * @see av_freep() */ void av_free(void *ptr); /** * Allocate a block of size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU) and * zero all the bytes of the block. * @param size Size in bytes for the memory block to be allocated. * @return Pointer to the allocated block, NULL if it cannot be allocated. * @see av_malloc() */ void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1); /** * Allocate a block of size * nmemb bytes with av_mallocz(). * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_mallocz() * @see av_malloc_array() */ av_alloc_size(1, 2) static inline void *av_mallocz_array(size_t nmemb, size_t size) { if (size <= 0 || nmemb >= INT_MAX / size) return NULL; return av_mallocz(nmemb * size); } /** * Duplicate the string s. * @param s string to be duplicated * @return Pointer to a newly-allocated string containing a * copy of s or NULL if the string cannot be allocated. */ char *av_strdup(const char *s) av_malloc_attrib; /** * Free a memory block which has been allocated with av_malloc(z)() or * av_realloc() and set the pointer pointing to it to NULL. * @param ptr Pointer to the pointer to the memory block which should * be freed. * @see av_free() */ void av_freep(void *ptr); /** * deliberately overlapping memcpy implementation * @param dst destination buffer * @param back how many bytes back we start (the initial size of the overlapping window) * @param cnt number of bytes to copy, must be >= 0 * * cnt > back is valid, this will copy the bytes we just copied, * thus creating a repeating pattern with a period length of back. */ void av_memcpy_backptr(uint8_t *dst, int back, int cnt); #endif /* AVUTIL_MEM_H */
#ifndef _ZEBRA_CONNECTED_H #define _ZEBRA_CONNECTED_H #include <zebra.h> #include <stdint.h> #include "lib/if.h" #include "lib/prefix.h" #ifdef __cplusplus extern "C" { #endif extern struct connected *connected_check(struct interface *ifp, union prefixconstptr p); extern struct connected *connected_check_ptp(struct interface *ifp, union prefixconstptr p, union prefixconstptr d); extern void connected_add_ipv4(struct interface *ifp, int flags, const struct in_addr *addr, uint16_t prefixlen, const struct in_addr *dest, const char *label, uint32_t metric); extern void <API key>(struct interface *ifp, int flags, const struct in_addr *addr, uint16_t prefixlen, const struct in_addr *dest); extern void <API key>(struct connected *ifc); extern void connected_up(struct interface *ifp, struct connected *ifc); extern void connected_down(struct interface *ifp, struct connected *ifc); extern void connected_add_ipv6(struct interface *ifp, int flags, const struct in6_addr *address, const struct in6_addr *dest, uint16_t prefixlen, const char *label, uint32_t metric); extern void <API key>(struct interface *ifp, const struct in6_addr *address, const struct in6_addr *dest, uint16_t prefixlen); extern int <API key>(struct interface *); #ifdef __cplusplus } #endif #endif /*_ZEBRA_CONNECTED_H */
! { dg-do compile } ! { dg-options "-fdump-tree-original" } ! ! PR fortran/56907 ! subroutine sub(xxx, yyy) use iso_c_binding implicit none integer, target, contiguous :: xxx(:) integer, target :: yyy(:) type(c_ptr) :: ptr1, ptr2, ptr3, ptr4 ptr1 = c_loc (xxx) ptr2 = c_loc (xxx(5:)) ptr3 = c_loc (yyy) ptr4 = c_loc (yyy(5:)) end ! { dg-final { scan-tree-dump-not " <API key>" "original" } } ! { dg-final { <API key> "parm.\[0-9\]+.data = \\(void .\\) &\\(.xxx.\[0-9\]+\\)\\\[0\\\];" 1 "original" } } ! { dg-final { <API key> "parm.\[0-9\]+.data = \\(void .\\) &\\(.xxx.\[0-9\]+\\)\\\[D.\[0-9\]+ \\* 4\\\];" 1 "original" } } ! { dg-final { <API key> "parm.\[0-9\]+.data = \\(void .\\) &\\(.yyy.\[0-9\]+\\)\\\[0\\\];" 1 "original" } } ! { dg-final { <API key> "parm.\[0-9\]+.data = \\(void .\\) &\\(.yyy.\[0-9\]+\\)\\\[D.\[0-9\]+ \\* 4\\\];" 1 "original" } } ! { dg-final { <API key> "D.\[0-9\]+ = parm.\[0-9\]+.data;\[^;]+ptr\[1-4\] = D.\[0-9\]+;" 4 "original" } } ! { dg-final { cleanup-tree-dump "optimized" } }
# This program is free software; you can redistribute it and/or modify # (at your option) any later version. # This program is distributed in the hope that it will be useful, but # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Module for object related utils.""" #: Supported container types for serialization/de-serialization (must be a #: tuple as it's used as a parameter for C{isinstance}) _SEQUENCE_TYPES = (list, tuple, set, frozenset) class AutoSlots(type): """Meta base class for __slots__ definitions. """ def __new__(mcs, name, bases, attrs): """Called when a class should be created. @param mcs: The meta class @param name: Name of created class @param bases: Base classes @type attrs: dict @param attrs: Class attributes """ assert "__slots__" not in attrs, \ "Class '%s' defines __slots__ when it should not" % name attrs["__slots__"] = mcs._GetSlots(attrs) return type.__new__(mcs, name, bases, attrs) @classmethod def _GetSlots(mcs, attrs): """Used to get the list of defined slots. @param attrs: The attributes of the class """ raise NotImplementedError class ValidatedSlots(object): """Sets and validates slots. """ __slots__ = [] def __init__(self, **kwargs): """Constructor for BaseOpCode. The constructor takes only keyword arguments and will set attributes on this object based on the passed arguments. As such, it means that you should not pass arguments which are not in the __slots__ attribute for this class. """ slots = self.GetAllSlots() for (key, value) in kwargs.items(): if key not in slots: raise TypeError("Object %s doesn't support the parameter '%s'" % (self.__class__.__name__, key)) setattr(self, key, value) @classmethod def GetAllSlots(cls): """Compute the list of all declared slots for a class. """ slots = [] for parent in cls.__mro__: slots.extend(getattr(parent, "__slots__", [])) return slots def Validate(self): """Validates the slots. This method must be implemented by the child classes. """ raise NotImplementedError def ContainerToDicts(container): """Convert the elements of a container to standard Python types. This method converts a container with elements to standard Python types. If the input container is of the type C{dict}, only its values are touched. Those values, as well as all elements of input sequences, must support a C{ToDict} method returning a serialized version. @type container: dict or sequence (see L{_SEQUENCE_TYPES}) """ if isinstance(container, dict): ret = dict([(k, v.ToDict()) for k, v in container.items()]) elif isinstance(container, _SEQUENCE_TYPES): ret = [elem.ToDict() for elem in container] else: raise TypeError("Unknown container type '%s'" % type(container)) return ret def ContainerFromDicts(source, c_type, e_type): """Convert a container from standard python types. This method converts a container with standard Python types to objects. If the container is a dict, we don't touch the keys, only the values. @type source: None, dict or sequence (see L{_SEQUENCE_TYPES}) @param source: Input data @type c_type: type class @param c_type: Desired type for returned container @type e_type: element type class @param e_type: Item type for elements in returned container (must have a C{FromDict} class method) """ if not isinstance(c_type, type): raise TypeError("Container type '%s' is not a type" % type(c_type)) if source is None: source = c_type() if c_type is dict: ret = dict([(k, e_type.FromDict(v)) for k, v in source.items()]) elif c_type in _SEQUENCE_TYPES: ret = c_type(map(e_type.FromDict, source)) else: raise TypeError("Unknown container type '%s'" % c_type) return ret
#ifndef <API key> #define <API key> #include "Common/Error.h" #include "AsyncComm/CommBuf.h" #include "AsyncComm/ResponseCallback.h" namespace Hyperspace { class <API key> : public Hypertable::ResponseCallback { public: <API key>(Hypertable::Comm *comm, Hypertable::EventPtr &event_ptr) : Hypertable::ResponseCallback(comm, event_ptr) { } int response(uint32_t status, uint64_t lock_generation=0); }; } #endif // <API key>
/* ScriptData Name: gps_commandscript %Complete: 100 Comment: GPS/WPGPS commands Category: commandscripts EndScriptData */ #include "ObjectAccessor.h" #include "ScriptMgr.h" #include "Chat.h" #include "CellImpl.h" class gps_commandscript : public CommandScript { public: gps_commandscript() : CommandScript("gps_commandscript") { } ChatCommand* GetCommands() const { static ChatCommand commandTable[] = { { "gps", SEC_ADMINISTRATOR, false, &HandleGPSCommand, "", NULL }, { "wpgps", SEC_ADMINISTRATOR, false, &HandleWPGPSCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; return commandTable; } static bool HandleGPSCommand(ChatHandler* handler, const char *args) { WorldObject* obj = NULL; if (*args) { uint64 guid = handler->extractGuidFromLink((char*)args); if (guid) obj = (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*handler->GetSession()->GetPlayer(), guid, TYPEMASK_UNIT|TYPEMASK_GAMEOBJECT); if (!obj) { handler->SendSysMessage(<API key>); handler->SetSentErrorMessage(true); return false; } } else { obj = handler->getSelectedUnit(); if (!obj) { handler->SendSysMessage(<API key>); handler->SetSentErrorMessage(true); return false; } } CellCoord cell_val = Trinity::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY()); Cell cell(cell_val); uint32 zone_id, area_id; obj->GetZoneAndAreaId(zone_id, area_id); MapEntry const* mapEntry = sMapStore.LookupEntry(obj->GetMapId()); AreaTableEntry const* zoneEntry = <API key>(zone_id); AreaTableEntry const* areaEntry = <API key>(area_id); float zone_x = obj->GetPositionX(); float zone_y = obj->GetPositionY(); Map2ZoneCoordinates(zone_x, zone_y, zone_id); Map const* map = obj->GetMap(); float ground_z = map->GetHeight(obj->GetPositionX(), obj->GetPositionY(), MAX_HEIGHT); float floor_z = map->GetHeight(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ()); GridCoord p = Trinity::ComputeGridCoord(obj->GetPositionX(), obj->GetPositionY()); // 63? WHY? int gx = 63 - p.x_coord; int gy = 63 - p.y_coord; uint32 have_map = Map::ExistMap(obj->GetMapId(), gx, gy) ? 1 : 0; uint32 have_vmap = Map::ExistVMap(obj->GetMapId(), gx, gy) ? 1 : 0; if (have_vmap) { if (map->IsOutdoors(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ())) handler->PSendSysMessage("You are outdoors"); else handler->PSendSysMessage("You are indoors"); } else handler->PSendSysMessage("no VMAP available for area info"); handler->PSendSysMessage(LANG_MAP_POSITION, obj->GetMapId(), (mapEntry ? mapEntry->name[handler->GetSessionDbcLocale()] : "<unknown>"), zone_id, (zoneEntry ? zoneEntry->area_name[handler->GetSessionDbcLocale()] : "<unknown>"), area_id, (areaEntry ? areaEntry->area_name[handler->GetSessionDbcLocale()] : "<unknown>"), obj->GetPhaseMask(), obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), obj->GetOrientation(), cell.GridX(), cell.GridY(), cell.CellX(), cell.CellY(), obj->GetInstanceId(), zone_x, zone_y, ground_z, floor_z, have_map, have_vmap); LiquidData liquid_status; ZLiquidStatus res = map->getLiquidStatus(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), MAP_ALL_LIQUIDS, &liquid_status); if (res) { handler->PSendSysMessage(LANG_LIQUID_STATUS, liquid_status.level, liquid_status.depth_level, liquid_status.type, res); } return true; } static bool HandleWPGPSCommand(ChatHandler* handler, const char* /*args*/) { Player* player = handler->GetSession()->GetPlayer(); sLog->outSQLDev("(@PATH, XX, %.3f, %.3f, %.5f, 0,0, 0,100, 0),", player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); handler->PSendSysMessage("Waypoint SQL written to SQL Developer log"); return true; } }; void <API key>() { new gps_commandscript(); }
#include <errno.h> #ifndef __PACKET_H__ #define __PACKET_H__ #include "nic.h" struct nic; struct nic_interface; typedef struct packet { struct packet *next; uint32_t flags; #define VLAN_TAGGED 0x0001 uint16_t vlan_tag; size_t max_buf_size; size_t buf_size; uint8_t *data_link_layer; uint8_t *network_layer; struct nic *nic; struct nic_interface *nic_iface; void *priv; uint8_t buf[]; } packet_t; int alloc_free_queue(struct nic *, size_t num_of_packets); void free_free_queue(struct nic *); void reset_packet(packet_t *pkt); #endif /* __PACKET_H__ */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ #include <glib.h> #include <glib/gi18n.h> #include <dbus/dbus.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include "nm-dhcp-dhcpcd.h" #include "nm-utils.h" #include "nm-logging.h" G_DEFINE_TYPE (NMDHCPDhcpcd, nm_dhcp_dhcpcd, NM_TYPE_DHCP_CLIENT) #define <API key>(o) (<API key> ((o), NM_TYPE_DHCP_DHCPCD, NMDHCPDhcpcdPrivate)) #define ACTION_SCRIPT_PATH LIBEXECDIR "/nm-dhcp-client.action" typedef struct { const char *path; char *pid_file; } NMDHCPDhcpcdPrivate; const char * <API key> (const char *try_first) { static const char *dhcpcd_paths[] = { "/sbin/dhcpcd", "/usr/sbin/dhcpcd", "/usr/pkg/sbin/dhcpcd", "/usr/local/sbin/dhcpcd", NULL }; const char **path = dhcpcd_paths; if (strlen (try_first) && g_file_test (try_first, G_FILE_TEST_EXISTS)) return try_first; while (*path != NULL) { if (g_file_test (*path, G_FILE_TEST_EXISTS)) break; path++; } return *path; } GSList * <API key> (const char *iface, const char *uuid) { return NULL; } static void dhcpcd_child_setup (gpointer user_data G_GNUC_UNUSED) { /* We are in the child process at this point */ pid_t pid = getpid (); setpgid (pid, pid); } static GPid real_ip4_start (NMDHCPClient *client, NMSettingIP4Config *s_ip4, guint8 *dhcp_anycast_addr, const char *hostname) { NMDHCPDhcpcdPrivate *priv = <API key> (client); GPtrArray *argv = NULL; GPid pid = -1; GError *error = NULL; char *pid_contents = NULL, *binary_name, *cmd_str; const char *iface, *uuid; <API key> (priv->pid_file == NULL, -1); iface = <API key> (client); uuid = <API key> (client); priv->pid_file = g_strdup_printf (LOCALSTATEDIR "/run/dhcpcd-%s.pid", iface); if (!priv->pid_file) { nm_log_warn (LOGD_DHCP4, "(%s): not enough memory for dhcpcd options.", iface); return -1; } if (!g_file_test (priv->path, G_FILE_TEST_EXISTS)) { nm_log_warn (LOGD_DHCP4, "%s does not exist.", priv->path); return -1; } /* Kill any existing dhcpcd from the pidfile */ binary_name = g_path_get_basename (priv->path); <API key> (priv->pid_file, binary_name); g_free (binary_name); argv = g_ptr_array_new (); g_ptr_array_add (argv, (gpointer) priv->path); g_ptr_array_add (argv, (gpointer) "-B"); /* Don't background on lease (disable fork()) */ g_ptr_array_add (argv, (gpointer) "-K"); /* Disable built-in carrier detection */ g_ptr_array_add (argv, (gpointer) "-L"); /* Disable built-in IPv4LL since we use avahi-autoipd */ g_ptr_array_add (argv, (gpointer) "-G"); /* Let NM handle routing */ g_ptr_array_add (argv, (gpointer) "-c"); /* Set script file */ g_ptr_array_add (argv, (gpointer) ACTION_SCRIPT_PATH ); if (hostname && strlen (hostname)) { g_ptr_array_add (argv, (gpointer) "-h"); /* Send hostname to DHCP server */ g_ptr_array_add (argv, (gpointer) hostname ); } g_ptr_array_add (argv, (gpointer) iface); g_ptr_array_add (argv, NULL); cmd_str = g_strjoinv (" ", (gchar **) argv->pdata); nm_log_dbg (LOGD_DHCP4, "running: %s", cmd_str); g_free (cmd_str); if (!g_spawn_async (NULL, (char **) argv->pdata, NULL, <API key>, &dhcpcd_child_setup, NULL, &pid, &error)) { nm_log_warn (LOGD_DHCP4, "dhcpcd failed to start. error: '%s'", error->message); g_error_free (error); pid = -1; } else nm_log_info (LOGD_DHCP4, "dhcpcd started with pid %d", pid); g_free (pid_contents); g_ptr_array_free (argv, TRUE); return pid; } static GPid real_ip6_start (NMDHCPClient *client, NMSettingIP6Config *s_ip6, guint8 *dhcp_anycast_addr, const char *hostname, gboolean info_only) { nm_log_warn (LOGD_DHCP6, "the dhcpcd backend does not support IPv6."); return -1; } static void real_stop (NMDHCPClient *client, gboolean release) { NMDHCPDhcpcdPrivate *priv = <API key> (client); /* Chain up to parent */ <API key> (<API key>)->stop (client, release); if (priv->pid_file) remove (priv->pid_file); /* FIXME: implement release... */ } static void nm_dhcp_dhcpcd_init (NMDHCPDhcpcd *self) { NMDHCPDhcpcdPrivate *priv = <API key> (self); priv->path = <API key> (DHCPCD_PATH); } static void dispose (GObject *object) { NMDHCPDhcpcdPrivate *priv = <API key> (object); g_free (priv->pid_file); G_OBJECT_CLASS (<API key>)->dispose (object); } static void <API key> (NMDHCPDhcpcdClass *dhcpcd_class) { NMDHCPClientClass *client_class = <API key> (dhcpcd_class); GObjectClass *object_class = G_OBJECT_CLASS (dhcpcd_class); <API key> (dhcpcd_class, sizeof (NMDHCPDhcpcdPrivate)); /* virtual methods */ object_class->dispose = dispose; client_class->ip4_start = real_ip4_start; client_class->ip6_start = real_ip6_start; client_class->stop = real_stop; }
# Wolfgang Denk, DENX Software Engineering, wd@denx.de. # <API key>: GPL-2.0+ obj-$(CONFIG_HAS_POST) += 20001122-1.o obj-$(CONFIG_HAS_POST) += 20010114-2.o obj-$(CONFIG_HAS_POST) += 20010226-1.o obj-$(CONFIG_HAS_POST) += 980619-1.o obj-$(CONFIG_HAS_POST) += acc1.o obj-$(CONFIG_HAS_POST) += compare-fp-1.o obj-$(CONFIG_HAS_POST) += fpu.o obj-$(CONFIG_HAS_POST) += <API key>.o obj-$(CONFIG_HAS_POST) += darwin-ldouble.o CFLAGS := $(shell echo $(CFLAGS) | sed s/-msoft-float CFLAGS += -mhard-float -<API key> $(obj)%.o: %.c $(CC) $(ALL_CFLAGS) -o $@.fp $< -c $(OBJCOPY) -R .gnu.attributes $@.fp $@ rm -f $@.fp
! { dg-do run } call test contains subroutine check (x, y, l) integer :: x, y logical :: l l = l .or. x .ne. y end subroutine check subroutine foo (c, d, e, f, g, h, i, j, k, n) use omp_lib integer :: n character (len = *) :: c character (len = n) :: d integer, dimension (2, 3:5, n) :: e integer, dimension (2, 3:n, n) :: f character (len = *), dimension (5, 3:n) :: g character (len = n), dimension (5, 3:n) :: h real, dimension (:, :, :) :: i double precision, dimension (3:, 5:, 7:) :: j integer, dimension (:, :, :) :: k logical :: l integer :: p, q, r character (len = n) :: s integer, dimension (2, 3:5, n) :: t integer, dimension (2, 3:n, n) :: u character (len = n), dimension (5, 3:n) :: v character (len = 2 * n + 24) :: w integer :: x, z character (len = 1) :: y l = .false. !$omp parallel default (none) private (c, d, e, f, g, h, i, j, k) & !$omp & private (s, t, u, v) reduction (.or.:l) num_threads (6) & !$omp private (p, q, r, w, x, y) shared (z) x = omp_get_thread_num () w = '' if (x .eq. 0) w = '<API key>' if (x .eq. 1) w = '<API key>' if (x .eq. 2) w = '<API key>' if (x .eq. 3) w = '<API key>' if (x .eq. 4) w = '<API key>' if (x .eq. 5) w = '<API key>' c = w(8:19) d = w(1:7) forall (p = 1:2, q = 3:5, r = 1:7) e(p, q, r) = 5 * x + p + q + 2 * r forall (p = 1:2, q = 3:7, r = 1:7) f(p, q, r) = 25 * x + p + q + 2 * r forall (p = 1:5, q = 3:7, p + q .le. 8) g(p, q) = w(8:19) forall (p = 1:5, q = 3:7, p + q .gt. 8) g(p, q) = w(27:38) forall (p = 1:5, q = 3:7, p + q .le. 8) h(p, q) = w(1:7) forall (p = 1:5, q = 3:7, p + q .gt. 8) h(p, q) = w(20:26) forall (p = 3:5, q = 2:6, r = 1:7) i(p - 2, q - 1, r) = (7.5 + x) * p * q * r forall (p = 3:5, q = 2:6, r = 1:7) j(p, q + 3, r + 6) = (9.5 + x) * p * q * r forall (p = 1:5, q = 7:7, r = 4:6) k(p, q - 6, r - 3) = 19 + x + p + q + 3 * r s = w(20:26) forall (p = 1:2, q = 3:5, r = 1:7) t(p, q, r) = -10 + x + p - q + 2 * r forall (p = 1:2, q = 3:7, r = 1:7) u(p, q, r) = 30 - x - p + q - 2 * r forall (p = 1:5, q = 3:7, p + q .le. 8) v(p, q) = w(1:7) forall (p = 1:5, q = 3:7, p + q .gt. 8) v(p, q) = w(20:26) !$omp barrier y = '' if (x .eq. 0) y = '0' if (x .eq. 1) y = '1' if (x .eq. 2) y = '2' if (x .eq. 3) y = '3' if (x .eq. 4) y = '4' if (x .eq. 5) y = '5' l = l .or. w(7:7) .ne. y l = l .or. w(19:19) .ne. y l = l .or. w(26:26) .ne. y l = l .or. w(38:38) .ne. y l = l .or. c .ne. w(8:19) l = l .or. d .ne. w(1:7) l = l .or. s .ne. w(20:26) do 103, p = 1, 2 do 103, q = 3, 7 do 103, r = 1, 7 if (q .lt. 6) l = l .or. e(p, q, r) .ne. 5 * x + p + q + 2 * r l = l .or. f(p, q, r) .ne. 25 * x + p + q + 2 * r if (r .lt. 6 .and. q + r .le. 8) l = l .or. g(r, q) .ne. w(8:19) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. g(r, q) .ne. w(27:38) if (r .lt. 6 .and. q + r .le. 8) l = l .or. h(r, q) .ne. w(1:7) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. h(r, q) .ne. w(20:26) if (q .lt. 6) l = l .or. t(p, q, r) .ne. -10 + x + p - q + 2 * r l = l .or. u(p, q, r) .ne. 30 - x - p + q - 2 * r if (r .lt. 6 .and. q + r .le. 8) l = l .or. v(r, q) .ne. w(1:7) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. v(r, q) .ne. w(20:26) 103 continue do 104, p = 3, 5 do 104, q = 2, 6 do 104, r = 1, 7 l = l .or. i(p - 2, q - 1, r) .ne. (7.5 + x) * p * q * r l = l .or. j(p, q + 3, r + 6) .ne. (9.5 + x) * p * q * r 104 continue do 105, p = 1, 5 do 105, q = 4, 6 l = l .or. k(p, 1, q - 3) .ne. 19 + x + p + 7 + 3 * q 105 continue call check (size (e, 1), 2, l) call check (size (e, 2), 3, l) call check (size (e, 3), 7, l) call check (size (e), 42, l) call check (size (f, 1), 2, l) call check (size (f, 2), 5, l) call check (size (f, 3), 7, l) call check (size (f), 70, l) call check (size (g, 1), 5, l) call check (size (g, 2), 5, l) call check (size (g), 25, l) call check (size (h, 1), 5, l) call check (size (h, 2), 5, l) call check (size (h), 25, l) call check (size (i, 1), 3, l) call check (size (i, 2), 5, l) call check (size (i, 3), 7, l) call check (size (i), 105, l) call check (size (j, 1), 4, l) call check (size (j, 2), 5, l) call check (size (j, 3), 7, l) call check (size (j), 140, l) call check (size (k, 1), 5, l) call check (size (k, 2), 1, l) call check (size (k, 3), 3, l) call check (size (k), 15, l) !$omp single z = omp_get_thread_num () !$omp end single copyprivate (c, d, e, f, g, h, i, j, k, s, t, u, v) w = '' x = z if (x .eq. 0) w = '<API key>' if (x .eq. 1) w = '<API key>' if (x .eq. 2) w = '<API key>' if (x .eq. 3) w = '<API key>' if (x .eq. 4) w = '<API key>' if (x .eq. 5) w = '<API key>' y = '' if (x .eq. 0) y = '0' if (x .eq. 1) y = '1' if (x .eq. 2) y = '2' if (x .eq. 3) y = '3' if (x .eq. 4) y = '4' if (x .eq. 5) y = '5' l = l .or. w(7:7) .ne. y l = l .or. w(19:19) .ne. y l = l .or. w(26:26) .ne. y l = l .or. w(38:38) .ne. y l = l .or. c .ne. w(8:19) l = l .or. d .ne. w(1:7) l = l .or. s .ne. w(20:26) do 113, p = 1, 2 do 113, q = 3, 7 do 113, r = 1, 7 if (q .lt. 6) l = l .or. e(p, q, r) .ne. 5 * x + p + q + 2 * r l = l .or. f(p, q, r) .ne. 25 * x + p + q + 2 * r if (r .lt. 6 .and. q + r .le. 8) l = l .or. g(r, q) .ne. w(8:19) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. g(r, q) .ne. w(27:38) if (r .lt. 6 .and. q + r .le. 8) l = l .or. h(r, q) .ne. w(1:7) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. h(r, q) .ne. w(20:26) if (q .lt. 6) l = l .or. t(p, q, r) .ne. -10 + x + p - q + 2 * r l = l .or. u(p, q, r) .ne. 30 - x - p + q - 2 * r if (r .lt. 6 .and. q + r .le. 8) l = l .or. v(r, q) .ne. w(1:7) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. v(r, q) .ne. w(20:26) 113 continue do 114, p = 3, 5 do 114, q = 2, 6 do 114, r = 1, 7 l = l .or. i(p - 2, q - 1, r) .ne. (7.5 + x) * p * q * r l = l .or. j(p, q + 3, r + 6) .ne. (9.5 + x) * p * q * r 114 continue do 115, p = 1, 5 do 115, q = 4, 6 l = l .or. k(p, 1, q - 3) .ne. 19 + x + p + 7 + 3 * q 115 continue x = omp_get_thread_num () w = '' if (x .eq. 0) w = '<API key>' if (x .eq. 1) w = '<API key>' if (x .eq. 2) w = '<API key>' if (x .eq. 3) w = '<API key>' if (x .eq. 4) w = '<API key>' if (x .eq. 5) w = '<API key>' c = w(8:19) d = w(1:7) forall (p = 1:2, q = 3:5, r = 1:7) e(p, q, r) = 5 * x + p + q + 2 * r forall (p = 1:2, q = 3:7, r = 1:7) f(p, q, r) = 25 * x + p + q + 2 * r forall (p = 1:5, q = 3:7, p + q .le. 8) g(p, q) = w(8:19) forall (p = 1:5, q = 3:7, p + q .gt. 8) g(p, q) = w(27:38) forall (p = 1:5, q = 3:7, p + q .le. 8) h(p, q) = w(1:7) forall (p = 1:5, q = 3:7, p + q .gt. 8) h(p, q) = w(20:26) forall (p = 3:5, q = 2:6, r = 1:7) i(p - 2, q - 1, r) = (7.5 + x) * p * q * r forall (p = 3:5, q = 2:6, r = 1:7) j(p, q + 3, r + 6) = (9.5 + x) * p * q * r forall (p = 1:5, q = 7:7, r = 4:6) k(p, q - 6, r - 3) = 19 + x + p + q + 3 * r s = w(20:26) forall (p = 1:2, q = 3:5, r = 1:7) t(p, q, r) = -10 + x + p - q + 2 * r forall (p = 1:2, q = 3:7, r = 1:7) u(p, q, r) = 30 - x - p + q - 2 * r forall (p = 1:5, q = 3:7, p + q .le. 8) v(p, q) = w(1:7) forall (p = 1:5, q = 3:7, p + q .gt. 8) v(p, q) = w(20:26) !$omp barrier y = '' if (x .eq. 0) y = '0' if (x .eq. 1) y = '1' if (x .eq. 2) y = '2' if (x .eq. 3) y = '3' if (x .eq. 4) y = '4' if (x .eq. 5) y = '5' l = l .or. w(7:7) .ne. y l = l .or. w(19:19) .ne. y l = l .or. w(26:26) .ne. y l = l .or. w(38:38) .ne. y l = l .or. c .ne. w(8:19) l = l .or. d .ne. w(1:7) l = l .or. s .ne. w(20:26) do 123, p = 1, 2 do 123, q = 3, 7 do 123, r = 1, 7 if (q .lt. 6) l = l .or. e(p, q, r) .ne. 5 * x + p + q + 2 * r l = l .or. f(p, q, r) .ne. 25 * x + p + q + 2 * r if (r .lt. 6 .and. q + r .le. 8) l = l .or. g(r, q) .ne. w(8:19) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. g(r, q) .ne. w(27:38) if (r .lt. 6 .and. q + r .le. 8) l = l .or. h(r, q) .ne. w(1:7) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. h(r, q) .ne. w(20:26) if (q .lt. 6) l = l .or. t(p, q, r) .ne. -10 + x + p - q + 2 * r l = l .or. u(p, q, r) .ne. 30 - x - p + q - 2 * r if (r .lt. 6 .and. q + r .le. 8) l = l .or. v(r, q) .ne. w(1:7) if (r .lt. 6 .and. q + r .gt. 8) l = l .or. v(r, q) .ne. w(20:26) 123 continue do 124, p = 3, 5 do 124, q = 2, 6 do 124, r = 1, 7 l = l .or. i(p - 2, q - 1, r) .ne. (7.5 + x) * p * q * r l = l .or. j(p, q + 3, r + 6) .ne. (9.5 + x) * p * q * r 124 continue do 125, p = 1, 5 do 125, q = 4, 6 l = l .or. k(p, 1, q - 3) .ne. 19 + x + p + 7 + 3 * q 125 continue !$omp end parallel if (l) call abort end subroutine foo subroutine test character (len = 12) :: c character (len = 7) :: d integer, dimension (2, 3:5, 7) :: e integer, dimension (2, 3:7, 7) :: f character (len = 12), dimension (5, 3:7) :: g character (len = 7), dimension (5, 3:7) :: h real, dimension (3:5, 2:6, 1:7) :: i double precision, dimension (3:6, 2:6, 1:7) :: j integer, dimension (1:5, 7:7, 4:6) :: k integer :: p, q, r call foo (c, d, e, f, g, h, i, j, k, 7) end subroutine test end
#ifndef ____H_AUTOSTATEDEP #define ____H_AUTOSTATEDEP /** @file * * AutoStateDep template classes, formerly in MachineImpl.h. Use these if * you need to ensure that the machine state does not change over a certain * period of time. */ /** * Helper class that safely manages the machine state dependency by * calling Machine::addStateDependency() on construction and * Machine::<API key>() on destruction. Intended for Machine * children. The usage pattern is: * * @code * AutoCaller autoCaller(this); * if (FAILED(autoCaller.rc())) return autoCaller.rc(); * * Machine::AutoStateDependency<MutableStateDep> adep(mParent); * if (FAILED(stateDep.rc())) return stateDep.rc(); * ... * // code that depends on the particular machine state * ... * @endcode * * Note that it is more convenient to use the following individual * shortcut classes instead of using this template directly: * <API key>, <API key> and * <API key>. The usage pattern is exactly the * same as above except that there is no need to specify the template * argument because it is already done by the shortcut class. * * @param taDepType Dependency type to manage. */ template <Machine::StateDependency taDepType = Machine::AnyStateDep> class AutoStateDependency { public: AutoStateDependency(Machine *aThat) : mThat(aThat), mRC(S_OK), mMachineState(MachineState_Null), mRegistered(FALSE) { Assert(aThat); mRC = aThat-><API key>(taDepType, &mMachineState, &mRegistered); } ~AutoStateDependency() { if (SUCCEEDED(mRC)) mThat-><API key>(); } /** Decreases the number of dependencies before the instance is * destroyed. Note that will reset #rc() to E_FAIL. */ void release() { AssertReturnVoid(SUCCEEDED(mRC)); mThat-><API key>(); mRC = E_FAIL; } /** Restores the number of callers after by #release(). #rc() will be * reset to the result of calling addStateDependency() and must be * rechecked to ensure the operation succeeded. */ void add() { AssertReturnVoid(!SUCCEEDED(mRC)); mRC = mThat-><API key>(taDepType, &mMachineState, &mRegistered); } /** Returns the result of Machine::addStateDependency(). */ HRESULT rc() const { return mRC; } /** Shortcut to SUCCEEDED(rc()). */ bool isOk() const { return SUCCEEDED(mRC); } /** Returns the machine state value as returned by * Machine::addStateDependency(). */ MachineState_T machineState() const { return mMachineState; } /** Returns the machine state value as returned by * Machine::addStateDependency(). */ BOOL machineRegistered() const { return mRegistered; } protected: Machine *mThat; HRESULT mRC; MachineState_T mMachineState; BOOL mRegistered; private: <API key>(AutoStateDependency) <API key>(AutoStateDependency) }; /** * Shortcut to AutoStateDependency<AnyStateDep>. * See AutoStateDependency to get the usage pattern. * * Accepts any machine state and guarantees the state won't change before * this object is destroyed. If the machine state cannot be protected (as * a result of the state change currently in progress), this instance's * #rc() method will indicate a failure, and the caller is not allowed to * rely on any particular machine state and should return the failed * result code to the upper level. */ typedef AutoStateDependency<Machine::AnyStateDep> <API key>; /** * Shortcut to AutoStateDependency<MutableStateDep>. * See AutoStateDependency to get the usage pattern. * * Succeeds only if the machine state is in one of the mutable states, and * guarantees the given mutable state won't change before this object is * destroyed. If the machine is not mutable, this instance's #rc() method * will indicate a failure, and the caller is not allowed to rely on any * particular machine state and should return the failed result code to * the upper level. * * Intended to be used within all setter methods of IMachine * children objects (DVDDrive, NetworkAdapter, AudioAdapter, etc.) to * provide data protection and consistency. */ typedef AutoStateDependency<Machine::MutableStateDep> <API key>; /** * Shortcut to AutoStateDependency<<API key>>. * See AutoStateDependency to get the usage pattern. * * Succeeds only if the machine state is in one of the mutable states, or * if the machine is in the Saved state, and guarantees the given mutable * state won't change before this object is destroyed. If the machine is * not mutable, this instance's #rc() method will indicate a failure, and * the caller is not allowed to rely on any particular machine state and * should return the failed result code to the upper level. * * Intended to be used within setter methods of IMachine * children objects that may also operate on Saved machines. */ typedef AutoStateDependency<Machine::<API key>> <API key>; #endif
#include "region_block.h" #include <cstring> #include "force.h" #include "domain.h" #include "math_extra.h" #include "error.h" using namespace LAMMPS_NS; #define BIG 1.0e20 RegBlock::RegBlock(LAMMPS *lmp, int narg, char **arg) : Region(lmp, narg, arg) { options(narg-8,&arg[8]); if (strcmp(arg[2],"INF") == 0 || strcmp(arg[2],"EDGE") == 0) { if (domain->box_exist == 0) error->all(FLERR,"Cannot use region INF or EDGE when box does not exist"); if (strcmp(arg[2],"INF") == 0) xlo = -BIG; else if (domain->triclinic == 0) xlo = domain->boxlo[0]; else xlo = domain->boxlo_bound[0]; } else xlo = xscale*force->numeric(FLERR,arg[2]); if (strcmp(arg[3],"INF") == 0 || strcmp(arg[3],"EDGE") == 0) { if (domain->box_exist == 0) error->all(FLERR,"Cannot use region INF or EDGE when box does not exist"); if (strcmp(arg[3],"INF") == 0) xhi = BIG; else if (domain->triclinic == 0) xhi = domain->boxhi[0]; else xhi = domain->boxhi_bound[0]; } else xhi = xscale*force->numeric(FLERR,arg[3]); if (strcmp(arg[4],"INF") == 0 || strcmp(arg[4],"EDGE") == 0) { if (domain->box_exist == 0) error->all(FLERR,"Cannot use region INF or EDGE when box does not exist"); if (strcmp(arg[4],"INF") == 0) ylo = -BIG; else if (domain->triclinic == 0) ylo = domain->boxlo[1]; else ylo = domain->boxlo_bound[1]; } else ylo = yscale*force->numeric(FLERR,arg[4]); if (strcmp(arg[5],"INF") == 0 || strcmp(arg[5],"EDGE") == 0) { if (domain->box_exist == 0) error->all(FLERR,"Cannot use region INF or EDGE when box does not exist"); if (strcmp(arg[5],"INF") == 0) yhi = BIG; else if (domain->triclinic == 0) yhi = domain->boxhi[1]; else yhi = domain->boxhi_bound[1]; } else yhi = yscale*force->numeric(FLERR,arg[5]); if (strcmp(arg[6],"INF") == 0 || strcmp(arg[6],"EDGE") == 0) { if (domain->box_exist == 0) error->all(FLERR,"Cannot use region INF or EDGE when box does not exist"); if (strcmp(arg[6],"INF") == 0) zlo = -BIG; else if (domain->triclinic == 0) zlo = domain->boxlo[2]; else zlo = domain->boxlo_bound[2]; } else zlo = zscale*force->numeric(FLERR,arg[6]); if (strcmp(arg[7],"INF") == 0 || strcmp(arg[7],"EDGE") == 0) { if (domain->box_exist == 0) error->all(FLERR,"Cannot use region INF or EDGE when box does not exist"); if (strcmp(arg[7],"INF") == 0) zhi = BIG; else if (domain->triclinic == 0) zhi = domain->boxhi[2]; else zhi = domain->boxhi_bound[2]; } else zhi = zscale*force->numeric(FLERR,arg[7]); // error check if (xlo > xhi || ylo > yhi || zlo > zhi) error->all(FLERR,"Illegal region block command"); // extent of block if (interior) { bboxflag = 1; extent_xlo = xlo; extent_xhi = xhi; extent_ylo = ylo; extent_yhi = yhi; extent_zlo = zlo; extent_zhi = zhi; } else bboxflag = 0; // particle could be close to all 6 planes // particle can only touch 3 planes cmax = 6; contact = new Contact[cmax]; if (interior) tmax = 3; else tmax = 1; // open face data structs face[0][0] = -1.0; face[0][1] = 0.0; face[0][2] = 0.0; face[1][0] = 1.0; face[1][1] = 0.0; face[1][2] = 0.0; face[2][0] = 0.0; face[2][1] = -1.0; face[2][2] = 0.0; face[3][0] = 0.0; face[3][1] = 1.0; face[3][2] = 0.0; face[4][0] = 0.0; face[4][1] = 0.0; face[4][2] = -1.0; face[5][0] = 0.0; face[5][1] = 0.0; face[5][2] = 1.0; // face[0] corners[0][0][0] = xlo; corners[0][0][1] = ylo; corners[0][0][2] = zlo; corners[0][1][0] = xlo; corners[0][1][1] = ylo; corners[0][1][2] = zhi; corners[0][2][0] = xlo; corners[0][2][1] = yhi; corners[0][2][2] = zhi; corners[0][3][0] = xlo; corners[0][3][1] = yhi; corners[0][3][2] = zlo; // face[1] corners[1][0][0] = xhi; corners[1][0][1] = ylo; corners[1][0][2] = zlo; corners[1][1][0] = xhi; corners[1][1][1] = ylo; corners[1][1][2] = zhi; corners[1][2][0] = xhi; corners[1][2][1] = yhi; corners[1][2][2] = zhi; corners[1][3][0] = xhi; corners[1][3][1] = yhi; corners[1][3][2] = zlo; // face[2] MathExtra::copy3(corners[0][0], corners[2][0]); MathExtra::copy3(corners[1][0], corners[2][1]); MathExtra::copy3(corners[1][1], corners[2][2]); MathExtra::copy3(corners[0][1], corners[2][3]); // face[3] MathExtra::copy3(corners[0][3], corners[3][0]); MathExtra::copy3(corners[0][2], corners[3][1]); MathExtra::copy3(corners[1][2], corners[3][2]); MathExtra::copy3(corners[1][3], corners[3][3]); // face[4] MathExtra::copy3(corners[0][0], corners[4][0]); MathExtra::copy3(corners[0][3], corners[4][1]); MathExtra::copy3(corners[1][3], corners[4][2]); MathExtra::copy3(corners[1][0], corners[4][3]); // face[5] MathExtra::copy3(corners[0][1], corners[5][0]); MathExtra::copy3(corners[1][1], corners[5][1]); MathExtra::copy3(corners[1][2], corners[5][2]); MathExtra::copy3(corners[0][2], corners[5][3]); } RegBlock::~RegBlock() { if (copymode) return; delete [] contact; } int RegBlock::inside(double x, double y, double z) { if (x >= xlo && x <= xhi && y >= ylo && y <= yhi && z >= zlo && z <= zhi) return 1; return 0; } int RegBlock::surface_interior(double *x, double cutoff) { double delta; // x is exterior to block if (x[0] < xlo || x[0] > xhi || x[1] < ylo || x[1] > yhi || x[2] < zlo || x[2] > zhi) return 0; // x is interior to block or on its surface int n = 0; delta = x[0] - xlo; if (delta < cutoff && !open_faces[0]) { contact[n].r = delta; contact[n].delx = delta; contact[n].dely = contact[n].delz = 0.0; contact[n].radius = 0; contact[n].iwall = 0; n++; } delta = xhi - x[0]; if (delta < cutoff && !open_faces[1]) { contact[n].r = delta; contact[n].delx = -delta; contact[n].dely = contact[n].delz = 0.0; contact[n].radius = 0; contact[n].iwall = 1; n++; } delta = x[1] - ylo; if (delta < cutoff && !open_faces[2]) { contact[n].r = delta; contact[n].dely = delta; contact[n].delx = contact[n].delz = 0.0; contact[n].radius = 0; contact[n].iwall = 2; n++; } delta = yhi - x[1]; if (delta < cutoff && !open_faces[3]) { contact[n].r = delta; contact[n].dely = -delta; contact[n].delx = contact[n].delz = 0.0; contact[n].radius = 0; contact[n].iwall = 3; n++; } delta = x[2] - zlo; if (delta < cutoff && !open_faces[4]) { contact[n].r = delta; contact[n].delz = delta; contact[n].delx = contact[n].dely = 0.0; contact[n].radius = 0; contact[n].iwall = 4; n++; } delta = zhi - x[2]; if (delta < cutoff && !open_faces[5]) { contact[n].r = delta; contact[n].delz = -delta; contact[n].delx = contact[n].dely = 0.0; contact[n].radius = 0; contact[n].iwall = 5; n++; } return n; } int RegBlock::surface_exterior(double *x, double cutoff) { double xp,yp,zp; double xc,yc,zc,dist,mindist; // x is far enough from block that there is no contact // x is interior to block if (x[0] <= xlo-cutoff || x[0] >= xhi+cutoff || x[1] <= ylo-cutoff || x[1] >= yhi+cutoff || x[2] <= zlo-cutoff || x[2] >= zhi+cutoff) return 0; if (x[0] > xlo && x[0] < xhi && x[1] > ylo && x[1] < yhi && x[2] > zlo && x[2] < zhi) return 0; // x is exterior to block or on its surface // xp,yp,zp = point on surface of block that x is closest to // could be edge or corner pt of block // do not add contact point if r >= cutoff if (!openflag) { if (x[0] < xlo) xp = xlo; else if (x[0] > xhi) xp = xhi; else xp = x[0]; if (x[1] < ylo) yp = ylo; else if (x[1] > yhi) yp = yhi; else yp = x[1]; if (x[2] < zlo) zp = zlo; else if (x[2] > zhi) zp = zhi; else zp = x[2]; } else { mindist = BIG; for (int i = 0; i < 6; i++){ if (open_faces[i]) continue; dist = find_closest_point(i,x,xc,yc,zc); if (dist < mindist) { xp = xc; yp = yc; zp = zc; mindist = dist; } } } add_contact(0,x,xp,yp,zp); contact[0].iwall = 0; if (contact[0].r < cutoff) return 1; return 0; } double RegBlock::find_closest_point(int i, double *x, double &xc, double &yc, double &zc) { double dot,d2,d2min; double xr[3],xproj[3],p[3]; xr[0] = x[0] - corners[i][0][0]; xr[1] = x[1] - corners[i][0][1]; xr[2] = x[2] - corners[i][0][2]; dot = face[i][0]*xr[0] + face[i][1]*xr[1] + face[i][2]*xr[2]; xproj[0] = xr[0] - dot*face[i][0]; xproj[1] = xr[1] - dot*face[i][1]; xproj[2] = xr[2] - dot*face[i][2]; d2min = BIG; // check if point projects inside of face if (inside_face(xproj, i)){ d2 = d2min = dot*dot; xc = xproj[0] + corners[i][0][0]; yc = xproj[1] + corners[i][0][1]; zc = xproj[2] + corners[i][0][2]; // check each edge } else { <API key>(corners[i][0],corners[i][1],x,p); d2 = (p[0]-x[0])*(p[0]-x[0]) + (p[1]-x[1])*(p[1]-x[1]) + (p[2]-x[2])*(p[2]-x[2]); if (d2 < d2min) { d2min = d2; xc = p[0]; yc = p[1]; zc = p[2]; } <API key>(corners[i][1],corners[i][2],x,p); d2 = (p[0]-x[0])*(p[0]-x[0]) + (p[1]-x[1])*(p[1]-x[1]) + (p[2]-x[2])*(p[2]-x[2]); if (d2 < d2min) { d2min = d2; xc = p[0]; yc = p[1]; zc = p[2]; } <API key>(corners[i][2],corners[i][3],x,p); d2 = (p[0]-x[0])*(p[0]-x[0]) + (p[1]-x[1])*(p[1]-x[1]) + (p[2]-x[2])*(p[2]-x[2]); if (d2 < d2min) { d2min = d2; xc = p[0]; yc = p[1]; zc = p[2]; } <API key>(corners[i][3],corners[i][0],x,p); d2 = (p[0]-x[0])*(p[0]-x[0]) + (p[1]-x[1])*(p[1]-x[1]) + (p[2]-x[2])*(p[2]-x[2]); if (d2 < d2min) { d2min = d2; xc = p[0]; yc = p[1]; zc = p[2]; } } return d2min; } int RegBlock::inside_face(double *xproj, int iface) { if (iface < 2) { if (xproj[1] > 0 && (xproj[1] < yhi-ylo) && xproj[2] > 0 && (xproj[2] < zhi-zlo)) return 1; } else if (iface < 4) { if (xproj[0] > 0 && (xproj[0] < (xhi-xlo)) && xproj[2] > 0 && (xproj[2] < (zhi-zlo))) return 1; } else { if (xproj[0] > 0 && xproj[0] < (xhi-xlo) && xproj[1] > 0 && xproj[1] < (yhi-ylo)) return 1; } return 0; }
// { dg-do run { target *-*-freebsd* *-*-netbsd* *-*-linux* *-*-gnu* *-*-solaris* *-*-cygwin *-*-darwin* powerpc-ibm-aix* } } // { dg-options " -std=gnu++0x -pthread" { target *-*-freebsd* *-*-netbsd* *-*-linux* *-*-gnu* powerpc-ibm-aix* } } // { dg-options " -std=gnu++0x -pthreads" { target *-*-solaris* } } // { dg-options " -std=gnu++0x " { target *-*-cygwin *-*-darwin* } } // { dg-require-cstdint "" } // { dg-require-gthreads "" } // { <API key> "" } // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING3. If not see #include <future> #include <testsuite_hooks.h> struct sum { typedef int result_type; int operator()(int i, int& j, const int& k) { return i + j + k; } }; void test01() { bool test __attribute__((unused)) = true; using namespace std; int a = 1; int b = 10; int c = 100; future<int> f1 = async(launch::async|launch::deferred, sum(), a, ref(b), cref(c)); future<int> f2 = async(sum(), a, ref(b), cref(c)); VERIFY( f1.valid() ); VERIFY( f2.valid() ); int r1 = f1.get(); int r2 = f2.get(); VERIFY( r1 == r2 ); } int main() { test01(); return 0; }
package NOCpulse::Probe::DataSource::MySQL; use strict; use NOCpulse::Probe::Error; use NOCpulse::Probe::Shell::Local; use base qw(NOCpulse::Probe::DataSource::AbstractOSCommand); use Class::MethodMaker new_with_init => 'new', ; my $Log = NOCpulse::Log::Logger->new(__PACKAGE__); use constant LOCAL_SHELL => 'NOCpulse::Probe::Shell::Local'; sub init { my ($self, %in_args) = @_; my $shell_class = LOCAL_SHELL; my %own_args = (); $self-><API key>(\%in_args, \%own_args); $in_args{timeout_seconds} = delete $in_args{timeout}; $own_args{shell} = $shell_class->new(%in_args); $self->SUPER::init(%own_args); return $self; } sub <API key> { my ($self, $program_path) = @_; my $old_die_flag = $self->die_on_failure; $self->die_on_failure(0); $self->execute("test -x $program_path"); $self->die_on_failure($old_die_flag); if ($self->command_status == 1) { my $msg = sprintf($self->_message_catalog->status('missing_program'), $program_path); throw NOCpulse::Probe::DataSource::MissingProgramError($msg); } } sub status { my ($self, $host, $port, $user, $password) = @_; my $binary = '/usr/bin/mysqladmin'; $self->die_on_failure(0); $self-><API key>($binary); #BZ 164820: IP addresses with leading zeros in any octets need #to be fixed so requests work correctly my @octets = split(/\./, $host); foreach my $octet (@octets) { $octet =~ s/^0* $octet = 0 unless $octet; } $host = join('.', @octets); my ($result); if ($password) { $Log->log_method(1, "Found password, using it\n"); $result = $self->execute("$binary -h $host -P $port -u $user -p$password extended-status"); } else { $Log->log_method(1, "No password found, using non -p version\n"); $result = $self->execute("$binary -h $host -P $port -u $user extended-status"); } if ($self->shell->stderr =~ /connect to server at .* failed/) { $Log->log_method(1, "Errors found: " . $self->shell->stderr); my $msg = "Could not establish connection to MySQL database on host $host"; throw NOCpulse::Probe::DataSource::ConnectError($msg); } return ($result); } sub accessibility { my ($self, $host, $port, $db, $user, $password) = @_; my $binary = '/usr/bin/mysql'; $self->die_on_failure(0); $self-><API key>($binary); #BZ 164820: IP addresses with leading zeros in any octets need #to be fixed so requests work correctly my @octets = split(/\./, $host); foreach my $octet (@octets) { $octet =~ s/^0* $octet = 0 unless $octet; } $host = join('.', @octets); my ($result); if ($password) { $Log->log_method(1, "Found password, using it\n"); $result = $self->execute("$binary -h $host -P $port -u $user -p$password $db -e status"); } else { $Log->log_method(1, "No password found, using non -p version\n"); $result = $self->execute("$binary -h $host -P $port -u $user $db -e status"); } return ($result); } 1; __END__ =head1 NAME NOCpulse::Probe::DataSource::MySQL.pm - Datasource that uses the mysqladmin program to report data about a given MySQL database =head1 SYNOPSIS The methods available are to be used by NOCpulse::Probe modules found in the NOCpulsePlugins package. This datasource is specifically for use by the probes in the /opt/home/nocpulse/libexec/MySQL directory. =head1 DESCRIPTION Need to add a description =head1 METHODS =over 4 =item =back =head1 BUGS Will add bugs as I find them. =head1 AUTHOR Nick Hansen <nhansen@redhat.com> Last updated: $id$ =head1 SEE ALSO L<NOCpulse::Probe::Overview|PerlModules::NP::Probe::Overview>, L<NOCpulse::Probe::DataSource::Overview|PerlModules::NP::Probe::DataSource::Overview>, L<NOCpulse::Probe::ProbeRunner|PerlModules::NP::Probe::ProbeRunner>, L<NOCpulse::Probe::ItemStatus|PerlModules::NP::Probe::ItemStatus> =cut
#include <linux/kernel.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/interrupt.h> #include <linux/semaphore.h> #include <linux/mutex.h> #include <mach/irqs.h> #include <mach/clock.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/uaccess.h> #include <linux/vmalloc.h> #include <linux/mm.h> #include <linux/bootmem.h> #include <linux/dma-mapping.h> #include <linux/slab.h> #include <linux/broadcom/mm_fw_hw_ifc.h> #include <linux/broadcom/mm_fw_usr_ifc.h> struct interlock_device_t { void *fmwk_handle; }; static int interlock_reset(void *device_id) { return 0; } static int interlock_get_regs(void *device_id, MM_REG_VALUE *ptr, int count) { return 0; } static int interlock_abort(void *device_id, mm_job_post_t *job) { return 0; } static mm_isr_type_e <API key>(void *device_id) { return MM_ISR_SUCCESS; } bool <API key>(void *device_id) { return false; } mm_job_status_e interlock_start_job(void *device_id, mm_job_post_t *job, unsigned int profmask) { job->status = <API key>; return <API key>; } static struct interlock_device_t *interlock_device; static void <API key>(void *vaddr) {} int __init interlock_init(void) { int ret = 0; MM_CORE_HW_IFC core_param; MM_DVFS_HW_IFC dvfs_param; MM_PROF_HW_IFC prof_param; interlock_device = kmalloc(sizeof(struct interlock_device_t), GFP_KERNEL); pr_debug("INTERLOCK driver Module Init"); core_param.mm_base_addr = 0; core_param.mm_hw_size = 0; core_param.mm_irq = 0; core_param.mm_timer = 0; core_param.mm_timeout = 0; core_param.mm_get_status = <API key>; core_param.mm_start_job = interlock_start_job; core_param.mm_process_irq = <API key>; core_param.mm_init = interlock_reset; core_param.mm_deinit = interlock_reset; core_param.mm_abort = interlock_abort; core_param.mm_get_regs = interlock_get_regs; core_param.mm_update_virt_addr = <API key>; core_param.mm_version_init = NULL; core_param.mm_device_id = (void *)interlock_device; core_param.mm_virt_addr = NULL; core_param.core_name = "INTERLOCK"; dvfs_param.__on = 0; dvfs_param.__mode = ECONOMY; dvfs_param.__ts = <API key>; dvfs_param.eco_ns_high = <API key>; dvfs_param.nor_ns_high = <API key>; dvfs_param.nor_ns_low = <API key>; dvfs_param.tur_ns_high = <API key>; dvfs_param.tur_ns_low = <API key>; dvfs_param.st_ns_low = <API key>; dvfs_param.eco_high = 0; dvfs_param.nor_high = 80; dvfs_param.nor_low = 0; dvfs_param.tur_high = 80; dvfs_param.tur_low = 45; dvfs_param.st_low = 45; dvfs_param.dvfs_bulk_job_cnt = 0; interlock_device->fmwk_handle = mm_fmwk_register(INTERLOCK_DEV_NAME, NULL, 1, &core_param, &dvfs_param, &prof_param); if (interlock_device->fmwk_handle == NULL) { ret = -ENOMEM; goto err; } pr_debug("INTERLOCK driver Module Init over"); return ret; err: pr_err("INTERLOCK driver Module Init Error"); return ret; } void __exit interlock_exit(void) { pr_debug("INTERLOCK driver Module Exit"); if (interlock_device->fmwk_handle) mm_fmwk_unregister(interlock_device->fmwk_handle); kfree(interlock_device); } module_init(interlock_init); module_exit(interlock_exit); MODULE_AUTHOR("Broadcom Corporation"); MODULE_DESCRIPTION("INTERLOCK device driver"); MODULE_LICENSE("GPL");
/*jslint browser: true */ /*global jQuery: true */ // TODO JsDoc /** * Create a cookie with the given key and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String key The key of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given key. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String key The key of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function (key, value, options) { // key and value given, set cookie... if (arguments.length > 1 && (value === null || typeof value !== "object")) { options = jQuery.extend({}, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || {}; var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent; return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null; }; ; ;(function($) { /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') { options = { success: options }; } var action = this.attr('action'); var url = (typeof action === 'string') ? $.trim(action) : ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^ } url = url || window.location.href || ''; options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('<API key>', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via <API key> trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var $form = this, callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) if (options.closeKeepAlive) { $.get(options.closeKeepAlive, fileUpload); } else { fileUpload(); } } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } var s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id; var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', <API key>: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function() { log('aborting upload...'); var e = 'aborted'; this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, 'error'); } }; var g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active } return; } if (xhr.aborted) { return; } var timedOut = 0; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') { form.setAttribute('method', 'POST'); } if (form.getAttribute('action') != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.<API key>) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { setTimeout(function() { timedOut = true; cb(); }, s.timeout); } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />') .appendTo(form)[0]); } } // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50; function cb() { if (xhr.aborted) { return; } var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; var scr = /(json|script)/.test(s.dataType); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.<API key>('textarea')[0]; if (ta) { xhr.responseText = ta.value; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.<API key>('pre')[0]; var b = doc.<API key>('body')[0]; if (pre) { xhr.responseText = pre.textContent; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = httpData(xhr, s.dataType, s); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); } if (xhr.aborted) { log('upload aborted'); ok = false; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error'); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.<API key>('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } }; })(jQuery); ; (function ($) { /** * Provides Ajax page updating via jQuery $.ajax (Asynchronous JavaScript and XML). * * Ajax is a method of making a request via JavaScript while viewing an HTML * page. The request returns an array of commands encoded in JSON, which is * then executed to make any changes that are necessary to the page. * * Drupal uses this file to enhance form elements with #ajax['path'] and * #ajax['wrapper'] properties. If set, this file will automatically be included * to provide Ajax capabilities. */ Drupal.ajax = Drupal.ajax || {}; /** * Attaches the Ajax behavior to each Ajax form element. */ Drupal.behaviors.AJAX = { attach: function (context, settings) { // Load all Ajax behaviors specified in the settings. for (var base in settings.ajax) { if (!$('#' + base + '.ajax-processed').length) { var element_settings = settings.ajax[base]; if (typeof element_settings.selector == 'undefined') { element_settings.selector = '#' + base; } $(element_settings.selector).each(function () { element_settings.element = this; Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); }); $('#' + base).addClass('ajax-processed'); } } // Bind Ajax behaviors to all items showing the class. $('.use-ajax:not(.ajax-processed)').addClass('ajax-processed').each(function () { var element_settings = {}; // Clicked links look better with the throbber than the progress bar. element_settings.progress = { 'type': 'throbber' }; // For anchor tags, these will go to the target of the anchor rather // than the usual location. if ($(this).attr('href')) { element_settings.url = $(this).attr('href'); element_settings.event = 'click'; } var base = $(this).attr('id'); Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); }); // This class means to submit the form to the action using Ajax. $('.use-ajax-submit:not(.ajax-processed)').addClass('ajax-processed').each(function () { var element_settings = {}; // Ajax submits specified in this manner automatically submit to the // normal form action. element_settings.url = $(this.form).attr('action'); // Form submit button clicks need to tell the form what was clicked so // it gets passed in the POST request. element_settings.setClick = true; // Form buttons use the 'click' event rather than mousedown. element_settings.event = 'click'; // Clicked form buttons look better with the throbber than the progress bar. element_settings.progress = { 'type': 'throbber' }; var base = $(this).attr('id'); Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); }); } }; /** * Ajax object. * * All Ajax objects on a page are accessible through the global Drupal.ajax * object and are keyed by the submit button's ID. You can access them from * your module's JavaScript file to override properties or functions. * * For example, if your Ajax enabled button has the ID 'edit-submit', you can * redefine the function that is called to insert the new content like this * (inside a Drupal.behaviors attach block): * @code * Drupal.behaviors.myCustomAJAXStuff = { * attach: function (context, settings) { * Drupal.ajax['edit-submit'].commands.insert = function (ajax, response, status) { * new_content = $(response.data); * $('#my-wrapper').append(new_content); * alert('New content was appended to #my-wrapper'); * } * } * }; * @endcode */ Drupal.ajax = function (base, element, element_settings) { var defaults = { url: 'system/ajax', event: 'mousedown', keypress: true, selector: '#' + base, effect: 'none', speed: 'none', method: 'replaceWith', progress: { type: 'throbber', message: Drupal.t('Please wait...') }, submit: { 'js': true } }; $.extend(this, defaults, element_settings); this.element = element; this.element_settings = element_settings; // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let // the server detect when it needs to degrade gracefully. // There are five scenarios to check for: // 1. /nojs/ // 2. /nojs$ - The end of a URL string. // 3. /nojs? - Followed by a query (with clean URLs enabled). // E.g.: path/nojs?destination=foobar // 4. /nojs& - Followed by a query (without clean URLs enabled). // E.g.: ?q=path/nojs&destination=foobar // 5. /nojs# - Followed by a fragment. // E.g.: path/nojs#myfragment this.url = element_settings.url.replace(/\/nojs(\/|$|\?|&|#)/g, '/ajax$1'); this.wrapper = '#' + element_settings.wrapper; // If there isn't a form, jQuery.ajax() will be used instead, allowing us to // bind Ajax to links as well. if (this.element.form) { this.form = $(this.element.form); } // Set the options for the ajaxSubmit function. // The 'this' variable will not persist inside of the options object. var ajax = this; ajax.options = { url: ajax.url, data: ajax.submit, beforeSerialize: function (element_settings, options) { return ajax.beforeSerialize(element_settings, options); }, beforeSubmit: function (form_values, element_settings, options) { ajax.ajaxing = true; return ajax.beforeSubmit(form_values, element_settings, options); }, beforeSend: function (xmlhttprequest, options) { ajax.ajaxing = true; return ajax.beforeSend(xmlhttprequest, options); }, success: function (response, status) { // Sanity check for browser support (object expected). // When using iFrame uploads, responses must be returned as a string. if (typeof response == 'string') { response = $.parseJSON(response); } return ajax.success(response, status); }, complete: function (response, status) { ajax.ajaxing = false; if (status == 'error' || status == 'parsererror') { return ajax.error(response, ajax.url); } }, dataType: 'json', type: 'POST' }; // Bind the ajaxSubmit function to the element event. $(ajax.element).bind(element_settings.event, function (event) { return ajax.eventResponse(this, event); }); // If necessary, enable keyboard submission so that Ajax behaviors // can be triggered through keyboard input as well as e.g. a mousedown // action. if (element_settings.keypress) { $(ajax.element).keypress(function (event) { return ajax.keypressResponse(this, event); }); } // If necessary, prevent the browser default action of an additional event. // For example, prevent the browser default action of a click, even if the // AJAX behavior binds to mousedown. if (element_settings.prevent) { $(ajax.element).bind(element_settings.prevent, false); } }; /** * Handle a key press. * * The Ajax object will, if instructed, bind to a key press response. This * will test to see if the key press is valid to trigger this event and * if it is, trigger it for us and prevent other keypresses from triggering. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13 * and 32. RETURN is often used to submit a form when in a textfield, and * SPACE is often used to activate an element without submitting. */ Drupal.ajax.prototype.keypressResponse = function (element, event) { // Create a synonym for this to reduce code confusion. var ajax = this; // Detect enter key and space bar and allow the standard response for them, // except for form elements of type 'text' and 'textarea', where the // spacebar activation causes inappropriate activation if #ajax['keypress'] is // TRUE. On a text-type widget a space should always be a space. if (event.which == 13 || (event.which == 32 && element.type != 'text' && element.type != 'textarea')) { $(ajax.element_settings.element).trigger(ajax.element_settings.event); return false; } }; /** * Handle an event that triggers an Ajax response. * * When an event that triggers an Ajax response happens, this method will * perform the actual Ajax call. It is bound to the event using * bind() in the constructor, and it uses the options specified on the * ajax object. */ Drupal.ajax.prototype.eventResponse = function (element, event) { // Create a synonym for this to reduce code confusion. var ajax = this; // Do not perform another ajax command if one is already in progress. if (ajax.ajaxing) { return false; } try { if (ajax.form) { // If setClick is set, we must set this to ensure that the button's // value is passed. if (ajax.setClick) { // Mark the clicked button. 'form.clk' is a special variable for // ajaxSubmit that tells the system which element got clicked to // trigger the submit. Without it there would be no 'op' or // equivalent. element.form.clk = element; } ajax.form.ajaxSubmit(ajax.options); } else { ajax.beforeSerialize(ajax.element, ajax.options); $.ajax(ajax.options); } } catch (e) { // Unset the ajax.ajaxing flag here because it won't be unset during // the complete response. ajax.ajaxing = false; alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message); } // For radio/checkbox, allow the default event. On IE, this means letting // it actually check the box. if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) { return true; } else { return false; } }; /** * Handler for the form serialization. * * Runs before the beforeSend() handler (see below), and unlike that one, runs * before field data is collected. */ Drupal.ajax.prototype.beforeSerialize = function (element, options) { // Allow detaching behaviors to update field values before collecting them. // This is only needed when field values are added to the POST data, so only // when there is a form such that this.form.ajaxSubmit() is used instead of // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize() // isn't called, but don't rely on that: explicitly check this.form. if (this.form) { var settings = this.settings || Drupal.settings; Drupal.detachBehaviors(this.form, settings, 'serialize'); } // Prevent duplicate HTML ids in the returned markup. // @see drupal_html_id() options.data['ajax_html_ids[]'] = []; $('[id]').each(function () { options.data['ajax_html_ids[]'].push(this.id); }); // Allow Drupal to return new JavaScript and CSS files to load without // returning the ones already loaded. // @see <API key>() // @see drupal_get_css() // @see drupal_get_js() options.data['ajax_page_state[theme]'] = Drupal.settings.ajaxPageState.theme; options.data['ajax_page_state[theme_token]'] = Drupal.settings.ajaxPageState.theme_token; for (var key in Drupal.settings.ajaxPageState.css) { options.data['ajax_page_state[css][' + key + ']'] = 1; } for (var key in Drupal.settings.ajaxPageState.js) { options.data['ajax_page_state[js][' + key + ']'] = 1; } }; /** * Modify form values prior to form submission. */ Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options) { // This function is left empty to make it simple to override for modules // that wish to add functionality here. }; /** * Prepare the Ajax request before it is sent. */ Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) { // For forms without file inputs, the jQuery Form plugin serializes the form // values, and then calls jQuery's $.ajax() function, which invokes this // handler. In this circumstance, options.extraData is never used. For forms // with file inputs, the jQuery Form plugin uses the browser's normal form // submission mechanism, but captures the response in a hidden IFRAME. In this // circumstance, it calls this handler first, and then appends hidden fields // to the form to submit the values in options.extraData. There is no simple // way to know which submission mechanism will be used, so we add to extraData // regardless, and allow it to be ignored in the former case. if (this.form) { options.extraData = options.extraData || {}; // Let the server know when the IFRAME submission mechanism is used. The // server can use this information to wrap the JSON response in a TEXTAREA, // as per http://jquery.malsup.com/form/#file-upload. options.extraData.ajax_iframe_upload = '1'; // The triggering element is about to be disabled (see below), but if it // contains a value (e.g., a checkbox, textfield, select, etc.), ensure that // value is included in the submission. As per above, submissions that use // $.ajax() are already serialized prior to the element being disabled, so // this is only needed for IFRAME submissions. var v = $.fieldValue(this.element); if (v !== null) { options.extraData[this.element.name] = Drupal.checkPlain(v); } } // Disable the element that received the change to prevent user interface // interaction while the Ajax request is in progress. ajax.ajaxing prevents // the element from triggering a new request, but does not prevent the user // from changing its value. $(this.element).addClass('progress-disabled').attr('disabled', true); // Insert progressbar or throbber. if (this.progress.type == 'bar') { var progressBar = new Drupal.progressBar('ajax-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback)); if (this.progress.message) { progressBar.setProgress(-1, this.progress.message); } if (this.progress.url) { progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500); } this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar'); this.progress.object = progressBar; $(this.element).after(this.progress.element); } else if (this.progress.type == 'throbber') { this.progress.element = $('<div class="ajax-progress <API key>"><div class="throbber">&nbsp;</div></div>'); if (this.progress.message) { $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>'); } $(this.element).after(this.progress.element); } }; /** * Handler for the form redirection completion. */ Drupal.ajax.prototype.success = function (response, status) { // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).removeClass('progress-disabled').removeAttr('disabled'); Drupal.freezeHeight(); for (var i in response) { if (response.hasOwnProperty(i) && response[i]['command'] && this.commands[response[i]['command']]) { this.commands[response[i]['command']](this, response[i], status); } } // Reattach behaviors, if they were detached in beforeSerialize(). The // attachBehaviors() called on the new content from processing the response // commands is not sufficient, because behaviors from the entire form need // to be reattached. if (this.form) { var settings = this.settings || Drupal.settings; Drupal.attachBehaviors(this.form, settings); } Drupal.unfreezeHeight(); // Remove any response-specific settings so they don't get used on the next // call by mistake. this.settings = null; }; /** * Build an effect object which tells us how to apply the effect when adding new HTML. */ Drupal.ajax.prototype.getEffect = function (response) { var type = response.effect || this.effect; var speed = response.speed || this.speed; var effect = {}; if (type == 'none') { effect.showEffect = 'show'; effect.hideEffect = 'hide'; effect.showSpeed = ''; } else if (type == 'fade') { effect.showEffect = 'fadeIn'; effect.hideEffect = 'fadeOut'; effect.showSpeed = speed; } else { effect.showEffect = type + 'Toggle'; effect.hideEffect = type + 'Toggle'; effect.showSpeed = speed; } return effect; }; /** * Handler for the form redirection error. */ Drupal.ajax.prototype.error = function (response, uri) { alert(Drupal.ajaxError(response, uri)); // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } // Undo hide. $(this.wrapper).show(); // Re-enable the element. $(this.element).removeClass('progress-disabled').removeAttr('disabled'); // Reattach behaviors, if they were detached in beforeSerialize(). if (this.form) { var settings = response.settings || this.settings || Drupal.settings; Drupal.attachBehaviors(this.form, settings); } }; /** * Provide a series of commands that the server can request the client perform. */ Drupal.ajax.prototype.commands = { /** * Command to insert new content into the DOM. */ insert: function (ajax, response, status) { // Get information from the response. If it is not there, default to // our presets. var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper); var method = response.method || ajax.method; var effect = ajax.getEffect(response); // We don't know what response.data contains: it might be a string of text // without HTML, so don't rely on jQuery correctly iterpreting // $(response.data) as new HTML rather than a CSS selector. Also, if // response.data contains top-level text nodes, they get lost with either // $(response.data) or $('<div></div>').replaceWith(response.data). var new_content_wrapped = $('<div></div>').html(response.data); var new_content = new_content_wrapped.contents(); // For legacy reasons, the effects processing code assumes that new_content // consists of a single top-level element. Also, it has not been // sufficiently tested whether attachBehaviors() can be successfully called // with a context object that includes top-level text nodes. However, to // give developers full control of the HTML appearing in the page, and to // enable Ajax content to be inserted in places where DIV elements are not // allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new // content satisfies the requirement of a single top-level element, and // only use the container DIV created above when it doesn't. For more if (new_content.length != 1 || new_content.get(0).nodeType != 1) { new_content = new_content_wrapped; } // If removing content from the wrapper, detach behaviors first. switch (method) { case 'html': case 'replaceWith': case 'replaceAll': case 'empty': case 'remove': var settings = response.settings || ajax.settings || Drupal.settings; Drupal.detachBehaviors(wrapper, settings); } // Add the new content to the page. wrapper[method](new_content); // Immediately hide the new content if we're using any effects. if (effect.showEffect != 'show') { new_content.hide(); } // Determine which effect to use and what content will receive the // effect, then show the new content. if ($('.ajax-new-content', new_content).length > 0) { $('.ajax-new-content', new_content).hide(); new_content.show(); $('.ajax-new-content', new_content)[effect.showEffect](effect.showSpeed); } else if (effect.showEffect != 'show') { new_content[effect.showEffect](effect.showSpeed); } // Attach all JavaScript behaviors to the new content, if it was successfully // added to the page, this if statement allows #ajax['wrapper'] to be // optional. if (new_content.parents('html').length > 0) { // Apply any settings from the returned JSON if available. var settings = response.settings || ajax.settings || Drupal.settings; Drupal.attachBehaviors(new_content, settings); } }, /** * Command to remove a chunk from the page. */ remove: function (ajax, response, status) { var settings = response.settings || ajax.settings || Drupal.settings; Drupal.detachBehaviors($(response.selector), settings); $(response.selector).remove(); }, /** * Command to mark a chunk changed. */ changed: function (ajax, response, status) { if (!$(response.selector).hasClass('ajax-changed')) { $(response.selector).addClass('ajax-changed'); if (response.asterisk) { $(response.selector).find(response.asterisk).append(' <span class="ajax-changed">*</span> '); } } }, /** * Command to provide an alert. */ alert: function (ajax, response, status) { alert(response.text, response.title); }, /** * Command to provide the jQuery css() function. */ css: function (ajax, response, status) { $(response.selector).css(response.argument); }, /** * Command to set the settings that will be used for other commands in this response. */ settings: function (ajax, response, status) { if (response.merge) { $.extend(true, Drupal.settings, response.settings); } else { ajax.settings = response.settings; } }, /** * Command to attach data using jQuery's data API. */ data: function (ajax, response, status) { $(response.selector).data(response.name, response.value); }, /** * Command to apply a jQuery method. */ invoke: function (ajax, response, status) { var $element = $(response.selector); $element[response.method].apply($element, response.arguments); }, /** * Command to restripe a table. */ restripe: function (ajax, response, status) { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr:visible, > tr:visible', $(response.selector)) .removeClass('odd even') .filter(':even').addClass('odd').end() .filter(':odd').addClass('even'); }, add_css: function (ajax, response, status) { // Add the styles in the normal way. $('head').prepend(response.data); // Add imports in the styles using the addImport method if available. var match, importMatch = /^@import url\("(.*)"\);$/igm; if (document.styleSheets[0].addImport && importMatch.test(response.data)) { importMatch.lastIndex = 0; while (match = importMatch.exec(response.data)) { document.styleSheets[0].addImport(match[1]); } } }, /** * Command to update a form's build ID. */ updateBuildId: function(ajax, response, status) { $('input[name="form_build_id"][value="' + response['old'] + '"]').val(response['new']); } }; })(jQuery); ; (function (D) { var beforeSerialize = D.ajax.prototype.beforeSerialize; D.ajax.prototype.beforeSerialize = function (element, options) { beforeSerialize.call(this, element, options); options.data['ajax_page_state[jquery_version]'] = D.settings.ajaxPageState.jquery_version; } })(Drupal); ;
class blueprnt_state : public driver_device { public: blueprnt_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_audiocpu(*this, "audiocpu"), m_videoram(*this, "videoram"), m_scrollram(*this, "scrollram"), m_spriteram(*this, "spriteram"), m_colorram(*this, "colorram"), m_maincpu(*this, "maincpu"), m_gfxdecode(*this, "gfxdecode"), m_palette(*this, "palette") { } /* device/memory pointers */ required_device<cpu_device> m_audiocpu; required_shared_ptr<UINT8> m_videoram; required_shared_ptr<UINT8> m_scrollram; required_shared_ptr<UINT8> m_spriteram; required_shared_ptr<UINT8> m_colorram; /* video-related */ tilemap_t *m_bg_tilemap; int m_gfx_bank; /* misc */ int m_dipsw; <API key>(blueprnt_sh_dipsw_r); <API key>(grasspin_sh_dipsw_r); <API key>(<API key>); <API key>(<API key>); <API key>(blueprnt_videoram_w); <API key>(blueprnt_colorram_w); <API key>(<API key>); <API key>(dipsw_w); <API key>(get_bg_tile_info); virtual void machine_start() override; virtual void machine_reset() override; DECLARE_VIDEO_START(blueprnt); <API key>(blueprnt); UINT32 <API key>(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); void draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect ); required_device<cpu_device> m_maincpu; required_device<gfxdecode_device> m_gfxdecode; required_device<palette_device> m_palette; };
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http: <!-- /home/qt/mkdist-qt-4.4.3-1222864207/<API key>.4.3/src/gui/text/qfontmetrics.cpp --> <head> <title>Qt 4.4: Qt 3 Support Members for QFontMetrics</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http: <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="namespaces.html"><font color="#004faf">All&nbsp;Namespaces</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"></td></tr></table><h1 class="title">Qt 3 Support Members for QFontMetrics</h1> <p><b>The following class members are part of the <a href="qt3support.html">Qt 3 support layer</a>.</b> They are provided to help you port old code to Qt 4. We advise against using them in new code.</p> <p><ul><li><a href="qfontmetrics.html">QFontMetrics class reference</a></li></ul></p> <h3>Public Functions</h3> <ul> <li><div class="fn"/>QRect <b><a href="qfontmetrics-qt3.html#boundingRect-3">boundingRect</a></b> ( const QString &amp; <i>text</i>, int <i>len</i> ) const</li> <li><div class="fn"/>QRect <b><a href="qfontmetrics-qt3.html#boundingRect-4">boundingRect</a></b> ( int <i>x</i>, int <i>y</i>, int <i>w</i>, int <i>h</i>, int <i>flags</i>, const QString &amp; <i>text</i>, int <i>len</i>, int <i>tabStops</i> = 0, int * <i>tabArray</i> = 0 ) const</li> <li><div class="fn"/>QSize <b><a href="qfontmetrics-qt3.html#size-2">size</a></b> ( int <i>flags</i>, const QString &amp; <i>text</i>, int <i>len</i>, int <i>tabStops</i> = 0, int * <i>tabArray</i> = 0 ) const</li> </ul> <hr /> <h2>Member Function Documentation</h2> <h3 class="fn"><a name="boundingRect-3"></a><a href="qrect.html">QRect</a> QFontMetrics::boundingRect ( const <a href="qstring.html">QString</a> &amp; <i>text</i>, int <i>len</i> ) const</h3> <p>This is an overloaded member function, provided for convenience.</p> <p>Use the <a href="qfontmetrics.html#boundingRect">boundingRect</a>() function in combination with <a href="qstring.html#left">QString::left</a>() instead.</p> <p>For example, if you have code like</p> <pre><font color="#404040"> QRect rect = boundingRect(text, len);</font></pre> <p>you can rewrite it as</p> <pre> QRect rect = boundingRect(text.left(len));</pre> <h3 class="fn"><a name="boundingRect-4"></a><a href="qrect.html">QRect</a> QFontMetrics::boundingRect ( int <i>x</i>, int <i>y</i>, int <i>w</i>, int <i>h</i>, int <i>flags</i>, const <a href="qstring.html">QString</a> &amp; <i>text</i>, int <i>len</i>, int <i>tabStops</i> = 0, int * <i>tabArray</i> = 0 ) const</h3> <p>This is an overloaded member function, provided for convenience.</p> <p>Use the <a href="qfontmetrics.html#boundingRect">boundingRect</a>() function in combination with <a href="qstring.html#left">QString::left</a>() and a <a href="qrect.html">QRect</a> constructor instead.</p> <p>For example, if you have code like</p> <pre><font color="#404040"> QRect rect = boundingRect(x, y, w, h , flags, text, len, tabStops, tabArray);</font></pre> <p>you can rewrite it as</p> <pre> QRect rect = boundingRect(QRect(x, y, w, h), flags, text.left(len), tabstops, tabarray);</pre> <h3 class="fn"><a name="size-2"></a><a href="qsize.html">QSize</a> QFontMetrics::size ( int <i>flags</i>, const <a href="qstring.html">QString</a> &amp; <i>text</i>, int <i>len</i>, int <i>tabStops</i> = 0, int * <i>tabArray</i> = 0 ) const</h3> <p>This is an overloaded member function, provided for convenience.</p> <p>Use the <a href="qfontmetrics.html#size">size</a>() function in combination with <a href="qstring.html#left">QString::left</a>() instead.</p> <p>For example, if you have code like</p> <pre><font color="#404040"> QSize size = size(flags, str, len, tabstops, tabarray);</font></pre> <p>you can rewrite it as</p> <pre> QSize size = size(flags, str.left(len), tabstops, tabarray);</pre> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%" align="left">Copyright &copy; 2008 Nokia</td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.4.3</div></td> </tr></table></div></address></body> </html>
package com.sri.csl.pvs.plugin.handlers; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.IStreamListener; import org.eclipse.debug.core.Launch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.IStreamMonitor; import org.eclipse.debug.core.model.IStreamsProxy; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.console.<API key>; import org.eclipse.ui.handlers.HandlerUtil; import org.json.JSONObject; import com.sri.csl.pvs.PVSCommandManager; import com.sri.csl.pvs.PVSConstants; import com.sri.csl.pvs.PVSException; import com.sri.csl.pvs.PVSExecutionManager; import com.sri.csl.pvs.PVSExecutionManager.PVSRespondListener; import com.sri.csl.pvs.PVSJsonWrapper; import com.sri.csl.pvs.PVSPromptProcessor; import com.sri.csl.pvs.plugin.Activator; import com.sri.csl.pvs.plugin.console.<API key>; import com.sri.csl.pvs.plugin.console.PVSConsole; import com.sri.csl.pvs.plugin.misc.EclipsePluginUtil; import com.sri.csl.pvs.plugin.preferences.PreferenceConstants; /** * Our sample handler extends AbstractHandler, an IHandler base class. * @see org.eclipse.core.commands.IHandler * @see org.eclipse.core.commands.AbstractHandler */ public class StartPVSHandler extends AbstractHandler { private IWorkbenchWindow window; protected static Logger log = Logger.getLogger(StartPVSHandler.class.getName()); /** * The constructor. */ public StartPVSHandler() { } /** * the command has been executed, so extract extract the needed information * from the application context. */ public Object execute(ExecutionEvent event) throws ExecutionException { log.fine("Message to start PVS was received"); window = HandlerUtil.<API key>(event); if ( PVSExecutionManager.INST().isPVSRunning() ) { MessageDialog.openInformation(window.getShell(), "PVS Running", "An instance of PVS is already running."); } else { try { final PVSConsole console = PVSConsole.getConsole(); console.activate(); console.clearConsole(); final <API key> outStream = console.newOutputStream(); Map<String, String> attributes = new HashMap<String, String>(); attributes.put(IProcess.ATTR_CMDLINE, PVSExecutionManager.INST().<API key>()); ILaunch launch = new Launch(null, ILaunchManager.RUN_MODE, null); IProcess process = DebugPlugin.newProcess(launch, PVSExecutionManager.INST().startPVS(), Activator.name, attributes); PVSExecutionManager.INST().setIProcess(process); DebugPlugin.getDefault().getLaunchManager().addLaunch(launch); DebugPlugin.getDefault().<API key>(PVSExecutionManager.INST()); PVSJsonWrapper.init(); PVSExecutionManager.INST().<API key>(); PVSExecutionManager.INST().addListener(new PVSRespondListener() { @Override public void onMessageReceived(String message) { log.log(Level.INFO, "Message received: {0}", message); try { outStream.write(message); } catch (IOException e) { e.printStackTrace(); } } @Override public void onMessageReceived(JSONObject message) { log.log(Level.INFO, "JSON received: {0}", message); PVSJsonWrapper.INST().addToJSONQueue(message); } @Override public void onPromptReceived(List<String> previousLines, String prompt) { log.log(Level.INFO, "Prompt received: {0}", prompt); try { outStream.write(prompt); } catch (IOException e) { e.printStackTrace(); } PVSPromptProcessor.processPrompt(previousLines, prompt); } }); IStreamsProxy streamProxy = process.getStreamsProxy(); IStreamMonitor outMonitor = streamProxy.<API key>(); outMonitor.addListener(new PVSStreamListener(EclipsePluginUtil.getLispType())); <API key>.init(console); <API key>.INST().addListener(new <API key>.<API key>() { public void onTextReceived(String text) { PVSExecutionManager.INST().writeToPVS(text); } }); <API key>.INST().start(); Thread.sleep(500); restorePVSContext(); } catch (IOException e) { log.severe("Failed to start PVS"); MessageDialog.openInformation(window.getShell(), "Error", "Failed to start PVS"); } catch (<API key> e) { log.severe("Failed to restore PVS context"); MessageDialog.openInformation(window.getShell(), "Error", "Failed to restore the PVS context"); } catch (PVSException e) { log.severe("Failed to restore PVS context"); MessageDialog.openInformation(window.getShell(), "Error", "Failed to restore the PVS context"); } } return null; } protected void restorePVSContext() throws PVSException { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); boolean restoreContext = store.getBoolean(PreferenceConstants.SAVEPVSCONTEXT); if ( restoreContext ) { String contextLocation = store.getString(PreferenceConstants.PVSCONTEXTPATH); if ( !PVSConstants.EMPTY.equals(contextLocation) ) { ArrayList<Object> args = new ArrayList<Object>(); args.add(contextLocation); args.add(false); PVSCommandManager.changeContext(args); } } } } class PVSStreamListener implements IStreamListener { private static Pattern pvsPromptPattern; private static String LCB = "{", RCB = "}"; private static ArrayList<String> bufferedLines = new ArrayList<String>(); StringBuffer jsonBuffer; boolean jsonStarted = false; protected static Logger log = Logger.getLogger(PVSStreamListener.class.getName()); public PVSStreamListener(int lispType) { pvsPromptPattern = PVSPromptProcessor.getPVSPromptPattern(lispType); bufferedLines.clear(); resetJSONBuffer(); } private void resetJSONBuffer() { jsonStarted = false; jsonBuffer = new StringBuffer(); } @Override public void streamAppended(String text, IStreamMonitor monitor) { log.log(Level.FINER, "Text was received: {0}", text); synchronized ( jsonBuffer ) { String[] lines = text.split(PVSConstants.NL); for (String line: lines) { if ( LCB.equals(line) ) { if ( jsonStarted ) { log.severe("Got another {, but did not expect it"); resetJSONBuffer(); } else { jsonStarted = true; jsonBuffer.append(line).append(PVSConstants.NL); } } else if ( RCB.equals(line) ) { if ( !jsonStarted ) { log.severe("Got and }, but did not expect it"); resetJSONBuffer(); } else { jsonBuffer.append(line).append(PVSConstants.NL); String jbs = jsonBuffer.toString(); PVSExecutionManager.INST().dispatchJSONMessage(jbs); resetJSONBuffer(); } } else if ( !jsonStarted ) { if ( pvsPromptPattern.matcher(line).matches() ) { synchronized ( bufferedLines ) { PVSExecutionManager.INST().pvsPromptReceived(bufferedLines, line); bufferedLines.clear(); } } else { // line is unstructured data if ( !"nil".equals(line) ) { // nil is the result of sending a JSON to PVS. For now let's ignore and not display them bufferedLines.add(line); PVSExecutionManager.INST().<API key>(line + PVSConstants.NL); } } } else { jsonBuffer.append(line).append(PVSConstants.NL); } } } } }
package org.efs.openreports.engine; import java.io.<API key>; import java.io.FileInputStream; import java.sql.Connection; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jxls.transformer.XLSTransformer; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.efs.openreports.ORStatics; import org.efs.openreports.engine.input.ReportEngineInput; import org.efs.openreports.engine.output.QueryEngineOutput; import org.efs.openreports.engine.output.ReportEngineOutput; import org.efs.openreports.objects.Report; import org.efs.openreports.providers.DataSourceProvider; import org.efs.openreports.providers.DirectoryProvider; import org.efs.openreports.providers.PropertiesProvider; import org.efs.openreports.providers.ProviderException; /** * Generates a ReportEngineOutput from a ReportEngineInput. The output consists * of a byte[] containing an XLS spreadsheet. * * @author Erik Swenson * */ public class JXLSReportEngine extends ReportEngine { protected static Logger log = Logger.getLogger(JXLSReportEngine.class); public JXLSReportEngine(DataSourceProvider dataSourceProvider, DirectoryProvider directoryProvider, PropertiesProvider propertiesProvider) { super(dataSourceProvider,directoryProvider, propertiesProvider); } public ReportEngineOutput generateReport(ReportEngineInput input) throws ProviderException { Connection conn = null; try { Report report = input.getReport(); // create new HashMap to send to JXLS in order to maintain original map of parameters Map<String,Object> jxlsReportMap = new HashMap<String,Object>(input.getParameters()); if (report.getQuery() != null && report.getQuery().trim().length() > 0) { QueryReportEngine queryEngine = new QueryReportEngine(dataSourceProvider, directoryProvider, propertiesProvider); // set ExportType to null so QueryReportEngine just returns a list of results input.setExportType(null); QueryEngineOutput output = (QueryEngineOutput) queryEngine .generateReport(input); jxlsReportMap.put(ORStatics.JXLS_REPORT_RESULTS, output.getResults()); } else { conn = dataSourceProvider.getConnection(report.getDataSource().getId()); <API key> rm = new <API key>(conn, jxlsReportMap, dataSourceProvider); jxlsReportMap.put("rm", rm); } FileInputStream template = new FileInputStream(directoryProvider .getReportDirectory() + report.getFile()); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook workbook = transformer.transformXLS(template, jxlsReportMap); <API key> out = new <API key>(); workbook.write(out); ReportEngineOutput output = new ReportEngineOutput(); output.setContent(out.toByteArray()); output.setContentType(ReportEngineOutput.CONTENT_TYPE_XLS); return output; } catch(Exception e) { e.printStackTrace(); throw new ProviderException(e); } finally { try { if (conn != null) conn.close(); } catch (Exception c) { log.error("Error closing"); } } } public List buildParameterList(Report report) throws ProviderException { throw new ProviderException("JXLSReportEngine: buildParameterList not implemented."); } }
#ifdef BOND_CLASS // clang-format off BondStyle(harmonic/shift,BondHarmonicShift); // clang-format on #else #ifndef <API key> #define <API key> #include "bond.h" namespace LAMMPS_NS { class BondHarmonicShift : public Bond { public: BondHarmonicShift(class LAMMPS *); ~BondHarmonicShift() override; void compute(int, int) override; void coeff(int, char **) override; double <API key>(int) override; void write_restart(FILE *) override; void read_restart(FILE *) override; void write_data(FILE *) override; double single(int, double, int, int, double &) override; protected: double *k, *r0, *r1; void allocate(); }; } // namespace LAMMPS_NS #endif #endif
<?php namespace Magento\GroupedProduct\Model\Product\Type; use Magento\Framework\Module\Manager; class Plugin { /** * @var \Magento\Framework\Module\Manager */ protected $moduleManager; /** * @param Manager $moduleManager */ public function __construct(Manager $moduleManager) { $this->moduleManager = $moduleManager; } /** * Remove grouped product from list of visible product types * * @param \Magento\Catalog\Model\Product\Type $subject * @param array $result * * @return array * @SuppressWarnings(PHPMD.<API key>) */ public function afterGetOptionArray(\Magento\Catalog\Model\Product\Type $subject, array $result) { if (!$this->moduleManager->isOutputEnabled('<API key>')) { unset($result[Grouped::TYPE_CODE]); } return $result; } }
#!/bin/sh test_description='signals work as we expect' <API key>=true . ./test-lib.sh cat >expect <<EOF three two one EOF test_expect_success 'sigchain works' ' { test-tool sigchain >actual; ret=$?; } && { # Signal death by raise() on Windows acts like exit(3), # regardless of the signal number. So we must allow that # as well as the normal signal check. test_match_signal 15 "$ret" || test "$ret" = 3 } && test_cmp expect actual ' test_expect_success !MINGW 'signals are propagated using shell convention' ' # we use exec here to avoid any sub-shell interpretation # of the exit code git config alias.sigterm "!exec test-tool sigchain" && test_expect_code 143 git sigterm ' large_git () { for i in $(test_seq 1 100) do git diff --cached --binary || return done } test_expect_success 'create blob' ' test-tool genrandom foo 16384 >file && git add file ' test_expect_success !MINGW 'a constipated git dies with SIGPIPE' ' OUT=$( ((large_git; echo $? 1>&3) | :) 3>&1 ) && test_match_signal 13 "$OUT" ' test_expect_success !MINGW 'a constipated git dies with SIGPIPE even if parent ignores it' ' OUT=$( ((trap "" PIPE; large_git; echo $? 1>&3) | :) 3>&1 ) && test_match_signal 13 "$OUT" ' test_done
<?php namespace Magento\Framework\Stdlib\Cookie; /** * Class CookieMetadata * @api */ class CookieMetadata { /**#@+ * Constant for metadata value key. */ const KEY_DOMAIN = 'domain'; const KEY_PATH = 'path'; const KEY_SECURE = 'secure'; const KEY_HTTP_ONLY = 'http_only'; const KEY_DURATION = 'duration'; /** * Store the metadata in array format to distinguish between null values and no value set. * * @var array */ private $metadata; /** * @param array $metadata */ public function __construct($metadata = []) { if (!is_array($metadata)) { $metadata = []; } $this->metadata = $metadata; } /** * Returns an array representation of this metadata. * * If a value has not yet been set then the key will not show up in the array. * * @return array */ public function __toArray() { return $this->metadata; } /** * Set the domain for the cookie * * @param string $domain * @return $this */ public function setDomain($domain) { return $this->set(self::KEY_DOMAIN, $domain); } /** * Get the domain for the cookie * * @return string|null */ public function getDomain() { return $this->get(self::KEY_DOMAIN); } /** * Set path of the cookie * * @param string $path * @return $this */ public function setPath($path) { return $this->set(self::KEY_PATH, $path); } /** * Get the path of the cookie * * @return string|null */ public function getPath() { return $this->get(self::KEY_PATH); } /** * Get a value from the metadata storage. * * @param string $name * @return int|float|string|bool|null */ protected function get($name) { if (isset($this->metadata[$name])) { return $this->metadata[$name]; } return null; } /** * Set a value to the metadata storage. * * @param string $name * @param int|float|string|bool|null $value * @return $this */ protected function set($name, $value) { $this->metadata[$name] = $value; return $this; } /** * Get HTTP Only flag * * @return bool|null */ public function getHttpOnly() { return $this->get(self::KEY_HTTP_ONLY); } /** * Get whether the cookie is only available under HTTPS * * @return bool|null */ public function getSecure() { return $this->get(self::KEY_SECURE); } }
#ifndef __DragonFly__ #include <uwsgi.h> #endif #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) #include <sys/user.h> #include <sys/sysctl.h> #include <kvm.h> #elif defined(__sun__) /* Terrible Hack !!! */ #ifndef _LP64 #undef _FILE_OFFSET_BITS #endif #include <procfs.h> #define _FILE_OFFSET_BITS 64 #endif #ifdef __DragonFly__ #include <uwsgi.h> #endif extern struct uwsgi_server uwsgi; //use this instead of fprintf to avoid buffering mess with udp logging void uwsgi_log(const char *fmt, ...) { va_list ap; char logpkt[4096]; int rlen = 0; int ret; struct timeval tv; char sftime[64]; char ctime_storage[26]; time_t now; if (uwsgi.logdate) { if (uwsgi.log_strftime) { now = uwsgi_now(); rlen = strftime(sftime, 64, uwsgi.log_strftime, localtime(&now)); memcpy(logpkt, sftime, rlen); memcpy(logpkt + rlen, " - ", 3); rlen += 3; } else { gettimeofday(&tv, NULL); #if defined(__sun__) && !defined(__clang__) ctime_r((const time_t *) &tv.tv_sec, ctime_storage, 26); #else ctime_r((const time_t *) &tv.tv_sec, ctime_storage); #endif memcpy(logpkt, ctime_storage, 24); memcpy(logpkt + 24, " - ", 3); rlen = 24 + 3; } } va_start(ap, fmt); ret = vsnprintf(logpkt + rlen, 4096 - rlen, fmt, ap); va_end(ap); if (ret >= 4096) { char *tmp_buf = uwsgi_malloc(rlen + ret + 1); memcpy(tmp_buf, logpkt, rlen); va_start(ap, fmt); ret = vsnprintf(tmp_buf + rlen, ret + 1, fmt, ap); va_end(ap); rlen = write(2, tmp_buf, rlen + ret); free(tmp_buf); return; } rlen += ret; // do not check for errors rlen = write(2, logpkt, rlen); } void uwsgi_log_verbose(const char *fmt, ...) { va_list ap; char logpkt[4096]; int rlen = 0; struct timeval tv; char sftime[64]; time_t now; char ctime_storage[26]; if (uwsgi.log_strftime) { now = uwsgi_now(); rlen = strftime(sftime, 64, uwsgi.log_strftime, localtime(&now)); memcpy(logpkt, sftime, rlen); memcpy(logpkt + rlen, " - ", 3); rlen += 3; } else { gettimeofday(&tv, NULL); #if defined(__sun__) && !defined(__clang__) ctime_r((const time_t *) &tv.tv_sec, ctime_storage, 26); #else ctime_r((const time_t *) &tv.tv_sec, ctime_storage); #endif memcpy(logpkt, ctime_storage, 24); memcpy(logpkt + 24, " - ", 3); rlen = 24 + 3; } va_start(ap, fmt); rlen += vsnprintf(logpkt + rlen, 4096 - rlen, fmt, ap); va_end(ap); // do not check for errors rlen = write(2, logpkt, rlen); } /* commodity function mainly useful in log rotation */ void uwsgi_logfile_write(const char *fmt, ...) { va_list ap; char logpkt[4096]; struct timeval tv; char ctime_storage[26]; gettimeofday(&tv, NULL); #if defined(__sun__) && !defined(__clang__) ctime_r((const time_t *) &tv.tv_sec, ctime_storage, 26); #else ctime_r((const time_t *) &tv.tv_sec, ctime_storage); #endif memcpy(logpkt, ctime_storage, 24); memcpy(logpkt + 24, " - ", 3); int rlen = 24 + 3; va_start(ap, fmt); rlen += vsnprintf(logpkt + rlen, 4096 - rlen, fmt, ap); va_end(ap); // do not check for errors rlen = write(uwsgi.original_log_fd, logpkt, rlen); } static void fix_logpipe_buf(int *fd) { int so_bufsize; socklen_t so_bufsize_len = sizeof(int); if (getsockopt(fd[0], SOL_SOCKET, SO_RCVBUF, &so_bufsize, &so_bufsize_len)) { uwsgi_error("fix_logpipe_buf()/getsockopt()"); return; } if ((size_t)so_bufsize < uwsgi.log_master_bufsize) { so_bufsize = uwsgi.log_master_bufsize; if (setsockopt(fd[0], SOL_SOCKET, SO_RCVBUF, &so_bufsize, so_bufsize_len)) { uwsgi_error("fix_logpipe_buf()/setsockopt()"); } } if (getsockopt(fd[1], SOL_SOCKET, SO_SNDBUF, &so_bufsize, &so_bufsize_len)) { uwsgi_error("fix_logpipe_buf()/getsockopt()"); return; } if ((size_t)so_bufsize < uwsgi.log_master_bufsize) { so_bufsize = uwsgi.log_master_bufsize; if (setsockopt(fd[1], SOL_SOCKET, SO_SNDBUF, &so_bufsize, so_bufsize_len)) { uwsgi_error("fix_logpipe_buf()/setsockopt()"); } } } // create the logpipe void create_logpipe(void) { if (uwsgi.log_master_stream) { if (socketpair(AF_UNIX, SOCK_STREAM, 0, uwsgi.shared->worker_log_pipe)) { uwsgi_error("create_logpipe()/socketpair()\n"); exit(1); } } else { #if defined(SOCK_SEQPACKET) && defined(__linux__) if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, uwsgi.shared->worker_log_pipe)) { #else if (socketpair(AF_UNIX, SOCK_DGRAM, 0, uwsgi.shared->worker_log_pipe)) { #endif uwsgi_error("create_logpipe()/socketpair()\n"); exit(1); } fix_logpipe_buf(uwsgi.shared->worker_log_pipe); } uwsgi_socket_nb(uwsgi.shared->worker_log_pipe[0]); uwsgi_socket_nb(uwsgi.shared->worker_log_pipe[1]); if (uwsgi.shared->worker_log_pipe[1] != 1) { if (dup2(uwsgi.shared->worker_log_pipe[1], 1) < 0) { uwsgi_error("dup2()"); exit(1); } } if (dup2(1, 2) < 0) { uwsgi_error("dup2()"); exit(1); } if (uwsgi.req_log_master) { if (uwsgi.<API key>) { if (socketpair(AF_UNIX, SOCK_STREAM, 0, uwsgi.shared->worker_req_log_pipe)) { uwsgi_error("create_logpipe()/socketpair()\n"); exit(1); } } else { #if defined(SOCK_SEQPACKET) && defined(__linux__) if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, uwsgi.shared->worker_req_log_pipe)) { #else if (socketpair(AF_UNIX, SOCK_DGRAM, 0, uwsgi.shared->worker_req_log_pipe)) { #endif uwsgi_error("create_logpipe()/socketpair()\n"); exit(1); } fix_logpipe_buf(uwsgi.shared->worker_req_log_pipe); } uwsgi_socket_nb(uwsgi.shared->worker_req_log_pipe[0]); uwsgi_socket_nb(uwsgi.shared->worker_req_log_pipe[1]); uwsgi.req_log_fd = uwsgi.shared->worker_req_log_pipe[1]; } } // log to the specified file or udp address void logto(char *logfile) { int fd; char *udp_port; struct sockaddr_in udp_addr; udp_port = strchr(logfile, ':'); if (udp_port) { udp_port[0] = 0; if (!udp_port[1] || !logfile[0]) { uwsgi_log("invalid udp address\n"); exit(1); } fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { uwsgi_error("socket()"); exit(1); } memset(&udp_addr, 0, sizeof(struct sockaddr_in)); udp_addr.sin_family = AF_INET; udp_addr.sin_port = htons(atoi(udp_port + 1)); char *resolved = uwsgi_resolve_ip(logfile); if (resolved) { udp_addr.sin_addr.s_addr = inet_addr(resolved); } else { udp_addr.sin_addr.s_addr = inet_addr(logfile); } if (connect(fd, (const struct sockaddr *) &udp_addr, sizeof(struct sockaddr_in)) < 0) { uwsgi_error("connect()"); exit(1); } } else { if (uwsgi.log_truncate) { fd = open(logfile, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP); } else { fd = open(logfile, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP); } if (fd < 0) { uwsgi_error_open(logfile); exit(1); } uwsgi.logfile = logfile; if (uwsgi.chmod_logfile_value) { if (fchmod(fd, uwsgi.chmod_logfile_value)) { uwsgi_error("fchmod()"); } } } // if the log-master is already active, just re-set the original_log_fd if (uwsgi.shared->worker_log_pipe[0] == -1) { /* stdout */ if (fd != 1) { if (dup2(fd, 1) < 0) { uwsgi_error("dup2()"); exit(1); } close(fd); } /* stderr */ if (dup2(1, 2) < 0) { uwsgi_error("dup2()"); exit(1); } uwsgi.original_log_fd = 2; } else { uwsgi.original_log_fd = fd; } } void uwsgi_setup_log() { <API key>(); if (uwsgi.daemonize) { if (uwsgi.has_emperor) { logto(uwsgi.daemonize); } else { if (!uwsgi.is_a_reload) { daemonize(uwsgi.daemonize); } else if (uwsgi.log_reopen) { logto(uwsgi.daemonize); } } } else if (uwsgi.logfile) { if (!uwsgi.is_a_reload || uwsgi.log_reopen) { logto(uwsgi.logfile); } } } static struct uwsgi_logger *<API key>(struct uwsgi_string_list *usl) { char *id = NULL; char *name = usl->value; char *space = strchr(name, ' '); if (space) { int is_id = 1; int i; for (i = 0; i < (space - name); i++) { if (!isalnum((int)name[i])) { is_id = 0; break; } } if (is_id) { id = uwsgi_concat2n(name, space - name, "", 0); name = space + 1; } } char *colon = strchr(name, ':'); if (colon) { *colon = 0; } struct uwsgi_logger *choosen_logger = uwsgi_get_logger(name); if (!choosen_logger) { uwsgi_log("unable to find logger %s\n", name); exit(1); } // make a copy of the logger struct uwsgi_logger *<API key> = uwsgi_malloc(sizeof(struct uwsgi_logger)); memcpy(<API key>, choosen_logger, sizeof(struct uwsgi_logger)); choosen_logger = <API key>; choosen_logger->id = id; choosen_logger->next = NULL; if (colon) { choosen_logger->arg = colon + 1; // check for empty string if (*choosen_logger->arg == 0) { choosen_logger->arg = NULL; } *colon = ':'; } return choosen_logger; } void <API key>(void) { struct uwsgi_string_list *usl = uwsgi.requested_logger; while (usl) { struct uwsgi_logger *choosen_logger = <API key>(usl); uwsgi_append_logger(choosen_logger); usl = usl->next; } usl = uwsgi.<API key>; while (usl) { struct uwsgi_logger *choosen_logger = <API key>(usl); <API key>(choosen_logger); usl = usl->next; } #ifdef UWSGI_PCRE // set logger by its id struct uwsgi_regexp_list *url = uwsgi.log_route; while (url) { url->custom_ptr = <API key>(url->custom_str); url = url->next; } url = uwsgi.log_req_route; while (url) { url->custom_ptr = <API key>(url->custom_str); url = url->next; } #endif uwsgi.original_log_fd = dup(1); create_logpipe(); } struct uwsgi_logvar *uwsgi_logvar_get(struct wsgi_request *wsgi_req, char *key, uint8_t keylen) { struct uwsgi_logvar *lv = wsgi_req->logvars; while (lv) { if (!uwsgi_strncmp(key, keylen, lv->key, lv->keylen)) { return lv; } lv = lv->next; } return NULL; } void uwsgi_logvar_add(struct wsgi_request *wsgi_req, char *key, uint8_t keylen, char *val, uint8_t vallen) { struct uwsgi_logvar *lv = uwsgi_logvar_get(wsgi_req, key, keylen); if (lv) { memcpy(lv->val, val, vallen); lv->vallen = vallen; return; } // add a new log object lv = wsgi_req->logvars; if (lv) { while (lv) { if (!lv->next) { lv->next = uwsgi_malloc(sizeof(struct uwsgi_logvar)); lv = lv->next; break; } lv = lv->next; } } else { lv = uwsgi_malloc(sizeof(struct uwsgi_logvar)); wsgi_req->logvars = lv; } memcpy(lv->key, key, keylen); lv->keylen = keylen; memcpy(lv->val, val, vallen); lv->vallen = vallen; lv->next = NULL; } void <API key>(void) { int need_rotation = 0; int need_reopen = 0; off_t logsize; if (uwsgi.log_master) { logsize = lseek(uwsgi.original_log_fd, 0, SEEK_CUR); } else { logsize = lseek(2, 0, SEEK_CUR); } if (logsize < 0) { uwsgi_error("<API key>()/lseek()"); return; } uwsgi.shared->logsize = logsize; if (uwsgi.log_maxsize > 0 && (uint64_t) uwsgi.shared->logsize > uwsgi.log_maxsize) { need_rotation = 1; } if (uwsgi_check_touches(uwsgi.touch_logrotate)) { need_rotation = 1; } if (uwsgi_check_touches(uwsgi.touch_logreopen)) { need_reopen = 1; } if (need_rotation) { uwsgi_log_rotate(); } else if (need_reopen) { uwsgi_log_reopen(); } } void uwsgi_log_do_rotate(char *logfile, char *rotatedfile, off_t logsize, int log_fd) { int need_free = 0; char *rot_name = rotatedfile; if (rot_name == NULL) { char *ts_str = uwsgi_num2str((int) uwsgi_now()); rot_name = uwsgi_concat3(logfile, ".", ts_str); free(ts_str); need_free = 1; } // this will be rawly written to the logfile uwsgi_logfile_write("logsize: %llu, triggering rotation to %s...\n", (unsigned long long) logsize, rot_name); if (rename(logfile, rot_name) == 0) { // reopen logfile and dup'it, on dup2 error, exit(1) int fd = open(logfile, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP); if (fd < 0) { // this will be written to the original file uwsgi_error_open(logfile); exit(1); } else { if (dup2(fd, log_fd) < 0) { // this could be lost :( uwsgi_error("uwsgi_log_do_rotate()/dup2()"); exit(1); } close(fd); } } else { uwsgi_error("unable to rotate log: rename()"); } if (need_free) free(rot_name); } void uwsgi_log_rotate() { if (!uwsgi.logfile) return; uwsgi_log_do_rotate(uwsgi.logfile, uwsgi.log_backupname, uwsgi.shared->logsize, uwsgi.original_log_fd); } void uwsgi_log_reopen() { char message[1024]; if (!uwsgi.logfile) return; int ret = snprintf(message, 1024, "[%d] logsize: %llu, triggering log-reopen...\n", (int) uwsgi_now(), (unsigned long long) uwsgi.shared->logsize); if (ret > 0 && ret < 1024) { if (write(uwsgi.original_log_fd, message, ret) != ret) { // very probably this will never be printed uwsgi_error("write()"); } } // reopen logfile; close(uwsgi.original_log_fd); uwsgi.original_log_fd = open(uwsgi.logfile, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP); if (uwsgi.original_log_fd < 0) { uwsgi_error_open(uwsgi.logfile); grace_them_all(0); return; } ret = snprintf(message, 1024, "[%d] %s reopened.\n", (int) uwsgi_now(), uwsgi.logfile); if (ret > 0 && ret < 1024) { if (write(uwsgi.original_log_fd, message, ret) != ret) { // very probably this will never be printed uwsgi_error("write()"); } } uwsgi.shared->logsize = lseek(uwsgi.original_log_fd, 0, SEEK_CUR); } void log_request(struct wsgi_request *wsgi_req) { int log_it = uwsgi.logging_options.enabled; if (wsgi_req->do_not_log) return; if (wsgi_req->log_this) { goto logit; } /* conditional logging */ if (uwsgi.logging_options.zero && wsgi_req->response_size == 0) { goto logit; } if (uwsgi.logging_options.slow && (uint32_t) wsgi_req_time >= uwsgi.logging_options.slow) { goto logit; } if (uwsgi.logging_options._4xx && (wsgi_req->status >= 400 && wsgi_req->status <= 499)) { goto logit; } if (uwsgi.logging_options._5xx && (wsgi_req->status >= 500 && wsgi_req->status <= 599)) { goto logit; } if (uwsgi.logging_options.big && (wsgi_req->response_size >= uwsgi.logging_options.big)) { goto logit; } if (uwsgi.logging_options.sendfile && wsgi_req->via == UWSGI_VIA_SENDFILE) { goto logit; } if (uwsgi.logging_options.ioerror && wsgi_req->read_errors > 0 && wsgi_req->write_errors > 0) { goto logit; } if (!log_it) return; logit: uwsgi.logit(wsgi_req); } void uwsgi_logit_simple(struct wsgi_request *wsgi_req) { // optimize this (please) char time_request[26]; int rlen; int app_req = -1; char *msg2 = " "; char *via = msg2; char mempkt[4096]; char logpkt[4096]; struct iovec logvec[4]; int logvecpos = 0; const char *msecs = "msecs"; const char *micros = "micros"; char *tsize = (char *) msecs; char *msg1 = " via sendfile() "; char *msg3 = " via route() "; char *msg4 = " via offload() "; struct uwsgi_app *wi; if (wsgi_req->app_id >= 0) { wi = &uwsgi_apps[wsgi_req->app_id]; if (wi->requests > 0) { app_req = wi->requests; } } // mark requests via (sendfile, route, offload...) switch(wsgi_req->via) { case UWSGI_VIA_SENDFILE: via = msg1; break; case UWSGI_VIA_ROUTE: via = msg3; break; case UWSGI_VIA_OFFLOAD: via = msg4; break; default: break; } #if defined(__sun__) && !defined(__clang__) ctime_r((const time_t *) &wsgi_req-><API key>, time_request, 26); #else ctime_r((const time_t *) &wsgi_req-><API key>, time_request); #endif uint64_t rt = wsgi_req->end_of_request - wsgi_req->start_of_request; if (uwsgi.log_micros) { tsize = (char *) micros; } else { rt /= 1000; } if (uwsgi.vhost) { logvec[logvecpos].iov_base = wsgi_req->host; logvec[logvecpos].iov_len = wsgi_req->host_len; logvecpos++; logvec[logvecpos].iov_base = " "; logvec[logvecpos].iov_len = 1; logvecpos++; } if (uwsgi.logging_options.memory_report == 1) { rlen = snprintf(mempkt, 4096, "{address space usage: %lld bytes/%lluMB} {rss usage: %llu bytes/%lluMB} ", (unsigned long long) uwsgi.workers[uwsgi.mywid].vsz_size, (unsigned long long) uwsgi.workers[uwsgi.mywid].vsz_size / 1024 / 1024, (unsigned long long) uwsgi.workers[uwsgi.mywid].rss_size, (unsigned long long) uwsgi.workers[uwsgi.mywid].rss_size / 1024 / 1024); logvec[logvecpos].iov_base = mempkt; logvec[logvecpos].iov_len = rlen; logvecpos++; } rlen = snprintf(logpkt, 4096, "[pid: %d|app: %d|req: %d/%llu] %.*s (%.*s) {%d vars in %llu bytes} [%.*s] %.*s %.*s => generated %llu bytes in %llu %s%s(%.*s %d) %d headers in %llu bytes (%d switches on core %d)\n", (int) uwsgi.mypid, wsgi_req->app_id, app_req, (unsigned long long) uwsgi.workers[0].requests, wsgi_req->remote_addr_len, wsgi_req->remote_addr, wsgi_req->remote_user_len, wsgi_req->remote_user, wsgi_req->var_cnt, (unsigned long long) wsgi_req->len, 24, time_request, wsgi_req->method_len, wsgi_req->method, wsgi_req->uri_len, wsgi_req->uri, (unsigned long long) wsgi_req->response_size, (unsigned long long) rt, tsize, via, wsgi_req->protocol_len, wsgi_req->protocol, wsgi_req->status, wsgi_req->header_cnt, (unsigned long long) wsgi_req->headers_size, wsgi_req->switches, wsgi_req->async_id); // not enough space for logging the request, just log a (safe) minimal message if (rlen > 4096) { rlen = snprintf(logpkt, 4096, "[pid: %d|app: %d|req: %d/%llu] 0.0.0.0 () {%d vars in %llu bytes} [%.*s] - - => generated %llu bytes in %llu %s%s(- %d) %d headers in %llu bytes (%d switches on core %d)\n", (int) uwsgi.mypid, wsgi_req->app_id, app_req, (unsigned long long) uwsgi.workers[0].requests, wsgi_req->var_cnt, (unsigned long long) wsgi_req->len, 24, time_request, (unsigned long long) wsgi_req->response_size, (unsigned long long) rt, tsize, via, wsgi_req->status, wsgi_req->header_cnt, (unsigned long long) wsgi_req->headers_size, wsgi_req->switches, wsgi_req->async_id); // argh, last resort, truncate it if (rlen > 4096) { rlen = 4096; } } logvec[logvecpos].iov_base = logpkt; logvec[logvecpos].iov_len = rlen; // do not check for errors rlen = writev(uwsgi.req_log_fd, logvec, logvecpos + 1); } void get_memusage(uint64_t * rss, uint64_t * vsz) { #ifdef UNBIT uint64_t ret[2]; ret[0] = 0; ret[1] = 0; syscall(358, ret); *vsz = ret[0]; *rss = ret[1] * uwsgi.page_size; #elif defined(__linux__) FILE *procfile; int i; procfile = fopen("/proc/self/stat", "r"); if (procfile) { i = fscanf(procfile, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %llu %lld", (unsigned long long *) vsz, (unsigned long long *) rss); if (i != 2) { uwsgi_log("warning: invalid record in /proc/self/stat\n"); } else { *rss = *rss * uwsgi.page_size; } fclose(procfile); } #elif defined(__CYGWIN__) // same as Linux but rss is not in pages... FILE *procfile; int i; procfile = fopen("/proc/self/stat", "r"); if (procfile) { i = fscanf(procfile, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %llu %lld", (unsigned long long *) vsz, (unsigned long long *) rss); if (i != 2) { uwsgi_log("warning: invalid record in /proc/self/stat\n"); } fclose(procfile); } #elif defined (__sun__) psinfo_t info; int procfd; procfd = open("/proc/self/psinfo", O_RDONLY); if (procfd >= 0) { if (read(procfd, (char *) &info, sizeof(info)) > 0) { *rss = (uint64_t) info.pr_rssize * 1024; *vsz = (uint64_t) info.pr_size * 1024; } close(procfd); } #elif defined(__APPLE__) /* darwin documentation says that the value are in pages, but they are bytes !!! */ struct task_basic_info t_info; <API key> t_size = sizeof(struct task_basic_info); if (task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t) & t_info, &t_size) == KERN_SUCCESS) { *rss = t_info.resident_size; *vsz = t_info.virtual_size; } #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) kvm_t *kv; int cnt; #if defined(__FreeBSD__) kv = kvm_open(NULL, "/dev/null", NULL, O_RDONLY, NULL); #elif defined(__NetBSD__) || defined(__OpenBSD__) kv = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); #else kv = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL); #endif if (kv) { #if defined(__FreeBSD__) || defined(__DragonFly__) struct kinfo_proc *kproc; kproc = kvm_getprocs(kv, KERN_PROC_PID, uwsgi.mypid, &cnt); if (kproc && cnt > 0) { #if defined(__FreeBSD__) *vsz = kproc->ki_size; *rss = kproc->ki_rssize * uwsgi.page_size; #elif defined(__DragonFly__) *vsz = kproc->kp_vm_map_size; *rss = kproc->kp_vm_rssize * uwsgi.page_size; #endif } #elif defined(UWSGI_NEW_OPENBSD) struct kinfo_proc *kproc; kproc = kvm_getprocs(kv, KERN_PROC_PID, uwsgi.mypid, sizeof(struct kinfo_proc), &cnt); if (kproc && cnt > 0) { *vsz = (kproc->p_vm_dsize + kproc->p_vm_ssize + kproc->p_vm_tsize) * uwsgi.page_size; *rss = kproc->p_vm_rssize * uwsgi.page_size; } #elif defined(__NetBSD__) || defined(__OpenBSD__) struct kinfo_proc2 *kproc2; kproc2 = kvm_getproc2(kv, KERN_PROC_PID, uwsgi.mypid, sizeof(struct kinfo_proc2), &cnt); if (kproc2 && cnt > 0) { #ifdef __OpenBSD__ *vsz = (kproc2->p_vm_dsize + kproc2->p_vm_ssize + kproc2->p_vm_tsize) * uwsgi.page_size; #else *vsz = kproc2->p_vm_msize * uwsgi.page_size; #endif *rss = kproc2->p_vm_rssize * uwsgi.page_size; } #endif kvm_close(kv); } #elif defined(__HAIKU__) area_info ai; int32 cookie; *vsz = 0; *rss = 0; while (get_next_area_info(0, &cookie, &ai) == B_OK) { *vsz += ai.ram_size; if ((ai.protection & B_WRITE_AREA) != 0) { *rss += ai.ram_size; } } #endif } void <API key>(char *name, ssize_t(*func) (struct uwsgi_logger *, char *, size_t)) { struct uwsgi_logger *ul = uwsgi.loggers, *old_ul; if (!ul) { uwsgi.loggers = uwsgi_malloc(sizeof(struct uwsgi_logger)); ul = uwsgi.loggers; } else { while (ul) { old_ul = ul; ul = ul->next; } ul = uwsgi_malloc(sizeof(struct uwsgi_logger)); old_ul->next = ul; } ul->name = name; ul->func = func; ul->next = NULL; ul->configured = 0; ul->fd = -1; ul->data = NULL; ul->buf = NULL; #ifdef UWSGI_DEBUG uwsgi_log("[uwsgi-logger] registered \"%s\"\n", ul->name); #endif } void uwsgi_append_logger(struct uwsgi_logger *ul) { if (!uwsgi.choosen_logger) { uwsgi.choosen_logger = ul; return; } struct uwsgi_logger *ucl = uwsgi.choosen_logger; while (ucl) { if (!ucl->next) { ucl->next = ul; return; } ucl = ucl->next; } } void <API key>(struct uwsgi_logger *ul) { if (!uwsgi.choosen_req_logger) { uwsgi.choosen_req_logger = ul; return; } struct uwsgi_logger *ucl = uwsgi.choosen_req_logger; while (ucl) { if (!ucl->next) { ucl->next = ul; return; } ucl = ucl->next; } } struct uwsgi_logger *uwsgi_get_logger(char *name) { struct uwsgi_logger *ul = uwsgi.loggers; while (ul) { if (!strcmp(ul->name, name)) { return ul; } ul = ul->next; } return NULL; } struct uwsgi_logger *<API key>(char *id) { struct uwsgi_logger *ul = uwsgi.choosen_logger; while (ul) { if (ul->id && !strcmp(ul->id, id)) { return ul; } ul = ul->next; } return NULL; } void uwsgi_logit_lf(struct wsgi_request *wsgi_req) { struct uwsgi_logchunk *logchunk = uwsgi.logchunks; ssize_t rlen = 0; const char *empty_var = "-"; while (logchunk) { int pos = logchunk->vec; // raw string if (logchunk->type == 0) { uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = logchunk->ptr; uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = logchunk->len; } // offsetof else if (logchunk->type == 1) { char **var = (char **) (((char *) wsgi_req) + logchunk->pos); uint16_t *varlen = (uint16_t *) (((char *) wsgi_req) + logchunk->pos_len); uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = *var; uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = *varlen; } // logvar else if (logchunk->type == 2) { struct uwsgi_logvar *lv = uwsgi_logvar_get(wsgi_req, logchunk->ptr, logchunk->len); if (lv) { uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = lv->val; uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = lv->vallen; } else { uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = NULL; uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = 0; } } // func else if (logchunk->type == 3) { rlen = logchunk->func(wsgi_req, (char **) &uwsgi.logvectors[wsgi_req->async_id][pos].iov_base); if (rlen > 0) { uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = rlen; } else { uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = 0; } } // var else if (logchunk->type == 5) { uint16_t value_len = 0; char *value = uwsgi_get_var(wsgi_req, logchunk->ptr, logchunk->len, &value_len); // could be NULL uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = value; uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = (size_t) value_len; } // metric else if (logchunk->type == 4) { int64_t metric = uwsgi_metric_get(logchunk->ptr, NULL); uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = uwsgi_64bit2str(metric); uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = strlen(uwsgi.logvectors[wsgi_req->async_id][pos].iov_base); } if (uwsgi.logvectors[wsgi_req->async_id][pos].iov_len == 0 && logchunk->type != 0) { uwsgi.logvectors[wsgi_req->async_id][pos].iov_base = (char *) empty_var; uwsgi.logvectors[wsgi_req->async_id][pos].iov_len = 1; } logchunk = logchunk->next; } // do not check for errors rlen = writev(uwsgi.req_log_fd, uwsgi.logvectors[wsgi_req->async_id], uwsgi.logformat_vectors); // free allocated memory logchunk = uwsgi.logchunks; while (logchunk) { if (logchunk->free) { if (uwsgi.logvectors[wsgi_req->async_id][logchunk->vec].iov_len > 0) { if (uwsgi.logvectors[wsgi_req->async_id][logchunk->vec].iov_base != empty_var) { free(uwsgi.logvectors[wsgi_req->async_id][logchunk->vec].iov_base); } } } logchunk = logchunk->next; } } void <API key>(char *format) { int state = 0; char *ptr = format; char *current = ptr; char *logvar = NULL; // get the number of required iovec while (*ptr) { if (*ptr == '%') { if (state == 0) { state = 1; } } // start of the variable else if (*ptr == '(') { if (state == 1) { state = 2; } } // end of the variable else if (*ptr == ')') { if (logvar) { uwsgi_add_logchunk(1, uwsgi.logformat_vectors, logvar, ptr - logvar); uwsgi.logformat_vectors++; state = 0; logvar = NULL; current = ptr + 1; } } else { if (state == 2) { uwsgi_add_logchunk(0, uwsgi.logformat_vectors, current, (ptr - current) - 2); uwsgi.logformat_vectors++; logvar = ptr; } state = 0; } ptr++; } if (ptr - current > 0) { uwsgi_add_logchunk(0, uwsgi.logformat_vectors, current, ptr - current); uwsgi.logformat_vectors++; } // +1 for "\n" uwsgi.logformat_vectors++; } static ssize_t uwsgi_lf_status(struct wsgi_request *wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->status); return strlen(*buf); } static ssize_t uwsgi_lf_rsize(struct wsgi_request *wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->response_size); return strlen(*buf); } static ssize_t uwsgi_lf_hsize(struct wsgi_request *wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->headers_size); return strlen(*buf); } static ssize_t uwsgi_lf_size(struct wsgi_request *wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->headers_size+wsgi_req->response_size); return strlen(*buf); } static ssize_t uwsgi_lf_cl(struct wsgi_request *wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->post_cl); return strlen(*buf); } static ssize_t uwsgi_lf_epoch(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi_now()); return strlen(*buf); } static ssize_t uwsgi_lf_ctime(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_malloc(26); #if defined(__sun__) && !defined(__clang__) ctime_r((const time_t *) &wsgi_req-><API key>, *buf, 26); #else ctime_r((const time_t *) &wsgi_req-><API key>, *buf); #endif return 24; } static ssize_t uwsgi_lf_time(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->start_of_request / 1000000); return strlen(*buf); } static ssize_t uwsgi_lf_ltime(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_malloc(64); time_t now = wsgi_req->start_of_request / 1000000; size_t ret = strftime(*buf, 64, "%d/%b/%Y:%H:%M:%S %z", localtime(&now)); if (ret == 0) { *buf[0] = 0; return 0; } return ret; } static ssize_t uwsgi_lf_ftime(struct wsgi_request * wsgi_req, char **buf) { if (!uwsgi.logformat_strftime || !uwsgi.log_strftime) { return uwsgi_lf_ltime(wsgi_req, buf); } *buf = uwsgi_malloc(64); time_t now = wsgi_req->start_of_request / 1000000; size_t ret = strftime(*buf, 64, uwsgi.log_strftime, localtime(&now)); if (ret == 0) { *buf[0] = 0; return 0; } return ret; } static ssize_t uwsgi_lf_tmsecs(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_64bit2str(wsgi_req->start_of_request / (int64_t) 1000); return strlen(*buf); } static ssize_t uwsgi_lf_tmicros(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_64bit2str(wsgi_req->start_of_request); return strlen(*buf); } static ssize_t uwsgi_lf_micros(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->end_of_request - wsgi_req->start_of_request); return strlen(*buf); } static ssize_t uwsgi_lf_msecs(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str((wsgi_req->end_of_request - wsgi_req->start_of_request) / 1000); return strlen(*buf); } static ssize_t uwsgi_lf_pid(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi.mypid); return strlen(*buf); } static ssize_t uwsgi_lf_wid(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi.mywid); return strlen(*buf); } static ssize_t uwsgi_lf_switches(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->switches); return strlen(*buf); } static ssize_t uwsgi_lf_vars(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->var_cnt); return strlen(*buf); } static ssize_t uwsgi_lf_core(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->async_id); return strlen(*buf); } static ssize_t uwsgi_lf_vsz(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi.workers[uwsgi.mywid].vsz_size); return strlen(*buf); } static ssize_t uwsgi_lf_rss(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi.workers[uwsgi.mywid].rss_size); return strlen(*buf); } static ssize_t uwsgi_lf_vszM(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi.workers[uwsgi.mywid].vsz_size / 1024 / 1024); return strlen(*buf); } static ssize_t uwsgi_lf_rssM(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(uwsgi.workers[uwsgi.mywid].rss_size / 1024 / 1024); return strlen(*buf); } static ssize_t uwsgi_lf_pktsize(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->len); return strlen(*buf); } static ssize_t uwsgi_lf_modifier1(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->uh->modifier1); return strlen(*buf); } static ssize_t uwsgi_lf_modifier2(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->uh->modifier2); return strlen(*buf); } static ssize_t uwsgi_lf_headers(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->header_cnt); return strlen(*buf); } static ssize_t uwsgi_lf_werr(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str((int) wsgi_req->write_errors); return strlen(*buf); } static ssize_t uwsgi_lf_rerr(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str((int) wsgi_req->read_errors); return strlen(*buf); } static ssize_t uwsgi_lf_ioerr(struct wsgi_request * wsgi_req, char **buf) { *buf = uwsgi_num2str((int) (wsgi_req->write_errors + wsgi_req->read_errors)); return strlen(*buf); } struct uwsgi_logchunk *<API key>(char *name, ssize_t (*func)(struct wsgi_request *, char **), int need_free) { struct uwsgi_logchunk *old_logchunk = NULL, *logchunk = uwsgi.<API key>; while(logchunk) { if (!strcmp(logchunk->name, name)) goto found; old_logchunk = logchunk; logchunk = logchunk->next; } logchunk = uwsgi_calloc(sizeof(struct uwsgi_logchunk)); logchunk->name = name; if (old_logchunk) { old_logchunk->next = logchunk; } else { uwsgi.<API key> = logchunk; } found: logchunk->func = func; logchunk->free = need_free; logchunk->type = 3; return logchunk; } struct uwsgi_logchunk *<API key>(char *name, size_t name_len) { struct uwsgi_logchunk *logchunk = uwsgi.<API key>; while(logchunk) { if (!uwsgi_strncmp(name, name_len, logchunk->name, strlen(logchunk->name))) { return logchunk; } logchunk = logchunk->next; } return NULL; } void uwsgi_add_logchunk(int variable, int pos, char *ptr, size_t len) { struct uwsgi_logchunk *logchunk = uwsgi.logchunks; if (logchunk) { while (logchunk) { if (!logchunk->next) { logchunk->next = uwsgi_calloc(sizeof(struct uwsgi_logchunk)); logchunk = logchunk->next; break; } logchunk = logchunk->next; } } else { uwsgi.logchunks = uwsgi_calloc(sizeof(struct uwsgi_logchunk)); logchunk = uwsgi.logchunks; } /* 0 -> raw text 1 -> offsetof variable 2 -> logvar 3 -> func 4 -> metric 5 -> request variable */ logchunk->type = variable; logchunk->vec = pos; // normal text logchunk->ptr = ptr; logchunk->len = len; // variable if (variable) { struct uwsgi_logchunk *rlc = <API key>(ptr, len); if (rlc) { if (rlc->type == 1) { logchunk->pos = rlc->pos; logchunk->pos_len = rlc->pos_len; } else if (rlc->type == 3) { logchunk->type = 3; logchunk->func = rlc->func; logchunk->free = rlc->free; } } // var else if (!uwsgi_starts_with(ptr, len, "var.", 4)) { logchunk->type = 5; logchunk->ptr = ptr+4; logchunk->len = len-4; logchunk->free = 0; } // metric else if (!uwsgi_starts_with(ptr, len, "metric.", 7)) { logchunk->type = 4; logchunk->ptr = uwsgi_concat2n(ptr+7, len - 7, "", 0); logchunk->free = 1; } // logvar else { logchunk->type = 2; } } } static void uwsgi_log_func_do(struct uwsgi_string_list *encoders, struct uwsgi_logger *ul, char *msg, size_t len) { struct uwsgi_string_list *usl = encoders; // note: msg must not be freed !!! char *new_msg = msg; size_t new_msg_len = len; while(usl) { struct uwsgi_log_encoder *ule = (struct uwsgi_log_encoder *) usl->custom_ptr; if (ule->use_for) { if (ul && ul->id) { if (strcmp(ule->use_for, ul->id)) { goto next; } } else { goto next; } } size_t rlen = 0; char *buf = ule->func(ule, new_msg, new_msg_len, &rlen); if (new_msg != msg) { free(new_msg); } new_msg = buf; new_msg_len = rlen; next: usl = usl->next; } if (ul) { ul->func(ul, new_msg, new_msg_len); } else { new_msg_len = (size_t) write(uwsgi.original_log_fd, new_msg, new_msg_len); } if (new_msg != msg) { free(new_msg); } } int uwsgi_master_log(void) { ssize_t rlen = read(uwsgi.shared->worker_log_pipe[0], uwsgi.log_master_buf, uwsgi.log_master_bufsize); if (rlen > 0) { #ifdef UWSGI_PCRE <API key>(uwsgi.log_master_buf, rlen); struct uwsgi_regexp_list *url = uwsgi.log_drain_rules; while (url) { if (uwsgi_regexp_match(url->pattern, url->pattern_extra, uwsgi.log_master_buf, rlen) >= 0) { return 0; } url = url->next; } if (uwsgi.log_filter_rules) { int show = 0; url = uwsgi.log_filter_rules; while (url) { if (uwsgi_regexp_match(url->pattern, url->pattern_extra, uwsgi.log_master_buf, rlen) >= 0) { show = 1; break; } url = url->next; } if (!show) return 0; } url = uwsgi.log_route; int finish = 0; while (url) { if (uwsgi_regexp_match(url->pattern, url->pattern_extra, uwsgi.log_master_buf, rlen) >= 0) { struct uwsgi_logger *ul_route = (struct uwsgi_logger *) url->custom_ptr; if (ul_route) { uwsgi_log_func_do(uwsgi.<API key>, ul_route, uwsgi.log_master_buf, rlen); finish = 1; } } url = url->next; } if (finish) return 0; #endif int raw_log = 1; struct uwsgi_logger *ul = uwsgi.choosen_logger; while (ul) { // check for named logger if (ul->id) { goto next; } uwsgi_log_func_do(uwsgi.<API key>, ul, uwsgi.log_master_buf, rlen); raw_log = 0; next: ul = ul->next; } if (raw_log) { uwsgi_log_func_do(uwsgi.<API key>, NULL, uwsgi.log_master_buf, rlen); } return 0; } return -1; } int <API key>(void) { ssize_t rlen = read(uwsgi.shared->worker_req_log_pipe[0], uwsgi.log_master_buf, uwsgi.log_master_bufsize); if (rlen > 0) { #ifdef UWSGI_PCRE struct uwsgi_regexp_list *url = uwsgi.log_req_route; int finish = 0; while (url) { if (uwsgi_regexp_match(url->pattern, url->pattern_extra, uwsgi.log_master_buf, rlen) >= 0) { struct uwsgi_logger *ul_route = (struct uwsgi_logger *) url->custom_ptr; if (ul_route) { uwsgi_log_func_do(uwsgi.<API key>, ul_route, uwsgi.log_master_buf, rlen); finish = 1; } } url = url->next; } if (finish) return 0; #endif int raw_log = 1; struct uwsgi_logger *ul = uwsgi.choosen_req_logger; while (ul) { // check for named logger if (ul->id) { goto next; } uwsgi_log_func_do(uwsgi.<API key>, ul, uwsgi.log_master_buf, rlen); raw_log = 0; next: ul = ul->next; } if (raw_log) { uwsgi_log_func_do(uwsgi.<API key>, NULL, uwsgi.log_master_buf, rlen); } return 0; } return -1; } static void *logger_thread_loop(void *noarg) { struct pollfd logpoll[2]; // block all signals sigset_t smask; sigfillset(&smask); pthread_sigmask(SIG_BLOCK, &smask, NULL); logpoll[0].events = POLLIN; logpoll[0].fd = uwsgi.shared->worker_log_pipe[0]; int logpolls = 1; if (uwsgi.req_log_master) { logpoll[1].events = POLLIN; logpoll[1].fd = uwsgi.shared->worker_req_log_pipe[0]; logpolls++; } for (;;) { int ret = poll(logpoll, logpolls, -1); if (ret > 0) { if (logpoll[0].revents & POLLIN) { pthread_mutex_lock(&uwsgi.<API key>); uwsgi_master_log(); <API key>(&uwsgi.<API key>); } else if (logpolls > 1 && logpoll[1].revents & POLLIN) { pthread_mutex_lock(&uwsgi.<API key>); <API key>(); <API key>(&uwsgi.<API key>); } } } return NULL; } void <API key>() { pthread_t logger_thread; if (pthread_create(&logger_thread, NULL, logger_thread_loop, NULL)) { uwsgi_error("pthread_create()"); uwsgi_log("falling back to non-threaded logger...\n"); <API key>(uwsgi.master_queue, uwsgi.shared->worker_log_pipe[0]); if (uwsgi.req_log_master) { <API key>(uwsgi.master_queue, uwsgi.shared->worker_req_log_pipe[0]); } uwsgi.threaded_logger = 0; } } void <API key>() { pthread_t logger_thread; pthread_mutex_init(&uwsgi.<API key>, NULL); uwsgi.log_master_buf = uwsgi_malloc(uwsgi.log_master_bufsize); if (pthread_create(&logger_thread, NULL, logger_thread_loop, NULL)) { uwsgi_error_safe("<API key>()/pthread_create()"); exit(1); } } void <API key>(char *name, char *(*func)(struct uwsgi_log_encoder *, char *, size_t, size_t *)) { struct uwsgi_log_encoder *old_ule = NULL, *ule = uwsgi.log_encoders; while(ule) { if (!strcmp(ule->name, name)) { ule->func = func; return; } old_ule = ule; ule = ule->next; } ule = uwsgi_calloc(sizeof(struct uwsgi_log_encoder)); ule->name = name; ule->func = func; if (old_ule) { old_ule->next = ule; } else { uwsgi.log_encoders = ule; } } struct uwsgi_log_encoder *<API key>(char *name) { struct uwsgi_log_encoder *ule = uwsgi.log_encoders; while(ule) { if (!strcmp(name, ule->name)) return ule; ule = ule->next; } return NULL; } void <API key>() { struct uwsgi_string_list *usl = NULL; uwsgi_foreach(usl, uwsgi.<API key>) { char *space = strchr(usl->value, ' '); if (space) *space = 0; char *use_for = strchr(usl->value, ':'); if (use_for) *use_for = 0; struct uwsgi_log_encoder *ule = <API key>(usl->value); if (!ule) { uwsgi_log("log encoder \"%s\" not found\n", usl->value); exit(1); } struct uwsgi_log_encoder *ule2 = uwsgi_malloc(sizeof(struct uwsgi_log_encoder)); memcpy(ule2, ule, sizeof(struct uwsgi_log_encoder)); if (use_for) { ule2->use_for = uwsgi_str(use_for+1); *use_for = ':'; } // we use a copy if (space) { *space = ' '; ule2->args = uwsgi_str(space+1); } else { ule2->args = uwsgi_str(""); } usl->custom_ptr = ule2; uwsgi_log("[log-encoder] registered %s\n", usl->value); } uwsgi_foreach(usl, uwsgi.<API key>) { char *space = strchr(usl->value, ' '); if (space) *space = 0; char *use_for = strchr(usl->value, ':'); if (use_for) *use_for = 0; struct uwsgi_log_encoder *ule = <API key>(usl->value); if (!ule) { uwsgi_log("log encoder \"%s\" not found\n", usl->value); exit(1); } struct uwsgi_log_encoder *ule2 = uwsgi_malloc(sizeof(struct uwsgi_log_encoder)); memcpy(ule2, ule, sizeof(struct uwsgi_log_encoder)); if (use_for) { ule2->use_for = uwsgi_str(use_for+1); *use_for = ':'; } // we use a copy if (space) { *space = ' '; ule2->args = uwsgi_str(space+1); } else { ule2->args = uwsgi_str(""); } usl->custom_ptr = ule2; uwsgi_log("[log-req-encoder] registered %s\n", usl->value); } } #ifdef UWSGI_ZLIB static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { struct uwsgi_buffer *ub = uwsgi_gzip(msg, len); if (!ub) return NULL; *rlen = ub->pos; // avoid destruction char *buf = ub->buf; ub->buf = NULL; <API key>(ub); return buf; } static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { size_t c_len = (size_t) compressBound(len); uLongf destLen = c_len; char *buf = uwsgi_malloc(c_len); if (compress((Bytef *) buf, &destLen, (Bytef *)msg, (uLong) len) == Z_OK) { *rlen = destLen; return buf; } free(buf); return NULL; } #endif /* really fast encoder adding only a prefix */ static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { char *buf = NULL; struct uwsgi_buffer *ub = uwsgi_buffer_new(len + strlen(ule->args)); if (uwsgi_buffer_append(ub, ule->args, strlen(ule->args))) goto end; if (uwsgi_buffer_append(ub, msg, len)) goto end; *rlen = ub->pos; buf = ub->buf; ub->buf = NULL; end: <API key>(ub); return buf; } /* really fast encoder adding only a newline */ static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { char *buf = NULL; struct uwsgi_buffer *ub = uwsgi_buffer_new(len + 1); if (uwsgi_buffer_append(ub, msg, len)) goto end; if (uwsgi_buffer_byte(ub, '\n')) goto end; *rlen = ub->pos; buf = ub->buf; ub->buf = NULL; end: <API key>(ub); return buf; } /* really fast encoder adding only a suffix */ static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { char *buf = NULL; struct uwsgi_buffer *ub = uwsgi_buffer_new(len + strlen(ule->args)); if (uwsgi_buffer_append(ub, msg, len)) goto end; if (uwsgi_buffer_append(ub, ule->args, strlen(ule->args))) goto end; *rlen = ub->pos; buf = ub->buf; ub->buf = NULL; end: <API key>(ub); return buf; } void <API key>(struct uwsgi_log_encoder *ule) { char *ptr = ule->args; size_t remains = strlen(ptr); char *base = ptr; size_t base_len = 0; char *var = NULL; size_t var_len = 0; int status = 0; // 1 -> $ 2-> { end -> } while(remains char b = *ptr++; if (status == 1) { if (b == '{') { status = 2; continue; } base_len+=2; status = 0; continue; } else if (status == 2) { if (b == '}') { status = 0; <API key>((struct uwsgi_string_list **) &ule->data, uwsgi_concat2n(base, base_len, "", 0)); struct uwsgi_string_list *usl = <API key>((struct uwsgi_string_list **) &ule->data, uwsgi_concat2n(var, var_len, "", 0)); usl->custom = 1; var = NULL; var_len = 0; base = NULL; base_len = 0; continue; } if (!var) var = (ptr-1); var_len++; continue; } // status == 0 if (b == '$') { status = 1; } else { if (!base) base = (ptr-1); base_len++; } } if (base) { if (status == 1) { base_len+=2; } else if (status == 2) { base_len+=3; } <API key>((struct uwsgi_string_list **) &ule->data, uwsgi_concat2n(base, base_len, "", 0)); } } /* // format: foo ${var} bar msg (the logline) msgnl (the logline with newline) unix (the time_t value) micros (current microseconds) strftime (strftime) */ static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { if (!ule->configured) { <API key>(ule); ule->configured = 1; } struct uwsgi_buffer *ub = uwsgi_buffer_new(strlen(ule->args) + len); struct uwsgi_string_list *usl = (struct uwsgi_string_list *) ule->data; char *buf = NULL; while(usl) { if (usl->custom) { if (!uwsgi_strncmp(usl->value, usl->len, "msg", 3)) { if (msg[len-1] == '\n') { if (uwsgi_buffer_append(ub, msg, len-1)) goto end; } else { if (uwsgi_buffer_append(ub, msg, len)) goto end; } } else if (!uwsgi_strncmp(usl->value, usl->len, "msgnl", 5)) { if (uwsgi_buffer_append(ub, msg, len)) goto end; } else if (!uwsgi_strncmp(usl->value, usl->len, "unix", 4)) { if (uwsgi_buffer_num64(ub, uwsgi_now())) goto end; } else if (!uwsgi_strncmp(usl->value, usl->len, "micros", 6)) { if (uwsgi_buffer_num64(ub, uwsgi_micros())) goto end; } else if (!uwsgi_starts_with(usl->value, usl->len, "strftime:", 9)) { char sftime[64]; time_t now = uwsgi_now(); char *buf = uwsgi_concat2n(usl->value+9, usl->len-9,"", 0); int strftime_len = strftime(sftime, 64, buf, localtime(&now)); free(buf); if (strftime_len > 0) { if (uwsgi_buffer_append(ub, sftime, strftime_len)) goto end; } } } else { if (uwsgi_buffer_append(ub, usl->value, usl->len)) goto end; } usl = usl->next; } buf = ub->buf; *rlen = ub->pos; ub->buf = NULL; end: <API key>(ub); return buf; } static char *<API key>(struct uwsgi_log_encoder *ule, char *msg, size_t len, size_t *rlen) { if (!ule->configured) { <API key>(ule); ule->configured = 1; } struct uwsgi_buffer *ub = uwsgi_buffer_new(strlen(ule->args) + len); struct uwsgi_string_list *usl = (struct uwsgi_string_list *) ule->data; char *buf = NULL; while(usl) { if (usl->custom) { if (!uwsgi_strncmp(usl->value, usl->len, "msg", 3)) { size_t msg_len = len; if (msg[len-1] == '\n') msg_len char *e_json = uwsgi_malloc((msg_len * 2)+1); escape_json(msg, msg_len, e_json); if (uwsgi_buffer_append(ub, e_json, strlen(e_json))){ free(e_json); goto end; } free(e_json); } else if (!uwsgi_strncmp(usl->value, usl->len, "msgnl", 5)) { char *e_json = uwsgi_malloc((len * 2)+1); escape_json(msg, len, e_json); if (uwsgi_buffer_append(ub, e_json, strlen(e_json))){ free(e_json); goto end; } free(e_json); } else if (!uwsgi_strncmp(usl->value, usl->len, "unix", 4)) { if (uwsgi_buffer_num64(ub, uwsgi_now())) goto end; } else if (!uwsgi_strncmp(usl->value, usl->len, "micros", 6)) { if (uwsgi_buffer_num64(ub, uwsgi_micros())) goto end; } else if (!uwsgi_starts_with(usl->value, usl->len, "strftime:", 9)) { char sftime[64]; time_t now = uwsgi_now(); char *buf = uwsgi_concat2n(usl->value+9, usl->len-9, "", 0); int strftime_len = strftime(sftime, 64, buf, localtime(&now)); free(buf); if (strftime_len > 0) { char *e_json = uwsgi_malloc((strftime_len * 2)+1); escape_json(sftime, strftime_len, e_json); if (uwsgi_buffer_append(ub, e_json, strlen(e_json))){ free(e_json); goto end; } free(e_json); } } } else { if (uwsgi_buffer_append(ub, usl->value, usl->len)) goto end; } usl = usl->next; } buf = ub->buf; *rlen = ub->pos; ub->buf = NULL; end: <API key>(ub); return buf; } #define r_logchunk(x) <API key>(#x, uwsgi_lf_ ## x, 1) #define r_logchunk_offset(x, y) { struct uwsgi_logchunk *lc = <API key>(#x, NULL, 0); lc->pos = offsetof(struct wsgi_request, y); lc->pos_len = offsetof(struct wsgi_request, y ## _len); lc->type = 1; lc->free=0;} void <API key>() { // offsets r_logchunk_offset(uri, uri); r_logchunk_offset(method, method); r_logchunk_offset(user, remote_user); r_logchunk_offset(addr, remote_addr); r_logchunk_offset(host, host); r_logchunk_offset(proto, protocol); r_logchunk_offset(uagent, user_agent); r_logchunk_offset(referer, referer); // funcs r_logchunk(status); r_logchunk(rsize); r_logchunk(hsize); r_logchunk(size); r_logchunk(cl); r_logchunk(micros); r_logchunk(msecs); r_logchunk(tmsecs); r_logchunk(tmicros); r_logchunk(time); r_logchunk(ltime); r_logchunk(ftime); r_logchunk(ctime); r_logchunk(epoch); r_logchunk(pid); r_logchunk(wid); r_logchunk(switches); r_logchunk(vars); r_logchunk(core); r_logchunk(vsz); r_logchunk(rss); r_logchunk(vszM); r_logchunk(rssM); r_logchunk(pktsize); r_logchunk(modifier1); r_logchunk(modifier2); r_logchunk(headers); r_logchunk(werr); r_logchunk(rerr); r_logchunk(ioerr); } void <API key>() { <API key>("prefix", <API key>); <API key>("suffix", <API key>); <API key>("nl", <API key>); <API key>("format", <API key>); <API key>("json", <API key>); #ifdef UWSGI_ZLIB <API key>("gzip", <API key>); <API key>("compress", <API key>); #endif }
<?php // No direct access. defined('_JEXEC') or die; jimport('joomla.application.component.modelform'); /** * Download model. * * @package Joomla.Administrator * @subpackage com_banners * @since 1.5 */ class <API key> extends JModelForm { protected $_context = 'com_banners.tracks'; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { $basename = JRequest::getString(JApplication::getHash($this->_context.'.basename'), '__SITE__', 'cookie'); $this->setState('basename', $basename); $compressed = JRequest::getInt(JApplication::getHash($this->_context.'.compressed'), 1, 'cookie'); $this->setState('compressed', $compressed); } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return mixed A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_banners.download', 'download', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { return array( 'basename' => $this->getState('basename'), 'compressed' => $this->getState('compressed') ); } }
#ifndef lint static const char rcsid[] = "@(#) $Header: /nfs/jade/vint/CVSROOT/ns-2/emulate/net-ip.cc,v 1.20 2003/10/12 21:13:09 xuanc Exp $ (LBL)"; #endif #include <stdio.h> #ifndef WIN32 #include <unistd.h> #endif #include <time.h> #include <errno.h> #include <string.h> #ifdef WIN32 #include <io.h> #define close closesocket #else #include <sys/param.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> typedef int Socket; #endif #if defined(sun) && defined(__svr4__) #include <sys/systeminfo.h> #endif #include "config.h" #include "net.h" #include "inet.h" #include "tclcl.h" #include "scheduler.h" //#define NIPDEBUG 1 #ifdef NIPDEBUG #define NIDEBUG(x) { if (NIPDEBUG) fprintf(stderr, (x)); } #define NIDEBUG2(x,y) { if (NIPDEBUG) fprintf(stderr, (x), (y)); } #define NIDEBUG3(x,y,z) { if (NIPDEBUG) fprintf(stderr, (x), (y), (z)); } #define NIDEBUG4(w,x,y,z) { if (NIPDEBUG) fprintf(stderr, (w), (x), (y), (z)); } #define NIDEBUG5(v,w,x,y,z) { if (NIPDEBUG) fprintf(stderr, (v), (w), (x), (y), (z)); } #else #define NIDEBUG(x) { } #define NIDEBUG2(x,y) { } #define NIDEBUG3(x,y,z) { } #define NIDEBUG4(w,x,y,z) { } #define NIDEBUG5(v,w,x,y,z) { } #endif /* * Net-ip.cc: this file defines the IP and IP/UDP network * objects. IP provides a raw IP interface and support functions * [such as setting multicast parameters]. IP/UDP provides a standard * UDP datagram interface. */ // IPNetwork: a low-level (raw) IP network object class IPNetwork : public Network { public: IPNetwork(); inline int ttl() const { return (mttl_); } // current mcast ttl inline int noloopback_broken() { // no loopback filter? return (noloopback_broken_); } int setmttl(Socket, int); // set mcast ttl int setmloop(Socket, int); // set mcast loopback int command(int argc, const char*const* argv); // virtual in Network inline Socket rchannel() { return(rsock_); } // virtual in Network inline Socket schannel() { return(ssock_); } // virtual in Network int send(u_char* buf, int len); // virtual in Network int recv(u_char* buf, int len, sockaddr& from, double& ); // virtual in Network inline in_addr& laddr() { return (localaddr_); } inline in_addr& dstaddr() { return (destaddr_); } int add_membership(Socket, in_addr& grp); // join mcast int drop_membership(Socket, in_addr& grp); // leave mcast /* generally useful routines */ static int bindsock(Socket, in_addr&, u_int16_t, sockaddr_in&); static int connectsock(Socket, in_addr&, u_int16_t, sockaddr_in&); static int rbufsize(Socket, int); static int sbufsize(Socket, int); protected: in_addr destaddr_; // remote side, if set (network order) in_addr localaddr_; // local side (network order) int mttl_; // multicast ttl to use Socket rsock_; // socket to receive on Socket ssock_; // socket to send on int noloopback_broken_; // couldn't turn (off) mcast loopback int loop_; // do we want loopbacks? // (system usually assumes yes) void reset(int reconfigure); // reset + reconfig? virtual int open(int mode); // open sockets/endpoints virtual void reconfigure(); // restore state after reset int close(); time_t last_reset_; }; class UDPIPNetwork : public IPNetwork { public: UDPIPNetwork(); int send(u_char*, int); int recv(u_char*, int, sockaddr&, double&); int open(int mode); // mode only int command(int argc, const char*const* argv); void reconfigure(); void add_membership(Socket, in_addr&, u_int16_t); // udp version protected: int bind(in_addr&, u_int16_t port); // bind to addr/port, mcast ok int connect(in_addr& remoteaddr, u_int16_t port); // connect() u_int16_t lport_; // local port (network order) u_int16_t port_; // remote (dst) port (network order) }; static class IPNetworkClass : public TclClass { public: IPNetworkClass() : TclClass("Network/IP") {} TclObject* create(int, const char*const*) { return (new IPNetwork); } } nm_ip; static class UDPIPNetworkClass : public TclClass { public: UDPIPNetworkClass() : TclClass("Network/IP/UDP") {} TclObject* create(int, const char*const*) { return (new UDPIPNetwork); } } nm_ip_udp; IPNetwork::IPNetwork() : mttl_(0), rsock_(-1), ssock_(-1), noloopback_broken_(0), loop_(1) { localaddr_.s_addr = 0L; destaddr_.s_addr = 0L; NIDEBUG("IPNetwork: ctor\n"); } UDPIPNetwork::UDPIPNetwork() : lport_(htons(0)), port_(htons(0)) { NIDEBUG("UDPIPNetwork: ctor\n"); } /* * UDPIP::send -- send "len" bytes in buffer "buf" out the sending * channel. * * returns the number of bytes written */ int UDPIPNetwork::send(u_char* buf, int len) { int cc = ::send(schannel(), (char*)buf, len, 0); NIDEBUG5("UDPIPNetwork(%s): ::send(%d, buf, %d) returned %d\n", name(), schannel(), len, cc); if (cc < 0) { switch (errno) { case ECONNREFUSED: /* no one listening at some site - ignore */ #if defined(__osf__) || defined(_AIX) || defined(__FreeBSD__) /* * Here's an old comment... * * Due to a bug in kern/uipc_socket.c, on several * systems, datagram sockets incorrectly persist * in an error state on receipt of an ICMP * port-unreachable. This causes unicast connection * rendezvous problems, and worse, multicast * transmission problems because several systems * incorrectly send port unreachables for * multicast destinations. Our work around * is to simply close and reopen the socket * (by calling reset() below). * * This bug originated at CSRG in Berkeley * and was present in the BSD Reno networking * code release. It has since been fixed * in 4.4BSD and OSF-3.x. It is known to remain * in AIX-4.1.3. * * A fix is to change the following lines from * kern/uipc_socket.c: * * if (so_serror) * snderr(so->so_error); * * to: * * if (so->so_error) { * error = so->so_error; * so->so_error = 0; * splx(s); * goto release; * } * */ reset(1); #endif break; case ENETUNREACH: case EHOSTUNREACH: /* * These "errors" are totally meaningless. * There is some broken host sending * icmp unreachables for multicast destinations. * UDP probably aborted the send because of them -- * try exactly once more. E.g., the send we * just did cleared the errno for the previous * icmp unreachable, so we should be able to * send now. */ cc = ::send(schannel(), (char*)buf, len, 0); break; default: fprintf(stderr, "UDPIPNetwork(%s): send failed: %s\n", name(), strerror(errno)); return (-1); } } return cc; // bytes sent } int UDPIPNetwork::recv(u_char* buf, int len, sockaddr& from, double& ts) { sockaddr_in sfrom; int fromlen = sizeof(sfrom); int cc = ::recvfrom(rsock_, (char*)buf, len, 0, (sockaddr*)&sfrom, (socklen_t*)&fromlen); NIDEBUG5("UDPIPNetwork(%s): ::recvfrom(%d, buf, %d) returned %d\n", name(), rsock_, len, cc); if (cc < 0) { if (errno != EWOULDBLOCK) { fprintf(stderr, "UDPIPNetwork(%s): recvfrom failed: %s\n", name(), strerror(errno)); } return (-1); } from = *((sockaddr*)&sfrom); /* * if we received multicast data and we don't want the look, * there is a chance it is * what we sent if "noloopback_broken_" is set. * If so, filter out the stuff we don't want right here. */ if (!loop_ && noloopback_broken_ && sfrom.sin_addr.s_addr == localaddr_.s_addr && sfrom.sin_port == lport_) { NIDEBUG2("UDPIPNetwork(%s): filtered out our own pkt\n", name()); return (0); // empty } ts = Scheduler::instance().clock(); return (cc); // number of bytes received } int UDPIPNetwork::open(int mode) { if (mode == O_RDONLY || mode == O_RDWR) { rsock_ = socket(AF_INET, SOCK_DGRAM, 0); if (rsock_ < 0) { fprintf(stderr, "UDPIPNetwork(%s): open: couldn't open rcv sock\n", name()); } nonblock(rsock_); int on = 1; if (::setsockopt(rsock_, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) { fprintf(stderr, "UDPIPNetwork(%s): open: warning: unable set REUSEADDR: %s\n", name(), strerror(errno)); } #ifdef SO_REUSEPORT on = 1; if (::setsockopt(rsock_, SOL_SOCKET, SO_REUSEPORT, (char *)&on, sizeof(on)) < 0) { fprintf(stderr, "UDPIPNetwork(%s): open: warning: unable set REUSEPORT: %s\n", name(), strerror(errno)); } #endif /* * XXX don't need this for the session socket. */ if (rbufsize(rsock_, 80*1024) < 0) { if (rbufsize(rsock_, 32*1024) < 0) { fprintf(stderr, "UDPIPNetwork(%s): open: unable to set r bufsize to %d: %s\n", name(), 32*1024, strerror(errno)); } } } if (mode == O_WRONLY || mode == O_RDWR) { ssock_ = socket(AF_INET, SOCK_DGRAM, 0); if (ssock_ < 0) { fprintf(stderr, "UDPIPNetwork(%s): open: couldn't open snd sock\n", name()); } nonblock(ssock_); int firsttry = 80 * 1024; int secondtry = 48 * 1024; if (sbufsize(ssock_, firsttry) < 0) { if (sbufsize(ssock_, secondtry) < 0) { fprintf(stderr, "UDPIPNetwork(%s): open: cannot set send sockbuf size to %d bytes, using default\n", name(), secondtry); } } } mode_ = mode; NIDEBUG5("UDPIPNetwork(%s): opened network w/mode %d, ssock:%d, rsock:%d\n", name(), mode_, rsock_, ssock_); return (0); } // IP/UDP version of add_membership: try binding void UDPIPNetwork::add_membership(Socket sock, in_addr& addr, u_int16_t port) { int failure = 0; sockaddr_in sin; if (bindsock(sock, addr, port, sin) < 0) failure = 1; if (failure) { in_addr addr2 = addr; addr2.s_addr = INADDR_ANY; if (bindsock(sock, addr2, port, sin) < 0) failure = 1; else failure = 0; } if (IPNetwork::add_membership(sock, addr) < 0) failure = 1; if (failure) { fprintf(stderr, "UDPIPNetwork(%s): add_membership: failed bind on mcast addr %s and INADDR_ANY\n", name(), inet_ntoa(addr)); } } // server-side bind (or mcast subscription) int UDPIPNetwork::bind(in_addr& addr, u_int16_t port) { NIDEBUG4("UDPIPNetwork(%s): attempt to bind to addr %s, port %d [net order]\n", name(), inet_ntoa(addr), ntohs(port)); if (rsock_ < 0) { fprintf(stderr, "UDPIPNetwork(%s): bind/listen called before net is open\n", name()); return (-1); } if (mode_ == O_WRONLY) { fprintf(stderr, "UDPIPNetwork(%s): attempted bind/listen but net is write-only\n", name()); return (-1); } #ifdef IP_ADD_MEMBERSHIP if (IN_CLASSD(ntohl(addr.s_addr))) { // MULTICAST case, call UDPIP vers of add_membership add_membership(rsock_, addr, port); } else #endif { // UNICAST case sockaddr_in sin; if (bindsock(rsock_, addr, port, sin) < 0) { port = ntohs(port); fprintf(stderr, "UDPIPNetwork(%s): bind: unable to bind %s [port:%hu]: %s\n", name(), inet_ntoa(addr), port, strerror(errno)); return (-1); } /* * MS Windows currently doesn't compy with the Internet Host * Requirements standard (RFC-1122) and won't let us include * the source address in the receive socket demux state. */ #ifndef WIN32 /* * (try to) connect the foreign host's address to this socket. */ (void)connectsock(rsock_, addr, 0, sin); #endif } localaddr_ = addr; lport_ = port; return (0); } // client-side connect int UDPIPNetwork::connect(in_addr& addr, u_int16_t port) { sockaddr_in sin; if (ssock_ < 0) { fprintf(stderr, "UDPIPNetwork(%s): connect called before net is open\n", name()); return (-1); } if (mode_ == O_RDONLY) { fprintf(stderr, "UDPIPNetwork(%s): attempted connect but net is read-only\n", name()); return (-1); } int rval = connectsock(ssock_, addr, port, sin); if (rval < 0) return (rval); destaddr_ = addr; port_ = port; last_reset_ = 0; return(rval); } int UDPIPNetwork::command(int argc, const char*const* argv) { Tcl& tcl = Tcl::instance(); if (argc == 2) { // $udpip port if (strcmp(argv[1], "port") == 0) { tcl.resultf("%d", ntohs(port_)); return (TCL_OK); } // $udpip lport if (strcmp(argv[1], "lport") == 0) { tcl.resultf("%d", ntohs(lport_)); return (TCL_OK); } } else if (argc == 4) { // $udpip listen addr port // $udpip bind addr port if (strcmp(argv[1], "listen") == 0 || strcmp(argv[1], "bind") == 0) { in_addr addr; if (strcmp(argv[2], "any") == 0) addr.s_addr = INADDR_ANY; else addr.s_addr = LookupHostAddr(argv[2]); u_int16_t port = htons(atoi(argv[3])); if (bind(addr, port) < 0) { tcl.resultf("%s %hu", inet_ntoa(addr), port); } else { tcl.result("0"); } return (TCL_OK); } // $udpip connect addr port if (strcmp(argv[1], "connect") == 0) { in_addr addr; addr.s_addr = LookupHostAddr(argv[2]); u_int16_t port = htons(atoi(argv[3])); if (connect(addr, port) < 0) { tcl.resultf("%s %hu", inet_ntoa(addr), port); } else { tcl.result("0"); } return (TCL_OK); } } return (IPNetwork::command(argc, argv)); } // raw IP network recv() int IPNetwork::recv(u_char* buf, int len, sockaddr& sa, double& ts) { if (mode_ == O_WRONLY) { fprintf(stderr, "IPNetwork(%s) recv while in writeonly mode!\n", name()); abort(); } int fromlen = sizeof(sa); int cc = ::recvfrom(rsock_, (char*)buf, len, 0, &sa, (socklen_t*)&fromlen); if (cc < 0) { if (errno != EWOULDBLOCK) perror("recvfrom"); return (-1); } ts = Scheduler::instance().clock(); return (cc); } // we are given a "raw" IP datagram. // the raw interface appears to want the len and off fields // in *host* order, so make it this way here // note also, that it will compute the cksum "for" us... :( int IPNetwork::send(u_char* buf, int len) { struct ip *ip = (struct ip*) buf; #ifdef __linux__ // For raw sockets on linux the send does not work, // all packets show up only on the loopback device and are not routed // to the correct host. Using sendto on a closed socket solves this problem ip->ip_len = (ip->ip_len); ip->ip_off = (ip->ip_off); sockaddr_in sin; memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr = ip->ip_dst; return (::sendto(ssock_, (char*)buf, len, 0,(sockaddr *) &sin,sizeof(sin))); #else ip->ip_len = ntohs(ip->ip_len); ip->ip_off = ntohs(ip->ip_off); return (::send(ssock_, (char*)buf, len, 0)); #endif } int IPNetwork::command(int argc, const char*const* argv) { Tcl& tcl = Tcl::instance(); if (argc == 2) { if (strcmp(argv[1], "close") == 0) { close(); return (TCL_OK); } // Old approach uses tcl.result() to get result buffer first // char* cp = tcl.result(); // new approach uses tcl.result(const char*) directly. // xuanc, 10/07/2003 if (strcmp(argv[1], "destaddr") == 0) { tcl.result(inet_ntoa(destaddr_)); return (TCL_OK); } if (strcmp(argv[1], "localaddr") == 0) { tcl.result(inet_ntoa(localaddr_)); return (TCL_OK); } if (strcmp(argv[1], "mttl") == 0) { tcl.resultf("%d", mttl_); return (TCL_OK); } /* for backward compatability */ if (strcmp(argv[1], "ismulticast") == 0) { tcl.result(IN_CLASSD(ntohl(destaddr_.s_addr)) ? "1" : "0"); return (TCL_OK); } if (strcmp(argv[1], "addr") == 0) { tcl.result(inet_ntoa(destaddr_)); return (TCL_OK); } if (strcmp(argv[1], "ttl") == 0) { tcl.resultf("%d", mttl_); return (TCL_OK); } if (strcmp(argv[1], "interface") == 0) { tcl.result(inet_ntoa(localaddr_)); return (TCL_OK); } } else if (argc == 3) { if (strcmp(argv[1], "open") == 0) { int mode = parsemode(argv[2]); if (open(mode) < 0) return (TCL_ERROR); return (TCL_OK); } if (strcmp(argv[1], "add-membership") == 0) { in_addr addr; addr.s_addr = LookupHostAddr(argv[2]); if (add_membership(rchannel(), addr) < 0) tcl.result("0"); else tcl.result("1"); return (TCL_OK); } if (strcmp(argv[1], "drop-membership") == 0) { in_addr addr; addr.s_addr = LookupHostAddr(argv[2]); if (drop_membership(rchannel(), addr) < 0) tcl.result("0"); else tcl.result("1"); return (TCL_OK); } if (strcmp(argv[1], "loopback") == 0) { int val = atoi(argv[2]); if (strcmp(argv[2], "true") == 0) val = 1; else if (strcmp(argv[2], "false") == 0) val = 0; if (setmloop(schannel(), val) < 0) tcl.result("0"); else tcl.result("1"); return (TCL_OK); } } return (Network::command(argc, argv)); } int IPNetwork::setmttl(Socket s, int ttl) { /* set the multicast TTL */ #ifdef WIN32 u_int t = ttl; #else u_char t = ttl; #endif t = (ttl > 255) ? 255 : (ttl < 0) ? 0 : ttl; if (::setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&t, sizeof(t)) < 0) { fprintf(stderr, "IPNetwork(%s): couldn't set multicast ttl to %d\n", name(), t); return (-1); } return (0); } /* * open a RAW IP socket (will require privilege). * turn on HDRINCL, specifying that we will be writing the raw IP header */ int IPNetwork::open(int mode) { // obtain a raw socket we can use to send ip datagrams Socket fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (fd < 0) { perror("socket(RAW)"); if (::getuid() != 0 && ::geteuid() != 0) { fprintf(stderr, "IPNetwork(%s): open: use of the Network/IP object requires super-user privs\n", name()); } return (-1); } // turn on HDRINCL option (we will be writing IP header) // in FreeBSD 2.2.5 (and possibly others), the IP id field // is set by the kernel routine rip_output() // only if it is non-zero, so we should be ok. int one = 1; if (::setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0) { fprintf(stderr, "IPNetwork(%s): open: unable to turn on IP_HDRINCL: %s\n", name(), strerror(errno)); return (-1); } #ifndef __linux__ // sort of curious, but do a connect() even though we have // HDRINCL on. Otherwise, we get ENOTCONN when doing a send() sockaddr_in sin; in_addr ia = { INADDR_ANY }; if (connectsock(fd, ia, 0, sin) < 0) { fprintf(stderr, "IPNetwork(%s): open: unable to connect : %s\n", name(), strerror(errno)); } #endif rsock_ = ssock_ = fd; mode_ = mode; NIDEBUG5("IPNetwork(%s): opened with mode %d, rsock_:%d, ssock_:%d\n", name(), mode_, rsock_, ssock_); return 0; } /* * close both sending and receiving sockets */ int IPNetwork::close() { if (ssock_ >= 0) { (void)::close(ssock_); ssock_ = -1; } if (rsock_ >= 0) { (void)::close(rsock_); rsock_ = -1; } return (0); } /* * add multicast group membership on the socket */ int IPNetwork::add_membership(Socket fd, in_addr& addr) { #if defined(IP_ADD_MEMBERSHIP) if (IN_CLASSD(ntohl(addr.s_addr))) { #ifdef notdef /* * Try to bind the multicast address as the socket * dest address. On many systems this won't work * so fall back to a destination of INADDR_ANY if * the first bind fails. */ sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr = addr; if (::bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) { sin.sin_addr.s_addr = INADDR_ANY; if (::bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) { fprintf(stderr, "IPNetwork(%s): add_membership: unable to bind to addr %s: %s\n", name(), inet_ntoa(sin.sin_addr), strerror(errno)); return (-1); } } #endif /* * XXX This is bogus multicast setup that really * shouldn't have to be done (group membership should be * implicit in the IP class D address, route should contain * ttl & no loopback flag, etc.). Steve Deering has promised * to fix this for the 4.4bsd release. We're all waiting * with bated breath. */ struct ip_mreq mr; mr.imr_multiaddr = addr; mr.imr_interface.s_addr = INADDR_ANY; if (::setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mr, sizeof(mr)) < 0) { fprintf(stderr, "IPNetwork(%s): add_membership: unable to add membership for addr %s: %s\n", name(), inet_ntoa(addr), strerror(errno)); return (-1); } NIDEBUG3("IPNetwork(%s): add_membership for grp %s done\n", name(), inet_ntoa(addr)); return (0); } #else fprintf(stderr, "IPNetwork(%s): add_membership: host does not support IP multicast\n", name()); #endif NIDEBUG3("IPNetwork(%s): add_membership for grp %s failed\n", name(), inet_ntoa(addr)); return (-1); } /* * drop membership from the specified group on the specified socket */ int IPNetwork::drop_membership(Socket fd, in_addr& addr) { #if defined(IP_DROP_MEMBERSHIP) if (IN_CLASSD(ntohl(addr.s_addr))) { struct ip_mreq mr; mr.imr_multiaddr = addr; mr.imr_interface.s_addr = INADDR_ANY; if (::setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&mr, sizeof(mr)) < 0) { fprintf(stderr, "IPNetwork(%s): drop_membership: unable to drop membership for addr %s: %s\n", name(), inet_ntoa(addr), strerror(errno)); return (-1); } NIDEBUG3("IPNetwork(%s): drop_membership for grp %s done\n", name(), inet_ntoa(addr)); return (0); } #else fprintf(stderr, "IPNetwork(%s): drop_membership: host does not support IP multicast\n", name()); #endif NIDEBUG3("IPNetwork(%s): drop_membership for grp %s failed\n", name(), inet_ntoa(addr)); return (-1); } int IPNetwork::bindsock(Socket s, in_addr& addr, u_int16_t port, sockaddr_in& sin) { memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = port; sin.sin_addr = addr; return(::bind(s, (struct sockaddr *)&sin, sizeof(sin))); } int IPNetwork::connectsock(Socket s, in_addr& addr, u_int16_t port, sockaddr_in& sin) { memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = port; sin.sin_addr = addr; return(::connect(s, (struct sockaddr *)&sin, sizeof(sin))); } int IPNetwork::sbufsize(Socket s, int cnt) { return(::setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&cnt, sizeof(cnt))); } int IPNetwork::rbufsize(Socket s, int cnt) { return(::setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&cnt, sizeof(cnt))); } int IPNetwork::setmloop(Socket s, int loop) { #ifdef IP_MULTICAST_LOOP u_char c = loop; if (::setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &c, sizeof(c)) < 0) { /* * If we cannot turn off loopback (Like on the * Microsoft TCP/IP stack), then declare this * option broken so that our packets can be * filtered on the recv path. */ if (c != loop) { noloopback_broken_ = 1; loop_ = c; } return (-1); } noloopback_broken_ = 0; #else fprintf(stderr, "IPNetwork(%s): msetloop: host does not support IP multicast\n", name()); #endif loop_ = c; return (0); } void IPNetwork::reset(int restart) { time_t t = time(0); int d = int(t - last_reset_); NIDEBUG2("IPNetwork(%s): reset\n", name()); if (d > 3) { // Steve: why? last_reset_ = t; if (ssock_ >= 0) (void)::close(ssock_); if (rsock_ >= 0) (void)::close(rsock_); if (open(mode_) < 0) { fprintf(stderr, "IPNetwork(%s): couldn't reset\n", name()); mode_ = -1; return; } if (restart) (void) reconfigure(); } } /* * after a reset, we may want to re-establish our state * [set up addressing, etc]. Do this here */ void IPNetwork::reconfigure() { } void UDPIPNetwork::reconfigure() { }
import kivy kivy.require('1.0.6') from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.graphics import Color, Rectangle, Point, GraphicException from random import random from math import sqrt def calculate_points(x1, y1, x2, y2, steps=5): dx = x2 - x1 dy = y2 - y1 dist = sqrt(dx * dx + dy * dy) if dist < steps: return None o = [] m = dist / steps for i in xrange(1, int(m)): mi = i / m lastx = x1 + dx * mi lasty = y1 + dy * mi o.extend([lastx, lasty]) return o class Touchtracer(FloatLayout): def on_touch_down(self, touch): win = self.get_parent_window() ud = touch.ud ud['group'] = g = str(touch.uid) with self.canvas: ud['color'] = Color(random(), 1, 1, mode='hsv', group=g) ud['lines'] = ( Rectangle(pos=(touch.x, 0), size=(1, win.height), group=g), Rectangle(pos=(0, touch.y), size=(win.width, 1), group=g), Point(points=(touch.x, touch.y), source='particle.png', pointsize=5, group=g)) ud['label'] = Label(size_hint=(None, None)) self.update_touch_label(ud['label'], touch) self.add_widget(ud['label']) touch.grab(self) return True def on_touch_move(self, touch): if touch.grab_current is not self: return ud = touch.ud ud['lines'][0].pos = touch.x, 0 ud['lines'][1].pos = 0, touch.y points = ud['lines'][2].points oldx, oldy = points[-2], points[-1] points = calculate_points(oldx, oldy, touch.x, touch.y) if points: try: lp = ud['lines'][2].add_point for idx in xrange(0, len(points), 2): lp(points[idx], points[idx+1]) except GraphicException: pass ud['label'].pos = touch.pos import time t = int(time.time()) if t not in ud: ud[t] = 1 else: ud[t] += 1 self.update_touch_label(ud['label'], touch) def on_touch_up(self, touch): if touch.grab_current is not self: return touch.ungrab(self) ud = touch.ud self.canvas.remove_group(ud['group']) self.remove_widget(ud['label']) def update_touch_label(self, label, touch): label.text = 'ID: %s\nPos: (%d, %d)\nClass: %s' % ( touch.id, touch.x, touch.y, touch.__class__.__name__) label.texture_update() label.pos = touch.pos label.size = label.texture_size[0] + 20, label.texture_size[1] + 20 class TouchtracerApp(App): title = 'Touchtracer' icon = 'icon.png' def build(self): return Touchtracer() def on_pause(self): return True if __name__ == '__main__': TouchtracerApp().run()
/** * DOC: RX A-MPDU aggregation * * Aggregation on the RX side requires only implementing the * @ampdu_action callback that is invoked to start/stop any * block-ack sessions for RX aggregation. * * When RX aggregation is started by the peer, the driver is * notified via @ampdu_action function, with the * %<API key> action, and may reject the request * in which case a negative response is sent to the peer, if it * accepts it a positive response is sent. * * While the session is active, the device/driver are required * to de-aggregate frames and pass them up one by one to mac80211, * which will handle the reorder buffer. * * When the aggregation session is stopped again by the peer or * ourselves, the driver's @ampdu_action function will be called * with the action %<API key>. In this case, the * call must not fail. */ #include <linux/ieee80211-ath.h> #include <linux/slab.h> #include <linux/export.h> #include <net/mac80211-ath.h> #include "ieee80211_i.h" #include "driver-ops.h" static void <API key>(struct rcu_head *h) { struct tid_ampdu_rx *tid_rx = container_of(h, struct tid_ampdu_rx, rcu_head); int i; for (i = 0; i < tid_rx->buf_size; i++) dev_kfree_skb(tid_rx->reorder_buf[i]); kfree(tid_rx->reorder_buf); kfree(tid_rx->reorder_time); kfree(tid_rx); } void <API key>(struct sta_info *sta, u16 tid, u16 initiator, u16 reason, bool tx) { struct ieee80211_local *local = sta->local; struct tid_ampdu_rx *tid_rx; lockdep_assert_held(&sta->ampdu_mlme.mtx); tid_rx = <API key>(sta->ampdu_mlme.tid_rx[tid], lockdep_is_held(&sta->ampdu_mlme.mtx)); if (!tid_rx) return; RCU_INIT_POINTER(sta->ampdu_mlme.tid_rx[tid], NULL); #ifdef <API key> printk(KERN_DEBUG "Rx BA session stop requested for %pM tid %u\n", sta->sta.addr, tid); #endif /* <API key> */ if (drv_ampdu_action(local, sta->sdata, <API key>, &sta->sta, tid, NULL, 0)) printk(KERN_DEBUG "HW problem - can not stop rx " "aggregation for tid %d\n", tid); /* check if this is a self generated aggregation halt */ if (initiator == WLAN_BACK_RECIPIENT && tx) <API key>(sta->sdata, sta->sta.addr, tid, 0, reason); del_timer_sync(&tid_rx->session_timer); del_timer_sync(&tid_rx->reorder_timer); call_rcu(&tid_rx->rcu_head, <API key>); } void <API key>(struct sta_info *sta, u16 tid, u16 initiator, u16 reason, bool tx) { mutex_lock(&sta->ampdu_mlme.mtx); <API key>(sta, tid, initiator, reason, tx); mutex_unlock(&sta->ampdu_mlme.mtx); } void <API key>(struct ieee80211_vif *vif, u16 ba_rx_bitmap, const u8 *addr) { struct <API key> *sdata = vif_to_sdata(vif); struct sta_info *sta; int i; rcu_read_lock(); sta = sta_info_get(sdata, addr); if (!sta) { rcu_read_unlock(); return; } for (i = 0; i < STA_TID_NUM; i++) if (ba_rx_bitmap & BIT(i)) set_bit(i, sta->ampdu_mlme.<API key>); <API key>(&sta->local->hw, &sta->ampdu_mlme.work); rcu_read_unlock(); } EXPORT_SYMBOL(<API key>); /* * After accepting the AddBA Request we activated a timer, * resetting it after each frame that arrives from the originator. */ static void <API key>(unsigned long data) { /* not an elegant detour, but there is no choice as the timer passes * only one argument, and various sta_info are needed here, so init * flow in sta_info_create gives the TID as data, while the timer_to_id * array gives the sta through container_of */ u8 *ptid = (u8 *)data; u8 *timer_to_id = ptid - *ptid; struct sta_info *sta = container_of(timer_to_id, struct sta_info, timer_to_tid[0]); #ifdef <API key> printk(KERN_DEBUG "rx session timer expired on tid %d\n", (u16)*ptid); #endif set_bit(*ptid, sta->ampdu_mlme.<API key>); <API key>(&sta->local->hw, &sta->ampdu_mlme.work); } static void <API key>(unsigned long data) { u8 *ptid = (u8 *)data; u8 *timer_to_id = ptid - *ptid; struct sta_info *sta = container_of(timer_to_id, struct sta_info, timer_to_tid[0]); rcu_read_lock(); <API key>(sta, *ptid); rcu_read_unlock(); } static void <API key>(struct <API key> *sdata, u8 *da, u16 tid, u8 dialog_token, u16 status, u16 policy, u16 buf_size, u16 timeout) { struct ieee80211_local *local = sdata->local; struct sk_buff *skb; struct ieee80211_mgmt *mgmt; u16 capab; skb = dev_alloc_skb(sizeof(*mgmt) + local->hw.extra_tx_headroom); if (!skb) return; skb_reserve(skb, local->hw.extra_tx_headroom); mgmt = (struct ieee80211_mgmt *) skb_put(skb, 24); memset(mgmt, 0, 24); memcpy(mgmt->da, da, ETH_ALEN); memcpy(mgmt->sa, sdata->vif.addr, ETH_ALEN); if (sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == <API key> || sdata->vif.type == <API key>) memcpy(mgmt->bssid, sdata->vif.addr, ETH_ALEN); else if (sdata->vif.type == <API key>) memcpy(mgmt->bssid, sdata->u.mgd.bssid, ETH_ALEN); mgmt->frame_control = cpu_to_le16(<API key> | <API key>); skb_put(skb, 1 + sizeof(mgmt->u.action.u.addba_resp)); mgmt->u.action.category = WLAN_CATEGORY_BACK; mgmt->u.action.u.addba_resp.action_code = <API key>; mgmt->u.action.u.addba_resp.dialog_token = dialog_token; capab = (u16)(policy << 1); /* bit 1 aggregation policy */ capab |= (u16)(tid << 2); /* bit 5:2 TID number */ capab |= (u16)(buf_size << 6); /* bit 15:6 max size of aggregation */ mgmt->u.action.u.addba_resp.capab = cpu_to_le16(capab); mgmt->u.action.u.addba_resp.timeout = cpu_to_le16(timeout); mgmt->u.action.u.addba_resp.status = cpu_to_le16(status); ieee80211_tx_skb(sdata, skb); } void <API key>(struct ieee80211_local *local, struct sta_info *sta, struct ieee80211_mgmt *mgmt, size_t len) { struct tid_ampdu_rx *tid_agg_rx; u16 capab, tid, timeout, ba_policy, buf_size, start_seq_num, status; u8 dialog_token; int ret = -EOPNOTSUPP; /* extract session parameters from addba request frame */ dialog_token = mgmt->u.action.u.addba_req.dialog_token; timeout = le16_to_cpu(mgmt->u.action.u.addba_req.timeout); start_seq_num = le16_to_cpu(mgmt->u.action.u.addba_req.start_seq_num) >> 4; capab = le16_to_cpu(mgmt->u.action.u.addba_req.capab); ba_policy = (capab & <API key>) >> 1; tid = (capab & <API key>) >> 2; buf_size = (capab & <API key>) >> 6; status = <API key>; if (test_sta_flag(sta, WLAN_STA_BLOCK_BA)) { #ifdef <API key> printk(KERN_DEBUG "Suspend in progress. " "Denying ADDBA request\n"); #endif goto end_no_lock; } /* sanity check for incoming parameters: * check if configuration can support the BA policy * and if buffer size does not exceeds max value */ /* XXX: check own ht delayed BA capability?? */ if (((ba_policy != 1) && (!(sta->sta.ht_cap.cap & <API key>))) || (buf_size > <API key>)) { status = <API key>; #ifdef <API key> if (net_ratelimit()) printk(KERN_DEBUG "AddBA Req with bad params from " "%pM on tid %u. policy %d, buffer size %d\n", mgmt->sa, tid, ba_policy, buf_size); #endif /* <API key> */ goto end_no_lock; } /* determine default buffer size */ if (buf_size == 0) buf_size = <API key>; /* make sure the size doesn't exceed the maximum supported by the hw */ if (buf_size > local->hw.<API key>) buf_size = local->hw.<API key>; /* examine state machine */ mutex_lock(&sta->ampdu_mlme.mtx); if (sta->ampdu_mlme.tid_rx[tid]) { #ifdef <API key> if (net_ratelimit()) printk(KERN_DEBUG "unexpected AddBA Req from " "%pM on tid %u\n", mgmt->sa, tid); #endif /* <API key> */ /* delete existing Rx BA session on the same tid */ <API key>(sta, tid, WLAN_BACK_RECIPIENT, <API key>, false); } /* prepare A-MPDU MLME for Rx aggregation */ tid_agg_rx = kmalloc(sizeof(struct tid_ampdu_rx), GFP_KERNEL); if (!tid_agg_rx) goto end; spin_lock_init(&tid_agg_rx->reorder_lock); /* rx timer */ tid_agg_rx->session_timer.function = <API key>; tid_agg_rx->session_timer.data = (unsigned long)&sta->timer_to_tid[tid]; init_timer(&tid_agg_rx->session_timer); /* rx reorder timer */ tid_agg_rx->reorder_timer.function = <API key>; tid_agg_rx->reorder_timer.data = (unsigned long)&sta->timer_to_tid[tid]; init_timer(&tid_agg_rx->reorder_timer); /* prepare reordering buffer */ tid_agg_rx->reorder_buf = kcalloc(buf_size, sizeof(struct sk_buff *), GFP_KERNEL); tid_agg_rx->reorder_time = kcalloc(buf_size, sizeof(unsigned long), GFP_KERNEL); if (!tid_agg_rx->reorder_buf || !tid_agg_rx->reorder_time) { kfree(tid_agg_rx->reorder_buf); kfree(tid_agg_rx->reorder_time); kfree(tid_agg_rx); goto end; } ret = drv_ampdu_action(local, sta->sdata, <API key>, &sta->sta, tid, &start_seq_num, 0); #ifdef <API key> printk(KERN_DEBUG "Rx A-MPDU request on tid %d result %d\n", tid, ret); #endif /* <API key> */ if (ret) { kfree(tid_agg_rx->reorder_buf); kfree(tid_agg_rx->reorder_time); kfree(tid_agg_rx); goto end; } /* update data */ tid_agg_rx->dialog_token = dialog_token; tid_agg_rx->ssn = start_seq_num; tid_agg_rx->head_seq_num = start_seq_num; tid_agg_rx->buf_size = buf_size; tid_agg_rx->timeout = timeout; tid_agg_rx->stored_mpdu_num = 0; status = WLAN_STATUS_SUCCESS; /* activate it for RX */ RCU_INIT_POINTER(sta->ampdu_mlme.tid_rx[tid], tid_agg_rx); if (timeout) mod_timer(&tid_agg_rx->session_timer, TU_TO_EXP_TIME(timeout)); end: mutex_unlock(&sta->ampdu_mlme.mtx); end_no_lock: <API key>(sta->sdata, sta->sta.addr, tid, dialog_token, status, 1, buf_size, timeout); }
<?php global $yith_wcwl; ?> <header id="masthead" class="site-header" role="banner"> <div class="row"> <div class="large-12 columns"> <div class="site-header-wrapper"> <div class="site-branding"> <?php if ( (isset($<API key>['site_logo']['url'])) && (trim($<API key>['site_logo']['url']) != "" ) ) { if (is_ssl()) { $site_logo = str_replace("http: } else { $site_logo = $<API key>['site_logo']['url']; } ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><img class="site-logo" src="<?php echo $site_logo; ?>" title="<?php bloginfo( 'description' ); ?>" alt="<?php bloginfo( 'name' ); ?>" /></a> <?php } else { ?> <div class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></div> <?php } ?> </div><!-- .site-branding --> <?php if ( (isset($<API key>['site_logo_retina']['url'])) && (trim($<API key>['site_logo_retina']['url']) != "" ) ) { ?> <script> //<![CDATA[ // Set pixelRatio to 1 if the browser doesn't offer it up. var pixelRatio = !!window.devicePixelRatio ? window.devicePixelRatio : 1; logo_image = new Image(); jQuery(window).load(function(){ if (pixelRatio > 1) { jQuery('.site-logo').each(function() { var logo_image_width = jQuery(this).width(); var logo_image_height = jQuery(this).height(); jQuery(this).css("width", logo_image_width); jQuery(this).css("height", logo_image_height); jQuery(this).attr('src', '<?php echo $<API key>['site_logo_retina']['url'] ?>'); }); }; }); </script> <?php } ?> <div id="site-menu"> <nav id="site-navigation" class="main-navigation" role="navigation"> <?php wp_nav_menu(array( 'theme_location' => 'main-navigation', 'fallback_cb' => false, 'container' => false, 'items_wrap' => '<ul id="%1$s">%3$s</ul>', )); ?> </nav><!-- #site-navigation --> <div class="site-tools"> <ul> <li class="mobile-menu-button"><a><i class="icon-menu"></i></a></li> <?php if (class_exists('YITH_WCWL')) : ?> <?php if ( (isset($<API key>['<API key>'])) && (trim($<API key>['<API key>']) == "1" ) ) : ?> <li class="wishlist-button"><a><i class="icon-heart"></i></a><span class="<API key>">&nbsp;<?php //echo <API key>(); ?></span></li> <script> //ajax on wishlist items number jQuery.ajax({ url: mrtailor_ajaxurl, data: { 'action' : '<API key>' }, success:function(data) { jQuery(".<API key>").html(data); } }); </script> <?php endif; ?> <?php endif; ?> <?php if (class_exists('WooCommerce')) : ?> <?php if ( (isset($<API key>['<API key>'])) && (trim($<API key>['<API key>']) == "1" ) ) : ?> <?php if ( (isset($<API key>['catalog_mode'])) && ($<API key>['catalog_mode'] == 1) ) : ?> <?php else : ?> <li class="shopping-bag-button" class="<API key>"><a><i class="icon-shop"></i></a><span class="<API key>">&nbsp;<?php //echo $woocommerce->cart->cart_contents_count; ?></span></li> <script> //ajax on shopping bag items number jQuery.ajax({ url: mrtailor_ajaxurl, data: { 'action' : '<API key>' }, success:function(data) { jQuery(".<API key>").html(data); } }); </script> <?php endif; ?> <?php endif; ?> <?php endif; ?> <?php if ( (isset($<API key>['<API key>'])) && (trim($<API key>['<API key>']) == "1" ) ) : ?> <li class="search-button"><a><i class="icon-search"></i></a></li> <?php endif; ?> </ul> </div> <div class="site-search"> <?php if (class_exists('WooCommerce')) { the_widget( '<API key>', 'title=' ); } else { the_widget( 'WP_Widget_Search', 'title=' ); } ?> </div><!-- .site-search --> </div><!-- #site-menu --> <div class="clearfix"></div> </div><!-- .site-header-wrapper --> </div><!-- .columns --> </div><!-- .row --> </header><!-- #masthead -->
#ifndef REGIONS_H #define REGIONS_H #define deletes //#define traditional #define sameregion #define parentptr #define RPAGELOG 12 typedef struct region_ *region; extern region permanent; #include <stdlib.h> void region_init(void); region newregion(void); region newsubregion(region parent); typedef int type_t; #define rctypeof(type) 0 /* Low-level alloc with dynamic type info */ void *typed_ralloc(region r, size_t size, type_t type); void *typed_rarrayalloc(region r, size_t n, size_t size, type_t type); void *typed_rarrayextend(region r, void *old, size_t n, size_t size, type_t type); void typed_rarraycopy(void *to, void *from, size_t n, size_t size, type_t type); void *__rcralloc_small0(region r, size_t size); /* In theory, the test at the start of qalloc should give the same benefit. In practice, it doesn't (gcc, at least, generates better code for __rcralloc_small0 than the equivalent path through typed_ralloc */ #define ralloc(r, type) (sizeof(type) < (1 << (RPAGELOG - 3)) ? __rcralloc_small0((r), sizeof(type)) : typed_ralloc((r), sizeof(type), rctypeof(type))) #define rarrayalloc(r, n, type) typed_rarrayalloc((r), (n), sizeof(type), rctypeof(type)) #define rarrayextend(r, old, n, type) typed_rarrayextend((r), (old), (n), sizeof(type), rctypeof(type)) #define rarraycopy(to, from, n, type) typed_rarraycopy((to), (from), (n), sizeof(type), rctypeof(type)) char *rstralloc(region r, size_t size); char *rstralloc0(region r, size_t size); char *rstrdup(region r, const char *s); /* rstrextend is used to extend an old string. The string MUST have been initially allocated by a call to rstrextend with old == NULL (you cannot initially allocate the string with rstralloc) */ char *rstrextend(region r, const char *old, size_t newsize); char *rstrextend0(region r, const char *old, size_t newsize); void deleteregion(region r); void deleteregion_ptr(region *r); void deleteregion_array(int n, region *regions); region regionof(void *ptr); typedef void (*nomem_handler)(void); nomem_handler set_nomem_handler(nomem_handler newhandler); /* Debugging support */ void findrefs(region r, void *from, void *to); void findgrefs(region r); void findrrefs(region r, region from); #endif
// modification, are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // * Neither the name of ARM Limited nor the names of its contributors may be // used to endorse or promote products derived from this software without // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // 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 file is auto generated using tools/<API key>.py. // PLEASE DO NOT EDIT. #ifndef <API key> #define <API key> const uint32_t <API key>[] = { 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, }; const unsigned <API key> = 961; #endif // <API key>
#ifndef MLX4_DEVICE_H #define MLX4_DEVICE_H #include <linux/if_ether.h> #include <linux/pci.h> #include <linux/completion.h> #include <linux/radix-tree.h> #include <linux/cpu_rmap.h> #include <linux/atomic.h> #include <linux/clocksource.h> #define MAX_MSIX_P_PORT 17 #define MAX_MSIX 64 #define MSIX_LEGACY_SZ 4 #define MIN_MSIX_P_PORT 5 #define MLX4_ROCE_MAX_GIDS 128 #define MLX4_ROCE_PF_GIDS 16 enum { MLX4_FLAG_MSI_X = 1 << 0, <API key> = 1 << 1, MLX4_FLAG_MASTER = 1 << 2, MLX4_FLAG_SLAVE = 1 << 3, MLX4_FLAG_SRIOV = 1 << 4, <API key> = 1 << 6, }; enum { MLX4_PORT_CAP_IS_SM = 1 << 1, <API key> = 1 << 19, }; enum { MLX4_MAX_PORTS = 2, MLX4_MAX_PORT_PKEYS = 128 }; /* base qkey for use in sriov tunnel-qp/proxy-qp communication. * These qkeys must not be allowed for general use. This is a 64k range, * and to test for violation, we use the mask (protect against future chg). */ #define <API key> (0xFFFF0000) #define <API key> (0xFFFF0000) enum { MLX4_BOARD_ID_LEN = 64 }; enum { MLX4_MAX_NUM_PF = 16, MLX4_MAX_NUM_VF = 64, <API key> = 64, MLX4_MFUNC_MAX = 80, MLX4_MAX_EQ_NUM = 1024, MLX4_MFUNC_EQ_NUM = 4, MLX4_MFUNC_MAX_EQES = 8, MLX4_MFUNC_EQE_MASK = (MLX4_MFUNC_MAX_EQES - 1) }; /* Driver supports 3 diffrent device methods to manage traffic steering: * -device managed - High level API for ib and eth flow steering. FW is * managing flow steering tables. * - B0 steering mode - Common low level API for ib and (if supported) eth. * - A0 steering mode - Limited low level API for eth. In case of IB, * B0 mode is in use. */ enum { <API key>, <API key>, <API key> }; static inline const char *<API key>(int steering_mode) { switch (steering_mode) { case <API key>: return "A0 steering"; case <API key>: return "B0 steering"; case <API key>: return "Device managed flow steering"; default: return "Unrecognize steering mode"; } } enum { <API key>, <API key> }; enum { <API key> = 1LL << 0, <API key> = 1LL << 1, <API key> = 1LL << 2, <API key> = 1LL << 3, <API key> = 1LL << 6, <API key> = 1LL << 7, <API key> = 1LL << 8, <API key> = 1LL << 9, <API key> = 1LL << 12, <API key> = 1LL << 15, <API key> = 1LL << 16, <API key> = 1LL << 17, <API key> = 1LL << 18, <API key> = 1LL << 19, <API key> = 1LL << 20, <API key> = 1LL << 21, <API key> = 1LL << 30, <API key> = 1LL << 32, <API key> = 1LL << 34, <API key> = 1LL << 37, <API key> = 1LL << 38, <API key> = 1LL << 40, <API key> = 1LL << 41, <API key> = 1LL << 42, <API key> = 1LL << 48, <API key> = 1LL << 53, <API key> = 1LL << 55, <API key> = 1LL << 59, <API key> = 1LL << 61, <API key> = 1LL << 62 }; enum { <API key> = 1LL << 0, <API key> = 1LL << 1, <API key> = 1LL << 2, <API key> = 1LL << 3, <API key> = 1LL << 4, <API key> = 1LL << 5, <API key> = 1LL << 6, <API key> = 1LL << 7, <API key> = 1LL << 8, <API key> = 1LL << 9, <API key> = 1LL << 10, <API key> = 1LL << 11, <API key> = 1LL << 12, <API key> = 1LL << 13, <API key> = 1LL << 14, <API key> = 1LL << 15 }; enum { <API key> = 1LL << 0, <API key> = 1LL << 1, <API key> = 1LL << 2, <API key> = 1LL << 3 }; enum { <API key> = 1L << 0 }; enum { <API key> = 1L << 0, <API key> = 1L << 1 }; #define <API key> cpu_to_be16(0xff90) enum { <API key> = 1 << 1, <API key> = 1 << 6, <API key> = 1 << 7, <API key> = 1 << 9, <API key> = 1 << 10, <API key> = 1 << 11, }; enum mlx4_event { <API key> = 0x00, <API key> = 0x01, <API key> = 0x02, <API key> = 0x03, <API key> = 0x13, <API key> = 0x14, <API key> = 0x04, <API key> = 0x05, <API key> = 0x06, <API key> = 0x07, <API key> = 0x10, <API key> = 0x11, <API key> = 0x12, <API key> = 0x08, <API key> = 0x09, <API key> = 0x0f, <API key> = 0x0e, MLX4_EVENT_TYPE_CMD = 0x0a, <API key> = 0x19, <API key> = 0x18, <API key> = 0x1a, <API key> = 0x1b, <API key> = 0x1c, <API key> = 0x1d, <API key> = 0xff, }; enum { <API key> = 1, <API key> = 4 }; enum { <API key> = 0, }; enum slave_port_state { SLAVE_PORT_DOWN = 0, SLAVE_PENDING_UP, SLAVE_PORT_UP, }; enum <API key> { <API key> = 0, <API key>, <API key>, }; enum <API key> { <API key>, <API key>, <API key>, <API key>, }; enum { <API key> = 1 << 10, <API key> = 1 << 11, <API key> = 1 << 12, <API key> = 1 << 13, MLX4_PERM_ATOMIC = 1 << 14, MLX4_PERM_BIND_MW = 1 << 15, }; enum { MLX4_OPCODE_NOP = 0x00, <API key> = 0x01, <API key> = 0x08, <API key> = 0x09, MLX4_OPCODE_SEND = 0x0a, <API key> = 0x0b, MLX4_OPCODE_LSO = 0x0e, <API key> = 0x10, <API key> = 0x11, <API key> = 0x12, <API key> = 0x14, <API key> = 0x15, MLX4_OPCODE_BIND_MW = 0x18, MLX4_OPCODE_FMR = 0x19, <API key> = 0x1b, <API key> = 0x1f, <API key> = 0x00, <API key> = 0x01, <API key> = 0x02, <API key> = 0x03, <API key> = 0x1e, <API key> = 0x16, }; enum { <API key> = 5 }; enum mlx4_protocol { MLX4_PROT_IB_IPV6 = 0, MLX4_PROT_ETH, MLX4_PROT_IB_IPV4, MLX4_PROT_FCOE }; enum { <API key> = 1 }; enum mlx4_qp_region { MLX4_QP_REGION_FW = 0, <API key>, <API key>, <API key>, MLX4_NUM_QP_REGION }; enum mlx4_port_type { MLX4_PORT_TYPE_NONE = 0, MLX4_PORT_TYPE_IB = 1, MLX4_PORT_TYPE_ETH = 2, MLX4_PORT_TYPE_AUTO = 3 }; enum <API key> { MLX4_NO_VLAN_IDX = 0, MLX4_VLAN_MISS_IDX, MLX4_VLAN_REGULAR }; enum mlx4_steer_type { MLX4_MC_STEER = 0, MLX4_UC_STEER, MLX4_NUM_STEERS }; enum { MLX4_NUM_FEXCH = 64 * 1024, }; enum { <API key> = 511, }; enum { <API key> = 0x14, <API key> = 0x15, <API key> = 0x16, }; /* Port mgmt change event handling */ enum { <API key> = 1 << 0, <API key> = 1 << 1, <API key> = 1 << 2, <API key> = 1 << 3, <API key> = 1 << 4, }; #define MSTR_SM_CHANGE_MASK (<API key> | \ <API key>) enum mlx4_module_id { MLX4_MODULE_ID_SFP = 0x3, MLX4_MODULE_ID_QSFP = 0xC, <API key> = 0xD, <API key> = 0x11, }; static inline u64 mlx4_fw_ver(u64 major, u64 minor, u64 subminor) { return (major << 32) | (minor << 16) | subminor; } struct mlx4_phys_caps { u32 gid_phys_table_len[MLX4_MAX_PORTS + 1]; u32 pkey_phys_table_len[MLX4_MAX_PORTS + 1]; u32 num_phys_eqs; u32 base_sqpn; u32 base_proxy_sqpn; u32 base_tunnel_sqpn; }; struct mlx4_caps { u64 fw_ver; u32 function; int num_ports; int vl_cap[MLX4_MAX_PORTS + 1]; int ib_mtu_cap[MLX4_MAX_PORTS + 1]; __be32 ib_port_def_cap[MLX4_MAX_PORTS + 1]; u64 def_mac[MLX4_MAX_PORTS + 1]; int eth_mtu_cap[MLX4_MAX_PORTS + 1]; int gid_table_len[MLX4_MAX_PORTS + 1]; int pkey_table_len[MLX4_MAX_PORTS + 1]; int trans_type[MLX4_MAX_PORTS + 1]; int vendor_oui[MLX4_MAX_PORTS + 1]; int wavelength[MLX4_MAX_PORTS + 1]; u64 trans_code[MLX4_MAX_PORTS + 1]; int local_ca_ack_delay; int num_uars; u32 uar_page_size; int bf_reg_size; int bf_regs_per_page; int max_sq_sg; int max_rq_sg; int num_qps; int max_wqes; int max_sq_desc_sz; int max_rq_desc_sz; int max_qp_init_rdma; int max_qp_dest_rdma; u32 *qp0_qkey; u32 *qp0_proxy; u32 *qp1_proxy; u32 *qp0_tunnel; u32 *qp1_tunnel; int num_srqs; int max_srq_wqes; int max_srq_sge; int reserved_srqs; int num_cqs; int max_cqes; int reserved_cqs; int num_eqs; int reserved_eqs; int num_comp_vectors; int comp_pool; int num_mpts; int max_fmr_maps; int num_mtts; int fmr_reserved_mtts; int reserved_mtts; int reserved_mrws; int reserved_uars; int num_mgms; int num_amgms; int reserved_mcgs; int num_qp_per_mgm; int steering_mode; int <API key>; int num_pds; int reserved_pds; int max_xrcds; int reserved_xrcds; int mtt_entry_sz; u32 max_msg_sz; u32 page_size_cap; u64 flags; u64 flags2; u32 bmme_flags; u32 reserved_lkey; u16 stat_rate_support; u8 port_width_cap[MLX4_MAX_PORTS + 1]; int max_gso_sz; int max_rss_tbl_sz; int reserved_qps_cnt[MLX4_NUM_QP_REGION]; int reserved_qps; int reserved_qps_base[MLX4_NUM_QP_REGION]; int log_num_macs; int log_num_vlans; enum mlx4_port_type port_type[MLX4_MAX_PORTS + 1]; u8 supported_type[MLX4_MAX_PORTS + 1]; u8 suggested_type[MLX4_MAX_PORTS + 1]; u8 default_sense[MLX4_MAX_PORTS + 1]; u32 port_mask[MLX4_MAX_PORTS + 1]; enum mlx4_port_type possible_type[MLX4_MAX_PORTS + 1]; u32 max_counters; u8 port_ib_mtu[MLX4_MAX_PORTS + 1]; u16 sqp_demux; u32 eqe_size; u32 cqe_size; u8 eqe_factor; u32 userspace_caps; /* userspace must be aware of these */ u32 function_caps; /* VFs must be aware of these */ u16 hca_core_clock; u64 phys_port_id[MLX4_MAX_PORTS + 1]; int tunnel_offload_mode; }; struct mlx4_buf_list { void *buf; dma_addr_t map; }; struct mlx4_buf { struct mlx4_buf_list direct; struct mlx4_buf_list *page_list; int nbufs; int npages; int page_shift; }; struct mlx4_mtt { u32 offset; int order; int page_shift; }; enum { MLX4_DB_PER_PAGE = PAGE_SIZE / 4 }; struct mlx4_db_pgdir { struct list_head list; DECLARE_BITMAP(order0, MLX4_DB_PER_PAGE); DECLARE_BITMAP(order1, MLX4_DB_PER_PAGE / 2); unsigned long *bits[2]; __be32 *db_page; dma_addr_t db_dma; }; struct <API key>; struct mlx4_db { __be32 *db; union { struct mlx4_db_pgdir *pgdir; struct <API key> *user_page; } u; dma_addr_t dma; int index; int order; }; struct mlx4_hwq_resources { struct mlx4_db db; struct mlx4_mtt mtt; struct mlx4_buf buf; }; struct mlx4_mr { struct mlx4_mtt mtt; u64 iova; u64 size; u32 key; u32 pd; u32 access; int enabled; }; enum mlx4_mw_type { MLX4_MW_TYPE_1 = 1, MLX4_MW_TYPE_2 = 2, }; struct mlx4_mw { u32 key; u32 pd; enum mlx4_mw_type type; int enabled; }; struct mlx4_fmr { struct mlx4_mr mr; struct mlx4_mpt_entry *mpt; __be64 *mtts; dma_addr_t dma_handle; int max_pages; int max_maps; int maps; u8 page_shift; }; struct mlx4_uar { unsigned long pfn; int index; struct list_head bf_list; unsigned free_bf_bmap; void __iomem *map; void __iomem *bf_map; }; struct mlx4_bf { unsigned long offset; int buf_size; struct mlx4_uar *uar; void __iomem *reg; }; struct mlx4_cq { void (*comp) (struct mlx4_cq *); void (*event) (struct mlx4_cq *, enum mlx4_event); struct mlx4_uar *uar; u32 cons_index; u16 irq; __be32 *set_ci_db; __be32 *arm_db; int arm_sn; int cqn; unsigned vector; atomic_t refcount; struct completion free; }; struct mlx4_qp { void (*event) (struct mlx4_qp *, enum mlx4_event); int qpn; atomic_t refcount; struct completion free; }; struct mlx4_srq { void (*event) (struct mlx4_srq *, enum mlx4_event); int srqn; int max; int max_gs; int wqe_shift; atomic_t refcount; struct completion free; }; struct mlx4_av { __be32 port_pd; u8 reserved1; u8 g_slid; __be16 dlid; u8 reserved2; u8 gid_index; u8 stat_rate; u8 hop_limit; __be32 sl_tclass_flowlabel; u8 dgid[16]; }; struct mlx4_eth_av { __be32 port_pd; u8 reserved1; u8 smac_idx; u16 reserved2; u8 reserved3; u8 gid_index; u8 stat_rate; u8 hop_limit; __be32 sl_tclass_flowlabel; u8 dgid[16]; u8 s_mac[6]; u8 reserved4[2]; __be16 vlan; u8 mac[ETH_ALEN]; }; union mlx4_ext_av { struct mlx4_av ib; struct mlx4_eth_av eth; }; struct mlx4_counter { u8 reserved1[3]; u8 counter_mode; __be32 num_ifc; u32 reserved2[2]; __be64 rx_frames; __be64 rx_bytes; __be64 tx_frames; __be64 tx_bytes; }; struct mlx4_quotas { int qp; int cq; int srq; int mpt; int mtt; int counter; int xrcd; }; struct mlx4_vf_dev { u8 min_port; u8 n_ports; }; struct mlx4_dev { struct pci_dev *pdev; unsigned long flags; unsigned long num_slaves; struct mlx4_caps caps; struct mlx4_phys_caps phys_caps; struct mlx4_quotas quotas; struct radix_tree_root qp_table_tree; u8 rev_id; char board_id[MLX4_BOARD_ID_LEN]; int num_vfs; int numa_node; int <API key>; u64 regid_promisc_array[MLX4_MAX_PORTS + 1]; u64 <API key>[MLX4_MAX_PORTS + 1]; struct mlx4_vf_dev *dev_vfs; }; struct mlx4_eqe { u8 reserved1; u8 type; u8 reserved2; u8 subtype; union { u32 raw[6]; struct { __be32 cqn; } __packed comp; struct { u16 reserved1; __be16 token; u32 reserved2; u8 reserved3[3]; u8 status; __be64 out_param; } __packed cmd; struct { __be32 qpn; } __packed qp; struct { __be32 srqn; } __packed srq; struct { __be32 cqn; u32 reserved1; u8 reserved2[3]; u8 syndrome; } __packed cq_err; struct { u32 reserved1[2]; __be32 port; } __packed port_change; struct { #define <API key> 4 u32 reserved; u32 bit_vec[<API key>]; } __packed comm_channel_arm; struct { u8 port; u8 reserved[3]; __be64 mac; } __packed mac_update; struct { __be32 slave_id; } __packed flr_event; struct { __be16 current_temperature; __be16 warning_threshold; } __packed warming; struct { u8 reserved[3]; u8 port; union { struct { __be16 mstr_sm_lid; __be16 port_lid; __be32 changed_attr; u8 reserved[3]; u8 mstr_sm_sl; __be64 gid_prefix; } __packed port_info; struct { __be32 block_ptr; __be32 tbl_entries_mask; } __packed tbl_change_info; } params; } __packed port_mgmt_change; } event; u8 slave_id; u8 reserved3[2]; u8 owner; } __packed; struct <API key> { int set_guid0; int set_node_guid; int set_si_guid; u16 mtu; int port_width_cap; u16 vl_cap; u16 max_gid; u16 max_pkey; u64 guid0; u64 node_guid; u64 si_guid; }; #define MAD_IFC_DATA_SZ 192 /* MAD IFC Mailbox */ struct mlx4_mad_ifc { u8 base_version; u8 mgmt_class; u8 class_version; u8 method; __be16 status; __be16 class_specific; __be64 tid; __be16 attr_id; __be16 resv; __be32 attr_mod; __be64 mkey; __be16 dr_slid; __be16 dr_dlid; u8 reserved[28]; u8 data[MAD_IFC_DATA_SZ]; } __packed; #define mlx4_foreach_port(port, dev, type) \ for ((port) = 1; (port) <= (dev)->caps.num_ports; (port)++) \ if ((type) == (dev)->caps.port_mask[(port)]) #define <API key>(port, dev) \ for ((port) = 1; (port) <= (dev)->caps.num_ports; (port)++) \ if (((dev)->caps.port_mask[port] != MLX4_PORT_TYPE_IB)) #define <API key>(port, dev) \ for ((port) = 1; (port) <= (dev)->caps.num_ports; (port)++) \ if (((dev)->caps.port_mask[port] == MLX4_PORT_TYPE_IB) || \ ((dev)->caps.flags & <API key>)) #define <API key> 0xFF void <API key>(struct work_struct *work); static inline int <API key>(struct mlx4_dev *dev) { return dev->caps.function; } static inline int mlx4_is_master(struct mlx4_dev *dev) { return dev->flags & MLX4_FLAG_MASTER; } static inline int <API key>(struct mlx4_dev *dev) { return dev->phys_caps.base_sqpn + 8 + 16 * MLX4_MFUNC_MAX * !!mlx4_is_master(dev); } static inline int mlx4_is_qp_reserved(struct mlx4_dev *dev, u32 qpn) { return (qpn < dev->phys_caps.base_sqpn + 8 + 16 * MLX4_MFUNC_MAX * !!mlx4_is_master(dev)); } static inline int mlx4_is_guest_proxy(struct mlx4_dev *dev, int slave, u32 qpn) { int guest_proxy_base = dev->phys_caps.base_proxy_sqpn + slave * 8; if (qpn >= guest_proxy_base && qpn < guest_proxy_base + 8) return 1; return 0; } static inline int mlx4_is_mfunc(struct mlx4_dev *dev) { return dev->flags & (MLX4_FLAG_SLAVE | MLX4_FLAG_MASTER); } static inline int mlx4_is_slave(struct mlx4_dev *dev) { return dev->flags & MLX4_FLAG_SLAVE; } int mlx4_buf_alloc(struct mlx4_dev *dev, int size, int max_direct, struct mlx4_buf *buf, gfp_t gfp); void mlx4_buf_free(struct mlx4_dev *dev, int size, struct mlx4_buf *buf); static inline void *mlx4_buf_offset(struct mlx4_buf *buf, int offset) { if (BITS_PER_LONG == 64 || buf->nbufs == 1) return buf->direct.buf + offset; else return buf->page_list[offset >> PAGE_SHIFT].buf + (offset & (PAGE_SIZE - 1)); } int mlx4_pd_alloc(struct mlx4_dev *dev, u32 *pdn); void mlx4_pd_free(struct mlx4_dev *dev, u32 pdn); int mlx4_xrcd_alloc(struct mlx4_dev *dev, u32 *xrcdn); void mlx4_xrcd_free(struct mlx4_dev *dev, u32 xrcdn); int mlx4_uar_alloc(struct mlx4_dev *dev, struct mlx4_uar *uar); void mlx4_uar_free(struct mlx4_dev *dev, struct mlx4_uar *uar); int mlx4_bf_alloc(struct mlx4_dev *dev, struct mlx4_bf *bf, int node); void mlx4_bf_free(struct mlx4_dev *dev, struct mlx4_bf *bf); int mlx4_mtt_init(struct mlx4_dev *dev, int npages, int page_shift, struct mlx4_mtt *mtt); void mlx4_mtt_cleanup(struct mlx4_dev *dev, struct mlx4_mtt *mtt); u64 mlx4_mtt_addr(struct mlx4_dev *dev, struct mlx4_mtt *mtt); int mlx4_mr_alloc(struct mlx4_dev *dev, u32 pd, u64 iova, u64 size, u32 access, int npages, int page_shift, struct mlx4_mr *mr); int mlx4_mr_free(struct mlx4_dev *dev, struct mlx4_mr *mr); int mlx4_mr_enable(struct mlx4_dev *dev, struct mlx4_mr *mr); int mlx4_mw_alloc(struct mlx4_dev *dev, u32 pd, enum mlx4_mw_type type, struct mlx4_mw *mw); void mlx4_mw_free(struct mlx4_dev *dev, struct mlx4_mw *mw); int mlx4_mw_enable(struct mlx4_dev *dev, struct mlx4_mw *mw); int mlx4_write_mtt(struct mlx4_dev *dev, struct mlx4_mtt *mtt, int start_index, int npages, u64 *page_list); int mlx4_buf_write_mtt(struct mlx4_dev *dev, struct mlx4_mtt *mtt, struct mlx4_buf *buf, gfp_t gfp); int mlx4_db_alloc(struct mlx4_dev *dev, struct mlx4_db *db, int order, gfp_t gfp); void mlx4_db_free(struct mlx4_dev *dev, struct mlx4_db *db); int mlx4_alloc_hwq_res(struct mlx4_dev *dev, struct mlx4_hwq_resources *wqres, int size, int max_direct); void mlx4_free_hwq_res(struct mlx4_dev *mdev, struct mlx4_hwq_resources *wqres, int size); int mlx4_cq_alloc(struct mlx4_dev *dev, int nent, struct mlx4_mtt *mtt, struct mlx4_uar *uar, u64 db_rec, struct mlx4_cq *cq, unsigned vector, int collapsed, int timestamp_en); void mlx4_cq_free(struct mlx4_dev *dev, struct mlx4_cq *cq); int <API key>(struct mlx4_dev *dev, int cnt, int align, int *base); void <API key>(struct mlx4_dev *dev, int base_qpn, int cnt); int mlx4_qp_alloc(struct mlx4_dev *dev, int qpn, struct mlx4_qp *qp, gfp_t gfp); void mlx4_qp_free(struct mlx4_dev *dev, struct mlx4_qp *qp); int mlx4_srq_alloc(struct mlx4_dev *dev, u32 pdn, u32 cqn, u16 xrcdn, struct mlx4_mtt *mtt, u64 db_rec, struct mlx4_srq *srq); void mlx4_srq_free(struct mlx4_dev *dev, struct mlx4_srq *srq); int mlx4_srq_arm(struct mlx4_dev *dev, struct mlx4_srq *srq, int limit_watermark); int mlx4_srq_query(struct mlx4_dev *dev, struct mlx4_srq *srq, int *limit_watermark); int mlx4_INIT_PORT(struct mlx4_dev *dev, int port); int mlx4_CLOSE_PORT(struct mlx4_dev *dev, int port); int mlx4_unicast_attach(struct mlx4_dev *dev, struct mlx4_qp *qp, u8 gid[16], int <API key>, enum mlx4_protocol prot); int mlx4_unicast_detach(struct mlx4_dev *dev, struct mlx4_qp *qp, u8 gid[16], enum mlx4_protocol prot); int <API key>(struct mlx4_dev *dev, struct mlx4_qp *qp, u8 gid[16], u8 port, int <API key>, enum mlx4_protocol protocol, u64 *reg_id); int <API key>(struct mlx4_dev *dev, struct mlx4_qp *qp, u8 gid[16], enum mlx4_protocol protocol, u64 reg_id); enum { MLX4_DOMAIN_UVERBS = 0x1000, MLX4_DOMAIN_ETHTOOL = 0x2000, MLX4_DOMAIN_RFS = 0x3000, MLX4_DOMAIN_NIC = 0x5000, }; enum <API key> { <API key> = 0, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, /* should be last */ }; extern const u16 __sw_id_hw[]; static inline int map_hw_to_sw_id(u16 header_id) { int i; for (i = 0; i < <API key>; i++) { if (header_id == __sw_id_hw[i]) return i; } return -EINVAL; } enum <API key> { MLX4_FS_REGULAR = 1, MLX4_FS_ALL_DEFAULT, MLX4_FS_MC_DEFAULT, MLX4_FS_UC_SNIFFER, MLX4_FS_MC_SNIFFER, MLX4_FS_MODE_NUM, /* should be last */ }; struct mlx4_spec_eth { u8 dst_mac[ETH_ALEN]; u8 dst_mac_msk[ETH_ALEN]; u8 src_mac[ETH_ALEN]; u8 src_mac_msk[ETH_ALEN]; u8 ether_type_enable; __be16 ether_type; __be16 vlan_id_msk; __be16 vlan_id; }; struct mlx4_spec_tcp_udp { __be16 dst_port; __be16 dst_port_msk; __be16 src_port; __be16 src_port_msk; }; struct mlx4_spec_ipv4 { __be32 dst_ip; __be32 dst_ip_msk; __be32 src_ip; __be32 src_ip_msk; }; struct mlx4_spec_ib { __be32 l3_qpn; __be32 qpn_msk; u8 dst_gid[16]; u8 dst_gid_msk[16]; }; struct mlx4_spec_vxlan { __be32 vni; __be32 vni_mask; }; struct mlx4_spec_list { struct list_head list; enum <API key> id; union { struct mlx4_spec_eth eth; struct mlx4_spec_ib ib; struct mlx4_spec_ipv4 ipv4; struct mlx4_spec_tcp_udp tcp_udp; struct mlx4_spec_vxlan vxlan; }; }; enum <API key> { <API key>, <API key>, }; struct mlx4_net_trans_rule { struct list_head list; enum <API key> queue_mode; bool exclusive; bool allow_loopback; enum <API key> promisc_mode; u8 port; u16 priority; u32 qpn; }; struct <API key> { __be16 prio; u8 type; u8 flags; u8 rsvd1; u8 funcid; u8 vep; u8 port; __be32 qpn; __be32 rsvd2; }; struct <API key> { u8 size; u8 rsvd1; __be16 id; u32 rsvd2; __be32 l3_qpn; __be32 qpn_mask; u8 dst_gid[16]; u8 dst_gid_msk[16]; } __packed; struct <API key> { u8 size; u8 rsvd; __be16 id; u8 rsvd1[6]; u8 dst_mac[6]; u16 rsvd2; u8 dst_mac_msk[6]; u16 rsvd3; u8 src_mac[6]; u16 rsvd4; u8 src_mac_msk[6]; u8 rsvd5; u8 ether_type_enable; __be16 ether_type; __be16 vlan_tag_msk; __be16 vlan_tag; } __packed; struct <API key> { u8 size; u8 rsvd; __be16 id; __be16 rsvd1[3]; __be16 dst_port; __be16 rsvd2; __be16 dst_port_msk; __be16 rsvd3; __be16 src_port; __be16 rsvd4; __be16 src_port_msk; } __packed; struct <API key> { u8 size; u8 rsvd; __be16 id; __be32 rsvd1; __be32 dst_ip; __be32 dst_ip_msk; __be32 src_ip; __be32 src_ip_msk; } __packed; struct <API key> { u8 size; u8 rsvd; __be16 id; __be32 rsvd1; __be32 vni; __be32 vni_mask; } __packed; struct _rule_hw { union { struct { u8 size; u8 rsvd; __be16 id; }; struct <API key> eth; struct <API key> ib; struct <API key> ipv4; struct <API key> tcp_udp; struct <API key> vxlan; }; }; enum { <API key> = 1 << 0, <API key> = 1 << 1, <API key> = 1 << 2, <API key> = 1 << 3, <API key> = 1 << 4, }; int <API key>(struct mlx4_dev *dev, u8 port, u32 qpn, enum <API key> mode); int <API key>(struct mlx4_dev *dev, u8 port, enum <API key> mode); int <API key>(struct mlx4_dev *dev, u32 qpn, u8 port); int <API key>(struct mlx4_dev *dev, u32 qpn, u8 port); int <API key>(struct mlx4_dev *dev, u32 qpn, u8 port); int <API key>(struct mlx4_dev *dev, u32 qpn, u8 port); int mlx4_SET_MCAST_FLTR(struct mlx4_dev *dev, u8 port, u64 mac, u64 clear, u8 mode); int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac); void mlx4_unregister_mac(struct mlx4_dev *dev, u8 port, u64 mac); int mlx4_get_base_qpn(struct mlx4_dev *dev, u8 port); int __mlx4_replace_mac(struct mlx4_dev *dev, u8 port, int qpn, u64 new_mac); void <API key>(struct mlx4_dev *dev, u64 *stats_bitmap); int <API key>(struct mlx4_dev *dev, u8 port, int mtu, u8 pptx, u8 pfctx, u8 pprx, u8 pfcrx); int <API key>(struct mlx4_dev *dev, u8 port, u32 base_qpn, u8 promisc); int <API key>(struct mlx4_dev *dev, u8 port, u8 *prio2tc); int <API key>(struct mlx4_dev *dev, u8 port, u8 *tc_tx_bw, u8 *pg, u16 *ratelimit); int mlx4_SET_PORT_VXLAN(struct mlx4_dev *dev, u8 port, u8 steering, int enable); int <API key>(struct mlx4_dev *dev, u8 port, u64 mac, int *idx); int <API key>(struct mlx4_dev *dev, u8 port, u16 vid, int *idx); int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index); void <API key>(struct mlx4_dev *dev, u8 port, u16 vlan); int mlx4_map_phys_fmr(struct mlx4_dev *dev, struct mlx4_fmr *fmr, u64 *page_list, int npages, u64 iova, u32 *lkey, u32 *rkey); int mlx4_fmr_alloc(struct mlx4_dev *dev, u32 pd, u32 access, int max_pages, int max_maps, u8 page_shift, struct mlx4_fmr *fmr); int mlx4_fmr_enable(struct mlx4_dev *dev, struct mlx4_fmr *fmr); void mlx4_fmr_unmap(struct mlx4_dev *dev, struct mlx4_fmr *fmr, u32 *lkey, u32 *rkey); int mlx4_fmr_free(struct mlx4_dev *dev, struct mlx4_fmr *fmr); int mlx4_SYNC_TPT(struct mlx4_dev *dev); int <API key>(struct mlx4_dev *dev); int mlx4_assign_eq(struct mlx4_dev *dev, char *name, struct cpu_rmap *rmap, int *vector); void mlx4_release_eq(struct mlx4_dev *dev, int vec); int mlx4_eq_get_irq(struct mlx4_dev *dev, int vec); int <API key>(struct mlx4_dev *dev); int mlx4_wol_read(struct mlx4_dev *dev, u64 *config, int port); int mlx4_wol_write(struct mlx4_dev *dev, u64 config, int port); int mlx4_counter_alloc(struct mlx4_dev *dev, u32 *idx); void mlx4_counter_free(struct mlx4_dev *dev, u32 idx); int mlx4_flow_attach(struct mlx4_dev *dev, struct mlx4_net_trans_rule *rule, u64 *reg_id); int mlx4_flow_detach(struct mlx4_dev *dev, u64 reg_id); int <API key>(struct mlx4_dev *dev, enum <API key> flow_type); int <API key>(struct mlx4_dev *dev, enum <API key> id); int mlx4_hw_rule_sz(struct mlx4_dev *dev, enum <API key> id); void <API key>(struct mlx4_dev *dev, int slave, int port, int i, int val); int mlx4_get_parav_qkey(struct mlx4_dev *dev, u32 qpn, u32 *qkey); int <API key>(struct mlx4_dev *dev, int slave); int mlx4_gen_pkey_eqe(struct mlx4_dev *dev, int slave, u8 port); int <API key>(struct mlx4_dev *dev, int slave, u8 port); int <API key>(struct mlx4_dev *dev, u8 port, int attr); int <API key>(struct mlx4_dev *dev, int slave, u8 port, u8 port_subtype_change); enum slave_port_state <API key>(struct mlx4_dev *dev, int slave, u8 port); int <API key>(struct mlx4_dev *dev, int slave, u8 port, int event, enum <API key> *gen_event); void <API key>(struct mlx4_dev *dev, int slave, __be64 guid); __be64 <API key>(struct mlx4_dev *dev, int slave); int <API key>(struct mlx4_dev *dev, int port, u8 *gid, int *slave_id); int <API key>(struct mlx4_dev *dev, int port, int slave_id, u8 *gid); int <API key>(struct mlx4_dev *dev, u32 min_range_qpn, u32 max_range_qpn); cycle_t mlx4_read_clock(struct mlx4_dev *dev); struct mlx4_active_ports { DECLARE_BITMAP(ports, MLX4_MAX_PORTS); }; /* Returns a bitmap of the physical ports which are assigned to slave */ struct mlx4_active_ports <API key>(struct mlx4_dev *dev, int slave); /* Returns the physical port that represents the virtual port of the slave, */ /* or a value < 0 in case of an error. If a slave has 2 ports, the identity */ /* mapping is returned. */ int <API key>(struct mlx4_dev *dev, int slave, int port); struct mlx4_slaves_pport { DECLARE_BITMAP(slaves, MLX4_MFUNC_MAX); }; /* Returns a bitmap of all slaves that are assigned to port. */ struct mlx4_slaves_pport <API key>(struct mlx4_dev *dev, int port); /* Returns a bitmap of all slaves that are assigned exactly to all the */ /* the ports that are set in crit_ports. */ struct mlx4_slaves_pport <API key>( struct mlx4_dev *dev, const struct mlx4_active_ports *crit_ports); /* Returns the slave's virtual port that represents the physical port. */ int <API key>(struct mlx4_dev *dev, int slave, int port); int <API key>(struct mlx4_dev *dev, int slave, int port); int <API key>(struct mlx4_dev *dev, __be16 udp_port); int mlx4_vf_smi_enabled(struct mlx4_dev *dev, int slave, int port); int <API key>(struct mlx4_dev *dev, int slave, int port); int <API key>(struct mlx4_dev *dev, int slave, int port, int enable); int <API key>(struct mlx4_dev *dev, u8 port, u16 offset, u16 size, u8 *data); /* Returns true if running in low memory profile (kdump kernel) */ static inline bool <API key>(void) { return reset_devices; } /* ACCESS REG commands */ enum <API key> { <API key> = 0x1, <API key> = 0x2, }; /* ACCESS PTYS Reg command */ enum mlx4_ptys_proto { MLX4_PTYS_IB = 1<<0, MLX4_PTYS_EN = 1<<2, }; struct mlx4_ptys_reg { u8 resrvd1; u8 local_port; u8 resrvd2; u8 proto_mask; __be32 resrvd3[2]; __be32 eth_proto_cap; __be16 ib_width_cap; __be16 ib_speed_cap; __be32 resrvd4; __be32 eth_proto_admin; __be16 ib_width_admin; __be16 ib_speed_admin; __be32 resrvd5; __be32 eth_proto_oper; __be16 ib_width_oper; __be16 ib_speed_oper; __be32 resrvd6; __be32 eth_proto_lp_adv; } __packed; int <API key>(struct mlx4_dev *dev, enum <API key> method, struct mlx4_ptys_reg *ptys_reg); #endif /* MLX4_DEVICE_H */
#!/usr/bin/perl use strict; use warnings; use FindBin; use lib "$FindBin::Bin/../lib"; use GMS::Schema; use DBIx::Class::Fixtures; my $db = GMS::Schema->do_connect; my $config_dir = "$FindBin::Bin/../t/etc"; my $fixtures = DBIx::Class::Fixtures->new({ config_dir => $config_dir }); $fixtures->dump({ config => 'basic_db.json', schema => $db, directory => "$config_dir/basic_db" });
// Use of this source code is governed by a BSD-style // +build arm64 // +build !linux // +build !freebsd // +build !android // +build !darwin ios package cpu func osInit() { // Other operating systems do not support reading HWCap from auxiliary vector, // reading privileged aarch64 system registers or sysctl in user space to detect // CPU features at runtime. }
#include "<API key>.h" #include "qgsapplication.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QScrollBar> #include <QUrl> /** * Constructor * @param parent - Pointer the to parent QWidget for modality * @param fl - Windown flags */ <API key>::<API key>( QWidget* parent, Qt::WindowFlags fl ) : QWidget( parent, fl ) , <API key>( 0 ) , mImageSizeRatio( 0.0 ) , mScaleFactor( 1.0 ) , mScaleToFit( 0.0 ) { //Setup zoom buttons pbtnZoomIn = new QPushButton(); pbtnZoomOut = new QPushButton(); pbtnZoomFull = new QPushButton(); pbtnZoomIn->setEnabled( false ); pbtnZoomOut->setEnabled( false ); pbtnZoomFull->setEnabled( false ); QString myThemePath = QgsApplication::activeThemePath(); pbtnZoomIn->setToolTip( tr( "Zoom in" ) ); pbtnZoomIn->setWhatsThis( tr( "Zoom in to see more detail." ) ); pbtnZoomOut->setToolTip( tr( "Zoom out" ) ); pbtnZoomOut->setWhatsThis( tr( "Zoom out to see more area." ) ); pbtnZoomFull->setToolTip( tr( "Zoom to full extent" ) ); pbtnZoomFull->setWhatsThis( tr( "Zoom to display the entire image." ) ); pbtnZoomIn->setIcon( QIcon( QPixmap( myThemePath + "/mActionZoomIn.svg" ) ) ); pbtnZoomOut->setIcon( QIcon( QPixmap( myThemePath + "/mActionZoomOut.svg" ) ) ); pbtnZoomFull->setIcon( QIcon( QPixmap( myThemePath + "/<API key>.svg" ) ) ); connect( pbtnZoomIn, SIGNAL( clicked() ), this, SLOT( <API key>() ) ); connect( pbtnZoomOut, SIGNAL( clicked() ), this, SLOT( <API key>() ) ); connect( pbtnZoomFull, SIGNAL( clicked() ), this, SLOT( <API key>() ) ); //Setup zoom button layout QWidget* myButtonBar = new QWidget(); QHBoxLayout* myButtonBarLayout = new QHBoxLayout(); myButtonBarLayout->addStretch(); myButtonBarLayout->addWidget( pbtnZoomIn ); myButtonBarLayout->addWidget( pbtnZoomOut ); myButtonBarLayout->addWidget( pbtnZoomFull ); myButtonBar->setLayout( myButtonBarLayout ); //setup display area mDisplayArea = new QScrollArea(); QVBoxLayout* myLayout = new QVBoxLayout; myLayout->addWidget( myButtonBar ); myLayout->addWidget( mDisplayArea ); setLayout( myLayout ); //setup label to hold image mImageLabel = new QLabel(); mImageLabel->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored ); mImageLabel->setScaledContents( true ); mDisplayArea->setWidget( mImageLabel ); //setup image mImageLoaded = false; mImage = new QPixmap( mDisplayArea->size().width(), mDisplayArea->size().height() ); mImage->fill(); mImageLabel->setPixmap( *mImage ); //setup http connection mHttpBuffer = new QBuffer(); #if QT_VERSION < 0x050000 mHttpConnection = new QHttp(); #endif mHttpBuffer->open( QBuffer::ReadWrite ); // TODO #if QT_VERSION < 0x050000 connect( mHttpConnection, SIGNAL( requestFinished( int, bool ) ), this, SLOT( displayUrlImage( int, bool ) ) ); #endif //initialize remaining variables mScaleByHeight = false; mScaleByWidth = false; mCurrentZoomStep = 0; ZOOM_STEPS = 5; } <API key>::~<API key>() { delete mImageLabel; delete mImage; delete mHttpBuffer; #if QT_VERSION < 0x050000 delete mHttpConnection; #endif delete pbtnZoomIn; delete pbtnZoomOut; delete pbtnZoomFull; delete mDisplayArea; } void <API key>::resizeEvent( QResizeEvent *event ) { event->accept(); setScalers(); displayImage(); } /** * Public method called to display an image loaded locally from disk * @param path - The path and filename of the image to load from disk */ void <API key>::displayImage( const QString& path ) { mImageLoaded = mImage->load( path, nullptr, Qt::AutoColor ); setToolTip( path ); mCurrentZoomStep = 0; pbtnZoomOut->setEnabled( false ); pbtnZoomFull->setEnabled( false ); if ( mImageLoaded ) { pbtnZoomIn->setEnabled( true ); } else { pbtnZoomIn->setEnabled( false ); } setScalers(); displayImage(); } /** * Private method which scales and actually displays the image in the widget */ void <API key>::displayImage() { QSize mySize; if ( mImageLoaded ) { //TODO: See about migrating these nasty scaling routines to use a QMatrix if ( mScaleByWidth ) { mySize.setWidth( static_cast<int>( mImage->width() *( mScaleToFit + ( mScaleFactor * mCurrentZoomStep ) ) ) ); mySize.setHeight( static_cast<int>(( double )mySize.width() * mImageSizeRatio ) ); } else { mySize.setHeight( static_cast<int>( mImage->height() *( mScaleToFit + ( mScaleFactor * mCurrentZoomStep ) ) ) ); mySize.setWidth( static_cast<int>(( double )mySize.height() * mImageSizeRatio ) ); } } else { mySize.setWidth( mDisplayArea->size().width() ); mySize.setHeight( mDisplayArea->size().height() ); mImage->fill(); } //the minus 4 is there to keep scroll bars from appearing at full extent view mImageLabel->resize( mySize.width() - 4, mySize.height() - 4 ); mImageLabel->setPixmap( *mImage ); } /** * Public method called to display an image loaded from a url * @param url - The url from which to load an image */ void <API key>::displayUrlImage( const QString& url ) { QUrl myUrl( url ); #if QT_VERSION < 0x050000 mHttpConnection->setHost( myUrl.host() ); <API key> = mHttpConnection->get( myUrl.path().replace( '\\', '/' ), mHttpBuffer ); #endif } /** * Private method to set the scaling and zoom steps for each new image */ void <API key>::setScalers() { if ( mImageLoaded ) { double xRatio = ( double )mDisplayArea->size().width() / ( double )mImage->width(); double yRatio = ( double )mDisplayArea->size().height() / ( double )mImage->height(); if ( xRatio < yRatio ) { mScaleByWidth = true; mScaleByHeight = false; mImageSizeRatio = ( double )mImage->height() / ( double )mImage->width(); mScaleToFit = ( double )mDisplayArea->size().width() / ( double )mImage->width(); mScaleFactor = ( 1.0 - mScaleToFit ) / ( double )ZOOM_STEPS; } else { mScaleByWidth = false; mScaleByHeight = true; mImageSizeRatio = ( double )mImage->width() / ( double )mImage->height(); mScaleToFit = ( double )mDisplayArea->size().height() / ( double )mImage->height(); mScaleFactor = ( 1.0 - mScaleToFit ) / ( double )ZOOM_STEPS; } } } /* * * Public and Private Slots * */ /** * Slot called when a http request is complete * @param requestId - The id of the http request * @param error - Boolean denoting success of http request */ void <API key>::displayUrlImage( int requestId, bool error ) { //only process if no error and the request id matches the request id stored in displayUrlImage if ( !error && requestId == <API key> ) { //reset to be beginning of the buffer mHttpBuffer->seek( 0 ); //load the image data from the buffer mImageLoaded = mImage->loadFromData( mHttpBuffer->buffer() ); mCurrentZoomStep = 0; pbtnZoomOut->setEnabled( false ); pbtnZoomFull->setEnabled( false ); if ( mImageLoaded ) { pbtnZoomIn->setEnabled( true ); } else { pbtnZoomIn->setEnabled( false ); } } setScalers(); displayImage(); } /** * Slot called when the pbtnZoomIn button is pressed */ void <API key>::<API key>() { if ( mCurrentZoomStep < ZOOM_STEPS ) { pbtnZoomOut->setEnabled( true ); pbtnZoomFull->setEnabled( true ); mCurrentZoomStep++; displayImage(); } if ( mCurrentZoomStep == ZOOM_STEPS ) { pbtnZoomIn->setEnabled( false ); } } /** * Slot called when the pbtnZoomOut button is pressed */ void <API key>::<API key>() { if ( mCurrentZoomStep > 0 ) { pbtnZoomIn->setEnabled( true ); mCurrentZoomStep displayImage(); } if ( mCurrentZoomStep == 0 ) { pbtnZoomOut->setEnabled( false ); pbtnZoomFull->setEnabled( false ); } } /** * Slot called when the pbtnZoomFull button is pressed */ void <API key>::<API key>() { pbtnZoomOut->setEnabled( false ); pbtnZoomFull->setEnabled( false ); pbtnZoomIn->setEnabled( true ); mCurrentZoomStep = 0; displayImage(); }
<?php namespace Drupal\Tests\devel\Functional; use Drupal\Core\Url; use Drupal\Tests\BrowserTestBase; /** * Tests container info pages and links. * * @group devel */ class <API key> extends BrowserTestBase { use <API key>; /** * {@inheritdoc} */ public static $modules = ['devel', 'devel_test', 'block']; /** * The user for tests. * * @var \Drupal\user\UserInterface */ protected $develUser; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->drupalPlaceBlock('local_tasks_block'); $this->drupalPlaceBlock('page_title_block'); $this->develUser = $this->drupalCreateUser(['access devel information']); $this->drupalLogin($this->develUser); } /** * Tests container info menu link. */ public function <API key>() { $this->drupalPlaceBlock('system_menu_block:devel'); // Ensures that the events info link is present on the devel menu and that // it points to the correct page. $this->drupalGet(''); $this->clickLink('Container Info'); $this->assertSession()->statusCodeEquals(200); $this->assertSession()->addressEquals('/devel/container/service'); $this->assertSession()->pageTextContains('Container services'); } /** * Tests service list page. */ public function testServiceList() { $this->drupalGet('/devel/container/service'); $this->assertSession()->statusCodeEquals(200); $this->assertSession()->pageTextContains('Container services'); $this-><API key>(); $page = $this->getSession()->getPage(); // Ensures that the services table is found. $table = $page->find('css', 'table.devel-service-list'); $this->assertNotNull($table); // Ensures that the expected table headers are found. /* @var $headers \Behat\Mink\Element\NodeElement[] */ $headers = $table->findAll('css', 'thead th'); $this->assertEquals(4, count($headers)); $expected_headers = ['ID', 'Class', 'Alias', 'Operations']; $actual_headers = array_map(function ($element) { return $element->getText(); }, $headers); $this->assertSame($expected_headers, $actual_headers); // Ensures that all the serivices are listed in the table. $cached_definition = \Drupal::service('kernel')-><API key>(); $this->assertNotNull($cached_definition); $rows = $table->findAll('css', 'tbody tr'); $this->assertEquals(count($cached_definition['services']), count($rows)); // Tests the presence of some (arbitrarily chosen) services in the table. $expected_services = [ 'config.factory' => [ 'class' => 'Drupal\Core\Config\ConfigFactory', 'alias' => '', ], 'devel.route_subscriber' => [ 'class' => 'Drupal\devel\Routing\RouteSubscriber', 'alias' => '', ], 'plugin.manager.element_info' => [ 'class' => 'Drupal\Core\Render\ElementInfoManager', 'alias' => 'element_info', ], ]; foreach ($expected_services as $service_id => $expected) { $row = $table->find('css', sprintf('tbody tr:contains("%s")', $service_id)); $this->assertNotNull($row); /* @var $cells \Behat\Mink\Element\NodeElement[] */ $cells = $row->findAll('css', 'td'); $this->assertEquals(4, count($cells)); $cell_service_id = $cells[0]; $this->assertEquals($service_id, $cell_service_id->getText()); $this->assertTrue($cell_service_id->hasClass('<API key>')); $cell_class = $cells[1]; $this->assertEquals($expected['class'], $cell_class->getText()); $this->assertTrue($cell_class->hasClass('<API key>')); $cell_alias = $cells[2]; $this->assertEquals($expected['alias'], $cell_alias->getText()); $this->assertTrue($cell_class->hasClass('<API key>')); $cell_operations = $cells[3]; $actual_href = $cell_operations->findLink('Devel')->getAttribute('href'); $expected_href = Url::fromRoute('devel.container_info.service.detail', ['service_id' => $service_id])->toString(); $this->assertEquals($expected_href, $actual_href); } // Ensures that the page is accessible ony to users with the adequate $this->drupalLogout(); $this->drupalGet('devel/container/service'); $this->assertSession()->statusCodeEquals(403); } /** * Tests service detail page. */ public function testServiceDetail() { $service_id = 'devel.dumper'; // Ensures that the page works as expected. $this->drupalGet("/devel/container/service/$service_id"); $this->assertSession()->statusCodeEquals(200); $this->assertSession()->pageTextContains("Service $service_id detail"); // Ensures that the page returns a 404 error if the requested service is // not defined. $this->drupalGet('/devel/container/service/not.exists'); $this->assertSession()->statusCodeEquals(404); // Ensures that the page is accessible ony to users with the adequate $this->drupalLogout(); $this->drupalGet("devel/container/service/$service_id"); $this->assertSession()->statusCodeEquals(403); } /** * Tests parameter list page. */ public function testParameterList() { // Ensures that the page works as expected. $this->drupalGet('/devel/container/parameter'); $this->assertSession()->statusCodeEquals(200); $this->assertSession()->pageTextContains('Container parameters'); $this-><API key>(); $page = $this->getSession()->getPage(); // Ensures that the parameters table is found. $table = $page->find('css', 'table.<API key>'); $this->assertNotNull($table); // Ensures that the expected table headers are found. /* @var $headers \Behat\Mink\Element\NodeElement[] */ $headers = $table->findAll('css', 'thead th'); $this->assertEquals(2, count($headers)); $expected_headers = ['Name', 'Operations']; $actual_headers = array_map(function ($element) { return $element->getText(); }, $headers); $this->assertSame($expected_headers, $actual_headers); // Ensures that all the parameters are listed in the table. $cached_definition = \Drupal::service('kernel')-><API key>(); $this->assertNotNull($cached_definition); $rows = $table->findAll('css', 'tbody tr'); $this->assertEquals(count($cached_definition['parameters']), count($rows)); // Tests the presence of some parameters in the table. $expected_parameters = [ 'container.modules', 'cache_bins', 'factory.keyvalue', 'twig.config', ]; foreach ($expected_parameters as $parameter_name) { $row = $table->find('css', sprintf('tbody tr:contains("%s")', $parameter_name)); $this->assertNotNull($row); /* @var $cells \Behat\Mink\Element\NodeElement[] */ $cells = $row->findAll('css', 'td'); $this->assertEquals(2, count($cells)); $cell_parameter_name = $cells[0]; $this->assertEquals($parameter_name, $cell_parameter_name->getText()); $this->assertTrue($cell_parameter_name->hasClass('<API key>')); $cell_operations = $cells[1]; $actual_href = $cell_operations->findLink('Devel')->getAttribute('href'); $expected_href = Url::fromRoute('devel.container_info.parameter.detail', ['parameter_name' => $parameter_name])->toString(); $this->assertEquals($expected_href, $actual_href); } // Ensures that the page is accessible ony to users with the adequate $this->drupalLogout(); $this->drupalGet('devel/container/service'); $this->assertSession()->statusCodeEquals(403); } /** * Tests parameter detail page. */ public function testParameterDetail() { $parameter_name = 'cache_bins'; // Ensures that the page works as expected. $this->drupalGet("/devel/container/parameter/$parameter_name"); $this->assertSession()->statusCodeEquals(200); $this->assertSession()->pageTextContains("Parameter $parameter_name value"); // Ensures that the page returns a 404 error if the requested parameter is // not defined. $this->drupalGet('/devel/container/parameter/not_exists'); $this->assertSession()->statusCodeEquals(404); // Ensures that the page is accessible ony to users with the adequate $this->drupalLogout(); $this->drupalGet("devel/container/service/$parameter_name"); $this->assertSession()->statusCodeEquals(403); } /** * Asserts that container info local tasks are present. */ protected function <API key>() { $<API key> = [ ['devel.container_info.service', []], ['devel.container_info.parameter', []], ]; $this->assertLocalTasks($<API key>); } }
ve.ce.imetests.push( [ '<API key>', [ /*jshint quotmark:double */ {"imeIdentifier":"Chinese Traditional Handwriting","userAgent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; .NET4.0C)","startDom":""}, {"seq":0,"time":33.748,"action":"sendEvent","args":["compositionstart",{}]}, {"seq":1,"time":33.752,"action":"changeText","args":[""]}, {"seq":2,"time":33.752,"action":"changeSel","args":[1,1]}, {"seq":3,"time":33.752,"action":"sendEvent","args":["compositionend",{}]}, {"seq":4,"time":33.846,"action":"endLoop","args":[]}, {"seq":5,"time":49.047,"action":"sendEvent","args":["compositionstart",{}]}, {"seq":6,"time":49.049,"action":"changeText","args":[""]}, {"seq":7,"time":49.049,"action":"changeSel","args":[2,2]}, {"seq":8,"time":49.049,"action":"sendEvent","args":["compositionend",{}]}, {"seq":9,"time":49.091,"action":"endLoop","args":[]} ] ] );
// <API key>: GPL-2.0 #include <common.h> #include <dm.h> #include <env.h> #include <fdtdec.h> #include <log.h> #include <malloc.h> #include <net.h> #include <asm/eth.h> #include <dm/test.h> #include <dm/device-internal.h> #include <dm/uclass-internal.h> #include <test/test.h> #include <test/ut.h> #define DM_TEST_ETH_NUM 4 static int dm_test_eth(struct unit_test_state *uts) { net_ping_ip = string_to_ip("1.1.2.2"); env_set("ethact", "eth@10002000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); env_set("ethact", "eth@10003000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10003000", env_get("ethact")); env_set("ethact", "eth@10004000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10004000", env_get("ethact")); return 0; } DM_TEST(dm_test_eth, UT_TESTF_SCAN_FDT); static int dm_test_eth_alias(struct unit_test_state *uts) { net_ping_ip = string_to_ip("1.1.2.2"); env_set("ethact", "eth0"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); env_set("ethact", "eth6"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10004000", env_get("ethact")); /* Expected to fail since eth2 is not defined in the device tree */ env_set("ethact", "eth2"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); env_set("ethact", "eth5"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10003000", env_get("ethact")); return 0; } DM_TEST(dm_test_eth_alias, UT_TESTF_SCAN_FDT); static int dm_test_eth_prime(struct unit_test_state *uts) { net_ping_ip = string_to_ip("1.1.2.2"); /* Expected to be "eth@10003000" because of ethprime variable */ env_set("ethact", NULL); env_set("ethprime", "eth5"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10003000", env_get("ethact")); /* Expected to be "eth@10002000" because it is first */ env_set("ethact", NULL); env_set("ethprime", NULL); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); return 0; } DM_TEST(dm_test_eth_prime, UT_TESTF_SCAN_FDT); /** * This test case is trying to test the following scenario: * - All ethernet devices are not probed * - "ethaddr" for all ethernet devices are not set * - "ethact" is set to a valid ethernet device name * * With Sandbox default test configuration, all ethernet devices are * probed after power-up, so we have to manually create such scenario: * - Remove all ethernet devices * - Remove all "ethaddr" environment variables * - Set "ethact" to the first ethernet device * * Do a ping test to see if anything goes wrong. */ static int dm_test_eth_act(struct unit_test_state *uts) { struct udevice *dev[DM_TEST_ETH_NUM]; const char *ethname[DM_TEST_ETH_NUM] = {"eth@10002000", "eth@10003000", "sbe5", "eth@10004000"}; const char *addrname[DM_TEST_ETH_NUM] = {"ethaddr", "eth5addr", "eth3addr", "eth6addr"}; char ethaddr[DM_TEST_ETH_NUM][18]; int i; memset(ethaddr, '\0', sizeof(ethaddr)); net_ping_ip = string_to_ip("1.1.2.2"); /* Prepare the test scenario */ for (i = 0; i < DM_TEST_ETH_NUM; i++) { ut_assertok(<API key>(UCLASS_ETH, ethname[i], &dev[i])); ut_assertok(device_remove(dev[i], DM_REMOVE_NORMAL)); /* Invalidate MAC address */ strncpy(ethaddr[i], env_get(addrname[i]), 17); /* Must disable access protection for ethaddr before clearing */ env_set(".flags", addrname[i]); env_set(addrname[i], NULL); } /* Set ethact to "eth@10002000" */ env_set("ethact", ethname[0]); /* Segment fault might happen if something is wrong */ ut_asserteq(-ENODEV, net_loop(PING)); for (i = 0; i < DM_TEST_ETH_NUM; i++) { /* Restore the env */ env_set(".flags", addrname[i]); env_set(addrname[i], ethaddr[i]); /* Probe the device again */ ut_assertok(device_probe(dev[i])); } env_set(".flags", NULL); env_set("ethact", NULL); return 0; } DM_TEST(dm_test_eth_act, UT_TESTF_SCAN_FDT); /* The asserts include a return on fail; cleanup in the caller */ static int <API key>(struct unit_test_state *uts) { /* Make sure that the default is to rotate to the next interface */ env_set("ethact", "eth@10004000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); /* If ethrotate is no, then we should fail on a bad MAC */ env_set("ethact", "eth@10004000"); env_set("ethrotate", "no"); ut_asserteq(-EINVAL, net_loop(PING)); ut_asserteq_str("eth@10004000", env_get("ethact")); return 0; } static int <API key>(struct unit_test_state *uts) { /* Make sure we can skip invalid devices */ env_set("ethact", "eth@10004000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10004000", env_get("ethact")); /* Make sure we can handle device name which is not eth# */ env_set("ethact", "sbe5"); ut_assertok(net_loop(PING)); ut_asserteq_str("sbe5", env_get("ethact")); return 0; } static int dm_test_eth_rotate(struct unit_test_state *uts) { char ethaddr[18]; int retval; /* Set target IP to mock ping */ net_ping_ip = string_to_ip("1.1.2.2"); /* Invalidate eth1's MAC address */ memset(ethaddr, '\0', sizeof(ethaddr)); strncpy(ethaddr, env_get("eth6addr"), 17); /* Must disable access protection for eth6addr before clearing */ env_set(".flags", "eth6addr"); env_set("eth6addr", NULL); retval = <API key>(uts); /* Restore the env */ env_set("eth6addr", ethaddr); env_set("ethrotate", NULL); if (!retval) { /* Invalidate eth0's MAC address */ strncpy(ethaddr, env_get("ethaddr"), 17); /* Must disable access protection for ethaddr before clearing */ env_set(".flags", "ethaddr"); env_set("ethaddr", NULL); retval = <API key>(uts); /* Restore the env */ env_set("ethaddr", ethaddr); } /* Restore the env */ env_set(".flags", NULL); return retval; } DM_TEST(dm_test_eth_rotate, UT_TESTF_SCAN_FDT); /* The asserts include a return on fail; cleanup in the caller */ static int _dm_test_net_retry(struct unit_test_state *uts) { /* * eth1 is disabled and netretry is yes, so the ping should succeed and * the active device should be eth0 */ <API key>(1, true); env_set("ethact", "eth@10004000"); env_set("netretry", "yes"); <API key>(); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); /* * eth1 is disabled and netretry is no, so the ping should fail and the * active device should be eth1 */ env_set("ethact", "eth@10004000"); env_set("netretry", "no"); <API key>(); ut_asserteq(-ENONET, net_loop(PING)); ut_asserteq_str("eth@10004000", env_get("ethact")); return 0; } static int dm_test_net_retry(struct unit_test_state *uts) { int retval; net_ping_ip = string_to_ip("1.1.2.2"); retval = _dm_test_net_retry(uts); /* Restore the env */ env_set("netretry", NULL); <API key>(1, false); return retval; } DM_TEST(dm_test_net_retry, UT_TESTF_SCAN_FDT); static int sb_check_arp_reply(struct udevice *dev, void *packet, unsigned int len) { struct eth_sandbox_priv *priv = dev_get_priv(dev); struct ethernet_hdr *eth = packet; struct arp_hdr *arp; /* Used by all of the ut_assert macros */ struct unit_test_state *uts = priv->priv; if (ntohs(eth->et_protlen) != PROT_ARP) return 0; arp = packet + ETHER_HDR_SIZE; if (ntohs(arp->ar_op) != ARPOP_REPLY) return 0; /* This test would be worthless if we are not waiting */ ut_assert(arp_is_waiting()); /* Validate response */ ut_asserteq_mem(eth->et_src, net_ethaddr, ARP_HLEN); ut_asserteq_mem(eth->et_dest, priv->fake_host_hwaddr, ARP_HLEN); ut_assert(eth->et_protlen == htons(PROT_ARP)); ut_assert(arp->ar_hrd == htons(ARP_ETHER)); ut_assert(arp->ar_pro == htons(PROT_IP)); ut_assert(arp->ar_hln == ARP_HLEN); ut_assert(arp->ar_pln == ARP_PLEN); ut_asserteq_mem(&arp->ar_sha, net_ethaddr, ARP_HLEN); ut_assert(net_read_ip(&arp->ar_spa).s_addr == net_ip.s_addr); ut_asserteq_mem(&arp->ar_tha, priv->fake_host_hwaddr, ARP_HLEN); ut_assert(net_read_ip(&arp->ar_tpa).s_addr == string_to_ip("1.1.2.4").s_addr); return 0; } static int <API key>(struct udevice *dev, void *packet, unsigned int len) { struct eth_sandbox_priv *priv = dev_get_priv(dev); struct ethernet_hdr *eth = packet; struct arp_hdr *arp = packet + ETHER_HDR_SIZE; int ret; /* * If we are about to generate a reply to ARP, first inject a request * from another host */ if (ntohs(eth->et_protlen) == PROT_ARP && ntohs(arp->ar_op) == ARPOP_REQUEST) { /* Make sure <API key>() knows who is asking */ priv->fake_host_ipaddr = string_to_ip("1.1.2.4"); ret = <API key>(dev); if (ret) return ret; } <API key>(dev, packet, len); <API key>(dev, packet, len); return sb_check_arp_reply(dev, packet, len); } static int <API key>(struct unit_test_state *uts) { net_ping_ip = string_to_ip("1.1.2.2"); <API key>(0, <API key>); /* Used by all of the ut_assert macros in the tx_handler */ <API key>(0, uts); env_set("ethact", "eth@10002000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); <API key>(0, NULL); return 0; } DM_TEST(<API key>, UT_TESTF_SCAN_FDT); static int sb_check_ping_reply(struct udevice *dev, void *packet, unsigned int len) { struct eth_sandbox_priv *priv = dev_get_priv(dev); struct ethernet_hdr *eth = packet; struct ip_udp_hdr *ip; struct icmp_hdr *icmp; /* Used by all of the ut_assert macros */ struct unit_test_state *uts = priv->priv; if (ntohs(eth->et_protlen) != PROT_IP) return 0; ip = packet + ETHER_HDR_SIZE; if (ip->ip_p != IPPROTO_ICMP) return 0; icmp = (struct icmp_hdr *)&ip->udp_src; if (icmp->type != ICMP_ECHO_REPLY) return 0; /* This test would be worthless if we are not waiting */ ut_assert(arp_is_waiting()); /* Validate response */ ut_asserteq_mem(eth->et_src, net_ethaddr, ARP_HLEN); ut_asserteq_mem(eth->et_dest, priv->fake_host_hwaddr, ARP_HLEN); ut_assert(eth->et_protlen == htons(PROT_IP)); ut_assert(net_read_ip(&ip->ip_src).s_addr == net_ip.s_addr); ut_assert(net_read_ip(&ip->ip_dst).s_addr == string_to_ip("1.1.2.4").s_addr); return 0; } static int <API key>(struct udevice *dev, void *packet, unsigned int len) { struct eth_sandbox_priv *priv = dev_get_priv(dev); struct ethernet_hdr *eth = packet; struct arp_hdr *arp = packet + ETHER_HDR_SIZE; int ret; /* * If we are about to generate a reply to ARP, first inject a request * from another host */ if (ntohs(eth->et_protlen) == PROT_ARP && ntohs(arp->ar_op) == ARPOP_REQUEST) { /* Make sure <API key>() knows who is asking */ priv->fake_host_ipaddr = string_to_ip("1.1.2.4"); ret = <API key>(dev); if (ret) return ret; } <API key>(dev, packet, len); <API key>(dev, packet, len); return sb_check_ping_reply(dev, packet, len); } static int <API key>(struct unit_test_state *uts) { net_ping_ip = string_to_ip("1.1.2.2"); <API key>(0, <API key>); /* Used by all of the ut_assert macros in the tx_handler */ <API key>(0, uts); env_set("ethact", "eth@10002000"); ut_assertok(net_loop(PING)); ut_asserteq_str("eth@10002000", env_get("ethact")); <API key>(0, NULL); return 0; } DM_TEST(<API key>, UT_TESTF_SCAN_FDT);
/** \file pprz_transport.h * \brief Extra datalink using PPRZ protocol * * Pprz frame: * * |STX|length|... payload=(length-4) bytes ...|Checksum A|Checksum B| * * where checksum is computed over length and payload: * ck_A = ck_B = length * for each byte b in payload * ck_A += b; ck_b += ck_A */ #ifndef EXTRA_PPRZ_DL_H #define EXTRA_PPRZ_DL_H #include "pprz_transport.h" #define __ExtraLink(dev, _x) dev #define _ExtraLink(dev, _x) __ExtraLink(dev, _x) #define ExtraLink(_x) _ExtraLink(<API key>, _x) /** 4 = STX + len + ck_a + ck_b */ #define <API key>(_payload) (_payload+4) #define <API key>(_x) ExtraLink(CheckFreeSpace(_x)) #define <API key>(_x) ExtraLink(Transmit(_x)) #define <API key>() ExtraLink(SendMessage()) #define <API key>(payload_len) { \ <API key>(STX); \ uint8_t msg_len = <API key>(payload_len); \ <API key>(msg_len); \ ck_a = msg_len; ck_b = msg_len; \ } #define <API key>() { \ <API key>(ck_a); \ <API key>(ck_b); \ <API key>() \ } #define <API key>(_byte) { \ ck_a += _byte; \ ck_b += ck_a; \ <API key>(_byte); \ } #define <API key>(_name, _byte) <API key>(_byte) #define <API key>(_byte) { \ uint8_t _x = *(_byte); \ <API key>(_x); \ } #define <API key>(_byte) { \ <API key>(_byte); \ <API key>((const uint8_t*)_byte+1); \ } #define <API key>(_byte) { \ <API key>(_byte); \ <API key>((const uint8_t*)_byte+2); \ } #ifdef __IEEE_BIG_ENDIAN /* From machine/ieeefp.h */ #define <API key>(_byte) { \ <API key>((const uint8_t*)_byte+4); \ <API key>((const uint8_t*)_byte); \ } #else #define <API key>(_byte) { \ <API key>((const uint8_t*)_byte); \ <API key>((const uint8_t*)_byte+4); \ } #endif #define <API key>(_x) <API key>(_x) #define <API key>(_x) <API key>((const uint8_t*)_x) #define <API key>(_x) <API key>((const uint8_t*)_x) #define <API key>(_x) <API key>((const uint8_t*)_x) #define <API key>(_x) <API key>((const uint8_t*)_x) #define <API key>(_x) <API key>((const uint8_t*)_x) #define <API key>(_x) <API key>((const uint8_t*)_x) #define <API key>(_put, _n, _x) { \ uint8_t _i; \ <API key>(_n); \ for(_i = 0; _i < _n; _i++) { \ _put(&_x[_i]); \ } \ } #define <API key>(_n, _x) <API key>(<API key>, _n, _x) #define <API key>(_n, _x) <API key>(<API key>, _n, _x) #define <API key>(_n, _x) <API key>(<API key>, _n, _x) #define <API key>(_n, _x) <API key>(<API key>, _n, _x) #define <API key>(_n, _x) <API key>(<API key>, _n, _x) #define <API key>(_n, _x) <API key>(<API key>, _n, _x) #define <API key>(_n, _x) <API key>(<API key>, _n, _x) /** Receiving pprz messages */ extern uint8_t extra_pprz_payload[PPRZ_PAYLOAD_LEN]; extern volatile bool_t <API key>; extern uint8_t extra_pprz_ovrn, extra_pprz_error; extern volatile uint8_t <API key>; #include "led.h" //#include "mcu_periph/uart.h" //#include "messages.h" //#include "downlink.h" static inline void parse_extra_pprz( uint8_t c ) { static uint8_t pprz_status = UNINIT; static uint8_t _ck_a, _ck_b, payload_idx; //uint8_t tab[] = { c }; //DOWNLINK_SEND_DEBUG(DefaultChannel,1,tab); switch (pprz_status) { case UNINIT: if (c == STX) pprz_status++; break; case GOT_STX: if (<API key>) { extra_pprz_ovrn++; goto error; } <API key> = c-4; /* Counting STX, LENGTH and CRC1 and CRC2 */ _ck_a = _ck_b = c; pprz_status++; payload_idx = 0; break; case GOT_LENGTH: extra_pprz_payload[payload_idx] = c; _ck_a += c; _ck_b += _ck_a; payload_idx++; if (payload_idx == <API key>) pprz_status++; break; case GOT_PAYLOAD: if (c != _ck_a) goto error; pprz_status++; break; case GOT_CRC1: if (c != _ck_b) goto error; <API key> = TRUE; goto restart; default: goto error; } return; error: extra_pprz_error++; restart: pprz_status = UNINIT; return; } static inline void <API key>(void) { uint8_t i; for(i = 0; i < <API key>; i++) dl_buffer[i] = extra_pprz_payload[i]; dl_msg_available = TRUE; } #define __ExtraPprzLink(dev, _x) dev #define _ExtraPprzLink(dev, _x) __ExtraPprzLink(dev, _x) #define ExtraPprzLink(_x) _ExtraPprzLink(EXTRA_PPRZ_UART, _x) #define ExtraPprzBuffer() ExtraPprzLink(ChAvailable()) #define ReadExtraPprzBuffer() { while (ExtraPprzLink(ChAvailable())&&!<API key>) parse_extra_pprz(ExtraPprzLink(Getch())); } /* Datalink Event */ #define ExtraDatalinkEvent() { \ if (ExtraPprzBuffer()) { \ ReadExtraPprzBuffer(); \ if (<API key>) { \ <API key>(); \ <API key> = FALSE; \ } \ } \ if (dl_msg_available) { \ dl_parse_msg(); \ dl_msg_available = FALSE; \ } \ } #endif /* EXTRA_PPRZ_DL_H */
<?php /** * Test Generated example of using country create API * * */ function <API key>(){ $params = array( 'name' => 'Made Up Land', 'iso_code' => 'ML', 'region_id' => 1, ); try{ $result = civicrm_api3('country', 'create', $params); } catch (<API key> $e) { // handle error here $errorMessage = $e->getMessage(); $errorCode = $e->getErrorCode(); $errorData = $e->getExtraParams(); return array('error' => $errorMessage, 'error_code' => $errorCode, 'error_data' => $errorData); } return $result; } /** * Function returns array of result expected from previous function */ function <API key>(){ $expectedResult = array( 'is_error' => 0, 'version' => 3, 'count' => 1, 'id' => 1, 'values' => array( '1' => array( 'id' => '1', 'name' => 'Made Up Land', 'iso_code' => 'ML', 'country_code' => '', 'address_format_id' => '', 'idd_prefix' => '', 'ndd_prefix' => '', 'region_id' => '1', '<API key>' => '', ), ), ); return $expectedResult; }
<?php namespace TYPO3\CMS\Backend\Tests\Unit\Form\NodeExpansion; use Prophecy\Argument; use TYPO3\CMS\Backend\Form\AbstractNode; use TYPO3\CMS\Backend\Form\NodeExpansion\FieldControl; use TYPO3\CMS\Backend\Form\NodeFactory; use TYPO3\CMS\Core\Localization\LanguageService; use TYPO3\TestingFramework\Core\Unit\UnitTestCase; /** * Test case */ class FieldControlTest extends UnitTestCase { /** * @test */ public function <API key>() { $<API key> = $this->prophesize(LanguageService::class); $<API key>->sL(Argument::cetera())->willReturnArgument(0); $GLOBALS['LANG'] = $<API key>->reveal(); $nodeFactoryProphecy = $this->prophesize(NodeFactory::class); $data = [ 'renderData' => [ 'fieldControl' => [ 'aControl' => [ 'renderType' => 'aControl', ], 'anotherControl' => [ 'renderType' => 'anotherControl', 'after' => [ 'aControl' ], ], ], ], ]; $aControlProphecy = $this->prophesize(AbstractNode::class); $aControlProphecy->render()->willReturn( [ 'iconIdentifier' => 'actions-open', 'title' => 'aTitle', 'linkAttributes' => [ 'href' => '' ], '<API key>' => [ 'someJavaScript' ], 'requireJsModules' => [ 'aModule', ], ] ); $<API key> = $data; $<API key>['renderData']['fieldControlOptions'] = []; $<API key>['renderType'] = 'aControl'; $nodeFactoryProphecy->create($<API key>)->willReturn($aControlProphecy->reveal()); $<API key> = $this->prophesize(AbstractNode::class); $<API key>->render()->willReturn( [ 'iconIdentifier' => 'actions-close', 'title' => 'aTitle', 'linkAttributes' => [ 'href' => '' ], 'requireJsModules' => [ 'anotherModule', ], ] ); $<API key> = $data; $<API key>['renderData']['fieldControlOptions'] = []; $<API key>['renderType'] = 'anotherControl'; $nodeFactoryProphecy->create($<API key>)->willReturn($<API key>->reveal()); $expected = [ '<API key>' => [ 'someJavaScript', ], '<API key>' => [], '<API key>' => [], '<API key>' => [], 'stylesheetFiles' => [], 'requireJsModules' => [ 'aModule', 'anotherModule', ], 'inlineData' => [], 'html' => '\n<a class="btn btn-default">\n...>\n</a>' ]; $result = (new FieldControl($nodeFactoryProphecy->reveal(), $data))->render(); // We're not interested in testing the html merge here $expected['html'] = $result['html']; $this->assertEquals($expected, $result); } }
#include <linux/platform_device.h> #include <linux/init.h> #include <linux/earlysuspend.h> #include <linux/device.h> #include <linux/miscdevice.h> #include <linux/bln.h> #include <linux/mutex.h> #include <linux/stat.h> #include <linux/export.h> #ifdef <API key> #include <linux/wakelock.h> #endif static bool bln_enabled = false; static bool bln_ongoing = false; /* ongoing LED Notification */ static int bln_blink_state = 0; static bool bln_suspended = false; /* is system suspended */ static struct bln_implementation *bln_imp = NULL; static long unsigned int <API key> = 0x0; #ifdef <API key> static bool use_wakelock = true; static struct wake_lock bln_wake_lock; #endif #ifdef <API key> static bool buttons_led_enabled = false; #endif #define <API key> 9 static int gen_all_leds_mask(void) { int i = 0; int mask = 0x0; for(; i < bln_imp->led_count; i++) mask |= 1 << i; return mask; } static int get_led_mask(void){ return (<API key> != 0) ? <API key> : gen_all_leds_mask(); } static void reset_bln_states(void) { bln_blink_state = 0; bln_ongoing = false; } static void <API key>(int mask) { if (likely(bln_imp && bln_imp->enable)) bln_imp->enable(mask); } static void <API key>(int mask) { if (likely(bln_imp && bln_imp->disable)) bln_imp->disable(mask); } static void bln_power_on(void) { if (likely(bln_imp && bln_imp->power_on)) { #ifdef <API key> if(use_wakelock && !wake_lock_active(&bln_wake_lock)){ wake_lock(&bln_wake_lock); } #endif bln_imp->power_on(); } } static void bln_power_off(void) { if (likely(bln_imp && bln_imp->power_off)) { bln_imp->power_off(); #ifdef <API key> if(wake_lock_active(&bln_wake_lock)){ wake_unlock(&bln_wake_lock); } #endif } } static void bln_early_suspend(struct early_suspend *h) { bln_suspended = true; } static void bln_late_resume(struct early_suspend *h) { bln_suspended = false; reset_bln_states(); } static struct early_suspend bln_suspend_data = { .level = <API key> + 1, .suspend = bln_early_suspend, .resume = bln_late_resume, }; static void <API key>(void) { if (!bln_enabled) return; /* * dont allow led notifications while the screen is on, * avoid to interfere with the normal buttons led */ if (!bln_suspended) return; bln_ongoing = true; bln_power_on(); <API key>(get_led_mask()); pr_info("%s: notification led enabled\n", __FUNCTION__); } static void <API key>(void) { if (bln_suspended && bln_ongoing) { <API key>(gen_all_leds_mask()); bln_power_off(); } reset_bln_states(); pr_info("%s: notification led disabled\n", __FUNCTION__); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { int ret = 0; if(unlikely(!bln_imp)) ret = -1; if(bln_enabled) ret = 1; else ret = 0; return sprintf(buf, "%u\n", ret); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { unsigned int data; if(unlikely(!bln_imp)) { pr_err("%s: no BLN implementation registered!\n", __FUNCTION__); return size; } if (sscanf(buf, "%u\n", &data) != 1) { pr_info("%s: input error\n", __FUNCTION__); return size; } pr_devel("%s: %u \n", __FUNCTION__, data); if (data == 1) { pr_info("%s: BLN function enabled\n", __FUNCTION__); bln_enabled = true; } else if (data == 0) { pr_info("%s: BLN function disabled\n", __FUNCTION__); bln_enabled = false; if (bln_ongoing) <API key>(); } else { pr_info("%s: invalid input range %u\n", __FUNCTION__, data); } return size; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf,"%u\n", (bln_ongoing ? 1 : 0)); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { unsigned int data; if (sscanf(buf, "%u\n", &data) != 1) { pr_info("%s: input error\n", __FUNCTION__); return size; } if (data == 1) <API key>(); else if (data == 0) <API key>(); else pr_info("%s: wrong input %u\n", __FUNCTION__, data); return size; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf,"%lu\n", <API key>); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { unsigned int data; if (sscanf(buf, "%u\n", &data) != 1) { pr_info("%s: input error\n", __FUNCTION__); return size; } if(data & gen_all_leds_mask()){ <API key> = data; } else { //TODO: correct error code return -1; } return size; } static ssize_t blink_control_read(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", bln_blink_state); } static ssize_t blink_control_write(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { unsigned int data; if (!bln_ongoing) return size; if (sscanf(buf, "%u\n", &data) != 1) { pr_info("%s: input error\n", __FUNCTION__); return size; } /* reversed logic: * 1 = leds off * 0 = leds on */ if (data == 1) { bln_blink_state = 1; <API key>(get_led_mask()); } else if (data == 0) { bln_blink_state = 0; <API key>(get_led_mask()); } else { pr_info("%s: wrong input %u\n", __FUNCTION__, data); } return size; } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", <API key>); } static ssize_t led_count_read(struct device *dev, struct device_attribute *attr, char *buf) { unsigned int ret = 0x0; if (bln_imp) ret = bln_imp->led_count; return sprintf(buf,"%u\n", ret); } #ifdef <API key> static ssize_t wakelock_read(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf,"%u\n", (use_wakelock ? 1 : 0)); } static ssize_t wakelock_write(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { unsigned int data; if (sscanf(buf, "%u\n", &data) != 1) { pr_info("%s: input error\n", __FUNCTION__); return size; } if (data == 1) { use_wakelock = true; } else if (data == 0) { use_wakelock = false; } else { pr_info("%s: wrong input %u\n", __FUNCTION__, data); } return size; } #endif #ifdef <API key> static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf,"%u\n", (buttons_led_enabled ? 1 : 0)); } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { unsigned int data; if (sscanf(buf, "%u\n", &data) != 1) { pr_info("%s: input error\n", __FUNCTION__); return size; } if (data == 1) { if(!bln_suspended){ buttons_led_enabled = true; bln_power_on(); <API key>(gen_all_leds_mask()); } } else if (data == 0) { if(!bln_suspended){ buttons_led_enabled = false; <API key>(gen_all_leds_mask()); } } else { pr_info("%s: wrong input %u\n", __FUNCTION__, data); } return size; } static DEVICE_ATTR(buttons_led, S_IRUGO | S_IWUGO, <API key>, <API key>); #endif static DEVICE_ATTR(blink_control, S_IRUGO | S_IWUGO, blink_control_read, blink_control_write); static DEVICE_ATTR(enabled, S_IRUGO | S_IWUGO, <API key>, <API key>); static DEVICE_ATTR(led_count, S_IRUGO , led_count_read, NULL); static DEVICE_ATTR(notification_led, S_IRUGO | S_IWUGO, <API key>, <API key>); static DEVICE_ATTR(<API key>, S_IRUGO | S_IWUGO, <API key>, <API key>); static DEVICE_ATTR(version, S_IRUGO , <API key>, NULL); #ifdef <API key> static DEVICE_ATTR(wakelock, S_IRUGO | S_IWUGO, wakelock_read, wakelock_write); #endif static struct attribute *<API key>[] = { &<API key>.attr, &dev_attr_enabled.attr, &dev_attr_led_count.attr, &<API key>.attr, &<API key>.attr, #ifdef <API key> &<API key>.attr, #endif #ifdef <API key> &dev_attr_wakelock.attr, #endif &dev_attr_version.attr, NULL }; static struct attribute_group <API key> = { .attrs = <API key>, }; static struct miscdevice bln_device = { .minor = MISC_DYNAMIC_MINOR, .name = "<API key>", }; /** * <API key> - register a bln implementation of a touchkey device device * @imp: bln implementation structure * * Register a bln implementation with the bln kernel module. */ void <API key>(struct bln_implementation *imp) { //TODO: more checks if(imp){ bln_imp = imp; } } EXPORT_SYMBOL(<API key>); /** * bln_is_ongoing - check if a bln (led) notification is ongoing */ bool bln_is_ongoing() { return bln_ongoing; } EXPORT_SYMBOL(bln_is_ongoing); static int __init bln_control_init(void) { int ret; pr_info("%s misc_register(%s)\n", __FUNCTION__, bln_device.name); ret = misc_register(&bln_device); if (ret) { pr_err("%s misc_register(%s) fail\n", __FUNCTION__, bln_device.name); return 1; } /* add the bln attributes */ if (sysfs_create_group(&bln_device.this_device->kobj, &<API key>) < 0) { pr_err("%s sysfs_create_group fail\n", __FUNCTION__); pr_err("Failed to create sysfs group for device (%s)!\n", bln_device.name); return 1; } #ifdef <API key> wake_lock_init(&bln_wake_lock, WAKE_LOCK_SUSPEND, "<API key>"); #endif <API key>(&bln_suspend_data); return 0; } device_initcall(bln_control_init);
/* * \brief CPU state * \author Norman Feske * \author Stefan Kalkowski * \author Martin Stein * \date 2011-05-06 */ #ifndef <API key> #define <API key> /* Genode includes */ #include <base/stdint.h> namespace Genode { /** * Basic CPU state */ struct Cpu_state { /** * Native exception types */ enum Cpu_exception { RESET = 1, <API key> = 2, SUPERVISOR_CALL = 3, PREFETCH_ABORT = 4, DATA_ABORT = 5, INTERRUPT_REQUEST = 6, <API key> = 7, }; /** * Registers */ addr_t r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12; /* general purpose register 0..12 */ addr_t sp; /* stack pointer */ addr_t lr; /* link register */ addr_t ip; /* instruction pointer */ addr_t cpsr; /* current program status register */ addr_t cpu_exception; /* last hardware exception */ }; /** * Extend CPU state by banked registers */ struct Cpu_state_modes : Cpu_state { /** * Common banked registers for exception modes */ struct Mode_state { enum Mode { UND, /* Undefined */ SVC, /* Supervisor */ ABORT, /* Abort */ IRQ, /* Interrupt */ FIQ, /* Fast Interrupt */ MAX }; addr_t spsr; /* saved program status register */ addr_t sp; /* banked stack pointer */ addr_t lr; /* banked link register */ }; Mode_state mode[Mode_state::MAX]; /* exception mode registers */ addr_t fiq_r[5]; /* fast-interrupt mode r8-r12 */ }; } #endif /* <API key> */
Nduino SDK - TCP Server Example ======================================== This simple project show how to output "Hello World" to the UART0 of NodeMCU V1.0 board (using ESP-12E / ESP-12F module). Build bash $ make Or make output more message: bash $ make V=1 The target file is at build/ directory. Upload bash $ make flash It use the ```/dev/ttyUSB0``` serial device to upload the firmware into board. You need to modify the varible ```ESPPORT``` according to your system in Makefile. It should be /dev/cu.SLAB_USBtoUART in Mac OS X or COM3 in windows. Check Using the cutecom to check the Serial port message in Linux: bash $ sudo apt-get install cutecom Run the cutecom, set: * Device: /dev/ttyUSB0 * Baud rate: 115200 * Data bits: 8 * Stop bits: 1 * Parity: None Then click the 'Open', and it will get a "Hello World!" every 3 seconds. Clean bash $ make clean
/* ScriptData SDName: Boss_Loatheb SD%Complete: 100 SDComment: SDCategory: Naxxramas EndScriptData */ #include "AI/ScriptDevAI/include/sc_common.h" #include "naxxramas.h" enum { EMOTE_AURA_BLOCKING = -1533143, EMOTE_AURA_WANE = -1533144, EMOTE_AURA_FADING = -1533145, SPELL_DEATHBLOOM = 29865, SPELL_DEATHBLOOM_H = 55053, <API key> = 29204, <API key> = 55052, SPELL_NECROTIC_AURA = 55593, SPELL_SUMMON_SPORE = 29234, SPELL_BERSERK = 26662, NPC_SPORE = 16286 }; struct boss_loathebAI : public ScriptedAI { boss_loathebAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_naxxramas* m_pInstance; bool m_bIsRegularMode; uint32 m_uiDeathbloomTimer; uint32 <API key>; uint32 <API key>; uint32 m_uiSummonTimer; uint32 m_uiBerserkTimer; uint8 <API key>; // Used for emotes, 5min check void Reset() override { m_uiDeathbloomTimer = 5000; <API key> = 12000; <API key> = MINUTE * 2 * IN_MILLISECONDS; m_uiSummonTimer = urand(10000, 15000); // first seen in vid after approx 12s m_uiBerserkTimer = MINUTE * 12 * IN_MILLISECONDS; // only in heroic, after 12min <API key> = 0; } void Aggro(Unit* /*pWho*/) override { if (m_pInstance) m_pInstance->SetData(TYPE_LOATHEB, IN_PROGRESS); } void JustDied(Unit* /*pKiller*/) override { if (m_pInstance) m_pInstance->SetData(TYPE_LOATHEB, DONE); } void JustReachedHome() override { if (m_pInstance) m_pInstance->SetData(TYPE_LOATHEB, NOT_STARTED); } void JustSummoned(Creature* pSummoned) override { if (pSummoned->GetEntry() != NPC_SPORE) return; if (Unit* pTarget = m_creature-><API key>(<API key>, 0)) pSummoned->AddThreat(pTarget); } void <API key>(Creature* pSummoned) override { if (pSummoned->GetEntry() == NPC_SPORE && m_pInstance) m_pInstance-><API key>(<API key>, false); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->GetVictim()) return; // Berserk (only heroic) if (!m_bIsRegularMode) { if (m_uiBerserkTimer < uiDiff) { DoCastSpellIfCan(m_creature, SPELL_BERSERK); m_uiBerserkTimer = 300000; } else m_uiBerserkTimer -= uiDiff; } // Inevitable Doom if (<API key> < uiDiff) { DoCastSpellIfCan(m_creature, m_bIsRegularMode ? <API key> : <API key>); <API key> = (<API key> <= 40) ? 30000 : 15000; } else <API key> -= uiDiff; // Necrotic Aura if (<API key> < uiDiff) { switch (<API key> % 3) { case 0: DoCastSpellIfCan(m_creature, SPELL_NECROTIC_AURA); DoScriptText(EMOTE_AURA_BLOCKING, m_creature); <API key> = 14000; break; case 1: DoScriptText(EMOTE_AURA_WANE, m_creature); <API key> = 3000; break; case 2: DoScriptText(EMOTE_AURA_FADING, m_creature); <API key> = 3000; break; } ++<API key>; } else <API key> -= uiDiff; // Summon if (m_uiSummonTimer < uiDiff) { DoCastSpellIfCan(m_creature, SPELL_SUMMON_SPORE); m_uiSummonTimer = m_bIsRegularMode ? 36000 : 18000; } else m_uiSummonTimer -= uiDiff; // Deathbloom if (m_uiDeathbloomTimer < uiDiff) { DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_DEATHBLOOM : SPELL_DEATHBLOOM_H); m_uiDeathbloomTimer = 30000; } else m_uiDeathbloomTimer -= uiDiff; <API key>(); } }; UnitAI* GetAI_boss_loatheb(Creature* pCreature) { return new boss_loathebAI(pCreature); } void AddSC_boss_loatheb() { Script* pNewScript = new Script; pNewScript->Name = "boss_loatheb"; pNewScript->GetAI = &GetAI_boss_loatheb; pNewScript->RegisterSelf(); }
#ifndef __PHYDMPATHDIV_H__ #define __PHYDMPATHDIV_H__ #define PATHDIV_VERSION "2.0" //2014.11.04 #if(defined(<API key>)) #define <API key> //for 8814 dynamic TX path selection #define <API key> 5 #define ANT_DECT_RSSI_TH 3 #define PATH_A 1 #define PATH_B 2 #define PATH_C 3 #define PATH_D 4 #define PHYDM_AUTO_PATH 0 #define PHYDM_FIX_PATH 1 #define NUM_CHOOSE2_FROM4 6 #define NUM_CHOOSE3_FROM4 4 #define PHYDM_A BIT0 #define PHYDM_B BIT1 #define PHYDM_C BIT2 #define PHYDM_D BIT3 #define PHYDM_AB (BIT0 | BIT1) #define PHYDM_AC (BIT0 | BIT2) #define PHYDM_AD (BIT0 | BIT3) #define PHYDM_BC (BIT1 | BIT2) #define PHYDM_BD (BIT1 | BIT3) #define PHYDM_CD (BIT2 | BIT3) #define PHYDM_ABC (BIT0 | BIT1 | BIT2) #define PHYDM_ABD (BIT0 | BIT1 | BIT4) #define PHYDM_ACD (BIT0 | BIT3 | BIT4) #define PHYDM_BCD (BIT2 | BIT3 | BIT4) #define PHYDM_ABCD (BIT0 | BIT1 | BIT2 | BIT3) typedef enum dtp_state { PHYDM_DTP_INIT=1, PHYDM_DTP_RUNNING_1 } PHYDM_DTP_STATE; typedef enum path_div_type { PHYDM_2R_PATH_DIV = 1, PHYDM_4R_PATH_DIV = 2 } PHYDM_PATH_DIV_TYPE; VOID <API key>( IN OUT PVOID pDM_VOID, IN PVOID p_phy_info_void, IN PVOID p_pkt_info_void ); typedef struct <API key> { u1Byte RespTxPath; u1Byte PathSel[<API key>]; u4Byte PathA_Sum[<API key>]; u4Byte PathB_Sum[<API key>]; u2Byte PathA_Cnt[<API key>]; u2Byte PathB_Cnt[<API key>]; u1Byte path_div_type; #if RTL8814A_SUPPORT u4Byte path_a_sum_all; u4Byte path_b_sum_all; u4Byte path_c_sum_all; u4Byte path_d_sum_all; u4Byte path_a_cnt_all; u4Byte path_b_cnt_all; u4Byte path_c_cnt_all; u4Byte path_d_cnt_all; u1Byte dtp_period; BOOLEAN bBecomeLinked; BOOLEAN is_u3_mode; u1Byte num_tx_path; u1Byte default_path; u1Byte num_candidate; u1Byte ant_candidate_1; u1Byte ant_candidate_2; u1Byte ant_candidate_3; u1Byte dtp_state; u1Byte <API key>; BOOLEAN fix_path_bfer; u1Byte search_space_2[NUM_CHOOSE2_FROM4]; u1Byte search_space_3[NUM_CHOOSE3_FROM4]; u1Byte pre_tx_path; u1Byte <API key>; BOOLEAN is_pathA_exist; #endif } PATHDIV_T, *pPATHDIV_T; #endif //#if(defined(<API key>)) VOID <API key>( IN PVOID pDM_VOID, IN pu1Byte CmdBuf, IN u1Byte CmdLen ); VOID <API key>( IN PVOID pDM_VOID ); VOID odm_PathDiversity( IN PVOID pDM_VOID ); VOID odm_pathdiv_debug( IN PVOID pDM_VOID, IN u4Byte *const dm_value ); #if(DM_ODM_SUPPORT_TYPE & (ODM_WIN)) //#define PATHDIV_ENABLE 1 #define <API key> <API key> #define <API key> <API key> typedef struct <API key> { u4Byte org_5g_RegE30; u4Byte org_5g_RegC14; u4Byte org_5g_RegCA0; u4Byte swt_5g_RegE30; u4Byte swt_5g_RegC14; u4Byte swt_5g_RegCA0; //for 2G IQK information u4Byte org_2g_RegC80; u4Byte org_2g_RegC4C; u4Byte org_2g_RegC94; u4Byte org_2g_RegC14; u4Byte org_2g_RegCA0; u4Byte swt_2g_RegC80; u4Byte swt_2g_RegC4C; u4Byte swt_2g_RegC94; u4Byte swt_2g_RegC14; u4Byte swt_2g_RegCA0; } PATHDIV_PARA,*pPATHDIV_PARA; VOID <API key>( IN PADAPTER Adapter ); VOID <API key>( IN PADAPTER Adapter ); VOID <API key>( IN PADAPTER Adapter ); BOOLEAN odm_IsConnected_92C( IN PADAPTER Adapter ); BOOLEAN <API key>( //IN PADAPTER Adapter IN PDM_ODM_T pDM_Odm ); VOID <API key>( IN PADAPTER Adapter ); VOID odm_SetRespPath_92C( IN PADAPTER Adapter, IN u1Byte DefaultRespPath ); VOID <API key>( IN PADAPTER Adapter ); VOID <API key>( IN PADAPTER Adapter ); VOID <API key>( IN PADAPTER Adapter ); VOID <API key>( PRT_TIMER pTimer ); VOID <API key>( IN PVOID pContext ); VOID <API key>( PRT_TIMER pTimer ); VOID <API key>( IN PVOID pContext ); VOID <API key>( PDM_ODM_T pDM_Odm ); VOID <API key>( PADAPTER Adapter, BOOLEAN bIsDefPort, BOOLEAN bMatchBSSID, PRT_WLAN_STA pEntry, PRT_RFD pRfd, pu1Byte pDesc ); VOID <API key>( PADAPTER Adapter, BOOLEAN bIsDefPort, BOOLEAN bMatchBSSID, PRT_WLAN_STA pEntry, PRT_RFD pRfd ); VOID <API key>( IN PDM_ODM_T pDM_Odm ); VOID <API key>( IN PADAPTER Adapter, IN PRT_TCB pTcb, IN pu1Byte pDesc ); VOID odm_PathDivInit_92D( IN PDM_ODM_T pDM_Odm ); u1Byte <API key>( IN PADAPTER Adapter ); VOID <API key>( IN PADAPTER Adapter, IN u1Byte ScanChnl ); #endif //#if(DM_ODM_SUPPORT_TYPE & (ODM_WIN)) #endif //#ifndef __ODMPATHDIV_H__
<?php /** * Custom functions that act independently of the theme templates * * Eventually, some of the functionality here could be replaced by core features * * @package pixeltaxi */ /** * Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link. * * @param array $args Configuration arguments. * @return array */ function <API key>( $args ) { $args['show_home'] = true; return $args; } add_filter( 'wp_page_menu_args', '<API key>' ); /** * Adds custom classes to the array of body classes. * * @param array $classes Classes for the body element. * @return array */ function <API key>( $classes ) { // Adds a class of group-blog to blogs with more than 1 published author. if ( is_multi_author() ) { $classes[] = 'group-blog'; } return $classes; } add_filter( 'body_class', '<API key>' ); /** * Filters wp_title to print a neat <title> tag based on what is being viewed. * * @param string $title Default title text for current view. * @param string $sep Optional separator. * @return string The filtered title. */ function pixeltaxi_wp_title( $title, $sep ) { global $page, $paged; if ( is_feed() ) { return $title; } // Add the blog name $title .= get_bloginfo( 'name' ); // Add the blog description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) { $title .= " $sep $site_description"; } // Add a page number if necessary: if ( $paged >= 2 || $page >= 2 ) { $title .= " $sep " . sprintf( __( 'Page %s', 'pixeltaxi' ), max( $paged, $page ) ); } return $title; } add_filter( 'wp_title', 'pixeltaxi_wp_title', 10, 2 );
<?php /* Posts navigation for single post pages, but not for Page post */ global $graphene_settings; global $wp_version; ?> <?php graphene_post_nav(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class( 'clearfix post-format post' ); ?>> <div class="entry-header"> <?php $has_uploaded_audio = false; $has_uploaded_video = false; global $post_format; switch ( $post_format){ case 'status': $format_title = __( 'Status update', 'graphene' ); break; case 'link': $format_title = __( 'Link', 'graphene' ); break; case 'audio': $format_title = __( 'Audio', 'graphene' ); if ( get_post_meta( get_the_ID(), '_wp_format_audio', true ) ) $has_uploaded_audio = true; break; case 'image': $format_title = __( 'Image', 'graphene' ); break; case 'video': $format_title = __( 'Video', 'graphene' ); if ( get_post_meta( get_the_ID(), '_wp_format_video', true ) ) $has_uploaded_video = true; break; default: $format_title = __( 'Post format', 'graphene' ); } ?> <p class="format-title"> <?php if ( ! is_singular() ) : ?><a href="<?php the_permalink(); ?>"><?php endif; ?> <?php echo $format_title; ?> <?php if ( ! is_singular() ) : ?></a><?php endif; ?> </p> <?php /* The post title */ ?> <div class="entry-title"> <?php if ( in_array( $post_format, array( 'status', 'link' ) ) ) : ?> <?php ?> <p class="entry-date updated"><?php printf( '%1$s &mdash; %2$s', get_the_time(__( 'l F j, Y', 'graphene' ) ), get_the_time(__( 'g:i A', 'graphene' ) ) ); ?></p> <?php endif; ?> <?php if (in_array( $post_format, array( 'audio', 'image', 'video' ) ) ) : ?> <p class="entry-permalink"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf(esc_attr__( 'Permalink to %s', 'graphene' ), the_title_attribute( 'echo=0' ) ); ?>"><?php if ( get_the_title() == '' ) {_e( '(No title)','graphene' );} else {the_title();} ?></a></p> <?php endif; ?> </div> <?php /* Edit post link, if user is logged in */ ?> <?php if (is_user_logged_in() ) : ?> <p class="edit-post"> <?php edit_post_link(__( 'Edit post','graphene' ), ' ( ', ' )' ); ?> </p> <?php endif; ?> <?php /* The comment link */ ?> <?php if ( ! is_singular() && <API key>() ) : ?> <p class="comment-link"> <?php $comments_num = get_comments_number(); comments_popup_link( __( 'Leave comment', 'graphene' ), sprintf( __( '%s comment', 'graphene' ), number_format_i18n( $comments_num ) ), sprintf( _n( '%s comment', "%s comments", $comments_num, 'graphene' ), number_format_i18n( $comments_num ) ), 'comments-link', __( "Comments off", 'graphene' ) ); ?> </p> <?php endif; ?> </div> <div class="entry-content clearfix"> <div class="<API key>"> <?php if ( $post_format == 'status' ) : /* Author's avatar, displayed only for the 'status' format */ ?> <?php echo get_avatar( get_the_author_meta( 'user_email' ), 110 ); ?> <?php endif; ?> <?php if ( $post_format == 'audio' ) : /* Featured image, displayed only for the 'audio' format */ if ( has_post_thumbnail( get_the_ID() ) ) { the_post_thumbnail( array( 110, 110 ) ); } endif; ?> </div> <?php /* Modify the content_width var for video post format */ if ( $post_format == 'video' ){ global $content_width; $gutter = $graphene_settings['gutter_width']; $content_width = $content_width - 110 + ($gutter * 2); } ?> <?php /* Output the post content */ ?> <?php if ( $wp_version >= 3.6 && $post_format == 'audio' && $has_uploaded_audio ) : ?> <div class="entry-media"> <div class="audio-content"> <?php <API key>(); ?> </div><!-- .audio-content --> </div><!-- .entry-media --> <?php endif; ?> <?php if ( $wp_version >= 3.6 && $post_format == 'video' && $has_uploaded_video ) : ?> <div class="entry-media"> <div class="video-content"> <?php <API key>(); ?> </div><!-- .video-content --> </div><!-- .entry-media --> <?php endif; ?> <?php if ( $has_uploaded_video || $has_uploaded_audio ) <API key>(); else the_content(); ?> <?php /* Revert the content_width var for video post format */ if ( $post_format == 'video' ){ $content_width = <API key>(); } ?> <?php if ( in_array( $post_format, array( 'image', 'video' ) ) ) : ?> <?php if ( has_excerpt() ) : ?> <div class="entry-description"><?php the_excerpt(); ?></div> <?php endif; ?> <p class="entry-date updated"><?php printf( __( 'Posted on: %s', 'graphene' ), '<br /><span>' . get_the_time( __( 'F j, Y', 'graphene' ) ) . '</span>' ); ?></p> <?php endif; ?> <?php if ( $post_format == 'status' ) : /* Post author, displayed only for the 'status' format */ ?> <p class="post-author vcard">&mdash; <span class="fn nickname"><?php <API key>(); ?></span></p> <?php endif; ?> </div> </div> <?php /* For printing: the permalink */ if ( $graphene_settings['print_css']) { echo <API key>( '<span class="printonly url"><strong>'.__( 'Permanent link to this article:', 'graphene' ).' </strong><span>'. get_permalink().'</span></span>' ); } /* Adsense */ graphene_adsense(); /* Comments */ comments_template(); do_action( '<API key>' ); ?>
// { dg-do run { target *-*-freebsd* *-*-netbsd* *-*-linux* *-*-solaris* *-*-cygwin *-*-darwin* powerpc-ibm-aix* } } // { dg-options " -std=gnu++0x -pthread" { target *-*-freebsd* *-*-netbsd* *-*-linux* powerpc-ibm-aix* } } // { dg-options " -std=gnu++0x -pthreads" { target *-*-solaris* } } // { dg-options " -std=gnu++0x " { target *-*-cygwin *-*-darwin* } } // { dg-require-cstdint "" } // { dg-require-gthreads "" } // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING3. If not see #include <functional> // std::unary_function, std::ref #include <thread> #include <system_error> #include <testsuite_hooks.h> struct nonconst : public std::unary_function<std::thread::id&, void> { void operator()(std::thread::id& id) { id = std::this_thread::get_id(); } }; void test01() { bool test __attribute__((unused)) = true; try { std::thread::id t1_id1; nonconst c1; std::thread t1(std::ref(c1), std::ref(t1_id1)); std::thread::id t1_id2 = t1.get_id(); VERIFY( t1.joinable() ); t1.join(); VERIFY( !t1.joinable() ); VERIFY( t1_id1 == t1_id2 ); std::thread::id t2_id1; nonconst c2; std::thread t2(c2, std::ref(t2_id1)); std::thread::id t2_id2 = t2.get_id(); VERIFY( t2.joinable() ); t2.join(); VERIFY( !t2.joinable() ); VERIFY( t2_id1 == t2_id2 ); } catch (const std::system_error&) { VERIFY( false ); } catch (...) { VERIFY( false ); } } int main() { test01(); return 0; }
#include "ucom_share.h" #include "ucom_comm.h" #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif UCOM_SET_SRAMSHARE <API key> g_stHifiShareAddr; VOS_VOID UCOM_SHARE_Init(VOS_VOID) { } #ifdef __cplusplus #if __cplusplus } #endif #endif
package Git::SVN::Editor; use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/; use strict; use warnings; use SVN::Core; use SVN::Delta; use Carp qw/croak/; use IO::File; use Git qw/command command_oneline command_noisy command_output_pipe command_input_pipe command_close_pipe command_bidi_pipe <API key>/; BEGIN { @ISA = qw(SVN::Delta::Editor); } sub new { my ($class, $opts) = @_; foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) { die "$_ required!\n" unless (defined $opts->{$_}); } my $pool = SVN::Pool->new; my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b}); my $types = check_diff_paths($opts->{ra}, $opts->{svn_path}, $opts->{r}, $mods); # $opts->{ra} functions should not be used after this: my @ce = $opts->{ra}->get_commit_editor($opts->{log}, $opts->{editor_cb}, $pool); my $self = SVN::Delta::Editor->new(@ce, $pool); bless $self, $class; foreach (qw/svn_path r tree_a tree_b/) { $self->{$_} = $opts->{$_}; } $self->{url} = $opts->{ra}->{url}; $self->{mods} = $mods; $self->{types} = $types; $self->{pool} = $pool; $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) }; $self->{rm} = { }; $self->{path_prefix} = length $self->{svn_path} ? "$self->{svn_path}/" : ''; $self->{config} = $opts->{config}; $self->{mergeinfo} = $opts->{mergeinfo}; return $self; } sub generate_diff { my ($tree_a, $tree_b) = @_; my @diff_tree = qw(diff-tree -z -r); if ($_cp_similarity) { push @diff_tree, "-C$_cp_similarity"; } else { push @diff_tree, '-C'; } push @diff_tree, '--find-copies-harder' if $_find_copies_harder; push @diff_tree, "-l$_rename_limit" if defined $_rename_limit; push @diff_tree, $tree_a, $tree_b; my ($diff_fh, $ctx) = command_output_pipe(@diff_tree); local $/ = "\0"; my $state = 'meta'; my @mods; while (<$diff_fh>) { chomp $_; # this gets rid of the trailing "\0" if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s ($::sha1)\s($::sha1)\s ([MTCRAD])\d*$/xo) { push @mods, { mode_a => $1, mode_b => $2, sha1_a => $3, sha1_b => $4, chg => $5 }; if ($5 =~ /^(?:C|R)$/) { $state = 'file_a'; } else { $state = 'file_b'; } } elsif ($state eq 'file_a') { my $x = $mods[$#mods] or croak "Empty array\n"; if ($x->{chg} !~ /^(?:C|R)$/) { croak "Error parsing $_, $x->{chg}\n"; } $x->{file_a} = $_; $state = 'file_b'; } elsif ($state eq 'file_b') { my $x = $mods[$#mods] or croak "Empty array\n"; if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) { croak "Error parsing $_, $x->{chg}\n"; } if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) { croak "Error parsing $_, $x->{chg}\n"; } $x->{file_b} = $_; $state = 'meta'; } else { croak "Error parsing $_\n"; } } command_close_pipe($diff_fh, $ctx); \@mods; } sub check_diff_paths { my ($ra, $pfx, $rev, $mods) = @_; my %types; $pfx .= '/' if length $pfx; sub type_diff_paths { my ($ra, $types, $path, $rev) = @_; my @p = split m#/+#, $path; my $c = shift @p; unless (defined $types->{$c}) { $types->{$c} = $ra->check_path($c, $rev); } while (@p) { $c .= '/' . shift @p; next if defined $types->{$c}; $types->{$c} = $ra->check_path($c, $rev); } } foreach my $m (@$mods) { foreach my $f (qw/file_a file_b/) { next unless defined $m->{$f}; my ($dir) = ($m->{$f} =~ m if (length $pfx.$dir && ! defined $types{$dir}) { type_diff_paths($ra, \%types, $pfx.$dir, $rev); } } } \%types; } sub split_path { return ($_[0] =~ m } sub repo_path { my ($self, $path) = @_; if (my $enc = $self->{pathnameencoding}) { require Encode; Encode::from_to($path, $enc, 'UTF-8'); } $self->{path_prefix}.(defined $path ? $path : ''); } sub url_path { my ($self, $path) = @_; if ($self->{url} =~ m#^https?://#) { # characters are taken from subversion/libsvn_subr/path.c $path =~ s#([^~a-zA-Z0-9_./!$&'()*+,-])#sprintf("%%%02X",ord($1))#eg; } $self->{url} . '/' . $self->repo_path($path); } sub rmdirs { my ($self) = @_; my $rm = $self->{rm}; delete $rm->{''}; # we never delete the url we're tracking return unless %$rm; foreach (keys %$rm) { my @d = split m my $c = shift @d; $rm->{$c} = 1; while (@d) { $c .= '/' . shift @d; $rm->{$c} = 1; } } delete $rm->{$self->{svn_path}}; delete $rm->{''}; # we never delete the url we're tracking return unless %$rm; my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/, $self->{tree_b}); local $/ = "\0"; while (<$fh>) { chomp; my @dn = split m while (pop @dn) { delete $rm->{join '/', @dn}; } unless (%$rm) { close $fh; return; } } command_close_pipe($fh, $ctx); my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat}); foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) { $self->close_directory($bat->{$d}, $p); my ($dn) = ($d =~ m print "\tD+\t$d/\n" unless $::_q; $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p); delete $bat->{$d}; } } sub open_or_add_dir { my ($self, $full_path, $baton, $deletions) = @_; my $t = $self->{types}->{$full_path}; if (!defined $t) { die "$full_path not known in r$self->{r} or we have a bug!\n"; } { no warnings 'once'; # SVN::Node::none and SVN::Node::file are used only once, # so we're shutting up Perl's warnings about them. if ($t == $SVN::Node::none || defined($deletions->{$full_path})) { return $self->add_directory($full_path, $baton, undef, -1, $self->{pool}); } elsif ($t == $SVN::Node::dir) { return $self->open_directory($full_path, $baton, $self->{r}, $self->{pool}); } # no warnings 'once' print STDERR "$full_path already exists in repository at ", "r$self->{r} and it is not a directory (", ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n"; } # no warnings 'once' exit 1; } sub ensure_path { my ($self, $path, $deletions) = @_; my $bat = $self->{bat}; my $repo_path = $self->repo_path($path); return $bat->{''} unless (length $repo_path); my @p = split m#/+#, $repo_path; my $c = shift @p; $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''}, $deletions); while (@p) { my $c0 = $c; $c .= '/' . shift @p; $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0}, $deletions); } return $bat->{$c}; } # Subroutine to convert a globbing pattern to a regular expression. # From perl cookbook. sub glob2pat { my $globstr = shift; my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']'); $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge; return '^' . $globstr . '$'; } sub check_autoprop { my ($self, $pattern, $properties, $file, $fbat) = @_; # Convert the globbing pattern to a regular expression. my $regex = glob2pat($pattern); # Check if the pattern matches the file name. if($file =~ m/($regex)/) { # Parse the list of properties to set. my @props = split(/;/, $properties); foreach my $prop (@props) { # Parse 'name=value' syntax and set the property. if ($prop =~ /([^=]+)=(.*)/) { my ($n,$v) = ($1,$2); for ($n, $v) { s/^\s+ } $self->change_file_prop($fbat, $n, $v); } } } } sub apply_autoprops { my ($self, $file, $fbat) = @_; my $conf_t = ${$self->{config}}{'config'}; no warnings 'once'; # Check [miscellany]/enable-auto-props in svn configuration. if (SVN::_Core::svn_config_get_bool( $conf_t, $SVN::_Core::<API key>, $SVN::_Core::<API key>, 0)) { # Auto-props are enabled. Enumerate them to look for matches. my $callback = sub { $self->check_autoprop($_[0], $_[1], $file, $fbat); }; SVN::_Core::<API key>( $conf_t, $SVN::_Core::<API key>, $callback); } } sub check_attr { my ($attr,$path) = @_; my $val = command_oneline("check-attr", $attr, "--", $path); if ($val) { $val =~ s/^[^:]*:\s*[^:]*:\s*(.*)\s*$/$1/; } return $val; } sub apply_manualprops { my ($self, $file, $fbat) = @_; my $pending_properties = check_attr( "svn-properties", $file ); if ($pending_properties eq "") { return; } # Parse the list of properties to set. my @props = split(/;/, $pending_properties); # TODO: get existing properties to compare to # - this fails for add so currently not done # my $existing_props = ::get_svnprops($file); my $existing_props = {}; # TODO: caching svn properties or storing them in .gitattributes # would make that faster foreach my $prop (@props) { # Parse 'name=value' syntax and set the property. if ($prop =~ /([^=]+)=(.*)/) { my ($n,$v) = ($1,$2); for ($n, $v) { s/^\s+ } my $existing = $existing_props->{$n}; if (!defined($existing) || $existing ne $v) { $self->change_file_prop($fbat, $n, $v); } } } } sub A { my ($self, $m, $deletions) = @_; my ($dir, $file) = split_path($m->{file_b}); my $pbat = $self->ensure_path($dir, $deletions); my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat, undef, -1); print "\tA\t$m->{file_b}\n" unless $::_q; $self->apply_autoprops($file, $fbat); $self->apply_manualprops($m->{file_b}, $fbat); $self->chg_file($fbat, $m); $self->close_file($fbat,undef,$self->{pool}); } sub C { my ($self, $m, $deletions) = @_; my ($dir, $file) = split_path($m->{file_b}); my $pbat = $self->ensure_path($dir, $deletions); # workaround for a bug in svn serf backend (v1.8.5 and below): # store third argument to ->add_file() in a local variable, to make it # have the same lifetime as $fbat my $upa = $self->url_path($m->{file_a}); my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat, $upa, $self->{r}); print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q; $self->apply_manualprops($m->{file_b}, $fbat); $self->chg_file($fbat, $m); $self->close_file($fbat,undef,$self->{pool}); } sub delete_entry { my ($self, $path, $pbat) = @_; my $rpath = $self->repo_path($path); my ($dir, $file) = split_path($rpath); $self->{rm}->{$dir} = 1; $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool}); } sub R { my ($self, $m, $deletions) = @_; my ($dir, $file) = split_path($m->{file_b}); my $pbat = $self->ensure_path($dir, $deletions); # workaround for a bug in svn serf backend, see comment in C() above my $upa = $self->url_path($m->{file_a}); my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat, $upa, $self->{r}); print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q; $self->apply_autoprops($file, $fbat); $self->apply_manualprops($m->{file_b}, $fbat); $self->chg_file($fbat, $m); $self->close_file($fbat,undef,$self->{pool}); ($dir, $file) = split_path($m->{file_a}); $pbat = $self->ensure_path($dir, $deletions); $self->delete_entry($m->{file_a}, $pbat); } sub M { my ($self, $m, $deletions) = @_; my ($dir, $file) = split_path($m->{file_b}); my $pbat = $self->ensure_path($dir, $deletions); my $fbat = $self->open_file($self->repo_path($m->{file_b}), $pbat,$self->{r},$self->{pool}); print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q; $self->apply_manualprops($m->{file_b}, $fbat); $self->chg_file($fbat, $m); $self->close_file($fbat,undef,$self->{pool}); } sub T { my ($self, $m, $deletions) = @_; # Work around subversion issue 4091: toggling the "is a # symlink" property requires removing and re-adding a # file or else "svn up" on affected clients trips an # assertion and aborts. if (($m->{mode_b} =~ /^120/ && $m->{mode_a} !~ /^120/) || ($m->{mode_b} !~ /^120/ && $m->{mode_a} =~ /^120/)) { $self->D({ mode_a => $m->{mode_a}, mode_b => '000000', sha1_a => $m->{sha1_a}, sha1_b => '0' x 40, chg => 'D', file_b => $m->{file_b} }, $deletions); $self->A({ mode_a => '000000', mode_b => $m->{mode_b}, sha1_a => '0' x 40, sha1_b => $m->{sha1_b}, chg => 'A', file_b => $m->{file_b} }, $deletions); return; } $self->M($m, $deletions); } sub change_file_prop { my ($self, $fbat, $pname, $pval) = @_; $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool}); } sub change_dir_prop { my ($self, $pbat, $pname, $pval) = @_; $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool}); } sub _chg_file_get_blob ($$$$) { my ($self, $fbat, $m, $which) = @_; my $fh = $::_repository->temp_acquire("git_blob_$which"); if ($m->{"mode_$which"} =~ /^120/) { print $fh 'link ' or croak $!; $self->change_file_prop($fbat,'svn:special','*'); } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) { $self->change_file_prop($fbat,'svn:special',undef); } my $blob = $m->{"sha1_$which"}; return ($fh,) if ($blob =~ /^0{40}$/); my $size = $::_repository->cat_blob($blob, $fh); croak "Failed to read object $blob" if ($size < 0); $fh->flush == 0 or croak $!; seek $fh, 0, 0 or croak $!; my $exp = ::md5sum($fh); seek $fh, 0, 0 or croak $!; return ($fh, $exp); } sub chg_file { my ($self, $fbat, $m) = @_; if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) { $self->change_file_prop($fbat,'svn:executable','*'); } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) { $self->change_file_prop($fbat,'svn:executable',undef); } my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a'; my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b'; my $pool = SVN::Pool->new; my $atd = $self->apply_textdelta($fbat, $exp_a, $pool); if (-s $fh_a) { my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool); my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool); if (defined $res) { die "Unexpected result from send_txstream: $res\n", "(SVN::Core::VERSION: $SVN::Core::VERSION)\n"; } } else { my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool); die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n" if ($got ne $exp_b); } Git::temp_release($fh_b, 1); Git::temp_release($fh_a, 1); $pool->clear; } sub D { my ($self, $m, $deletions) = @_; my ($dir, $file) = split_path($m->{file_b}); my $pbat = $self->ensure_path($dir, $deletions); print "\tD\t$m->{file_b}\n" unless $::_q; $self->delete_entry($m->{file_b}, $pbat); } sub close_edit { my ($self) = @_; my ($p,$bat) = ($self->{pool}, $self->{bat}); foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) { next if $_ eq ''; $self->close_directory($bat->{$_}, $p); } $self->close_directory($bat->{''}, $p); $self->SUPER::close_edit($p); $p->clear; } sub abort_edit { my ($self) = @_; $self->SUPER::abort_edit($self->{pool}); } sub DESTROY { my $self = shift; $self->SUPER::DESTROY(@_); $self->{pool}->clear; } # this drives the editor sub apply_diff { my ($self) = @_; my $mods = $self->{mods}; my %o = ( D => 0, C => 1, R => 2, A => 3, M => 4, T => 5 ); my %deletions; foreach my $m (@$mods) { if ($m->{chg} eq "D") { $deletions{$m->{file_b}} = 1; } } foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) { my $f = $m->{chg}; if (defined $o{$f}) { $self->$f($m, \%deletions); } else { fatal("Invalid change type: $f"); } } if (defined($self->{mergeinfo})) { $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo", $self->{mergeinfo}); } $self->rmdirs if $_rmdir; if (@$mods == 0 && !defined($self->{mergeinfo})) { $self->abort_edit; } else { $self->close_edit; } return scalar @$mods; } 1; __END__ =head1 NAME Git::SVN::Editor - commit driver for "git svn set-tree" and dcommit =head1 SYNOPSIS use Git::SVN::Editor; use Git::SVN::Ra; my $ra = Git::SVN::Ra->new($url); my %opts = ( r => 19, log => "log message", ra => $ra, config => SVN::Core::config_get_config($svn_config_dir), tree_a => "$commit^", tree_b => "$commit", editor_cb => sub { print "Committed r$_[0]\n"; }, mergeinfo => "/branches/foo:1-10", svn_path => "trunk" ); Git::SVN::Editor->new(\%opts)->apply_diff or print "No changes\n";
""" DIRAC Graphs package provides tools for creation of various plots to provide graphical representation of the DIRAC Monitoring and Accounting data The DIRAC Graphs package is derived from the GraphTool plotting package of the CMS/Phedex Project by ... <to be added> """ from __future__ import print_function __RCSID__ = "$Id$" # Make sure the the Agg backend is used despite arbitrary configuration import matplotlib matplotlib.use( 'agg' ) import DIRAC from DIRAC.Core.Utilities.Graphs.Graph import Graph from DIRAC.Core.Utilities.Graphs.GraphUtilities import evalPrefs common_prefs = { 'background_color':'white', 'figure_padding':12, 'plot_grid':'1:1', 'plot_padding':0, 'frame':'On', 'font' : 'Lucida Grande', 'font_family' : 'sans-serif', 'dpi':100, 'legend':True, 'legend_position':'bottom', 'legend_max_rows':99, 'legend_max_columns':4, 'square_axis':False, 'scale_data': None, 'scale_ticks': None } graph_large_prefs = { 'width':1000, 'height':700, 'text_size':8, 'subtitle_size':10, 'subtitle_padding':5, 'title_size':15, 'title_padding':5, 'text_padding':5, 'figure_padding':15, 'plot_title_size':12, 'legend_width':980, 'legend_height':150, 'legend_padding':20, 'limit_labels':15, 'graph_time_stamp':True } graph_normal_prefs = { 'width':800, 'height':600, 'text_size':8, 'subtitle_size':10, 'subtitle_padding':5, 'title_size':15, 'title_padding':10, 'text_padding':5, 'figure_padding':12, 'plot_title_size':12, 'legend_width':780, 'legend_height':120, 'legend_padding':20, 'limit_labels':15, 'graph_time_stamp':True, 'label_text_size' : 14 } graph_small_prefs = { 'width':450, 'height':330, 'text_size':10, 'subtitle_size':5, 'subtitle_padding':4, 'title_size':10, 'title_padding':6, 'text_padding':3, 'figure_padding':10, 'plot_title_size':8, 'legend_width':430, 'legend_height':50, 'legend_padding':10, 'limit_labels':15, 'graph_time_stamp':True } <API key> = { 'width':100, 'height':80, 'text_size':6, 'subtitle_size':0, 'subtitle_padding':0, 'title_size':8, 'title_padding':2, 'text_padding':1, 'figure_padding':2, 'plot_title':'NoTitle', 'legend':False, 'plot_axis_grid':False, 'plot_axis':False, 'plot_axis_labels':False, 'graph_time_stamp':False, 'tight_bars':True } def graph( data, fileName, *args, **kw ): prefs = evalPrefs( *args, **kw ) graph_size = prefs.get('graph_size', 'normal') if graph_size == "normal": defaults = graph_normal_prefs elif graph_size == "small": defaults = graph_small_prefs elif graph_size == "thumbnail": defaults = <API key> elif graph_size == "large": defaults = graph_large_prefs graph = Graph() graph.makeGraph( data, common_prefs, defaults, prefs ) graph.writeGraph( fileName, 'PNG' ) return DIRAC.S_OK( {'plot':fileName} ) def __checkKW( kw ): if 'watermark' not in kw: kw[ 'watermark' ] = "%s/DIRAC/Core/Utilities/Graphs/Dwatermark.png" % DIRAC.rootPath return kw def barGraph( data, fileName, *args, **kw ): kw = __checkKW( kw ) graph( data, fileName, plot_type = 'BarGraph', statistics_line = True, *args, **kw ) def lineGraph( data, fileName, *args, **kw ): kw = __checkKW( kw ) graph( data, fileName, plot_type = 'LineGraph', statistics_line = True, *args, **kw ) def curveGraph( data, fileName, *args, **kw ): kw = __checkKW( kw ) graph( data, fileName, plot_type = 'CurveGraph', statistics_line = False, *args, **kw ) def cumulativeGraph( data, fileName, *args, **kw ): kw = __checkKW( kw ) graph( data, fileName, plot_type = 'LineGraph', cumulate_data = True, *args, **kw ) def pieGraph( data, fileName, *args, **kw ): kw = __checkKW( kw ) prefs = {'xticks':False, 'yticks':False, 'legend_position':'right'} graph( data, fileName, prefs, plot_type = 'PieGraph', *args, **kw ) def qualityGraph( data, fileName, *args, **kw ): kw = __checkKW( kw ) prefs = {'plot_axis_grid':False} graph( data, fileName, prefs, plot_type = 'QualityMapGraph', *args, **kw ) def textGraph( text, fileName, *args, **kw ): kw = __checkKW( kw ) prefs = {'text_image':text} graph( {}, fileName, prefs, *args, **kw ) def histogram( data, fileName, bins, *args, **kw ): try: from pylab import hist except: print("No pylab module available") return kw = __checkKW( kw ) values, vbins, _patches = hist( data, bins ) histo = dict( zip( vbins, values ) ) span = ( max( data ) - min( data ) ) / float( bins ) * 0.95 kw = __checkKW( kw ) graph( histo, fileName, plot_type = 'BarGraph', span = span, statistics_line = True, *args, **kw )
use vars qw(%result_texis %result_texts %result_trees %result_errors %result_indices %result_sectioning %result_nodes %result_menus %result_floats %result_converted %<API key> %result_elements %<API key>); use utf8; $result_trees{'ref_in_center'} = { 'contents' => [ { 'contents' => [], 'parent' => {}, 'type' => 'text_root' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => '<API key>' }, { 'parent' => {}, 'text' => 'Top' }, { 'parent' => {}, 'text' => ' ', 'type' => 'spaces_at_end' } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'node', 'contents' => [ { 'parent' => {}, 'text' => ' ', 'type' => 'empty_line' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => '<API key>' }, { 'args' => [ { 'contents' => [ { 'parent' => {}, 'text' => 'Top' } ], 'parent' => {}, 'type' => 'brace_command_arg' } ], 'cmdname' => 'ref', 'contents' => [], 'extra' => { '<API key>' => [ [ {} ] ], 'label' => {}, 'node_argument' => { 'node_content' => [ {} ], 'normalized' => 'Top' }, '<API key>' => { 'text' => '', 'type' => '<API key>' } }, 'line_nr' => { 'file_name' => '', 'line_nr' => 3, 'macro' => '' }, 'parent' => {} }, { 'parent' => {}, 'text' => ' ', 'type' => 'spaces_at_end' } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'center', 'extra' => { 'misc_content' => [ {} ], '<API key>' => {} }, 'line_nr' => {}, 'parent' => {} }, { 'parent' => {}, 'text' => ' ', 'type' => 'empty_line' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => '<API key>' }, { 'args' => [ { 'contents' => [ { 'parent' => {}, 'text' => 'Top' } ], 'parent' => {}, 'type' => 'brace_command_arg' }, { 'contents' => [ { 'text' => ' ', 'type' => '<API key>' } ], 'parent' => {}, 'type' => 'brace_command_arg' }, { 'contents' => [ { 'parent' => {}, 'text' => 'title ' } ], 'parent' => {}, 'type' => 'brace_command_arg' } ], 'cmdname' => 'ref', 'contents' => [], 'extra' => { '<API key>' => [ [ {} ], undef ], '<API key>' => { 'text' => '', 'type' => '<API key>' } }, 'line_nr' => { 'file_name' => '', 'line_nr' => 5, 'macro' => '' }, 'parent' => {}, 'remaining_args' => 2 } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'center', 'extra' => { 'misc_content' => [ {} ], '<API key>' => {} }, 'line_nr' => {}, 'parent' => {} }, { 'contents' => [ { 'parent' => {}, 'text' => 'very long ' } ], 'parent' => {}, 'type' => 'paragraph' } ], 'extra' => { 'node_content' => [ {} ], 'nodes_manuals' => [ { 'node_content' => [], 'normalized' => 'Top' } ], 'normalized' => 'Top', '<API key>' => {} }, 'line_nr' => { 'file_name' => '', 'line_nr' => 1, 'macro' => '' }, 'parent' => {} } ], 'type' => 'document_root' }; $result_trees{'ref_in_center'}{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}; $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'contents'}[2]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'extra'}{'<API key>'}[0][0] = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'args'}[0]{'contents'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'extra'}{'label'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'extra'}{'node_argument'}{'node_content'}[0] = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'args'}[0]{'contents'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[2]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'extra'}{'misc_content'}[0] = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'extra'}{'<API key>'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'line_nr'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'args'}[0]{'contents'}[1]{'line_nr'}; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[1]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[2]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[1]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[2]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[2]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[2]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'extra'}{'<API key>'}[0][0] = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'args'}[0]{'contents'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'extra'}{'misc_content'}[0] = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'extra'}{'<API key>'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'line_nr'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'args'}[0]{'contents'}[1]{'line_nr'}; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[3]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[4]{'contents'}[0]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[4]; $result_trees{'ref_in_center'}{'contents'}[1]{'contents'}[4]{'parent'} = $result_trees{'ref_in_center'}{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'extra'}{'node_content'}[0] = $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'contents'}[1]; $result_trees{'ref_in_center'}{'contents'}[1]{'extra'}{'nodes_manuals'}[0]{'node_content'} = $result_trees{'ref_in_center'}{'contents'}[1]{'extra'}{'node_content'}; $result_trees{'ref_in_center'}{'contents'}[1]{'extra'}{'<API key>'} = $result_trees{'ref_in_center'}{'contents'}[1]{'args'}[0]{'contents'}[0]; $result_trees{'ref_in_center'}{'contents'}[1]{'parent'} = $result_trees{'ref_in_center'}; $result_texis{'ref_in_center'} = '@node Top @center @ref{Top} @center @ref{Top, ,title }very long '; $result_texts{'ref_in_center'} = ' Top Top very long '; $result_sectioning{'ref_in_center'} = {}; $result_nodes{'ref_in_center'} = { 'cmdname' => 'node', 'extra' => { 'normalized' => 'Top' }, 'node_up' => { 'extra' => { 'manual_content' => [ { 'text' => 'dir' } ], 'top_node_up' => {} }, 'type' => 'top_node_up' } }; $result_nodes{'ref_in_center'}{'node_up'}{'extra'}{'top_node_up'} = $result_nodes{'ref_in_center'}; $result_menus{'ref_in_center'} = { 'cmdname' => 'node', 'extra' => { 'normalized' => 'Top' } }; $result_errors{'ref_in_center'} = [ { 'error_line' => ':5: @ref missing close brace ', 'file_name' => '', 'line_nr' => 5, 'macro' => '', 'text' => '@ref missing close brace', 'type' => 'error' }, { 'error_line' => ':6: misplaced } ', 'file_name' => '', 'line_nr' => 6, 'macro' => '', 'text' => 'misplaced }', 'type' => 'error' } ]; $result_converted{'plaintext'}->{'ref_in_center'} = ' *note Top:: *note Top:: very long '; $result_converted{'html_text'}->{'ref_in_center'} = '<a name="Top"></a> <h1 class="node-heading">Top</h1> <div align="center"><a href="#Top">Top</a> </div> <div align="center">&lsquo;title &rsquo; </div><p>very long </p><hr> '; $result_converted{'docbook'}->{'ref_in_center'} = '<anchor id="Top"/> <link linkend="Top">Top</link> <link>Top</link> <para>very long </para>'; 1;
<?php use yii\helpers\Html; /* @var $this \yii\web\View */ /* @var $generators \yii\gii\Generator[] */ /* @var $content string */ $generators = Yii::$app->controller->module->generators; $this->title = 'Welcome to Gii'; ?> <div class="default-index"> <div class="row"> <?php foreach ($generators as $id => $generator): ?> <div class="col-md-4"> <div class="box"> <div class="box-header with-border"> <h3 class="box-title"><?= Html::encode($generator->getName()) ?></h3> </div> <div class="box-body"> <p><?= $generator->getDescription() ?></p> <p><?= Html::a('Start »', ['default/view', 'id' => $id], ['class' => 'btn btn-default']) ?></p> </div> </div> </div> <?php endforeach; ?> </div> </div>
// PlotSquared - A plot manager and world generator for the Bukkit API / // This program is free software; you can redistribute it and/or modify / // (at your option) any later version. / // This program is distributed in the hope that it will be useful, / // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / // along with this program; if not, write to the Free Software Foundation, / // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / // You can contact us via: support@intellectualsites.com / package com.plotsquared.bukkit.events; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import com.<API key>.plot.flag.Flag; import com.<API key>.plot.object.Plot; /** * Called when a Flag is added to a plot * * @author Citymonstret * @author Empire92 */ public class PlotFlagAddEvent extends PlotEvent implements Cancellable { private static HandlerList handlers = new HandlerList(); private final Flag flag; private boolean cancelled; /** * PlotFlagAddEvent: Called when a Flag is added to a plot * * @param flag Flag that was added * @param plot Plot to which the flag was added */ public PlotFlagAddEvent(final Flag flag, final Plot plot) { super(plot); this.flag = flag; } public static HandlerList getHandlerList() { return handlers; } /** * Get the flag involved * * @return Flag */ public Flag getFlag() { return this.flag; } @Override public HandlerList getHandlers() { return handlers; } @Override public final boolean isCancelled() { return this.cancelled; } @Override public final void setCancelled(boolean cancelled) { this.cancelled = cancelled; } }
Ext.ns('Flamingo2.view.designer.property.ankus'); Ext.define('Flamingo2.view.designer.property.ankus.ALG_ANKUS_CF_SIM', { extend: 'Flamingo2.view.designer.property._NODE_ALG', alias: 'widget.ALG_ANKUS_CF_SIM', requires: [ 'Flamingo2.view.designer.property.<API key>', 'Flamingo2.view.designer.property._BrowserField', 'Flamingo2.view.designer.property._ColumnGrid', 'Flamingo2.view.designer.property._DependencyGrid', 'Flamingo2.view.designer.property._NameValueGrid', 'Flamingo2.view.designer.property._KeyValueGrid', 'Flamingo2.view.designer.property._EnvironmentGrid' ], width: 450, height: 320, items: [ { title: message.msg('workflow.common.parameter'), xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 150 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'fieldcontainer', fieldLabel: message.msg('workflow.dm.cf.sim.cal.standard'), layout: 'hbox', items: [ { xtype: 'combo', name: 'basedType', value: 'user', flex: 1, tooltip: message.msg('workflow.dm.cf.sim.cal.standard.detail'), forceSelection: true, multiSelect: false, disabled: false, editable: false, displayField: 'name', valueField: 'value', mode: 'local', queryMode: 'local', triggerAction: 'all', store: Ext.create('Ext.data.Store', { fields: ['name', 'value', 'description'], data: [ { name: 'USER', value: 'user', description: message.msg('workflow.dm.sim.user.based') }, { name: 'ITEM', value: 'item', description: message.msg('workflow.dm.sim.item.based') } ] }) } ] }, { xtype: 'fieldcontainer', fieldLabel: message.msg('workflow.dm.sim.algorithm'), layout: 'hbox', items: [ { xtype: 'combo', name: 'algorithmOption', value: 'pearson', flex: 1, forceSelection: true, multiSelect: false, disabled: false, editable: false, displayField: 'name', valueField: 'value', mode: 'local', queryMode: 'local', triggerAction: 'all', store: Ext.create('Ext.data.Store', { fields: ['name', 'value', 'description'], data: [ {name: 'PEARSON COEFFICIENT', value: 'pearson', description: 'PEARSON COEFFICIENT'}, {name: 'COSINE COEFFICIENT', value: 'cosine', description: 'COSINE COEFFICIENT'} ] }) } ] }, { xtype: 'textfield', fieldLabel: message.msg('workflow.dm.cf.sim.minimum.eval.number'), name: 'commonCount', vtype: 'numeric', value: 20, tooltip: message.msg('workflow.dm.cf.sim.minimum.eval.number.detail'), allowBlank: false }, { xtype: 'textfield', name: 'threshold', vtype: 'decimalpoint', tooltip: message.msg('workflow.dm.cf.sim.minimum.print.threshold.detail'), fieldLabel: message.msg('workflow.dm.cf.sim.minimum.print.threshold'), value: 0.8, allowBlank: false }, { xtype: 'fieldcontainer', fieldLabel: message.msg('workflow.common.delimiter'), tooltip: message.msg('workflow.common.delimiter.message'), layout: 'hbox', items: [ { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'combo', name: 'delimiter', value: ',', flex: 1, forceSelection: true, multiSelect: false, editable: false, readOnly: this.readOnly, displayField: 'name', valueField: 'value', mode: 'local', queryMode: 'local', triggerAction: 'all', tpl: '<tpl for="."><div class="x-boundlist-item" data-qtip="{description}">{name}</div></tpl>', store: Ext.create('Ext.data.Store', { fields: ['name', 'value', 'description'], data: [ { name: message.msg('workflow.common.delimiter.double.colon'), value: '::', description: '::' }, { name: message.msg('workflow.common.delimiter.comma'), value: ',', description: ',' }, { name: message.msg('workflow.common.delimiter.pipe'), value: '|', description: '|' }, { name: message.msg('workflow.common.delimiter.tab'), value: '\'\\t\'', description: '\'\\t\'' }, { name: message.msg('workflow.common.delimiter.blank'), value: '\'\\s\'', description: '\'\\s\'' }, { name: message.msg('workflow.common.delimiter.user.def'), value: 'CUSTOM', description: message.msg('workflow.common.delimiter.user.def') } ] }), listeners: { change: function (combo, newValue, oldValue, eOpts) { // textfield enable | disable . var customValueField = combo.nextSibling('textfield'); if (newValue === 'CUSTOM') { customValueField.enable(); customValueField.isValid(); } else { customValueField.disable(); if (newValue) { customValueField.setValue(newValue); } else { customValueField.setValue(','); } } } } }, { xtype: 'textfield', name: 'delimiterValue', vtype: 'exceptcommaspace', flex: 1, disabled: true, readOnly: this.readOnly, allowBlank: false, value: ',' } ] } ] } ] }, { title: message.msg('workflow.common.mapreduce'), xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'textfield', name: 'jar', fieldLabel: message.msg('workflow.common.mapreduce.jar'), value: ANKUS.JAR, disabledCls: 'disabled-plain', readOnly: true }, { xtype: 'textfield', name: 'driver', fieldLabel: message.msg('workflow.common.mapreduce.driver'), value: 'CFBasedSimilarity', disabledCls: 'disabled-plain', readOnly: true } ] }, { title: message.msg('workflow.common.inout.path'), xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ // Ankus MapReduce . N . { xtype: '_inputGrid', title: message.msg('workflow.common.input.path'), flex: 1 }, // Ankus MapReduce . 1 . { xtype: 'fieldcontainer', fieldLabel: message.msg('workflow.common.output.path'), defaults: { hideLabel: true, margin: "5 0 0 0" // Same as CSS ordering (top, right, bottom, left) }, layout: 'hbox', items: [ { xtype: '_browserField', name: 'output', allowBlank: false, readOnly: false, flex: 1 } ] } ] }, { title: message.msg('workflow.common.hadoop.conf'), xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'displayfield', height: 20, value: message.msg('workflow.common.hadoop.conf.guide') }, { xtype: '_keyValueGrid', flex: 1 } ] }, { title: message.msg('common.references'), xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'displayfield', height: 20, value: '<a href="http: } ] } ], /** * UI Key . * * ex) . * propFilters: { * // * add : [ * {'test1': '1'}, * {'test2': '2'} * ], * * // * modify: [ * {'delimiterType': 'delimiterType2'}, * {'config': 'config2'} * ], * * // * remove: ['script', 'metadata'] * } */ propFilters: { add: [], modify: [], remove: ['config'] }, /** * MapReduce . * Flamingo2 Workflow Engine props.mapreduce Key . * * @param props UI Key Value */ afterPropertySet: function (props) { props.mapreduce = { "driver": props.driver ? props.driver : '', "jar": props.jar ? props.jar : '', "confKey": props.hadoopKeys ? props.hadoopKeys : '', "confValue": props.hadoopValues ? props.hadoopValues : '', params: [] }; if (props.input) { props.mapreduce.params.push("-input", props.input); } if (props.output) { props.mapreduce.params.push("-output", props.output); } if (props.basedType) { props.mapreduce.params.push("-basedType", props.basedType); } if (props.algorithmOption) { props.mapreduce.params.push("-algorithmOption", props.algorithmOption); } if (props.commonCount) { props.mapreduce.params.push("-commonCount", props.commonCount); } if (props.threshold) { props.mapreduce.params.push("-threshold", props.threshold); } if (props.delimiter) { if (props.delimiter == 'CUSTOM') { props.mapreduce.params.push("-delimiter", props.delimiterValue); } else { props.mapreduce.params.push("-delimiter", props.delimiter); } } this.callParent(arguments); } });
#include "S1ap-MME-UE-S1AP-ID.h" int <API key>(<API key> *td, const void *sptr, <API key> *ctfailcb, void *app_key) { if(!sptr) { _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } /* Constraint check succeeded */ return 0; } /* * This type is implemented using NativeInteger, * so here we adjust the DEF accordingly. */ static void <API key>(<API key> *td) { td->free_struct = <API key>.free_struct; td->print_struct = <API key>.print_struct; td->ber_decoder = <API key>.ber_decoder; td->der_encoder = <API key>.der_encoder; td->xer_decoder = <API key>.xer_decoder; td->xer_encoder = <API key>.xer_encoder; td->uper_decoder = <API key>.uper_decoder; td->uper_encoder = <API key>.uper_encoder; td->aper_decoder = <API key>.aper_decoder; td->aper_encoder = <API key>.aper_encoder; if(!td->per_constraints) td->per_constraints = <API key>.per_constraints; td->elements = <API key>.elements; td->elements_count = <API key>.elements_count; /* td->specifics = <API key>.specifics; // Defined explicitly */ } void <API key>(<API key> *td, void *struct_ptr, int contents_only) { <API key>(td); td->free_struct(td, struct_ptr, contents_only); } int <API key>(<API key> *td, const void *struct_ptr, int ilevel, <API key> *cb, void *app_key) { <API key>(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t <API key>(asn_codec_ctx_t *opt_codec_ctx, <API key> *td, void **structure, const void *bufptr, size_t size, int tag_mode) { <API key>(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t <API key>(<API key> *td, void *structure, int tag_mode, ber_tlv_tag_t tag, <API key> *cb, void *app_key) { <API key>(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t <API key>(asn_codec_ctx_t *opt_codec_ctx, <API key> *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { <API key>(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t <API key>(<API key> *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, <API key> *cb, void *app_key) { <API key>(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } asn_dec_rval_t <API key>(asn_codec_ctx_t *opt_codec_ctx, <API key> *td, <API key> *constraints, void **structure, asn_per_data_t *per_data) { <API key>(td); return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); } asn_enc_rval_t <API key>(<API key> *td, <API key> *constraints, void *structure, asn_per_outp_t *per_out) { <API key>(td); return td->uper_encoder(td, constraints, structure, per_out); } asn_enc_rval_t <API key>(<API key> *td, <API key> *constraints, void *structure, asn_per_outp_t *per_out) { <API key>(td); return td->aper_encoder(td, constraints, structure, per_out); } asn_dec_rval_t <API key>(asn_codec_ctx_t *opt_codec_ctx, <API key> *td, <API key> *constraints, void **structure, asn_per_data_t *per_data) { <API key>(td); return td->aper_decoder(opt_codec_ctx, td, constraints, structure, per_data); } static <API key> <API key> GCC_NOTUSED = { { APC_CONSTRAINED, 32, -1, 0, 4294967295U } /* (0..4294967295) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static <API key> <API key> = { 0, 0, 0, 0, 0, 0, /* Native long size */ 1 /* Unsigned representation */ }; static ber_tlv_tag_t <API key>[] = { (<API key> | (2 << 2)) }; <API key> <API key> = { "S1ap-MME-UE-S1AP-ID", "S1ap-MME-UE-S1AP-ID", <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, 0, /* Use generic outmost tag fetcher */ <API key>, sizeof(<API key>) /sizeof(<API key>[0]), <API key>, /* Same as above */ sizeof(<API key>) /sizeof(<API key>[0]), &<API key>, 0, 0, /* No members */ &<API key> /* Additional specs */ };
namespace ACE.Server.Network.GameEvent.Events { public class <API key> : GameEventMessage { public <API key>(Session session, uint target, float mana, uint success) : base(GameEventType.<API key>, GameMessageGroup.UIQueue, session) { Writer.Write(target); Writer.Write(mana); Writer.Write(success); } } }
// -*- Mode: Go; indent-tabs-mode: t -*- package squashfs_test import ( "bytes" "errors" "fmt" "io/ioutil" "math" "os" "os/exec" "path/filepath" "strings" "syscall" "testing" "time" . "gopkg.in/check.v1" "gopkg.in/yaml.v2" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/snap" "github.com/snapcore/snapd/snap/snapdir" "github.com/snapcore/snapd/snap/squashfs" "github.com/snapcore/snapd/testutil" ) // Hook up check.v1 into the "go test" runner func Test(t *testing.T) { TestingT(t) } type SquashfsTestSuite struct { oldStdout, oldStderr, outf *os.File testutil.BaseTest } var _ = Suite(&SquashfsTestSuite{}) func makeSnap(c *C, manifest, data string) *squashfs.Snap { cur, _ := os.Getwd() return makeSnapInDir(c, cur, manifest, data) } func makeSnapContents(c *C, manifest, data string) string { tmp := c.MkDir() err := os.MkdirAll(filepath.Join(tmp, "meta", "hooks", "dir"), 0755) c.Assert(err, IsNil) // our regular snap.yaml err = ioutil.WriteFile(filepath.Join(tmp, "meta", "snap.yaml"), []byte(manifest), 0644) c.Assert(err, IsNil) // some hooks err = ioutil.WriteFile(filepath.Join(tmp, "meta", "hooks", "foo-hook"), nil, 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(tmp, "meta", "hooks", "bar-hook"), nil, 0755) c.Assert(err, IsNil) // And a file in another directory in there, just for testing (not a valid // hook) err = ioutil.WriteFile(filepath.Join(tmp, "meta", "hooks", "dir", "baz"), nil, 0755) c.Assert(err, IsNil) // some empty directories err = os.MkdirAll(filepath.Join(tmp, "food", "bard", "bazd"), 0755) c.Assert(err, IsNil) // some data err = ioutil.WriteFile(filepath.Join(tmp, "data.bin"), []byte(data), 0644) c.Assert(err, IsNil) return tmp } func makeSnapInDir(c *C, dir, manifest, data string) *squashfs.Snap { snapType := "app" var m struct { Type string `yaml:"type"` } if err := yaml.Unmarshal([]byte(manifest), &m); err == nil && m.Type != "" { snapType = m.Type } tmp := makeSnapContents(c, manifest, data) // build it sn := squashfs.New(filepath.Join(dir, "foo.snap")) err := sn.Build(tmp, &squashfs.BuildOpts{SnapType: snapType}) c.Assert(err, IsNil) return sn } func (s *SquashfsTestSuite) SetUpTest(c *C) { d := c.MkDir() dirs.SetRootDir(d) err := os.Chdir(d) c.Assert(err, IsNil) restore := osutil.MockMountInfo("") s.AddCleanup(restore) s.outf, err = ioutil.TempFile(c.MkDir(), "") c.Assert(err, IsNil) s.oldStdout, s.oldStderr = os.Stdout, os.Stderr os.Stdout, os.Stderr = s.outf, s.outf } func (s *SquashfsTestSuite) TearDownTest(c *C) { os.Stdout, os.Stderr = s.oldStdout, s.oldStderr // this ensures things were quiet _, err := s.outf.Seek(0, 0) c.Assert(err, IsNil) outbuf, err := ioutil.ReadAll(s.outf) c.Assert(err, IsNil) c.Check(string(outbuf), Equals, "") } func (s *SquashfsTestSuite) <API key>(c *C) { sn := makeSnap(c, "name: test", "") c.Check(squashfs.<API key>(sn.Path()), Equals, true) } func (s *SquashfsTestSuite) <API key>(c *C) { data := []string{ "hsqs", "hsqs\x00", "hsqs" + strings.Repeat("\x00", squashfs.SuperblockSize-4), "hsqt" + strings.Repeat("\x00", squashfs.SuperblockSize-4+1), "not a snap", } for _, d := range data { err := ioutil.WriteFile("not-a-snap", []byte(d), 0644) c.Assert(err, IsNil) c.Check(squashfs.<API key>("not-a-snap"), Equals, false) } } func (s *SquashfsTestSuite) <API key>(c *C) { // mock cp but still cp cmd := testutil.MockCommand(c, "cp", `#!/bin/sh exec /bin/cp "$@" `) defer cmd.Restore() // mock link but still link linked := 0 r := squashfs.MockLink(func(a, b string) error { linked++ return os.Link(a, b) }) defer r() sn := makeSnap(c, "name: test", "") targetPath := filepath.Join(c.MkDir(), "target.snap") mountDir := c.MkDir() didNothing, err := sn.Install(targetPath, mountDir, nil) c.Assert(err, IsNil) c.Assert(didNothing, Equals, false) c.Check(osutil.FileExists(targetPath), Equals, true) c.Check(linked, Equals, 1) c.Check(cmd.Calls(), HasLen, 0) } func (s *SquashfsTestSuite) <API key>(c *C) { cmd := testutil.MockCommand(c, "cp", "") defer cmd.Restore() // mock link but still link linked := 0 r := squashfs.MockLink(func(a, b string) error { linked++ return os.Link(a, b) }) defer r() // pretend we are on overlayfs restore := squashfs.<API key>(func() (string, error) { return "/upper", nil }) defer restore() c.Assert(os.MkdirAll(dirs.SnapSeedDir, 0755), IsNil) sn := makeSnapInDir(c, dirs.SnapSeedDir, "name: test2", "") targetPath := filepath.Join(c.MkDir(), "target.snap") _, err := os.Lstat(targetPath) c.Check(os.IsNotExist(err), Equals, true) didNothing, err := sn.Install(targetPath, c.MkDir(), nil) c.Assert(err, IsNil) c.Assert(didNothing, Equals, false) // symlink in place c.Check(osutil.IsSymlink(targetPath), Equals, true) // no link / no cp c.Check(linked, Equals, 0) c.Check(cmd.Calls(), HasLen, 0) } func noLink() func() { return squashfs.MockLink(func(string, string) error { return errors.New("no.") }) } func (s *SquashfsTestSuite) <API key>(c *C) { // first, disable os.Link defer noLink()() // then, mock cp but still cp cmd := testutil.MockCommand(c, "cp", `#!/bin/sh exec /bin/cp "$@" `) defer cmd.Restore() sn := makeSnap(c, "name: test2", "") targetPath := filepath.Join(c.MkDir(), "target.snap") mountDir := c.MkDir() didNothing, err := sn.Install(targetPath, mountDir, nil) c.Assert(err, IsNil) c.Assert(didNothing, Equals, false) c.Check(cmd.Calls(), HasLen, 1) didNothing, err = sn.Install(targetPath, mountDir, nil) c.Assert(err, IsNil) c.Assert(didNothing, Equals, true) c.Check(cmd.Calls(), HasLen, 1) // and not 2 \o/ } func (s *SquashfsTestSuite) <API key>(c *C) { defer noLink()() c.Assert(os.MkdirAll(dirs.SnapSeedDir, 0755), IsNil) sn := makeSnapInDir(c, dirs.SnapSeedDir, "name: test2", "") targetPath := filepath.Join(c.MkDir(), "target.snap") _, err := os.Lstat(targetPath) c.Check(os.IsNotExist(err), Equals, true) didNothing, err := sn.Install(targetPath, c.MkDir(), nil) c.Assert(err, IsNil) c.Assert(didNothing, Equals, false) c.Check(osutil.IsSymlink(targetPath), Equals, true) } func (s *SquashfsTestSuite) <API key>(c *C) { defer noLink()() systemSnapsDir := filepath.Join(dirs.SnapSeedDir, "systems", "20200521", "snaps") c.Assert(os.MkdirAll(systemSnapsDir, 0755), IsNil) snap := makeSnapInDir(c, systemSnapsDir, "name: test2", "") targetPath := filepath.Join(c.MkDir(), "target.snap") _, err := os.Lstat(targetPath) c.Check(os.IsNotExist(err), Equals, true) didNothing, err := snap.Install(targetPath, c.MkDir(), nil) c.Assert(err, IsNil) c.Assert(didNothing, Equals, false) c.Check(osutil.IsSymlink(targetPath), Equals, true) } func (s *SquashfsTestSuite) <API key>(c *C) { defer noLink()() c.Assert(os.MkdirAll(dirs.SnapSeedDir, 0755), IsNil) sn := makeSnapInDir(c, dirs.SnapSeedDir, "name: test2", "") targetPath := filepath.Join(c.MkDir(), "target.snap") _, err := os.Lstat(targetPath) c.Check(os.IsNotExist(err), Equals, true) didNothing, err := sn.Install(targetPath, c.MkDir(), &snap.InstallOptions{MustNotCrossDevices: true}) c.Assert(err, IsNil) c.Assert(didNothing, Equals, false) c.Check(osutil.IsSymlink(targetPath), Equals, false) } func (s *SquashfsTestSuite) <API key>(c *C) { sn := makeSnap(c, "name: test2", "") targetPath := filepath.Join(c.MkDir(), "foo.snap") c.Assert(os.Symlink(sn.Path(), targetPath), IsNil) didNothing, err := sn.Install(targetPath, c.MkDir(), nil) c.Assert(err, IsNil) c.Check(didNothing, Equals, true) } func (s *SquashfsTestSuite) TestPath(c *C) { p := "/path/to/foo.snap" sn := squashfs.New("/path/to/foo.snap") c.Assert(sn.Path(), Equals, p) } func (s *SquashfsTestSuite) TestReadFile(c *C) { sn := makeSnap(c, "name: foo", "") content, err := sn.ReadFile("meta/snap.yaml") c.Assert(err, IsNil) c.Assert(string(content), Equals, "name: foo") } func (s *SquashfsTestSuite) TestReadFileFail(c *C) { mockUnsquashfs := testutil.MockCommand(c, "unsquashfs", `echo boom; exit 1`) defer mockUnsquashfs.Restore() sn := makeSnap(c, "name: foo", "") _, err := sn.ReadFile("meta/snap.yaml") c.Assert(err, ErrorMatches, "cannot run unsquashfs: boom") } func (s *SquashfsTestSuite) <API key>(c *C) { sn := makeSnap(c, "name: foo", "") r, err := sn.RandomAccessFile("meta/snap.yaml") c.Assert(err, IsNil) defer r.Close() c.Assert(r.Size(), Equals, int64(9)) b := make([]byte, 4) n, err := r.ReadAt(b, 4) c.Assert(err, IsNil) c.Assert(n, Equals, 4) c.Check(string(b), Equals, ": fo") } func (s *SquashfsTestSuite) TestListDir(c *C) { sn := makeSnap(c, "name: foo", "") fileNames, err := sn.ListDir("meta/hooks") c.Assert(err, IsNil) c.Assert(len(fileNames), Equals, 3) c.Check(fileNames[0], Equals, "bar-hook") c.Check(fileNames[1], Equals, "dir") c.Check(fileNames[2], Equals, "foo-hook") } func (s *SquashfsTestSuite) TestWalkNative(c *C) { sub := "." sn := makeSnap(c, "name: foo", "") sqw := map[string]os.FileInfo{} sn.Walk(sub, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == "food" { return filepath.SkipDir } sqw[path] = info return nil }) base := c.MkDir() c.Assert(sn.Unpack("*", base), IsNil) sdw := map[string]os.FileInfo{} snapdir.New(base).Walk(sub, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == "food" { return filepath.SkipDir } sdw[path] = info return nil }) fpw := map[string]os.FileInfo{} filepath.Walk(filepath.Join(base, sub), func(path string, info os.FileInfo, err error) error { if err != nil { return err } path, err = filepath.Rel(base, path) if err != nil { return err } if path == "food" { return filepath.SkipDir } fpw[path] = info return nil }) for k := range fpw { squashfs.Alike(sqw[k], fpw[k], c, Commentf(k)) squashfs.Alike(sdw[k], fpw[k], c, Commentf(k)) } for k := range sqw { squashfs.Alike(fpw[k], sqw[k], c, Commentf(k)) squashfs.Alike(sdw[k], sqw[k], c, Commentf(k)) } for k := range sdw { squashfs.Alike(fpw[k], sdw[k], c, Commentf(k)) squashfs.Alike(sqw[k], sdw[k], c, Commentf(k)) } } func (s *SquashfsTestSuite) <API key>(c *C) { expectingNames := []string{ ".", "data.bin", "food", "meta", "meta/hooks", "meta/hooks/bar-hook", "meta/hooks/dir", "meta/hooks/dir/baz", "meta/hooks/foo-hook", "meta/snap.yaml", } sub := "." sn := makeSnap(c, "name: foo", "") var seen []string sn.Walk(sub, func(path string, info os.FileInfo, err error) error { c.Logf("got %v", path) if err != nil { return err } seen = append(seen, path) if path == "food" { return filepath.SkipDir } return nil }) c.Assert(len(seen), Equals, len(expectingNames)) for idx, name := range seen { c.Check(name, Equals, expectingNames[idx]) } } func (s *SquashfsTestSuite) <API key>(c *C) { // mock behavior of squashfs-tools 4.5 and later mockUnsquashfs := testutil.MockCommand(c, "unsquashfs", ` cat <<EOF drwx -rw-r--r-- root/root 0 2021-07-27 13:31 ./data.bin drwxr-xr-x root/root 27 2021-07-27 13:31 ./food drwxr-xr-x root/root 27 2021-07-27 13:31 ./food/bard drwxr-xr-x root/root 3 2021-07-27 13:31 ./food/bard/bazd drwxr-xr-x root/root 45 2021-07-27 13:31 ./meta drwxr-xr-x root/root 58 2021-07-27 13:31 ./meta/hooks -rwxr-xr-x root/root 0 2021-07-27 13:31 ./meta/hooks/bar-hook drwxr-xr-x root/root 26 2021-07-27 13:31 ./meta/hooks/dir -rwxr-xr-x root/root 0 2021-07-27 13:31 ./meta/hooks/dir/baz -rwxr-xr-x root/root 0 2021-07-27 13:31 ./meta/hooks/foo-hook -rw-r--r-- root/root 9 2021-07-27 13:31 ./meta/snap.yaml EOF `) defer mockUnsquashfs.Restore() s.<API key>(c) } func (s *SquashfsTestSuite) <API key>(c *C) { // mock behavior of pre-4.5 squashfs-tools mockUnsquashfs := testutil.MockCommand(c, "unsquashfs", ` cat <<EOF Parallel unsquashfs: Using 1 processor 5 inodes (1 blocks) to write drwx -rw-r--r-- root/root 0 2021-07-27 13:31 ./data.bin drwxr-xr-x root/root 27 2021-07-27 13:31 ./food drwxr-xr-x root/root 27 2021-07-27 13:31 ./food/bard drwxr-xr-x root/root 3 2021-07-27 13:31 ./food/bard/bazd drwxr-xr-x root/root 45 2021-07-27 13:31 ./meta drwxr-xr-x root/root 58 2021-07-27 13:31 ./meta/hooks -rwxr-xr-x root/root 0 2021-07-27 13:31 ./meta/hooks/bar-hook drwxr-xr-x root/root 26 2021-07-27 13:31 ./meta/hooks/dir -rwxr-xr-x root/root 0 2021-07-27 13:31 ./meta/hooks/dir/baz -rwxr-xr-x root/root 0 2021-07-27 13:31 ./meta/hooks/foo-hook -rw-r--r-- root/root 9 2021-07-27 13:31 ./meta/snap.yaml EOF `) defer mockUnsquashfs.Restore() s.<API key>(c) } // TestUnpackGlob tests the internal unpack func (s *SquashfsTestSuite) TestUnpackGlob(c *C) { data := "some random data" sn := makeSnap(c, "", data) outputDir := c.MkDir() err := sn.Unpack("data*", outputDir) c.Assert(err, IsNil) // this is the file we expect c.Assert(filepath.Join(outputDir, "data.bin"), testutil.FileEquals, data) // ensure glob was honored c.Assert(osutil.FileExists(filepath.Join(outputDir, "meta/snap.yaml")), Equals, false) } func (s *SquashfsTestSuite) <API key>(c *C) { mockUnsquashfs := testutil.MockCommand(c, "unsquashfs", ` cat >&2 <<EOF Failed to write /tmp/1/modules/4.4.0-112-generic/modules.symbols, skipping Write on output file failed because No space left on device writer: failed to write data block 0 Failed to write /tmp/1/modules/4.4.0-112-generic/modules.symbols.bin, skipping Write on output file failed because No space left on device writer: failed to write data block 0 Failed to write /tmp/1/modules/4.4.0-112-generic/vdso/vdso32.so, skipping Write on output file failed because No space left on device writer: failed to write data block 0 Failed to write /tmp/1/modules/4.4.0-112-generic/vdso/vdso64.so, skipping Write on output file failed because No space left on device writer: failed to write data block 0 Failed to write /tmp/1/modules/4.4.0-112-generic/vdso/vdsox32.so, skipping Write on output file failed because No space left on device writer: failed to write data block 0 Failed to write /tmp/1/snap/manifest.yaml, skipping Write on output file failed because No space left on device writer: failed to write data block 0 Failed to write /tmp/1/snap/snapcraft.yaml, skipping EOF `) defer mockUnsquashfs.Restore() data := "mock kernel snap" sn := makeSnap(c, "", data) err := sn.Unpack("*", "some-output-dir") c.Assert(err, NotNil) c.Check(err.Error(), Equals, `cannot extract "*" to "some-output-dir": failed: "Failed to write /tmp/1/modules/4.4.0-112-generic/modules.symbols, skipping", "Write on output file failed because No space left on device", "writer: failed to write data block 0", "Failed to write /tmp/1/modules/4.4.0-112-generic/modules.symbols.bin, skipping", and 15 more`) } func (s *SquashfsTestSuite) TestBuildAll(c *C) { // please keep <API key> in sync with this one so it makes sense. buildDir := c.MkDir() err := os.MkdirAll(filepath.Join(buildDir, "/random/dir"), 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(buildDir, "data.bin"), []byte("data"), 0644) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(buildDir, "random", "data.bin"), []byte("more data"), 0644) c.Assert(err, IsNil) sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err = sn.Build(buildDir, &squashfs.BuildOpts{SnapType: "app"}) c.Assert(err, IsNil) // pre-4.5 unsquashfs writes a funny header like: // "Parallel unsquashfs: Using 1 processor" // "1 inodes (1 blocks) to write" outputWithHeader, err := exec.Command("unsquashfs", "-n", "-l", sn.Path()).Output() c.Assert(err, IsNil) output := outputWithHeader if bytes.HasPrefix(outputWithHeader, []byte(`Parallel unsquashfs: `)) { split := bytes.Split(outputWithHeader, []byte("\n")) output = bytes.Join(split[3:], []byte("\n")) } c.Assert(string(output), Equals, ` squashfs-root squashfs-root/data.bin squashfs-root/random squashfs-root/random/data.bin squashfs-root/random/dir `[1:]) // skip the first newline :-) } func (s *SquashfsTestSuite) <API key>(c *C) { // please keep TestBuild in sync with this one so it makes sense. buildDir := c.MkDir() err := os.MkdirAll(filepath.Join(buildDir, "/random/dir"), 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(buildDir, "data.bin"), []byte("data"), 0644) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(buildDir, "random", "data.bin"), []byte("more data"), 0644) c.Assert(err, IsNil) excludesFilename := filepath.Join(buildDir, ".snapignore") err = ioutil.WriteFile(excludesFilename, []byte(` # ignore just one of the data.bin files we just added (the toplevel one) data.bin # also ignore ourselves .snapignore # oh and anything called "dir" anywhere dir `), 0644) c.Assert(err, IsNil) sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err = sn.Build(buildDir, &squashfs.BuildOpts{ SnapType: "app", ExcludeFiles: []string{excludesFilename}, }) c.Assert(err, IsNil) outputWithHeader, err := exec.Command("unsquashfs", "-n", "-l", sn.Path()).Output() c.Assert(err, IsNil) output := outputWithHeader if bytes.HasPrefix(outputWithHeader, []byte(`Parallel unsquashfs: `)) { split := bytes.Split(outputWithHeader, []byte("\n")) output = bytes.Join(split[3:], []byte("\n")) } // compare with TestBuild c.Assert(string(output), Equals, ` squashfs-root squashfs-root/random squashfs-root/random/data.bin `[1:]) // skip the first newline :-) } func (s *SquashfsTestSuite) <API key>(c *C) { defer squashfs.<API key>(func(cmd string, args ...string) (*exec.Cmd, error) { c.Check(cmd, Equals, "/usr/bin/mksquashfs") return nil, errors.New("bzzt") })() mksq := testutil.MockCommand(c, "mksquashfs", "") defer mksq.Restore() snapPath := filepath.Join(c.MkDir(), "foo.snap") sn := squashfs.New(snapPath) err := sn.Build(c.MkDir(), &squashfs.BuildOpts{ SnapType: "core", ExcludeFiles: []string{"exclude1", "exclude2", "exclude3"}, }) c.Assert(err, IsNil) calls := mksq.Calls() c.Assert(calls, HasLen, 1) c.Check(calls[0], DeepEquals, []string{ // the usual: "mksquashfs", ".", snapPath, "-noappend", "-comp", "xz", "-no-fragments", "-no-progress", // the interesting bits: "-wildcards", "-ef", "exclude1", "-ef", "exclude2", "-ef", "exclude3", }) } func (s *SquashfsTestSuite) <API key>(c *C) { usedFromCore := false defer squashfs.<API key>(func(cmd string, args ...string) (*exec.Cmd, error) { usedFromCore = true c.Check(cmd, Equals, "/usr/bin/mksquashfs") return &exec.Cmd{Path: "/bin/true"}, nil })() mksq := testutil.MockCommand(c, "mksquashfs", "exit 1") defer mksq.Restore() buildDir := c.MkDir() sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err := sn.Build(buildDir, nil) c.Assert(err, IsNil) c.Check(usedFromCore, Equals, true) c.Check(mksq.Calls(), HasLen, 0) } func (s *SquashfsTestSuite) <API key>(c *C) { triedFromCore := false defer squashfs.<API key>(func(cmd string, args ...string) (*exec.Cmd, error) { triedFromCore = true c.Check(cmd, Equals, "/usr/bin/mksquashfs") return nil, errors.New("bzzt") })() mksq := testutil.MockCommand(c, "mksquashfs", "") defer mksq.Restore() buildDir := c.MkDir() sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err := sn.Build(buildDir, nil) c.Assert(err, IsNil) c.Check(triedFromCore, Equals, true) c.Check(mksq.Calls(), HasLen, 1) } func (s *SquashfsTestSuite) <API key>(c *C) { triedFromCore := false defer squashfs.<API key>(func(cmd string, args ...string) (*exec.Cmd, error) { triedFromCore = true c.Check(cmd, Equals, "/usr/bin/mksquashfs") return nil, errors.New("bzzt") })() mksq := testutil.MockCommand(c, "mksquashfs", "exit 1") defer mksq.Restore() buildDir := c.MkDir() sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err := sn.Build(buildDir, nil) c.Assert(err, ErrorMatches, "mksquashfs call failed:.*") c.Check(triedFromCore, Equals, true) c.Check(mksq.Calls(), HasLen, 1) } func (s *SquashfsTestSuite) <API key>(c *C) { defer squashfs.<API key>(func(cmd string, args ...string) (*exec.Cmd, error) { return nil, errors.New("bzzt") })() mksq := testutil.MockCommand(c, "mksquashfs", "") defer mksq.Restore() buildDir := c.MkDir() filename := filepath.Join(c.MkDir(), "foo.snap") snap := squashfs.New(filename) permissiveTypeArgs := []string{".", filename, "-noappend", "-comp", "xz", "-no-fragments", "-no-progress"} restrictedTypeArgs := append(permissiveTypeArgs, "-all-root", "-no-xattrs") tests := []struct { snapType string args []string }{ {"", restrictedTypeArgs}, {"app", restrictedTypeArgs}, {"gadget", restrictedTypeArgs}, {"kernel", restrictedTypeArgs}, {"snapd", restrictedTypeArgs}, {"base", permissiveTypeArgs}, {"os", permissiveTypeArgs}, {"core", permissiveTypeArgs}, } for _, t := range tests { mksq.ForgetCalls() comm := Commentf("type: %s", t.snapType) c.Check(snap.Build(buildDir, &squashfs.BuildOpts{SnapType: t.snapType}), IsNil, comm) c.Assert(mksq.Calls(), HasLen, 1, comm) c.Assert(mksq.Calls()[0], HasLen, len(t.args)+1) c.Check(mksq.Calls()[0][0], Equals, "mksquashfs", comm) c.Check(mksq.Calls()[0][1:], DeepEquals, t.args, comm) } } func (s *SquashfsTestSuite) <API key>(c *C) { mockUnsquashfs := testutil.MockCommand(c, "mksquashfs", ` echo Yeah, nah. >&2 exit 1 `) defer mockUnsquashfs.Restore() data := "mock kernel snap" dir := makeSnapContents(c, "", data) sn := squashfs.New("foo.snap") c.Check(sn.Build(dir, &squashfs.BuildOpts{SnapType: "kernel"}), ErrorMatches, `mksquashfs call failed: Yeah, nah.`) } func (s *SquashfsTestSuite) <API key>(c *C) { for _, t := range []struct { inp []string expectedErr string }{ { inp: []string{"failed to write something\n"}, expectedErr: `failed: "failed to write something"`, }, { inp: []string{"fai", "led to write", " something\nunrelated\n"}, expectedErr: `failed: "failed to write something"`, }, { inp: []string{"failed to write\nfailed to read\n"}, expectedErr: `failed: "failed to write", and "failed to read"`, }, { inp: []string{"failed 1\nfailed 2\n3 failed\n"}, expectedErr: `failed: "failed 1", "failed 2", and "3 failed"`, }, { inp: []string{"failed 1\nfailed 2\n3 Failed\n4 Failed\n"}, expectedErr: `failed: "failed 1", "failed 2", "3 Failed", and "4 Failed"`, }, { inp: []string{"failed 1\nfailed 2\n3 Failed\n4 Failed\nfailed expectedErr: `failed: "failed 1", "failed 2", "3 Failed", "4 Failed", and 1 more`, }, } { usw := squashfs.<API key>() for _, l := range t.inp { usw.Write([]byte(l)) } if t.expectedErr != "" { c.Check(usw.Err(), ErrorMatches, t.expectedErr, Commentf("inp: %q failed", t.inp)) } else { c.Check(usw.Err(), IsNil) } } } func (s *SquashfsTestSuite) TestBuildDate(c *C) { // This env is used in reproducible builds and will force // squashfs to use a specific date. We need to unset it // for this specific test. if oldEnv := os.Getenv("SOURCE_DATE_EPOCH"); oldEnv != "" { os.Unsetenv("SOURCE_DATE_EPOCH") defer func() { os.Setenv("SOURCE_DATE_EPOCH", oldEnv) }() } // make a directory d := c.MkDir() // set its time waaay back now := time.Now() then := now.Add(-10000 * time.Hour) c.Assert(os.Chtimes(d, then, then), IsNil) // make a snap using this directory filename := filepath.Join(c.MkDir(), "foo.snap") sn := squashfs.New(filename) c.Assert(sn.Build(d, nil), IsNil) // and see it's BuildDate is _now_, not _then_. c.Check(squashfs.BuildDate(filename), Equals, sn.BuildDate()) c.Check(math.Abs(now.Sub(sn.BuildDate()).Seconds()) <= 61, Equals, true, Commentf("Unexpected build date %s", sn.BuildDate())) } func (s *SquashfsTestSuite) <API key>(c *C) { if os.Geteuid() == 0 { c.Skip("cannot be tested when running as root") } // make a directory d := c.MkDir() err := os.MkdirAll(filepath.Join(d, "ro-dir"), 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(d, "ro-dir", "in-ro-dir"), []byte("123"), 0664) c.Assert(err, IsNil) err = os.Chmod(filepath.Join(d, "ro-dir"), 0000) c.Assert(err, IsNil) // so that tear down does not complain defer os.Chmod(filepath.Join(d, "ro-dir"), 0755) err = ioutil.WriteFile(filepath.Join(d, "ro-file"), []byte("123"), 0000) c.Assert(err, IsNil) err = ioutil.WriteFile(filepath.Join(d, "ro-empty-file"), nil, 0000) c.Assert(err, IsNil) err = syscall.Mkfifo(filepath.Join(d, "fifo"), 0000) c.Assert(err, IsNil) filename := filepath.Join(c.MkDir(), "foo.snap") sn := squashfs.New(filename) err = sn.Build(d, nil) c.Assert(err, ErrorMatches, `(?s)cannot access the following locations in the snap source directory: - ro-(file|dir) \(owner [0-9]+:[0-9]+ mode 000\) - ro-(file|dir) \(owner [0-9]+:[0-9]+ mode 000\) `) } func (s *SquashfsTestSuite) <API key>(c *C) { if os.Geteuid() == 0 { c.Skip("cannot be tested when running as root") } // make a directory d := c.MkDir() // make more than maxErrPaths entries for i := 0; i < squashfs.MaxErrPaths; i++ { p := filepath.Join(d, fmt.Sprintf("0%d", i)) err := ioutil.WriteFile(p, []byte("123"), 0000) c.Assert(err, IsNil) err = os.Chmod(p, 0000) c.Assert(err, IsNil) } filename := filepath.Join(c.MkDir(), "foo.snap") sn := squashfs.New(filename) err := sn.Build(d, nil) c.Assert(err, ErrorMatches, `(?s)cannot access the following locations in the snap source directory: (- [0-9]+ \(owner [0-9]+:[0-9]+ mode 000.*\).){10}- too many errors, listing first 10 entries `) } func (s *SquashfsTestSuite) TestBuildBadSource(c *C) { filename := filepath.Join(c.MkDir(), "foo.snap") sn := squashfs.New(filename) err := sn.Build("does-not-exist", nil) c.Assert(err, ErrorMatches, ".*does-not-exist/: no such file or directory") } func (s *SquashfsTestSuite) <API key>(c *C) { buildDir := c.MkDir() err := os.MkdirAll(filepath.Join(buildDir, "/random/dir"), 0755) c.Assert(err, IsNil) defaultComp := "xz" for _, comp := range []string{"", "xz", "gzip", "lzo"} { sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err = sn.Build(buildDir, &squashfs.BuildOpts{ Compression: comp, }) c.Assert(err, IsNil) // check compression outputWithHeader, err := exec.Command("unsquashfs", "-n", "-s", sn.Path()).CombinedOutput() c.Assert(err, IsNil) // ensure default is xz if comp == "" { comp = defaultComp } c.Assert(string(outputWithHeader), Matches, fmt.Sprintf(`(?ms).*Compression %s$`, comp)) } } func (s *SquashfsTestSuite) <API key>(c *C) { buildDir := c.MkDir() err := os.MkdirAll(filepath.Join(buildDir, "/random/dir"), 0755) c.Assert(err, IsNil) sn := squashfs.New(filepath.Join(c.MkDir(), "foo.snap")) err = sn.Build(buildDir, &squashfs.BuildOpts{ Compression: "silly", }) c.Assert(err, ErrorMatches, "(?m)^mksquashfs call failed: ") }
#pragma once #include "../compat.h" #include "../basic/ftdi_basic.h" #ifndef __MARLIN_FIRMWARE__ #define FTDI_EXTENDED #endif #ifdef FTDI_EXTENDED #include "unicode/font_size_t.h" #include "unicode/unicode.h" #include "unicode/standard_char_set.h" #include "unicode/western_char_set.h" #include "unicode/font_bitmaps.h" #include "rgb_t.h" #include "bitmap_info.h" #include "tiny_timer.h" #include "grid_layout.h" #include "dl_cache.h" #include "event_loop.h" #include "command_processor.h" #include "screen_types.h" #include "sound_player.h" #include "sound_list.h" #include "polygon.h" #include "text_box.h" #endif
#include "<API key>.hpp" #include "Correlator.hpp" #include "<API key>.hpp" #include "TimeSeries.hpp" namespace ScriptInterface { namespace Accumulators { void initialize(Utils::Factory<ObjectHandle> *om) { om->register_new<<API key>>( "Accumulators::<API key>"); om->register_new<<API key>>( "Accumulators::<API key>"); om->register_new<TimeSeries>("Accumulators::TimeSeries"); om->register_new<Correlator>("Accumulators::Correlator"); } } /* namespace Accumulators */ } /* namespace ScriptInterface */
<?php class <API key> implements AmcFilterIF { public function getTitle() { return "AMC_304a_3 Numerator"; } public function test( AmcPatient $patient, $beginDate, $endDate ) { // MEASURE STAGE2: Medication Order(s) Created as CPOE // Still TODO // AMC MU2 TODO : // Note the counter for this is using prescriptions which does not incorporate the cpoe_stat field. if(isset($patient->object['cpoe_stat']) && $patient->object['cpoe_stat'] == 1){ return true; }else { return false; } } }
using NUnit.Framework; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.ExtractInterface; using Rubberduck.VBEditor.SafeComWrappers; using RubberduckTests.Mocks; using System.Linq; namespace RubberduckTests.Refactoring.ExtractInterface { [TestFixture] public class <API key> { [TestCase("ITestModule1", true)] //default interfaceName [TestCase("TestType", false)] //Public UDT - conflicts [TestCase("TestEnum", false)] //Public Enum - conflicts [TestCase("TestType2", true)] //Private UDT - OK [TestCase("TestEnum2", true)] //Private Enum - OK [TestCase("AnotherModule", false)] //Module Identifier - conflicts [Category("Refactorings")] [Category("Extract Interface")] public void <API key>(string interfaceName, bool expectedResult) { var testModuleCode = @"Option Explicit Public Sub MySub() End Sub"; var otherModuleName = "AnotherModule"; var otherModuleCode = @"Option Explicit Public Type TestType FirstMember As Long End Type Public Enum TestEnum FirstEnum End Enum Private Type TestType2 FirstMember As Long End Type Private Enum TestEnum2 FirstEnum End Enum "; var vbe = MockVbeBuilder.BuildFromModules((MockVbeBuilder.TestModuleName, testModuleCode, ComponentType.ClassModule), (otherModuleName, otherModuleCode, ComponentType.StandardModule)); using (var state = MockParser.CreateAndParse(vbe.Object)) { var module = state.DeclarationFinder.MatchName(MockVbeBuilder.TestModuleName).OfType<<API key>>().Single(); var conflictFinder = new <API key>().Create(state, module.ProjectId); Assert.AreEqual(expectedResult, !conflictFinder.<API key>(interfaceName)); } } [Test] [Category("Refactorings")] [Category("Extract Interface")] public void <API key>() { var testModuleName = "TargetModule"; var testModuleCode = @"Option Explicit Public Sub MySub() End Sub"; var otherModuleName = testModuleName; var otherModuleCode = @"Option Explicit "; var vbe = MockVbeBuilder.BuildFromModules((MockVbeBuilder.TestModuleName, testModuleCode, ComponentType.ClassModule), (otherModuleName, otherModuleCode, ComponentType.StandardModule)); using (var state = MockParser.CreateAndParse(vbe.Object)) { var module = state.DeclarationFinder.MatchName(MockVbeBuilder.TestModuleName).OfType<<API key>>().Single(); var conflictFinder = new <API key>().Create(state, module.ProjectId); var interfaceModuleName = conflictFinder.<API key>(otherModuleName); Assert.AreEqual($"{testModuleName}1", interfaceModuleName); } } private class <API key> : <API key> { public <API key> Create(<API key> <API key>, string projectId) { return new <API key>(<API key>, projectId); } } } }
#ifndef APATHING_H #define APATHING_H #include <mysql.h> #include <gd.h> #define DB_HOST "10.1.1.1" #define DB_LOGIN "eqserver" #define DB_PASSWORD "pw4eqserver" #define DB_NAME "peq" //for now, all of these were arbitrarily chosen //load up doors as spawn points, since they are also valid locations extern bool INCLUDE_DOORS; //this is the furthest a mob can be from a fear point and still expect //to find the node. extern float <API key>; extern float <API key>; //begin and end point must be this close extern float MIN_FIX_Z; //minimum drop before correcting waypoint #define ALMOST_COLINEAR_COS 0.99f //cosine of an angle to consider colinear... .99== 8 degrees //if we miss the map on one Z-checking try, move the point by these #define X_JITTER 3 #define Y_JITTER 3 //if two nodes are this close together, consider them the same extern float CLOSE_ENOUGH; //this causes us to check all of a node's edges for LOS from the new //node when we are considering combining into that node //this is not working as well as one might hope, leads to many invalids extern bool <API key>; //this is bigger than close enough, since we check LOS when combining these //so that we prevent little juntions extern float <API key>; //a second link on a spawn must be this far away from the first. extern float <API key>; //uncomment to split a pathin with two waypoints which cannot see eachother into two extern bool SPLIT_INVALID_PATHS; //enabled linking of path endpoints as if they were spawn points. extern bool LINK_PATH_ENDPOINTS; //the maximum distance of the closest point to a spawn inorder to link it extern float MAX_LINK_SPAWN_DIST; //before we generate pathing info, we try to link all points within this range to eachother extern float <API key>; //enables linking a spawn point to two nodes instead of just one. extern bool SPAWN_LINK_TWICE; extern bool SPAWN_LINK_THRICE; //link up to 3 times.. requires twice enabled //a second link point must be further than this from the first for closest merge extern float <API key>; //if an edge is longer than this, it will get cut into pieces interval long extern float SPLIT_LINE_LENGTH; extern float SPLIT_LINE_INTERVAL; //an edge must cross this many lines before being considered for cross reduction extern int CROSS_REDUCE_COUNT; //an edge must be longer than this before we think it can cross anything extern float CROSS_MIN_LENGTH; //The intersect points of two edges must be within this range of Z to count extern float CROSS_MAX_Z_DIFF; //the max distance between two nodes to consider them the same when crossing extern float CLOSE_ENOUGH_CROSS; //check long paths on load for LOS //#define LONG_PATH_CHECK_LOS //minimum number of nodes for a graph to possible be a disjoint graph #define MIN_DISJOINT_NODES 3 //divide the image scale by this number in each direction extern int IMAGE_SCALE; //enable drawing of a <API key> graph when coloring a graph #define DRAW_ALL_COLORS 1 //enable drawing of the original non-reduced combined graph. #define DRAW_PRETREE_GRAPH 1 #include "gpoint.h" #include <vector> #include <list> using namespace std; class PathNode : public GPoint { public: PathNode() { init(); } PathNode(const GPoint &them) : GPoint(them) { init(); } PathNode(float ix, float iy, float iz) : GPoint(ix, iy, iz) { init(); } void init() { color = 0; // color2 = 0; final_id = -1; longest_path = 0; valid = true; forced = false; disjoint = false; } int node_id; int final_id; // inherited: // float x; // float y; // float z; // VertDesc vert; int color; int longest_path; char valid:1, forced:1, disjoint:1, extra:5; float Dist2(const GPoint *o) const { float tmp; float sum; tmp = x - o->x; sum = tmp*tmp; tmp = y - o->y; sum += tmp*tmp; tmp = z - o->z; sum += tmp*tmp; return(sum); } }; class PathEdge { public: PathEdge( PathNode *_from, PathNode *_to) { from = _from; to = _to; normal_reach = -1; reverse_reach = -1; valid = true; } PathNode *from; PathNode *to; int normal_reach; int reverse_reach; bool valid; // EdgeDesc edge_id; }; class PathGraph { public: ~PathGraph() { { list<PathNode *>::iterator cur,end; cur = nodes.begin(); end = nodes.end(); for(; cur != end; cur++) { delete *cur; } } { list<PathEdge *>::iterator cur,end; cur = edges.begin(); end = edges.end(); for(; cur != end; cur++) { delete *cur; } } } void add_edge(PathNode *b, PathNode *e) { edges.push_back(new PathEdge(b, e)); } void add_edges(list<PathEdge *> &o) { list<PathEdge *>::iterator cur,end; cur = o.begin(); end = o.end(); for(; cur != end; cur++) { edges.push_back(*cur); } } list<PathNode *> nodes; list<PathEdge *> edges; //used for graph color accounts int curcolor; int ccount; }; class ColorRecord { public: int color; float height; }; extern int load_split_paths; extern int z_fixed_count; extern int z_not_fixed_count; extern int z_no_map_count; extern float z_fixed_diffs; extern float z_not_fixed_diffs; extern int wp_reduce_count; extern int trivial_merge_count; extern int closest_merge_count; extern int <API key>; extern int link_spawn_count; extern int link_spawn_invalid; extern int link_spawn2_count; extern int link_spawn3_count; extern int link_spawn_nocount; extern int combine_broke_los; extern int <API key>; extern int removed_edges_los; extern int <API key>; extern int broke_paths; extern int cross_edge_count; extern int cross_add_count; extern int los_cache_misses; extern int los_cache_hits; #include <vector> #include <map> #include <string> #include <algorithm> using namespace std; class QTNode; //ye-olde prototypes bool load_paths_from_db(MYSQL *m, Map *map, const char *zone, list<PathGraph*> &db_paths, list<PathNode*> &end_points); bool load_spawns_from_db(MYSQL *m, const char *zone, list<PathNode*> &db_spawns); bool load_doors_from_db(MYSQL *m, const char *zone, list<PathNode*> &db_spawns); bool load_hints_from_db(MYSQL *m, const char *zone, list<PathNode*> &db_spawns); bool <API key>(MYSQL *m, const char *zone); void <API key>(Map *map, PathNode *it); void <API key>(Map *map, list<PathGraph*> &db_paths, list<PathNode*> &db_spawns); bool almost_colinear(PathNode *first, PathNode *second, PathNode *third); void reduce_waypoints(list<PathGraph*> &db_paths); void break_long_lines(list<PathGraph*> &db_paths); //void build_big_graph(PathGraph *big, list<PathGraph*> &db_paths, list<PathNode*> &db_spawns); void <API key>(Map *map, list<PathGraph*> &db_paths); void <API key>(Map *map, list<PathGraph*> &db_paths); void link_spawns(Map *map, PathGraph *big, list<PathNode*> &db_spawns, float maxdist, map< pair<PathNode *, PathNode *>, bool > *edgelist); void combine_grid_points(Map *map, PathGraph *big, float close_enough); void draw_paths(Map *map, list<PathEdge *> &edges, list<PathEdge *> &edges2, const char *fname); void draw_paths2(Map *map, list<PathEdge *> &edges1, list<PathEdge *> &edges2, list<PathEdge *> &edges3, list<PathNode *> &spawns, const char *fname); void check_edge_los(Map *map, PathGraph *big); void check_long_edge_los(Map *map, PathGraph *big); bool CheckLOS(Map *map, PathNode *from, PathNode *to); void cut_crossed_grids(PathGraph *big, map<PathEdge*, vector<GPoint> > &cross_list); void rebuild_node_list(list<PathEdge *> &edges, list<PathNode *> &nodes, list<PathNode *> *excess_nodes = NULL); QTNode *build_quadtree(Map *map, PathGraph *big); bool write_path_file(QTNode *_root, PathGraph *big, const char *file, vector< vector<PathEdge*> > &path_finding); bool load_eq_map(const char *zone, PathGraph *eqmap); void write_eq_map(list<PathEdge *> &edges, const char *fname); //void edge_stats(list<PathEdge*> &edges, const char *s); void <API key>(PathGraph *big, vector<int> &counts, vector<int> &first_node); void find_path_info(Map *map, PathGraph *big, vector< vector<PathEdge *> > &path_finding); void find_node_edges(PathGraph *big, std::map<PathNode*, vector<PathEdge*> > &node_edges); void validate_edges(Map *map, PathGraph *big); void DrawGradientLine(gdImagePtr im, GPoint *first, GPoint *second, vector<ColorRecord> &colors); void allocateGradient(gdImagePtr im, float r1, float g1, float b1, float r2, float g2, float b2, float min, float max, float divs, vector<ColorRecord> &colors); #endif
import threading import queue import logging from ..configmanager import ConfigManager from ..<API key> import INTERFACE_TYPE from ..interface import XRecordInterface, AtSpiInterface from autokey.model import SendMode from .key import Key from .constants import X_RECORD_INTERFACE, KEY_SPLIT_RE, MODIFIERS, HELD_MODIFIERS CURRENT_INTERFACE = None _logger = logging.getLogger("iomediator") class IoMediator(threading.Thread): """ The IoMediator is responsible for tracking the state of modifier keys and interfacing with the various Interface classes to obtain the correct characters to pass to the expansion service. This class must not store or maintain any configuration details. """ # List of targets interested in receiving keypress, hotkey and mouse events listeners = [] def __init__(self, service): threading.Thread.__init__(self, name="<API key>") self.queue = queue.Queue() self.listeners.append(service) self.interfaceType = ConfigManager.SETTINGS[INTERFACE_TYPE] # Modifier tracking self.modifiers = { Key.CONTROL: False, Key.ALT: False, Key.ALT_GR: False, Key.SHIFT: False, Key.SUPER: False, Key.HYPER: False, Key.META: False, Key.CAPSLOCK: False, Key.NUMLOCK: False } if self.interfaceType == X_RECORD_INTERFACE: self.interface = XRecordInterface(self, service.app) else: self.interface = AtSpiInterface(self, service.app) global CURRENT_INTERFACE CURRENT_INTERFACE = self.interface _logger.info("Created IoMediator instance, current interface is: {}".format(CURRENT_INTERFACE)) def shutdown(self): _logger.debug("IoMediator shutting down") self.interface.cancel() self.queue.put_nowait((None, None)) _logger.debug("Waiting for IoMediator thread to end") self.join() _logger.debug("IoMediator shutdown completed") def set_modifier_state(self, modifier, state): _logger.debug("Set modifier %s to %r", modifier, state) self.modifiers[modifier] = state def <API key>(self, modifier): """ Updates the state of the given modifier key to 'pressed' """ _logger.debug("%s pressed", modifier) if modifier in (Key.CAPSLOCK, Key.NUMLOCK): if self.modifiers[modifier]: self.modifiers[modifier] = False else: self.modifiers[modifier] = True else: self.modifiers[modifier] = True def handle_modifier_up(self, modifier): """ Updates the state of the given modifier key to 'released'. """ _logger.debug("%s released", modifier) # Caps and num lock are handled on key down only if modifier not in (Key.CAPSLOCK, Key.NUMLOCK): self.modifiers[modifier] = False def handle_keypress(self, keyCode, window_info): """ Looks up the character for the given key code, applying any modifiers currently in effect, and passes it to the expansion service. """ self.queue.put_nowait((keyCode, window_info)) def run(self): while True: keyCode, window_info = self.queue.get() if keyCode is None and window_info is None: break numLock = self.modifiers[Key.NUMLOCK] modifiers = self.__getModifiersOn() shifted = self.modifiers[Key.CAPSLOCK] ^ self.modifiers[Key.SHIFT] key = self.interface.lookup_string(keyCode, shifted, numLock, self.modifiers[Key.ALT_GR]) rawKey = self.interface.lookup_string(keyCode, False, False, False) for target in self.listeners: target.handle_keypress(rawKey, modifiers, key, window_info) self.queue.task_done() def handle_mouse_click(self, rootX, rootY, relX, relY, button, windowInfo): for target in self.listeners: target.handle_mouseclick(rootX, rootY, relX, relY, button, windowInfo) def send_string(self, string: str): """ Sends the given string for output. """ if not string: return string = string.replace('\n', "<enter>") string = string.replace('\t', "<tab>") _logger.debug("Send via event interface") self.__clearModifiers() modifiers = [] for section in KEY_SPLIT_RE.split(string): if len(section) > 0: if Key.is_key(section[:-1]) and section[-1] == '+' and section[:-1] in MODIFIERS: # Section is a modifier application (modifier followed by '+') modifiers.append(section[:-1]) else: if len(modifiers) > 0: # Modifiers ready for application - send modified key if Key.is_key(section): self.interface.send_modified_key(section, modifiers) modifiers = [] else: self.interface.send_modified_key(section[0], modifiers) if len(section) > 1: self.interface.send_string(section[1:]) modifiers = [] else: # Normal string/key operation if Key.is_key(section): self.interface.send_key(section) else: self.interface.send_string(section) self.__reapplyModifiers() def paste_string(self, string, pasteCommand: SendMode): if len(string) > 0: _logger.debug("Send via clipboard") self.interface.<API key>(string, pasteCommand) def remove_string(self, string): backspaces = -1 # Start from -1 to discount the backspace already pressed by the user for section in KEY_SPLIT_RE.split(string): if Key.is_key(section): # TODO: Only a subset of keys defined in Key are printable, thus require a backspace. # Many keys are not printable, like the modifier keys or F-Keys. # If the current key is a modifier, it may affect the printability of the next character. # For example, if section == <alt>, and the next section begins with "+a", both the "+" and "a" are not # printable, because both belong to the keyboard combination "<alt>+a" backspaces += 1 else: backspaces += len(section) self.send_backspace(backspaces) def send_key(self, keyName): keyName = keyName.replace('\n', "<enter>") self.interface.send_key(keyName) def press_key(self, keyName): keyName = keyName.replace('\n', "<enter>") self.interface.fake_keydown(keyName) def release_key(self, keyName): keyName = keyName.replace('\n', "<enter>") self.interface.fake_keyup(keyName) def fake_keypress(self, keyName): keyName = keyName.replace('\n', "<enter>") self.interface.fake_keypress(keyName) def send_left(self, count): """ Sends the given number of left key presses. """ for i in range(count): self.interface.send_key(Key.LEFT) def send_right(self, count): for i in range(count): self.interface.send_key(Key.RIGHT) def send_up(self, count): """ Sends the given number of up key presses. """ for i in range(count): self.interface.send_key(Key.UP) def send_backspace(self, count): """ Sends the given number of backspace key presses. """ for i in range(count): self.interface.send_key(Key.BACKSPACE) def flush(self): self.interface.flush() def __clearModifiers(self): self.releasedModifiers = [] for modifier in list(self.modifiers.keys()): if self.modifiers[modifier] and modifier not in (Key.CAPSLOCK, Key.NUMLOCK): self.releasedModifiers.append(modifier) self.interface.release_key(modifier) def __reapplyModifiers(self): for modifier in self.releasedModifiers: self.interface.press_key(modifier) def __getModifiersOn(self): modifiers = [] for modifier in HELD_MODIFIERS: if self.modifiers[modifier]: modifiers.append(modifier) modifiers.sort() return modifiers
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the class <API key> extends \mod_dataform\pluginbase\dataformfieldform { protected function field_definition() { $mform =& $this->_form; // Field width (param2, param3). $this-><API key>('width', get_string('fieldwidth', 'dataform')); // Format rules. $options = array( '' => get_string('choosedots'), 'alphanumeric' => get_string('err_alphanumeric', 'form'), 'lettersonly' => get_string('err_lettersonly', 'form'), 'numeric' => get_string('err_numeric', 'form'), 'email' => get_string('err_email', 'form'), 'nopunctuation' => get_string('err_nopunctuation', 'form') ); $mform->addElement('select', 'param4', get_string('format'), $options); // Length (param5, 6, 7): min, max, range. $options = array( '' => get_string('choosedots'), 'minlength' => get_string('min', 'dataform'), 'maxlength' => get_string('max', 'dataform'), 'rangelength' => get_string('range', 'dataform'), ); $grp = array(); $grp[] = &$mform->createElement('select', 'param5', null, $options); $grp[] = &$mform->createElement('text', 'param6', null, array('size' => 8)); $grp[] = &$mform->createElement('text', 'param7', null, array('size' => 8)); $mform->addGroup($grp, 'lengthgrp', get_string('numcharsallowed', 'dataformfield_text'), ' ', false); $mform->addGroupRule('lengthgrp', array('param6' => array(array(null, 'numeric', null, 'client')))); $mform->addGroupRule('lengthgrp', array('param7' => array(array(null, 'numeric', null, 'client')))); $mform->disabledIf('param6', 'param5', 'eq', ''); $mform->disabledIf('param6', 'param5', 'eq', 'maxlength'); $mform->disabledIf('param7', 'param5', 'eq', ''); $mform->disabledIf('param7', 'param5', 'eq', 'minlength'); $mform->setType('param6', PARAM_INT); $mform->setType('param7', PARAM_INT); } public function <API key>() { $mform = &$this->_form; $field = &$this->_field; // Content elements. $mform->addElement('text', 'contentdefault', get_string('fielddefaultvalue', 'dataform')); $mform->setType('contentdefault', PARAM_TEXT); } public function data_preprocessing(&$data) { $field = &$this->_field; $data->width = !empty($data->param2) ? $data->param2 : null; $data->widthunit = !empty($data->param3) ? $data->param3 : null; // Default content. $data->contentdefault = $field->defaultcontent; } /** * Returns the default content data. * * @param stdClass $data * @return mix|null */ protected function <API key>(\stdClass $data) { if (!empty($data->contentdefault)) { return $data->contentdefault; } return null; } public function get_data() { if ($data = parent::get_data()) { // Field width (only numeric data). $data->param2 = $data->param3 = null; if (!empty($data->width) and is_numeric($data->width)) { $data->param2 = $data->width; if ($data->widthunit != 'px') { $data->param3 = $data->widthunit; } } } return $data; } }
#ifndef __ASF_VIEW_H #define __ASF_VIEW_H #include <asf_version.h> #define VERSION <API key> // Define <API key> to turn on support for // JASC (Paint Shop Pro and other) palettes // FIXME: We need to make generic the way that we assign/remember // combo box indices (or peruse the list) so that when a new lut is picked // and applied that the right item is selected in the drop-down box. // FOR NOW... Don't enable <API key> until we do this, or just // enable it for development reasons. #define <API key> #define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <gtk/gtk.h> #include <glade/glade.h> #include <glib.h> #include <glib/gprintf.h> #include "asf.h" #include "asf_meta.h" #include "asf_endian.h" #include "envi.h" #include "float_image.h" #include "asf_raster.h" #include "asf_vector.h" #include "cache.h" #include "asf_tiff.h" #define <API key> "<API key>" #define <API key> "<API key>.lut" #define <API key> "<API key>" #define <API key> "<API key>.lut" typedef struct { unsigned char *data; int size_x; int size_y; } ThumbnailData; /* for win32, need __declspec(dllexport) on all signal handlers. */ #if !defined(SIGNAL_CALLBACK) # if defined(win32) # define SIGNAL_CALLBACK __declspec(dllexport) # else # define SIGNAL_CALLBACK # endif #endif typedef struct { int is_rgb; int band_gs; int band_r; int band_g; int band_b; } BandConfig; typedef struct { int nl, ns; meta_parameters *meta; CachedImage *data_ci; BandConfig band_cfg; ImageStats stats; ImageStatsRGB stats_r; ImageStatsRGB stats_g; ImageStatsRGB stats_b; char *filename; char *data_name; char *meta_name; } ImageInfo; typedef struct { // metadata int num_meta_cols; csv_meta_column_t *meta_cols; char **meta_info; // data int num_points; double *lines; double *samps; // display information int color_code; int marker_code; } Shape; /* font.c */ void set_font(void); /* utility.c */ void clear_combobox(const char *widget_name); void add_to_combobox(const char *widget_name, const char *txt); void set_combo_box_item(const char *widget_name, gint index); int get_combo_box_item(const char *widget_name); char *get_band_combo_text(meta_parameters *meta, const char *widget_name); void rb_select(const char *widget_name, gboolean is_on); double <API key>(const char *widget_name); void put_double_to_entry(const char *widget_name, double val); void <API key>(const char *widget_name, double val, const char *format); int get_int_from_entry(const char *widget_name); void put_int_to_entry(const char *widget_name, int val); int get_checked(const char *widget_name); void set_checked(const char *widget_name, int checked); void message_box(const char *format, ...); GtkWidget *get_widget_checked(const char *widget_name); void <API key>(const char *widget_name, int maxlen); char* <API key>(const char *widget_name); int entry_has_text(const char *widget_name); void put_string_to_entry(const char *widget_name, char *txt); char *<API key>(const char *widget_name); void <API key>(const char *widget_name, char *txt); void <API key>(const char *file, const char *widget_name); void <API key>(const char *txt, const char *widget_name); void put_string_to_label(const char *widget_name, const char *txt); void show_widget(const char *widget_name, int show); void enable_widget(const char *widget_name, int enable); char *trim_whitespace(const char *s); /* asf_view.c */ char *find_in_share(const char * filename); void image_info_free(ImageInfo *ii); /* read.c */ int read_file(const char *filename, const char *band, int multilook, int on_fail_abort); int try_ext(const char *filename, const char *ext); int try_prepension(const char *filename, const char *prepension); /* read_asf.c */ int try_asf(const char *filename, int try_extensions); int handle_asf_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *read_asf_meta(const char *meta_name); int open_asf_data(const char *filename, const char *band, int multilook, meta_parameters *meta, ClientInterface *client); void <API key>(void *read_client_info); /* read_ceos.c */ int try_ceos(const char *filename); int handle_ceos_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *read_ceos_meta(const char *meta_name); int open_ceos_data(const char *dataname, const char *metaname, const char *band, int multilook, meta_parameters *meta, ClientInterface *client); void <API key>(void *read_client_info); /* read_airsar.c */ int try_airsar(const char *filename); int handle_airsar_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *open_airsar(const char *data_name, const char *meta_name, const char *band, ClientInterface *client); // read_roipac.c int try_roipac(const char *filename); int handle_roipac_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *open_roipac(const char *filename, const char *band, const char *metaname, const char *dataname, int multilook, ClientInterface *client); // read_ras.c int try_ras(const char *filename); int handle_ras_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *open_ras(const char *filename, const char *band, const char *metaname, const char *dataname, int multilook, ClientInterface *client); // read_terrasar.c int try_terrasar(const char *filename); int <API key>(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *open_terrasar(const char *data_name, const char *meta_name, const char *band, int multilook, ClientInterface *client); /* read_jpeg.c */ int try_jpeg(const char *filename, int try_extensions); int handle_jpeg_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters* open_jpeg(const char *data_name, ClientInterface *client); /* read_tiff.c */ int try_tiff(const char *filename, int try_extensions); int handle_tiff_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *read_tiff_meta(const char *meta_name, ClientInterface *client, const char *filename); int open_tiff_data(const char *data_name, const char *band, ClientInterface *client); /* read_png.c */ int try_png(const char *filename, int try_extensions); int handle_png_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters* open_png(const char *data_name, ClientInterface *client); /* read_pgm.c */ int try_pgm(const char *filename, int try_extensions); int handle_pgm_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters* open_pgm(const char *data_name, ClientInterface *client); /* read_brs.c */ int try_brs(const char *filename, int try_extensions); int handle_brs_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters* open_brs(const char *data_name, ClientInterface *client); // read_envi.c int try_envi(const char *filename, int try_extensions); int handle_envi_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters* open_envi(const char *meta_name, const char *data_name, const char *band_str, ClientInterface *client); // read_generic.c int handle_generic_file(const char *filename, char **err); meta_parameters *read_generic_meta(const char *filename); int open_generic_data(const char *filename, meta_parameters *meta, ClientInterface *client); // read_uavsar.c int try_uavsar(const char *filename, int try_extensions); int handle_uavsar_file(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *read_uavsar_meta(const char *meta_name, const char *data_name); int open_uavsar_data(const char *filename, int multilook, meta_parameters *meta, ClientInterface *client); // read_seasat_h5.c int try_seasat_h5(const char *filename, int try_extensions); int <API key>(const char *filename, char *meta_name, char *data_name, char **err); meta_parameters *read_seasat_h5_meta(const char *meta_name); int open_seasat_h5_data(const char *filename, meta_parameters *meta, ClientInterface *client); /* big_image.c */ GdkPixbuf * make_big_image(ImageInfo *ii, int show_crosshair); void fill_big(ImageInfo *ii); void update_zoom(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); GdkPixbuf *get_saved_pb(); void get_color(int color, unsigned char *r, unsigned char *g, unsigned char *b); void big_clicked(GdkEventButton *event); void small_clicked(GdkEventButton *event); void img2ls(int x, int y, double *line, double *samp); void put_line(GdkPixbuf *pixbuf, double line0, double samp0, double line1, double samp1, int color, ImageInfo *ii); /* small_image.c */ ThumbnailData *get_thumbnail_data(ImageInfo *ii); void fill_small(ImageInfo *ii); void <API key>(ImageInfo *ii); void <API key>(ThumbnailData *thumbnail_data, ImageInfo *ii); void <API key>(void); /* meta.c */ char * escapify(const char * s); void fill_meta_info(void); void open_mdv(void); char *br(const char *s); void <API key>(); /* stats.c */ unsigned char *<API key>(ImageInfo *ii, int tsx, int tsy); int fill_stats(ImageInfo *ii); void calc_stats_thread(gpointer user_data); int is_ignored(ImageStats *stats, float val); int is_ignored_rgb(ImageStatsRGB *stats, float val); int <API key>(ImageStats *stats, float val); int <API key>(ImageStatsRGB *stats, float val); void clear_stats(ImageInfo *ii); void update_map_settings(ImageInfo *ii); void <API key>(ImageInfo *ii); void <API key>(ImageInfo *ii, ImageInfo *mask, int l, int s, unsigned char *r, unsigned char *g, unsigned char *b); int apply_mask(int v, unsigned char *r, unsigned char *g, unsigned char *b); /* google.c */ char *find_in_path(char * file); int open_google_earth(void); /* new.c */ void new_file(void); void load_file(const char *file); void load_file_banded(const char *file, const char *band, int multilook); void reload_file_banded(const char *file, const char *band, int multilook); void reset_globals(int reset_position); void set_title(int band_specified, const char *band); /* subset.c */ void save_subset(ImageInfo *ii); void update_poly_extents(meta_parameters *meta); /* bands.c */ void setup_bands_tab(meta_parameters *meta); void set_bands_rgb(int r, int g, int b); void set_bands_greyscale(int b); /* info.c */ int <API key>(meta_parameters *meta); void update_pixel_info(ImageInfo *); /* lut.c */ void populate_lut_combo(void); void set_lut(const char *lut_basename); void select_lut(const char *lut_basename); void check_lut(void); int have_lut(void); void apply_lut(int val, unsigned char *r, unsigned char *g, unsigned char *b); int <API key>(image_data_type_t image_data_type); void apply_lut_to_data(ThumbnailData *thumbnail_data); int <API key> (char *curr_file, int *lut_specified, char *lut); int <API key>(void); int <API key>(void); int get_dem_lut_index(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); int <API key>(void); int get_tiff_lut_index(void); int get_asf_lut_index(void); void set_current_index(int index); int get_current_index(void); int <API key>(char *file); /* plan.c */ int planner_is_active(void); void setup_planner(void); int row_is_checked(int); void <API key>(void); void planner_click(int l, int s); /* csv.c */ const char * detect_csv_assoc(); void open_csv(const char *csv_file); /* pan.c */ void clear_nb_callback(void); void <API key>(void); /* shape.c */ void free_shapes(); /* plugins.c */ void <API key>(); const char *<API key>(); void <API key>(); #ifdef HAVE_DELTA_CR void add_delta_shapes(meta_parameters *meta); #endif #ifdef win32 #ifdef DIR_SEPARATOR #undef DIR_SEPARATOR #endif extern const char DIR_SEPARATOR; #endif extern const char PATH_SEPATATOR; #define MAX_POLY_LEN 1450 typedef struct { int n; // How many points in the polygon int c; // Currently "active" point (-1 for none) double line[MAX_POLY_LEN];// vertices of the polygon double samp[MAX_POLY_LEN]; int show_extent; // draw bounding box of polygon? int extent_x_min, extent_x_max; // bounding box values int extent_y_min, extent_y_max; // when show_extent==TRUE, these must // be made valid } UserPolygon; extern GladeXML *glade_xml; // Can hold five images #define MAX_IMAGES 5 extern ImageInfo image_info[MAX_IMAGES]; // "curr" always points to the currently being displayed image info extern ImageInfo *curr; extern ImageInfo *mask; extern int <API key>; extern int n_images_loaded; // these globals all relate to the current viewing settings #define MAX_POLYS 50 extern UserPolygon g_polys[MAX_POLYS]; extern UserPolygon *g_poly; extern int which_poly; extern int g_show_north_arrow; extern int g_outline; extern Shape **g_shapes; extern int num_shapes; extern double zoom; extern double center_line, center_samp; extern double crosshair_line, crosshair_samp; extern int subimages; extern int g_saved_line_count; extern int g_startup; // keeps track of whether or not the arrow keys should affect the // crosshair or the ctrl-crosshair extern int last_was_crosshair; extern int is_asf_internal; extern int ignore_grey_value; extern int ignore_red_value; extern int ignore_green_value; extern int ignore_blue_value; // if using generic binary extern int generic_specified; extern int generic_bin_width, generic_bin_height, <API key>, <API key>; #define MAX_PTS 50 extern int pt_specified; char *pt_name[MAX_PTS]; extern double pt_lat[MAX_PTS], pt_lon[MAX_PTS]; #endif
// This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import { shallow } from 'enzyme'; import React from 'react'; import Dapps from './'; import { createStore } from './dapps.test.js'; let component; let store; function render (history = []) { store = createStore(); component = shallow( <Dapps history={ history } store={ store } /> ); return component; } describe('views/Home/Dapps', () => { it('renders defaults', () => { expect(render()).to.be.ok; }); describe('no history', () => { beforeEach(() => { render(); }); it('renders empty message', () => { expect(component.find('FormattedMessage').props().id).to.equal('home.dapps.none'); }); }); describe('with history', () => { const HISTORY = [ { timestamp: 1, entry: 'testABC' }, { timestamp: 2, entry: 'testDEF' } ]; beforeEach(() => { render(HISTORY); }); it('renders SectionList', () => { expect(component.find('SectionList').length).to.equal(1); }); }); });
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # Ansible is free software: you can redistribute it and/or modify # (at your option) any later version. # Ansible is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} EXAMPLES = ''' # Ensure a host is present but disabled - local_action: module: cs_host name: ix-pod01-esx01.example.com cluster: vcenter.example.com/ch-zrh-ix/pod01-cluster01 pod: pod01 zone: ch-zrh-ix-01 hypervisor: VMware allocation_state: disabled host_tags: - perf - gpu # Ensure an existing host is disabled - local_action: module: cs_host name: ix-pod01-esx01.example.com zone: ch-zrh-ix-01 allocation_state: disabled # Ensure an existing host is disabled - local_action: module: cs_host name: ix-pod01-esx01.example.com zone: ch-zrh-ix-01 allocation_state: enabled # Ensure a host is absent - local_action: module: cs_host name: ix-pod01-esx01.example.com zone: ch-zrh-ix-01 state: absent ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, CloudStackException, cs_argument_spec, <API key>, CS_HYPERVISORS ) import time class <API key>(AnsibleCloudStack): def __init__(self, module): super(<API key>, self).__init__(module) self.returns = { 'averageload': 'average_load', 'capabilities': 'capabilities', 'clustername': 'cluster', 'clustertype': 'cluster_type', 'cpuallocated': 'cpu_allocated', 'cpunumber': 'cpu_number', 'cpusockets': 'cpu_sockets', 'cpuspeed': 'cpu_speed', 'cpuused': 'cpu_used', '<API key>': '<API key>', 'disconnected': 'disconnected', 'details': 'details', 'disksizeallocated': 'disk_size_allocated', 'disksizetotal': 'disk_size_total', 'events': 'events', 'hahost': 'ha_host', 'hasenoughcapacity': 'has_enough_capacity', 'hypervisor': 'hypervisor', 'hypervisorversion': 'hypervisor_version', 'ipaddress': 'ip_address', '<API key>': '<API key>', 'lastpinged': 'last_pinged', 'managementserverid': '<API key>', 'memoryallocated': 'memory_allocated', 'memorytotal': 'memory_total', 'memoryused': 'memory_used', 'networkkbsread': 'network_kbs_read', 'networkkbswrite': 'network_kbs_write', 'oscategoryname': 'os_category', 'outofbandmanagement': '<API key>', 'podname': 'pod', 'removed': 'removed', 'resourcestate': 'resource_state', '<API key>': '<API key>', 'type': 'host_type', 'version': 'host_version', 'gpugroup': 'gpu_group', } self.allocation_states = { 'enabled': 'Enable', 'disabled': 'Disable', } self.host = None def get_pod(self, key=None): pod_name = self.module.params.get('pod') if not pod_name: return None args = { 'name': pod_name, 'zoneid': self.get_zone(key='id'), } pods = self.cs.listPods(**args) if pods: return self._get_by_key(key, pods['pod'][0]) self.module.fail_json(msg="Pod %s not found" % pod_name) def get_cluster(self, key=None): cluster_name = self.module.params.get('cluster') if not cluster_name: return None args = { 'name': cluster_name, 'zoneid': self.get_zone(key='id'), } clusters = self.cs.listClusters(**args) if clusters: return self._get_by_key(key, clusters['cluster'][0]) self.module.fail_json(msg="Cluster %s not found" % cluster_name) def get_host_tags(self): host_tags = self.module.params.get('host_tags') if host_tags is None: return None return ','.join(host_tags) def <API key>(self): allocation_state = self.module.params.get('allocation_state') if allocation_state is None: return None return self.allocation_states[allocation_state] def get_host(self, refresh=False): if self.host is not None and not refresh: return self.host name = self.module.params.get('name') args = { 'zoneid': self.get_zone(key='id'), } res = self.cs.listHosts(**args) if res: for h in res['host']: if name in [h['ipaddress'], h['name']]: self.host = h return self.host def present_host(self): host = self.get_host() if not host: host = self._create_host(host) else: host = self._update_host(host) return host def _get_url(self): url = self.module.params.get('url') if url: return url else: return "http://%s" % self.module.params.get('name') def _create_host(self, host): required_params = [ 'password', 'username', 'hypervisor', 'pod', ] self.module.<API key>(required_params=required_params) self.result['changed'] = True args = { 'hypervisor': self.module.params.get('hypervisor'), 'url': self._get_url(), 'username': self.module.params.get('username'), 'password': self.module.params.get('password'), 'podid': self.get_pod(key='id'), 'zoneid': self.get_zone(key='id'), 'clusterid': self.get_cluster(key='id'), 'allocationstate': self.<API key>(), 'hosttags': self.get_host_tags(), } if not self.module.check_mode: host = self.cs.addHost(**args) if 'errortext' in host: self.module.fail_json(msg="Failed: '%s'" % host['errortext']) host = host['host'][0] return host def _update_host(self, host): args = { 'id': host['id'], 'hosttags': self.get_host_tags(), 'allocationstate': self.<API key>() } host['allocationstate'] = self.allocation_states[host['resourcestate'].lower()] if self.has_changed(args, host): self.result['changed'] = True if not self.module.check_mode: host = self.cs.updateHost(**args) if 'errortext' in host: self.module.fail_json(msg="Failed: '%s'" % host['errortext']) host = host['host'] return host def absent_host(self): host = self.get_host() if host: self.result['changed'] = True args = { 'id': host['id'], } if not self.module.check_mode: res = self.enable_maintenance() if res: res = self.cs.deleteHost(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) return host def enable_maintenance(self): host = self.get_host() if host['resourcestate'] not in ['<API key>', 'Maintenance']: self.result['changed'] = True args = { 'id': host['id'], } if not self.module.check_mode: res = self.cs.<API key>(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) host = self.poll_job(res, 'host') self.<API key>() return host def <API key>(self): for i in range(0, 300): time.sleep(2) host = self.get_host(refresh=True) if not host: return None elif host['resourcestate'] != '<API key>': return host self.fail_json("Polling for maintenance timed out") def get_result(self, host): super(<API key>, self).get_result(host) if host: self.result['allocation_state'] = host['resourcestate'].lower() self.result['host_tags'] = host['hosttags'].split(',') if host.get('hosttags') else [] return self.result def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True, aliases=['ip_address']), url=dict(), password=dict(default=None, no_log=True), username=dict(default=None), hypervisor=dict(choices=CS_HYPERVISORS, default=None), allocation_state=dict(default=None), pod=dict(default=None), cluster=dict(default=None), host_tags=dict(default=None, type='list'), zone=dict(default=None), state=dict(choices=['present', 'absent'], default='present'), )) module = AnsibleModule( argument_spec=argument_spec, required_together=<API key>(), supports_check_mode=True ) try: acs_host = <API key>(module) state = module.params.get('state') if state == 'absent': host = acs_host.absent_host() else: host = acs_host.present_host() result = acs_host.get_result(host) except CloudStackException as e: module.fail_json(msg='CloudStackException: %s' % str(e)) module.exit_json(**result) if __name__ == '__main__': main()
<?php require_once("class2.php"); $tmp = explode(".", e_QUERY); $forum_id = intval($tmp[0]); if($forum_id) { header("Location:".SITEURL.$PLUGINS_DIRECTORY."forum/forum_viewforum.php?{$forum_id}"); exit; } header("Location:".SITEURL."index.php"); exit; ?>
// In case of problems make sure that you are using the font file with the correct version! const uint8_t <API key>[] PROGMEM = { // Bitmap Data: 0x00, 0xFF,0xFF,0xFF,0x03,0xC0, 0xCF,0x3C,0xC0, 0x01,0x81,0x80,0xC0,0xC0,0x30,0x30,0x0C,0x0C,0x7F,0xFF,0xDF,0xFF,0xF0,0x60,0x60,0x30,0x30,0x0C,0x0C,0x03,0x03,0x01,0x81,0x83,0xFF,0xFE,0xFF,0xFF,0x8C,0x04,0x03,0x03,0x00,0xC0,0xC0,0x20,0x30,0x00, // ' 0x00,0xC0,0x00,0x30,0x00,0x0C,0x01,0xFF,0xFE,0xFF,0xFF,0xF0,0x30,0x3C,0x0C,0x03,0x03,0x00,0xC0,0xC0,0x30,0x30,0x0F,0xFF,0xF9,0xFF,0xFF,0x00,0xC0,0xC0,0x30,0x30,0x0C,0x0C,0x03,0x03,0xC0,0xC0,0xF0,0x30,0x3F,0xFF,0xFD,0xFF,0xFE,0x00,0xC0,0x00,0x30,0x00,0x0C,0x00, 0x00,0x00,0x03,0xF0,0x00,0xBF,0xC0,0x0D,0x86,0x00,0xEC,0x30,0x1E,0x61,0x81,0xE3,0x0C,0x1C,0x1F,0xE1,0xC0,0x7E,0x3C,0x00,0x03,0xC0,0x00,0x3C,0xFC,0x03,0x8F,0xF0,0x38,0x60,0x87,0x83,0x04,0x78,0x18,0x23,0x80,0xC1,0x10,0x07,0xF8,0x00,0x1F,0x80, 0x3F,0xFF,0x03,0xFF,0xFC,0x18,0x00,0x60,0xC0,0x03,0x06,0x00,0x00,0x30,0x00,0x01,0xC0,0x00,0x07,0x80,0x00,0xCE,0x00,0x06,0x1C,0x0C,0x30,0x38,0x61,0x80,0x73,0x0C,0x00,0xF8,0x60,0x01,0xE3,0x00,0x07,0xDF,0xFF,0xF7,0x7F,0xFF,0x08, 0xFC, // ''' 0x7F,0xCC,0xCC,0xCC,0xCC,0xCC,0xCC,0xCF,0x70, // '(' 0xEF,0x33,0x33,0x33,0x33,0x33,0x33,0x3F,0xE0, // ')' 0x06,0x00,0x60,0x06,0x07,0x6E,0x7F,0xE0,0xF0,0x0F,0x01,0x98,0x39,0xC1,0x08, // '*' 0x0C,0x06,0x03,0x1F,0xFF,0xF8,0x60,0x30,0x18,0x0C,0x00, // '+' 0xFF,0x80, // ',' 0xFF,0xFF,0xC0, // '-' 0xF0, // '.' 0x00,0x00,0x01,0x00,0x30,0x03,0x00,0x60,0x0C,0x01,0x80,0x38,0x03,0x00,0x60,0x0C,0x01,0x80,0x30,0x03,0x00,0x60,0x0C,0x00,0x80,0x00,0x00, // '/' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0xF8,0x00,0xFC,0x00,0xFE,0x00,0xEF,0x01,0xC7,0x81,0xC3,0xC1,0xC1,0xE1,0xC0,0xF1,0xC0,0x7B,0x80,0x3F,0x80,0x1F,0x80,0x0F,0x80,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // '0' 0x07,0x0F,0x1F,0x3B,0x73,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03, // '1' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x7F,0xFF,0xFF,0xFF,0xB0,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0xFF,0xFF,0xFF,0xFF,0x80, // '2' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x3F,0xFF,0x1F,0xFF,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // '3' 0x00,0x1C,0x00,0x1E,0x00,0x1F,0x00,0x1F,0x80,0x1C,0xC0,0x1C,0x60,0x1C,0x30,0x1C,0x18,0x3C,0x0C,0x38,0x06,0x38,0x03,0x1F,0xFF,0xFF,0xFF,0xF8,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0C,0x00, // '4' 0xFF,0xFF,0xFF,0xFF,0xF0,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0xFF,0xFE,0xFF,0xFF,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // '5' 0x7F,0xFC,0x7F,0xFE,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0xFF,0xFE,0xFF,0xFF,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // '6' 0xFF,0xFD,0xFF,0xFC,0x00,0x18,0x00,0x30,0x00,0x60,0x00,0xC0,0x01,0x80,0x03,0x00,0x06,0x00,0x0C,0x00,0x18,0x00,0x30,0x00,0x60,0x00,0xC0,0x01,0x80,0x03,0x00,0x06, // '7' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0xFF,0xFF,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // '8' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xFF,0xFF,0xBF,0xFF,0xC0,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0C,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // '9' 0xF0,0x00,0x00,0xF0, // ':' 0xF0,0x00,0x00,0xFF,0x80, // ';' 0x00,0x40,0x70,0x78,0x3C,0x3C,0x3C,0x0E,0x03,0x80,0x78,0x07,0x00,0xF0,0x0F,0x00,0xC0,0x10, // '<' 0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x0F,0xFF,0xFF,0xF0, // '=' 0x80,0x30,0x0F,0x00,0xF0,0x1E,0x01,0xE0,0x1C,0x07,0x07,0x87,0x87,0x83,0xC0,0xC0,0x00,0x00, // '>' 0xFF,0xFD,0xFF,0xFC,0x00,0x18,0x00,0x30,0x00,0x60,0x00,0xC0,0x01,0x80,0x03,0x0F,0xFE,0x3F,0xF8,0x60,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x18,0x00, // '?' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x3E,0x1E,0x3F,0x8F,0x30,0x67,0x98,0x33,0xCC,0x19,0xE6,0x0C,0xF3,0x06,0x79,0xFF,0xFC,0x7F,0xFE,0x00,0x03,0x00,0x01,0xFF,0xFF,0x7F,0xFF,0x80, // '@' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0xFF,0xFF,0xFF,0xFF,0xF8,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0x80, // 'A' 0xFF,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0xFF,0xFF,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0xFF,0xFF,0x00, // 'B' 0x7F,0xFF,0xFF,0xFF,0xF0,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0xFF,0xFF,0x7F,0xFF,0x80, // 'C' 0xFF,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0xFF,0xFF,0x00, // 'D' 0xFF,0xFF,0xFF,0xFF,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xFF,0xF8,0xFF,0xF8,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xFF,0xFF,0xFF,0xFF, // 'E' 0xFF,0xFF,0xFF,0xFF,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xFF,0xF8,0xFF,0xF8,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00,0xC0,0x00, // 'F' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x06,0x00,0x03,0x00,0x01,0x80,0x00,0xC0,0x1F,0xE0,0x0F,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // 'G' 0xC0,0x00,0xF0,0x00,0x3C,0x00,0x0F,0x00,0x03,0xC0,0x00,0xF0,0x00,0x3C,0x00,0x0F,0xFF,0xFF,0xFF,0xFF,0xF0,0x00,0x3C,0x00,0x0F,0x00,0x03,0xC0,0x00,0xF0,0x00,0x3C,0x00,0x0F,0x00,0x03,0xC0,0x00,0xC0, // 'H' 0xFF,0xFF,0xFF,0xFF,0xC0, // 'I' 0x00,0x01,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // 'J' 0xC0,0x03,0x60,0x03,0x30,0x03,0x18,0x03,0x0C,0x03,0x06,0x03,0x83,0x03,0x81,0xFF,0x80,0xFF,0xC0,0x60,0x60,0x30,0x18,0x18,0x06,0x0C,0x03,0x86,0x00,0xE3,0x00,0x31,0x80,0x0C,0xC0,0x03,0x00, // 'K' 0xC0,0x00,0x30,0x00,0x0C,0x00,0x03,0x00,0x00,0xC0,0x00,0x30,0x00,0x0C,0x00,0x03,0x00,0x00,0xC0,0x00,0x30,0x00,0x0C,0x00,0x03,0x00,0x00,0xC0,0x00,0x30,0x00,0x0C,0x00,0x03,0xFF,0xFF,0xFF,0xFF,0xC0, // 'L' 0xE0,0x00,0x7F,0x00,0x0F,0xF8,0x01,0xFD,0xC0,0x3B,0xCE,0x07,0x3C,0x60,0xE3,0xC3,0x0C,0x3C,0x19,0x83,0xC1,0xF8,0x3C,0x0F,0x03,0xC0,0x60,0x3C,0x00,0x03,0xC0,0x00,0x3C,0x00,0x03,0xC0,0x00,0x3C,0x00,0x03,0xC0,0x00,0x30, // 'M' 0xE0,0x01,0xF8,0x00,0xFE,0x00,0x7B,0x80,0x3C,0xC0,0x1E,0x30,0x0F,0x0C,0x07,0x87,0x03,0xC1,0xC1,0xE0,0x70,0xF0,0x18,0x78,0x06,0x3C,0x01,0x9E,0x00,0xEF,0x00,0x3F,0x80,0x0F,0xC0,0x03,0x80, // 'N' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // 'O' 0xFF,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0xFF,0xFF,0xFF,0xFF,0xD8,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0x80,0x00,0xC0,0x00,0x00, // 'P' 0x7F,0xFF,0x0F,0xFF,0xF8,0xC0,0x01,0x8C,0x00,0x18,0xC0,0x01,0x8C,0x00,0x18,0xC0,0x01,0x8C,0x00,0x18,0xC0,0x01,0x8C,0x00,0x18,0xC0,0x01,0x8C,0x00,0x18,0xC0,0x01,0x8C,0x00,0x18,0xC0,0x01,0x8F,0xFF,0xFF,0x7F,0xFF,0xF0, // 'Q' 0xFF,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0xFF,0xFF,0xFF,0xFF,0xD8,0x06,0x0C,0x03,0x86,0x00,0xE3,0x00,0x39,0x80,0x0E,0xC0,0x03,0x00, // 'R' 0x7F,0xFF,0x7F,0xFF,0xF0,0x00,0x78,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0xFF,0xFE,0x7F,0xFF,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // 'S' 0xFF,0xFF,0xFF,0xFF,0xC0,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0x80,0x00,0xC0,0x00,0x60,0x00,0x30,0x00,0x18,0x00,0x0C,0x00,0x06,0x00,0x03,0x00,0x01,0x80,0x00,0xC0,0x00, // 'T' 0xC0,0x01,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0x80,0x03,0xC0,0x01,0xE0,0x00,0xF0,0x00,0x78,0x00,0x3C,0x00,0x1E,0x00,0x0F,0x00,0x07,0xFF,0xFF,0x7F,0xFF,0x00, // 'U' 0x60,0x00,0x0E,0x30,0x00,0x0C,0x38,0x00,0x1C,0x18,0x00,0x18,0x1C,0x00,0x30,0x0C,0x00,0x30,0x06,0x00,0x60,0x07,0x00,0xE0,0x03,0x00,0xC0,0x03,0x81,0xC0,0x01,0x81,0x80,0x00,0xC3,0x00,0x00,0xC7,0x00,0x00,0x66,0x00,0x00,0x7E,0x00,0x00,0x3C,0x00,0x00,0x18,0x00, // 'V' 0x60,0x07,0x00,0x66,0x00,0xF0,0x06,0x30,0x0F,0x00,0xE3,0x00,0xD8,0x0C,0x18,0x19,0x80,0xC1,0x81,0x98,0x1C,0x18,0x18,0xC1,0x80,0xC3,0x0C,0x18,0x0C,0x30,0xE3,0x00,0xC7,0x06,0x30,0x06,0x60,0x63,0x00,0x66,0x03,0x60,0x07,0xE0,0x36,0x00,0x3C,0x03,0xE0,0x03,0xC0,0x1C,0x00,0x18,0x01,0xC0,0x01,0x80,0x18,0x00, // 'W' 0x60,0x03,0x9C,0x01,0xC3,0x80,0xE0,0x70,0x30,0x0C,0x18,0x01,0x8C,0x00,0x37,0x00,0x07,0x80,0x01,0xC0,0x00,0xF8,0x00,0x37,0x00,0x18,0xC0,0x0C,0x18,0x07,0x03,0x03,0x80,0xE1,0xC0,0x1C,0x60,0x03,0x80, // 'X' 0xE0,0x01,0xD8,0x00,0xE3,0x00,0x30,0x60,0x18,0x1C,0x0E,0x03,0x87,0x00,0x73,0x80,0x0C,0xC0,0x03,0xF0,0x00,0x78,0x00,0x0C,0x00,0x03,0x00,0x00,0xC0,0x00,0x30,0x00,0x0C,0x00,0x03,0x00,0x00,0xC0,0x00, // 'Y' 0xFF,0xFF,0xFF,0xFF,0xC0,0x00,0xE0,0x00,0xE0,0x00,0xE0,0x00,0xE0,0x01,0xC0,0x01,0xC0,0x01,0xC0,0x01,0xC0,0x01,0xC0,0x03,0x80,0x03,0x80,0x03,0x80,0x03,0x80,0x01,0xFF,0xFF,0xFF,0xFF,0x80, // 'Z' 0xFF,0xCC,0xCC,0xCC,0xCC,0xCC,0xCC,0xCF,0xF0, // '[' 0x00,0x08,0x00,0xC0,0x0C,0x00,0x60,0x03,0x00,0x18,0x00,0xC0,0x0C,0x00,0x60,0x03,0x00,0x18,0x00,0xC0,0x0C,0x00,0x60,0x03,0x00,0x10,0x00, // '\' 0xFF,0x33,0x33,0x33,0x33,0x33,0x33,0x3F,0xF0, // ']' 0x00, // '^' 0xFF,0xFF,0xFF,0xFF,0xC0, // '_' 0x66,0x60, // '`' 0xFF,0xFB,0xFF,0xF0,0x00,0xC0,0x03,0x00,0x0C,0x00,0x3F,0xFF,0xFF,0xFF,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xF0, // 'a' 0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xC0,0x03,0xFF,0xEF,0xFF,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0xFF,0xFF,0xFF,0x80, // 'b' 0x7F,0xFF,0xFF,0xFC,0x00,0x30,0x00,0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xFF,0xFD,0xFF,0xF0, // 'c' 0x00,0x0C,0x00,0x30,0x00,0xC0,0x03,0x00,0x0D,0xFF,0xFF,0xFF,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0xFF,0xF7,0xFF,0xC0, // 'd' 0x7F,0xFB,0xFF,0xFC,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3F,0xFF,0xFF,0xFF,0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xFF,0xFD,0xFF,0xF0, // 'e' 0x7F,0xFF,0xC0,0xC0,0xC0,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0, // 'f' 0x7F,0xFB,0xFF,0xFC,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xF0,0x00,0xC0,0x03,0x00,0x0C,0x00,0x31,0xFF,0xC7,0xFE, // 'g' 0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xC0,0x03,0xFF,0xEF,0xFF,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xC0, // 'h' 0xF0,0x3F,0xFF,0xFF,0xFC, // 'i' 0x01,0x80,0xC0,0x00,0x00,0x00,0x0C,0x06,0x03,0x01,0x80,0xC0,0x60,0x30,0x18,0x0C,0x06,0x03,0x01,0x80,0xC0,0x60,0x30,0x18,0x0C,0x07,0xFF,0xFF,0x00, // 'j' 0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xC0,0x03,0x00,0x6C,0x03,0xB0,0x1C,0xC0,0xE3,0x07,0x0C,0x38,0x3F,0xC0,0xFF,0x03,0x0E,0x0C,0x1C,0x30,0x38,0xC0,0x73,0x00,0xEC,0x01,0x80, // 'k' 0xC3,0x0C,0x30,0xC3,0x0C,0x30,0xC3,0x0C,0x30,0xC3,0x0C,0x30,0xC3,0xF7,0xC0, // 'l' 0xFF,0xFF,0xFB,0xFF,0xFF,0xFC,0x03,0x00,0xF0,0x0C,0x03,0xC0,0x30,0x0F,0x00,0xC0,0x3C,0x03,0x00,0xF0,0x0C,0x03,0xC0,0x30,0x0F,0x00,0xC0,0x3C,0x03,0x00,0xF0,0x0C,0x03,0xC0,0x30,0x0F,0x00,0xC0,0x30, // 'm' 0xFF,0xFB,0xFF,0xFC,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x30, // 'n' 0x7F,0xFB,0xFF,0xFC,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xE0, // 'o' 0xFF,0xFB,0xFF,0xFC,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFF,0xFF,0xEC,0x00,0x30,0x00,0xC0,0x03,0x00,0x0C,0x00,0x30,0x00, // 'p' 0x7F,0xFF,0xFF,0xFC,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xF0,0x00,0xC0,0x03,0x00,0x0C,0x00,0x30,0x00,0xC0,0x03, // 'q' 0x7F,0xFF,0xFF,0x00,0x60,0x0C,0x01,0x80,0x30,0x06,0x00,0xC0,0x18,0x03,0x00,0x60,0x0C,0x01,0x80,0x00, // 'r' 0x7F,0xFB,0xFF,0xFC,0x00,0xF0,0x00,0xC0,0x03,0x00,0x0F,0xFF,0x9F,0xFF,0x00,0x0C,0x00,0x30,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xE0, // 's' 0xC0,0xC0,0xC0,0xC0,0xC0,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xFF,0x7F, // 't' 0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xE0, // 'u' 0x60,0x00,0xCE,0x00,0x30,0xC0,0x0E,0x1C,0x01,0x81,0x80,0x70,0x18,0x0C,0x03,0x03,0x80,0x30,0x60,0x06,0x1C,0x00,0x63,0x00,0x0C,0xC0,0x00,0xD8,0x00,0x1E,0x00,0x01,0xC0,0x00, // 'v' 0x60,0x1C,0x01,0x9C,0x07,0x80,0xE3,0x01,0xE0,0x30,0xC0,0xFC,0x0C,0x18,0x33,0x06,0x06,0x1C,0xE1,0x81,0xC6,0x18,0xE0,0x33,0x87,0x30,0x0C,0xC0,0xCC,0x01,0xB0,0x3F,0x00,0x7C,0x07,0x80,0x1E,0x01,0xE0,0x03,0x80,0x70,0x00,0xC0,0x0C,0x00, // 'w' 0x60,0x1C,0xE0,0x70,0xE0,0xC0,0xE3,0x00,0xEE,0x00,0xF8,0x00,0xE0,0x03,0xC0,0x07,0xC0,0x19,0xC0,0x71,0x81,0xC1,0x87,0x01,0x8C,0x03,0x80, // 'x' 0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xC0,0x0F,0x00,0x3C,0x00,0xF0,0x03,0xFF,0xFD,0xFF,0xF0,0x00,0xC0,0x03,0x00,0x0C,0x00,0x31,0xFF,0xC7,0xFE, // 'y' 0xFF,0xFF,0xFF,0xF0,0x01,0xC0,0x0E,0x00,0x70,0x07,0x00,0x38,0x01,0xC0,0x0E,0x00,0xE0,0x07,0x00,0x38,0x00,0xFF,0xFF,0xFF,0xF0, // 'z' 0x3B,0xD8,0xC6,0x31,0x98,0x86,0x18,0xC6,0x31,0x8F,0x38, // '{' 0xFF,0xFF,0xFF,0xFF,0xFF,0xFC, // '|' 0xE7,0x8C,0x63,0x18,0xC3,0x08,0xCC,0x63,0x18,0xDE,0xE0 // '}' }; const GFXglyph <API key>[] PROGMEM = { // bitmapOffset, width, height, xAdvance, xOffset, yOffset { 0, 1, 1, 8, 0, 0 }, // ' ' { 1, 2, 17, 6, 1, -17 }, // '!' { 6, 6, 3, 10, 1, -17 }, // '"' { 9, 18, 17, 21, 1, -17 }, // '#' { 48, 18, 23, 21, 1, -20 }, // '$' { 100, 21, 18, 24, 1, -18 }, // '%' { 148, 21, 17, 23, 1, -17 }, // '&' { 193, 2, 3, 6, 1, -17 }, // ''' { 194, 4, 17, 7, 1, -17 }, { 203, 4, 17, 8, 1, -17 }, { 212, 12, 10, 13, 0, -17 }, { 227, 9, 9, 12, 1, -11 }, { 238, 2, 6, 5, 1, -2 }, { 240, 9, 2, 13, 1, -8 }, { 243, 2, 2, 6, 1, -2 }, { 244, 12, 18, 15, 1, -18 }, { 271, 17, 17, 20, 1, -17 }, { 308, 8, 17, 10, -1, -17 }, { 325, 17, 17, 20, 1, -17 }, { 362, 17, 17, 20, 1, -17 }, { 399, 17, 17, 20, 1, -17 }, { 436, 17, 17, 20, 1, -17 }, { 473, 17, 17, 20, 1, -17 }, { 510, 15, 17, 17, 0, -17 }, { 542, 17, 17, 20, 1, -17 }, { 579, 17, 17, 20, 1, -17 }, { 616, 2, 14, 6, 1, -14 }, { 620, 2, 18, 5, 1, -14 }, { 625, 10, 14, 13, 1, -14 }, { 643, 12, 7, 15, 1, -11 }, { 654, 10, 14, 12, 1, -14 }, { 672, 15, 17, 18, 1, -17 }, { 704, 17, 17, 20, 1, -17 }, { 741, 17, 17, 20, 1, -17 }, { 778, 17, 17, 20, 1, -17 }, { 815, 17, 17, 20, 1, -17 }, { 852, 17, 17, 20, 1, -17 }, { 889, 16, 17, 19, 1, -17 }, { 923, 16, 17, 19, 1, -17 }, { 957, 17, 17, 20, 1, -17 }, { 994, 18, 17, 21, 1, -17 }, { 1033, 2, 17, 6, 1, -17 }, { 1038, 17, 17, 20, 1, -17 }, { 1075, 17, 17, 20, 1, -17 }, { 1112, 18, 17, 20, 1, -17 }, { 1151, 20, 17, 23, 1, -17 }, { 1194, 17, 17, 20, 1, -17 }, { 1231, 17, 17, 20, 1, -17 }, { 1268, 17, 17, 20, 1, -17 }, { 1305, 20, 17, 22, 1, -17 }, { 1348, 17, 17, 20, 1, -17 }, { 1385, 17, 17, 20, 1, -17 }, { 1422, 17, 17, 20, 1, -17 }, { 1459, 17, 17, 20, 1, -17 }, { 1496, 24, 17, 25, 0, -17 }, { 1547, 28, 17, 29, 0, -17 }, { 1607, 18, 17, 20, 1, -17 }, { 1646, 18, 17, 20, 0, -17 }, { 1685, 17, 17, 20, 1, -17 }, { 1722, 4, 17, 7, 1, -17 }, { 1731, 12, 18, 15, 1, -18 }, { 1758, 4, 17, 8, 1, -17 }, { 1767, 1, 1, 1, 0, 0 }, { 1768, 17, 2, 20, 1, 0 }, { 1773, 4, 3, 6, 0, -24 }, { 1775, 14, 14, 17, 1, -14 }, { 1800, 14, 19, 17, 1, -19 }, { 1834, 14, 14, 17, 1, -14 }, { 1859, 14, 19, 17, 1, -19 }, { 1893, 14, 14, 17, 1, -14 }, { 1918, 8, 19, 11, 1, -19 }, { 1937, 14, 20, 17, 1, -14 }, { 1972, 14, 19, 17, 1, -19 }, { 2006, 2, 19, 6, 1, -19 }, { 2011, 9, 25, 7, -4, -19 }, { 2040, 14, 19, 16, 1, -19 }, { 2074, 6, 19, 8, 1, -19 }, { 2089, 22, 14, 25, 1, -14 }, { 2128, 14, 14, 17, 1, -14 }, { 2153, 14, 14, 17, 1, -14 }, { 2178, 14, 20, 17, 1, -14 }, { 2213, 14, 20, 17, 1, -14 }, { 2248, 11, 14, 13, 1, -14 }, { 2268, 14, 14, 17, 1, -14 }, { 2293, 8, 19, 11, 1, -19 }, { 2312, 14, 14, 17, 1, -14 }, { 2337, 19, 14, 20, 0, -14 }, { 2371, 26, 14, 27, 0, -14 }, { 2417, 15, 14, 18, 1, -14 }, { 2444, 14, 20, 17, 1, -14 }, { 2479, 14, 14, 17, 1, -14 }, { 2504, 5, 17, 8, 1, -17 }, { 2515, 2, 23, 6, 1, -20 }, { 2521, 5, 17, 8, 1, -17 } }; const GFXfont Orbitron_Light_24 PROGMEM = { (uint8_t *)<API key>,(GFXglyph *)<API key>,0x20, 0x7D, 24};
#ifndef QHELPINDEXWIDGET_H #define QHELPINDEXWIDGET_H #include <QtHelp/qhelp_global.h> #include <QtCore/QUrl> #include <QtCore/QStringListModel> #include <QtWidgets/QListView> QT_BEGIN_NAMESPACE class QHelpEnginePrivate; class <API key>; class QHELP_EXPORT QHelpIndexModel : public QStringListModel { Q_OBJECT public: void createIndex(const QString &customFilterName); QModelIndex filter(const QString &filter, const QString &wildcard = QString()); QMap<QString, QUrl> linksForKeyword(const QString &keyword) const; bool isCreatingIndex() const; Q_SIGNALS: void <API key>(); void indexCreated(); private Q_SLOTS: void insertIndices(); void invalidateIndex(bool onShutDown = false); private: QHelpIndexModel(QHelpEnginePrivate *helpEngine); ~QHelpIndexModel(); <API key> *d; friend class QHelpEnginePrivate; }; class QHELP_EXPORT QHelpIndexWidget : public QListView { Q_OBJECT Q_SIGNALS: void linkActivated(const QUrl &link, const QString &keyword); void linksActivated(const QMap<QString, QUrl> &links, const QString &keyword); public Q_SLOTS: void filterIndices(const QString &filter, const QString &wildcard = QString()); void activateCurrentItem(); private Q_SLOTS: void showLink(const QModelIndex &index); private: QHelpIndexWidget(); friend class QHelpEngine; }; QT_END_NAMESPACE #endif
// # src / katex.js // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the function loadDisqus2() { window.DISQUS.reset({ reload: true, config() { this.page.url = window.location.href; this.page.title = document.title; }, }); } export default function loadDisqus() { if (document.getElementById('disqus_thread')) { if (window.DISQUS) { loadDisqus2(); } else { window.disqus_config = function disqusConfig() { this.page.url = window.location.href; this.page.title = document.title; }; window.loadJSDeferred(document.getElementById('_disqusJS').href); } } } loadDisqus();
#ifndef <API key> #define <API key> #include <asn_application.h> /* Including external dependencies */ #include <asn_SEQUENCE_OF.h> #include <constr_SEQUENCE_OF.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct SupportedBandEUTRA; /* <API key> */ typedef struct <API key> { A_SEQUENCE_OF(struct SupportedBandEUTRA) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } <API key>; /* Implementation */ extern <API key> <API key>; #ifdef __cplusplus } #endif /* Referred external types */ #include "SupportedBandEUTRA.h" #endif /* <API key> */ #include <asn_internal.h>
GO.billing.DeliveriesGrid = function(config){ if(!config) { config = {}; } config.layout='fit'; config.autoScroll=true; config.split=true; config.store = new GO.data.JsonStore({ url: GO.url("billing/item/deliveries"), baseParams: { order_id:"0" }, fields: ['id', 'description', 'amount', 'new_delivered', 'amount_to_deliver'], remoteSort: true }); config.paging=true; var columns = [{ header: GO.lang.strDescription, dataIndex: 'description', id:'name' },{ header: GO.billing.lang.amount, dataIndex: 'amount', width:50, renderer:this.numberRenderer },{ header: GO.billing.lang.amountToBeDelivered, dataIndex: 'amount_to_deliver', width:50, renderer:this.numberRenderer },{ header: GO.billing.lang.delivered, width:80, dataIndex: 'new_delivered', renderer:this.numberRenderer, editor:this.<API key> = new GO.form.NumberField({ width:80, dataIndex: 'new_delivered', fieldLabel: GO.billing.lang.delivered }) }]; var columnModel = new Ext.grid.ColumnModel({ defaults:{ sortable:true }, columns:columns }); config.cm=columnModel; config.autoExpandColumn='name'; config.view=new Ext.grid.GridView({ emptyText: GO.lang['strNoItems'] }), config.sm=new Ext.grid.RowSelectionModel(); config.loadMask=true; config.clicksToEdit=1; GO.billing.DeliveriesGrid.superclass.constructor.call(this, config); // this.store.on('beforeload',function() // this.getModifiedRecords(); // }, this); // this.store.on('load', function() // for(var i=0; i<this.store.data.items.length; i++) // var record = this.store.data.items[i]; // var new_delivered = this.itemSelected(record.id) // if(!new_delivered) // new_delivered = 0; // }else // record.set('new_delivered', new_delivered); // }, this) this.on('afteredit', this.afterEdit, this); this.on('beforeedit', this.beforeEdit, this); this.addEvents({ 'afternoedit' : true }); this.on('afternoedit', this.afterNoEdit, this); }; Ext.extend(GO.billing.DeliveriesGrid, GO.grid.EditorGridPanel,{ changed : false, selectedItems: [], selectItem: function(id, amount) { this.selectedItems.push({ id:id, new_delivered:amount }); }, itemSelected: function(id) { for(var i=0; i<this.selectedItems.length; i++) { if(this.selectedItems[i].id == id) { return this.selectedItems[i].new_delivered; } } return false; }, <API key>: function(id, amount) { for(var i=0; i<this.selectedItems.length; i++) { if(this.selectedItems[i].id == id) { this.selectedItems[i].new_delivered = amount; } } return false; }, getModifiedRecords: function() { var records = this.store.getModifiedRecords(); for(var i=0; i<records.length; i++) { var record = records[i]; if(record.data.new_delivered) { // make sure amount is always a number and not a string var amount = 1* record.data.new_delivered; if(this.itemSelected(record.id)) { this.<API key>(record.id, amount); }else { this.selectItem(record.id, amount); } } } //this.store.rejectChanges(); }, getSelectedItems: function(check_latest) { if(check_latest) { this.getModifiedRecords(); } return this.selectedItems; }, removeSelectedItems: function() { this.selectedItems = []; this.store.rejectChanges(); }, iconRenderer : function(src,cell,record){ return '<div class="' + record.data.iconCls +'"></div>'; }, /* * Overide ext method because there's no way to capture afteredit when there's no change. * We need this because we format /unformat numbers before and after edit. */ onEditComplete : function(ed, value, startValue){ GO.billing.DeliveriesGrid.superclass.onEditComplete.call(this, ed, value, startValue); if(startValue != 'undefined' && String(value) === String(startValue)){ var r = ed.record; var field = this.colModel.getDataIndex(ed.col); value = this.postEditValue(value, startValue, r, field); var e = { grid: this, record: r, field: field, originalValue: startValue, value: value, row: ed.row, column: ed.col, cancel:false }; this.fireEvent('afternoedit', e); } }, afterNoEdit : function (e) { e.record.set(e.field, this.<API key>); }, afterEdit : function (e) { this.changed=true; e.record.set(e.field, GO.util.unlocalizeNumber(e.value)); var r = e.record.data; }, beforeEdit : function(e) { var type = e.record.id.substr(0, 1); if(type == 'f') { return false; }else { var colId = this.colModel.getColumnId(e.column); var col = this.colModel.getColumnById(colId); this.<API key>=e.value; if(col && col.editor && col.editor.decimals) { e.record.set(e.field, GO.util.numberFormat(e.value)); } } }, numberRenderer : function(v) { //v = GO.util.unlocalizeNumber(v); return GO.util.numberFormat(v); } });
// Check that -march works for all supported targets. // RUN: not %clang -target s390x -S -emit-llvm -march=z9 %s -o - 2>&1 | FileCheck --check-prefix=CHECK-Z9 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=z10 %s 2>&1 | FileCheck --check-prefix=CHECK-Z10 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=arch8 %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH8 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=z196 %s 2>&1 | FileCheck --check-prefix=CHECK-Z196 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=arch9 %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH9 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=zEC12 %s 2>&1 | FileCheck --check-prefix=CHECK-ZEC12 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=arch10 %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH10 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=z13 %s 2>&1 | FileCheck --check-prefix=CHECK-Z13 %s // RUN: %clang -target s390x -### -S -emit-llvm -march=arch11 %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH11 %s // CHECK-Z9: error: unknown target CPU 'z9' // CHECK-Z10: "-target-cpu" "z10" // CHECK-ARCH8: "-target-cpu" "arch8" // CHECK-Z196: "-target-cpu" "z196" // CHECK-ARCH9: "-target-cpu" "arch9" // CHECK-ZEC12: "-target-cpu" "zEC12" // CHECK-ARCH10: "-target-cpu" "arch10" // CHECK-Z13: "-target-cpu" "z13" // CHECK-ARCH11: "-target-cpu" "arch11" int x;
# This file is part of Ansible # Ansible is free software: you can redistribute it and/or modify # (at your option) any later version. # Ansible is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import itertools import operator import uuid from functools import partial from inspect import getmembers from io import FileIO from six import iteritems, string_types from jinja2.exceptions import UndefinedError from ansible.errors import AnsibleParserError from ansible.parsing import DataLoader from ansible.playbook.attribute import Attribute, FieldAttribute from ansible.template import Templar from ansible.utils.boolean import boolean from ansible.utils.debug import debug from ansible.utils.vars import combine_vars from ansible.template import template class Base: # connection/transport _connection = FieldAttribute(isa='string') _port = FieldAttribute(isa='int') _remote_user = FieldAttribute(isa='string') # variables _vars = FieldAttribute(isa='dict', default=dict()) # flags and misc. settings _environment = FieldAttribute(isa='list') _no_log = FieldAttribute(isa='bool') def __init__(self): # initialize the data loader and variable manager, which will be provided # later when the object is actually loaded self._loader = None self._variable_manager = None # every object gets a random uuid: self._uuid = uuid.uuid4() # and initialize the base attributes self.<API key>() try: from __main__ import display self._display = display except ImportError: from ansible.utils.display import Display self._display = Display() # The following three functions are used to programatically define data # descriptors (aka properties) for the Attributes of all of the playbook # objects (tasks, blocks, plays, etc). # The function signature is a little strange because of how we define # them. We use partial to give each method the name of the Attribute that # it is for. Since partial prefills the positional arguments at the # beginning of the function we end up with the first positional argument # being allocated to the name instead of to the class instance (self) as # normal. To deal with that we make the property name field the first # positional argument and self the second arg. # Because these methods are defined inside of the class, they get bound to # the instance when the object is created. After we run partial on them # and put the result back into the class as a property, they get bound # a second time. This leads to self being placed in the arguments twice. # To work around that, we mark the functions as @staticmethod so that the # first binding to the instance doesn't happen. @staticmethod def _generic_g(prop_name, self): method = "_get_attr_%s" % prop_name if hasattr(self, method): return getattr(self, method)() return self._attributes[prop_name] @staticmethod def _generic_s(prop_name, self, value): self._attributes[prop_name] = value @staticmethod def _generic_d(prop_name, self): del self._attributes[prop_name] def <API key>(self): ''' Returns the list of attributes for this class (or any subclass thereof). If the attribute name starts with an underscore, it is removed ''' base_attributes = dict() for (name, value) in getmembers(self.__class__): if isinstance(value, Attribute): if name.startswith('_'): name = name[1:] base_attributes[name] = value return base_attributes def <API key>(self): # each class knows attributes set upon it, see Task.py for example self._attributes = dict() for (name, value) in self.<API key>().items(): getter = partial(self._generic_g, name) setter = partial(self._generic_s, name) deleter = partial(self._generic_d, name) # Place the property into the class so that cls.name is the # property functions. setattr(Base, name, property(getter, setter, deleter)) # Place the value into the instance so that the property can # process and hold that value/ setattr(self, name, value.default) def preprocess_data(self, ds): ''' infrequently used method to do some pre-processing of legacy terms ''' for base_class in self.__class__.mro(): method = getattr(self, "_preprocess_data_%s" % base_class.__name__.lower(), None) if method: return method(ds) return ds def load_data(self, ds, variable_manager=None, loader=None): ''' walk the input datastructure and assign any values ''' assert ds is not None # the variable manager class is used to manage and merge variables # down to a single dictionary for reference in templating, etc. self._variable_manager = variable_manager # the data loader class is used to parse data from strings and files if loader is not None: self._loader = loader else: self._loader = DataLoader() # call the preprocess_data() function to massage the data into # something we can more easily parse, and then call the validation # function on it to ensure there are no incorrect key values ds = self.preprocess_data(ds) self.<API key>(ds) # Walk all attributes in the class. We sort them based on their priority # so that certain fields can be loaded before others, if they are dependent. # FIXME: we currently don't do anything with private attributes but # may later decide to filter them out of 'ds' here. base_attributes = self.<API key>() for name, attr in sorted(base_attributes.items(), key=operator.itemgetter(1)): # copy the value over unless a _load_field method is defined if name in ds: method = getattr(self, '_load_%s' % name, None) if method: self._attributes[name] = method(name, ds[name]) else: self._attributes[name] = ds[name] # run early, non-critical validation self.validate() # cache the datastructure internally setattr(self, '_ds', ds) # return the constructed object return self def get_ds(self): try: return getattr(self, '_ds') except AttributeError: return None def get_loader(self): return self._loader def <API key>(self): return self._variable_manager def <API key>(self, ds): ''' Ensures that there are no keys in the datastructure which do not map to attributes for this object. ''' valid_attrs = frozenset(name for name in self.<API key>()) for key in ds: if key not in valid_attrs: raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=ds) def validate(self, all_vars=dict()): ''' validation that is done at parse time, not load time ''' # walk all fields in the object for (name, attribute) in iteritems(self.<API key>()): # run validator only if present method = getattr(self, '_validate_%s' % name, None) if method: method(attribute, name, getattr(self, name)) def copy(self): ''' Create a copy of this object and return it. ''' new_me = self.__class__() for name in self.<API key>(): setattr(new_me, name, getattr(self, name)) new_me._loader = self._loader new_me._variable_manager = self._variable_manager # if the ds value was set on the object, copy it to the new copy too if hasattr(self, '_ds'): new_me._ds = self._ds return new_me def post_validate(self, templar): ''' we can't tell that everything is of the right type until we have all the variables. Run basic types (from isa) as well as any _post_validate_<foo> functions. ''' basedir = None if self._loader is not None: basedir = self._loader.get_basedir() # save the omit value for later checking omit_value = templar.<API key>.get('omit') for (name, attribute) in iteritems(self.<API key>()): if getattr(self, name) is None: if not attribute.required: continue else: raise AnsibleParserError("the field '%s' is required but was not set" % name) try: # Run the post-validator if present. These methods are responsible for # using the given templar to template the values, if required. method = getattr(self, '_post_validate_%s' % name, None) if method: value = method(attribute, getattr(self, name), templar) else: # if the attribute contains a variable, template it now value = templar.template(getattr(self, name)) # if this evaluated to the omit value, set the value back to # the default specified in the FieldAttribute and move on if omit_value is not None and value == omit_value: value = attribute.default continue # and make sure the attribute is of the type it should be if value is not None: if attribute.isa == 'string': value = unicode(value) elif attribute.isa == 'int': value = int(value) elif attribute.isa == 'float': value = float(value) elif attribute.isa == 'bool': value = boolean(value) elif attribute.isa == 'percent': # special value, which may be an integer or float # with an optional '%' at the end if isinstance(value, string_types) and '%' in value: value = value.replace('%', '') value = float(value) elif attribute.isa == 'list': if value is None: value = [] elif not isinstance(value, list): value = [ value ] if attribute.listof is not None: for item in value: if not isinstance(item, attribute.listof): raise AnsibleParserError("the field '%s' should be a list of %s, but the item '%s' is a %s" % (name, attribute.listof, item, type(item)), obj=self.get_ds()) elif attribute.required and attribute.listof == string_types: if item is None or item.strip() == "": raise AnsibleParserError("the field '%s' is required, and cannot have empty values" % (name,), obj=self.get_ds()) elif attribute.isa == 'set': if value is None: value = set() else: if not isinstance(value, (list, set)): value = [ value ] if not isinstance(value, set): value = set(value) elif attribute.isa == 'dict': if value is None: value = dict() elif not isinstance(value, dict): raise TypeError("%s is not a dictionary" % value) # and assign the massaged value back to the attribute field setattr(self, name, value) except (TypeError, ValueError) as e: raise AnsibleParserError("the field '%s' has an invalid value (%s), and could not be converted to an %s. Error was: %s" % (name, value, attribute.isa, e), obj=self.get_ds()) except UndefinedError as e: if templar.<API key> and name != 'name': raise AnsibleParserError("the field '%s' has an invalid value, which appears to include a variable that is undefined. The error was: %s" % (name,e), obj=self.get_ds()) def serialize(self): ''' Serializes the object derived from the base object into a dictionary of values. This only serializes the field attributes for the object, so this may need to be overridden for any classes which wish to add additional items not stored as field attributes. ''' repr = dict() for name in self.<API key>(): repr[name] = getattr(self, name) # serialize the uuid field repr['uuid'] = getattr(self, '_uuid') return repr def deserialize(self, data): ''' Given a dictionary of values, load up the field attributes for this object. As with serialize(), if there are any non-field attribute data members, this method will need to be overridden and extended. ''' assert isinstance(data, dict) for (name, attribute) in iteritems(self.<API key>()): if name in data: setattr(self, name, data[name]) else: setattr(self, name, attribute.default) # restore the UUID field setattr(self, '_uuid', data.get('uuid')) def _load_vars(self, attr, ds): ''' Vars in a play can be specified either as a dictionary directly, or as a list of dictionaries. If the later, this method will turn the list into a single dictionary. ''' try: if isinstance(ds, dict): return ds elif isinstance(ds, list): all_vars = dict() for item in ds: if not isinstance(item, dict): raise ValueError all_vars = combine_vars(all_vars, item) return all_vars elif ds is None: return {} else: raise ValueError except ValueError: raise AnsibleParserError("Vars in a %s must be specified as a dictionary, or a list of dictionaries" % self.__class__.__name__, obj=ds) def _extend_value(self, value, new_value): ''' Will extend the value given with new_value (and will turn both into lists if they are not so already). The values are run through a set to remove duplicate values. ''' if not isinstance(value, list): value = [ value ] if not isinstance(new_value, list): new_value = [ new_value ] #return list(set(value + new_value)) return [i for i,_ in itertools.groupby(value + new_value)] def __getstate__(self): return self.serialize() def __setstate__(self, data): self.__init__() self.deserialize(data)
<?php namespace Magento\TestFramework\Isolation; use Magento\TestFramework\Helper\Bootstrap; use Magento\Framework\App\DeploymentConfig\Reader; /** * A listener that watches for integrity of deployment configuration */ class DeploymentConfig { /** * Deployment configuration reader * * @var Reader */ private $reader; /** * Initial value of deployment configuration * * @var mixed */ private $config; /** * Memorizes the initial value of configuration reader and the configuration value * * Assumption: this is done once right before executing very first test suite. * It is assumed that deployment configuration is valid at this point * * @return void */ public function startTestSuite() { if (null === $this->reader) { $this->reader = Bootstrap::getObjectManager()->get('Magento\Framework\App\DeploymentConfig\Reader'); $this->config = $this->reader->load(); } } /** * Checks if deployment configuration has been changed by a test * * Changing deployment configuration violates isolation between tests, so further tests may become broken. * To fix this issue, find out why this test changes deployment configuration. * If this is intentional, then it must be reverted to the previous state within the test. * After that, the application needs to be wiped out and reinstalled. * * @param \<API key> $test * @return void */ public function endTest(\<API key> $test) { $config = $this->reader->load(); if ($this->config != $config) { $error = "\n\nERROR: deployment configuration is corrupted. The application state is no longer valid.\n" . 'Further tests may fail.' . " This test failure may be misleading, if you are re-running it on a corrupted application.\n" . $test->toString() . "\n"; $test->fail($error); } } }
<?php /** * Class for handling updates to Oracle databases. * * @ingroup Deployment * @since 1.17 */ class OracleUpdater extends DatabaseUpdater { /** * Handle to the database subclass * * @var DatabaseOracle */ protected $db; protected function getCoreUpdateList() { return [ [ '<API key>' ], // 1.17 [ 'doNamespaceDefaults' ], [ 'doFKRenameDeferr' ], [ 'doFunctions17' ], [ 'doSchemaUpgrade17' ], [ 'doInsertPage0' ], [ '<API key>' ], [ 'addTable', 'user_former_groups', '<API key>.sql' ], // 1.18 [ 'addIndex', 'user', 'i02', '<API key>.sql' ], [ 'modifyField', 'user_properties', 'up_property', 'patch-up_property.sql' ], [ 'addTable', 'uploadstash', 'patch-uploadstash.sql' ], [ '<API key>' ], // 1.19 [ 'addIndex', 'logging', 'i05', '<API key>.sql' ], [ 'addField', 'revision', 'rev_sha1', '<API key>.sql' ], [ 'addField', 'archive', 'ar_sha1', 'patch-ar_sha1_field.sql' ], [ '<API key>' ], [ 'addIndex', 'page', 'i03', '<API key>.sql' ], [ 'addField', 'uploadstash', 'us_chunk_inx', '<API key>.sql' ], [ 'addField', 'job', 'job_timestamp', '<API key>.sql' ], [ 'addIndex', 'job', 'i02', '<API key>.sql' ], [ '<API key>' ], // 1.20 [ 'addIndex', 'ipblocks', 'i05', '<API key>.sql' ], [ 'addIndex', 'revision', 'i05', '<API key>.sql' ], [ 'dropField', 'category', 'cat_hidden', 'patch-cat_hidden.sql' ], // 1.21 [ 'addField', 'revision', 'rev_content_format', '<API key>.sql' ], [ 'addField', 'revision', 'rev_content_model', '<API key>.sql' ], [ 'addField', 'archive', 'ar_content_format', '<API key>.sql' ], [ 'addField', 'archive', 'ar_content_model', '<API key>.sql' ], [ 'addField', 'archive', 'ar_id', 'patch-archive-ar_id.sql' ], [ 'addField', 'externallinks', 'el_id', '<API key>.sql' ], [ 'addField', 'page', 'page_content_model', '<API key>.sql' ], [ '<API key>' ], [ 'dropField', 'site_stats', 'ss_admins', 'patch-ss_admins.sql' ], [ 'dropField', 'recentchanges', 'rc_moved_to_title', 'patch-rc_moved.sql' ], [ 'addTable', 'sites', 'patch-sites.sql' ], [ 'addField', 'filearchive', 'fa_sha1', 'patch-fa_sha1.sql' ], [ 'addField', 'job', 'job_token', 'patch-job_token.sql' ], [ 'addField', 'job', 'job_attempts', 'patch-job_attempts.sql' ], [ 'addField', 'uploadstash', 'us_props', '<API key>.sql' ], [ 'modifyField', 'user_groups', 'ug_group', '<API key>.sql' ], [ 'modifyField', 'user_former_groups', 'ufg_group', '<API key>.sql' ], // 1.23 [ 'addIndex', 'logging', 'i06', '<API key>.sql' ], [ 'addIndex', 'logging', 'i07', '<API key>.sql' ], [ 'addField', 'user', '<API key>', '<API key>.sql' ], [ 'addField', 'page', 'page_links_updated', '<API key>.sql' ], [ 'addField', 'recentchanges', 'rc_source', 'patch-rc_source.sql' ], // 1.24 [ 'addField', 'page', 'page_lang', '<API key>.sql' ], // 1.25 [ 'dropTable', 'hitcounter' ], [ 'dropField', 'site_stats', 'ss_total_views', '<API key>.sql' ], [ 'dropField', 'page', 'page_counter', '<API key>.sql' ], // 1.27 [ 'dropTable', 'msg_resource_links' ], [ 'dropTable', 'msg_resource' ], [ 'addField', 'watchlist', 'wl_id', '<API key>.sql' ], // 1.28 [ 'addIndex', 'recentchanges', '<API key>', '<API key>.sql' ], [ 'addField', 'change_tag', 'ct_id', '<API key>.sql' ], [ 'addField', 'tag_summary', 'ts_id', '<API key>.sql' ], // KEEP THIS AT THE BOTTOM!! [ '<API key>' ], ]; } /** * MySQL uses datatype defaults for NULL inserted into NOT NULL fields * In namespace case that results into insert of 0 which is default namespace * Oracle inserts NULL, so namespace fields should have a default value */ protected function doNamespaceDefaults() { $meta = $this->db->fieldInfo( 'page', 'page_namespace' ); if ( $meta->defaultValue() != null ) { return; } $this->applyPatch( '<API key>.sql', false, 'Altering namespace fields with default value' ); } /** * Uniform FK names + deferrable state */ protected function doFKRenameDeferr() { $meta = $this->db->query( ' SELECT COUNT(*) cnt FROM user_constraints WHERE constraint_type = \'R\' AND deferrable = \'DEFERRABLE\'' ); $row = $meta->fetchRow(); if ( $row && $row['cnt'] > 0 ) { return; } $this->applyPatch( '<API key>.sql', false, "Altering foreign keys ... " ); } /** * Recreate functions to 17 schema layout */ protected function doFunctions17() { $this->applyPatch( '<API key>.sql', false, "Recreating functions" ); } /** * Schema upgrade 16->17 * there are no incremental patches prior to this */ protected function doSchemaUpgrade17() { // check if iwlinks table exists which was added in 1.17 if ( $this->db->tableExists( 'iwlinks' ) ) { return; } $this->applyPatch( '<API key>.sql', false, "Updating schema to 17" ); } /** * Insert page (page_id = 0) to prevent FK constraint violation */ protected function doInsertPage0() { $this->output( "Inserting page 0 if missing ... " ); $row = [ 'page_id' => 0, 'page_namespace' => 0, 'page_title' => ' ', 'page_is_redirect' => 0, 'page_is_new' => 0, 'page_random' => 0, 'page_touched' => $this->db->timestamp(), 'page_latest' => 0, 'page_len' => 0 ]; $this->db->insert( 'page', $row, 'OracleUpdater:doInserPage0', [ 'IGNORE' ] ); $this->output( "ok\n" ); } /** * Remove DEFAULT '' NOT NULL constraints from fields as '' is internally * converted to NULL in Oracle */ protected function <API key>() { $meta = $this->db->fieldInfo( 'categorylinks', 'cl_sortkey_prefix' ); if ( $meta->isNullable() ) { return; } $this->applyPatch( '<API key>.sql', false, 'Removing not null empty constraints' ); } protected function <API key>() { $meta = $this->db->fieldInfo( 'ipblocks', 'ipb_by_text' ); if ( $meta->isNullable() ) { return; } $this->applyPatch( '<API key>.sql', false, 'Removing not null empty constraints' ); } /** * Removed forcing of invalid state on recentchanges_fk2. * cascading taken in account in the deleting function */ protected function <API key>() { $meta = $this->db->query( 'SELECT 1 FROM all_constraints WHERE owner = \'' . strtoupper( $this->db->getDBname() ) . '\' AND constraint_name = \'' . $this->db->tablePrefix() . 'RECENTCHANGES_FK2\' AND delete_rule = \'CASCADE\'' ); $row = $meta->fetchRow(); if ( $row ) { return; } $this->applyPatch( '<API key>.sql', false, "Altering RECENTCHANGES_FK2" ); } /** * Fixed wrong PK, UK definition */ protected function <API key>() { $this->output( "Altering PAGE_RESTRICTIONS keys ... " ); $meta = $this->db->query( 'SELECT column_name FROM all_cons_columns WHERE owner = \'' . strtoupper( $this->db->getDBname() ) . '\' AND constraint_name = \'' . $this->db->tablePrefix() . '<API key>\' AND rownum = 1' ); $row = $meta->fetchRow(); if ( $row['column_name'] == 'PR_ID' ) { $this->output( "seems to be up to date.\n" ); return; } $this->applyPatch( '<API key>.sql', false ); $this->output( "ok\n" ); } /** * rebuilding of the function that duplicates tables for tests */ protected function <API key>() { $this->applyPatch( '<API key>.sql', false, "Rebuilding duplicate function" ); } /** * Overload: after this action field info table has to be rebuilt * * @param array $what */ public function doUpdates( $what = [ 'core', 'extensions', 'purge', 'stats' ] ) { parent::doUpdates( $what ); $this->db->query( 'BEGIN fill_wiki_info; END;' ); } /** * Overload: because of the DDL_MODE tablename escaping is a bit dodgy */ public function purgeCache() { # We can't guarantee that the user will be able to use TRUNCATE, # but we know that DELETE is available to us $this->output( "Purging caches..." ); $this->db->delete( '' . $this->db->tableName( 'objectcache' ), '*', __METHOD__ ); $this->output( "done.\n" ); } }
#ifndef NETWORK_H #define NETWORK_H #ifdef PLAN9 #include <u.h> //Plan 9 requires this is imported first #include <libc.h> #endif #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <time.h> #if defined(_WIN32) || defined(__WIN32__) || defined (WIN32) /* Put win32 includes here */ #ifndef WINVER //Windows XP #define WINVER 0x0501 #endif #include <winsock2.h> #include <windows.h> #include <ws2tcpip.h> #ifndef IPV6_V6ONLY #define IPV6_V6ONLY 27 #endif typedef unsigned int sock_t; /* sa_family_t is the sockaddr_in / sockaddr_in6 family field */ typedef short sa_family_t; #ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK #endif #else // Linux includes #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <sys/time.h> #include <sys/types.h> #include <netdb.h> #include <unistd.h> typedef int sock_t; #endif #if defined(__AIX__) # define _XOPEN_SOURCE 1 #endif #if defined(__sun__) #define __EXTENSIONS__ 1 // SunOS! #if defined(__SunOS5_6__) || defined(__SunOS5_7__) || defined(__SunOS5_8__) || defined(__SunOS5_9__) || defined(__SunOS5_10__) //Nothing needed #else #define <API key> 1 #endif #endif #ifndef IPV6_ADD_MEMBERSHIP #ifdef IPV6_JOIN_GROUP #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP #define <API key> IPV6_LEAVE_GROUP #endif #endif #define MAX_UDP_PACKET_SIZE 2048 #define <API key> 0 /* Ping request packet ID. */ #define <API key> 1 /* Ping response packet ID. */ #define <API key> 2 /* Get nodes request packet ID. */ #define <API key> 4 /* Send nodes response packet ID for other addresses. */ #define <API key> 24 /* Cookie request packet */ #define <API key> 25 /* Cookie response packet */ #define <API key> 26 /* Crypto handshake packet */ #define <API key> 27 /* Crypto data packet */ #define NET_PACKET_CRYPTO 32 /* Encrypted data packet ID. */ #define <API key> 33 /* LAN discovery packet ID. */ /* See: docs/Prevent_Tracking.txt and onion.{c, h} */ #define <API key> 128 #define <API key> 129 #define <API key> 130 #define <API key> 131 #define <API key> 132 #define <API key> 133 #define <API key> 134 #define <API key> 140 #define <API key> 141 #define <API key> 142 /* Only used for bootstrap nodes */ #define <API key> 240 #define TOX_PORTRANGE_FROM 33445 #define TOX_PORTRANGE_TO 33545 #define TOX_PORT_DEFAULT TOX_PORTRANGE_FROM /* TCP related */ #define TCP_ONION_FAMILY (AF_INET6 + 1) #define TCP_INET (AF_INET6 + 2) #define TCP_INET6 (AF_INET6 + 3) #define TCP_FAMILY (AF_INET6 + 4) typedef union { uint8_t uint8[4]; uint16_t uint16[2]; uint32_t uint32; struct in_addr in_addr; } IP4; typedef union { uint8_t uint8[16]; uint16_t uint16[8]; uint32_t uint32[4]; uint64_t uint64[2]; struct in6_addr in6_addr; } IP6; typedef struct { uint8_t family; union { IP4 ip4; IP6 ip6; }; } IP; typedef struct { IP ip; uint16_t port; } IP_Port; /* Does the IP6 struct a contain an IPv4 address in an IPv6 one? */ #define IPV6_IPV4_IN_V6(a) ((a.uint64[0] == 0) && (a.uint32[2] == htonl (0xffff))) #define SIZE_IP4 4 #define SIZE_IP6 16 #define SIZE_IP (1 + SIZE_IP6) #define SIZE_PORT 2 #define SIZE_IPPORT (SIZE_IP + SIZE_PORT) #define <API key> 1 /* addr_resolve return values */ #define <API key> 1 #define <API key> 2 /* ip_ntoa * converts ip into a string * uses a static buffer, so mustn't used multiple times in the same output * * IPv6 addresses are enclosed into square brackets, i.e. "[IPv6]" * writes error message into the buffer on error */ const char *ip_ntoa(const IP *ip); /* * ip_parse_addr * parses IP structure into an address string * * input * ip: ip of AF_INET or AF_INET6 families * length: length of the address buffer * Must be at least INET_ADDRSTRLEN for AF_INET * and INET6_ADDRSTRLEN for AF_INET6 * * output * address: dotted notation (IPv4: quad, IPv6: 16) or colon notation (IPv6) * * returns 1 on success, 0 on failure */ int ip_parse_addr(const IP *ip, char *address, size_t length); /* * addr_parse_ip * directly parses the input into an IP structure * tries IPv4 first, then IPv6 * * input * address: dotted notation (IPv4: quad, IPv6: 16) or colon notation (IPv6) * * output * IP: family and the value is set on success * * returns 1 on success, 0 on failure */ int addr_parse_ip(const char *address, IP *to); /* ip_equal * compares two IPAny structures * unset means unequal * * returns 0 when not equal or when uninitialized */ int ip_equal(const IP *a, const IP *b); /* ipport_equal * compares two IPAny_Port structures * unset means unequal * * returns 0 when not equal or when uninitialized */ int ipport_equal(const IP_Port *a, const IP_Port *b); /* nulls out ip */ void ip_reset(IP *ip); /* nulls out ip, sets family according to flag */ void ip_init(IP *ip, uint8_t ipv6enabled); /* checks if ip is valid */ int ip_isset(const IP *ip); /* checks if ip is valid */ int ipport_isset(const IP_Port *ipport); /* copies an ip structure */ void ip_copy(IP *target, const IP *source); /* copies an ip_port structure */ void ipport_copy(IP_Port *target, const IP_Port *source); /* * addr_resolve(): * uses getaddrinfo to resolve an address into an IP address * uses the first IPv4/IPv6 addresses returned by getaddrinfo * * input * address: a hostname (or something parseable to an IP address) * to: to.family MUST be initialized, either set to a specific IP version * (AF_INET/AF_INET6) or to the unspecified AF_UNSPEC (= 0), if both * IP versions are acceptable * extra can be NULL and is only set in special circumstances, see returns * * returns in *to a valid IPAny (v4/v6), * prefers v6 if ip.family was AF_UNSPEC and both available * returns in *extra an IPv4 address, if family was AF_UNSPEC and *to is AF_INET6 * returns 0 on failure */ int addr_resolve(const char *address, IP *to, IP *extra); /* * <API key> * resolves string into an IP address * * address: a hostname (or something parseable to an IP address) * to: to.family MUST be initialized, either set to a specific IP version * (AF_INET/AF_INET6) or to the unspecified AF_UNSPEC (= 0), if both * IP versions are acceptable * extra can be NULL and is only set in special circumstances, see returns * * returns in *tro a matching address (IPv6 or IPv4) * returns in *extra, if not NULL, an IPv4 address, if to->family was AF_UNSPEC * returns 1 on success * returns 0 on failure */ int <API key>(const char *address, IP *to, IP *extra); /* Function to receive data, ip and port of sender is put into ip_port. * Packet data is put into data. * Packet length is put into length. */ typedef int (*<API key>)(void *object, IP_Port ip_port, const uint8_t *data, uint16_t len); typedef struct { <API key> function; void *object; } Packet_Handles; typedef struct { Packet_Handles packethandlers[256]; sa_family_t family; uint16_t port; /* Our UDP socket. */ sock_t sock; } Networking_Core; /* Run this before creating sockets. * * return 0 on success * return -1 on failure */ int <API key>(void); /* Check if socket is valid. * * return 1 if valid * return 0 if not valid */ int sock_valid(sock_t sock); /* Close the socket. */ void kill_sock(sock_t sock); /* Set socket as nonblocking * * return 1 on success * return 0 on failure */ int set_socket_nonblock(sock_t sock); /* Set socket to not emit SIGPIPE * * return 1 on success * return 0 on failure */ int <API key>(sock_t sock); /* Enable SO_REUSEADDR on socket. * * return 1 on success * return 0 on failure */ int <API key>(sock_t sock); /* Set socket to dual (IPv4 + IPv6 socket) * * return 1 on success * return 0 on failure */ int <API key>(sock_t sock); /* return current monotonic time in milliseconds (ms). */ uint64_t <API key>(void); /* Basic network functions: */ /* Function to send packet(data) of length length to ip_port. */ int sendpacket(Networking_Core *net, IP_Port ip_port, const uint8_t *data, uint16_t length); /* Function to call when packet beginning with byte is received. */ void <API key>(Networking_Core *net, uint8_t byte, <API key> cb, void *object); /* Call this several times a second. */ void networking_poll(Networking_Core *net); /* Initialize networking. * bind to ip and port. * ip must be in network order EX: 127.0.0.1 = (7F000001). * port is in host byte order (this means don't worry about it). * * return Networking_Core object if no problems * return NULL if there are problems. * * If error is non NULL it is set to 0 if no issues, 1 if socket related error, 2 if other. */ Networking_Core *new_networking(IP ip, uint16_t port); Networking_Core *new_networking_ex(IP ip, uint16_t port_from, uint16_t port_to, unsigned int *error); /* Function to cleanup networking stuff (doesn't do much right now). */ void kill_networking(Networking_Core *net); #endif
package com.thundermoose.plugins.utils; import com.atlassian.sal.api.auth.LoginUriProvider; import org.joda.time.DateTime; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.util.UUID; public class Utils { private final LoginUriProvider loginUriProvider; public Utils(LoginUriProvider loginUriProvider) { this.loginUriProvider = loginUriProvider; } public void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendRedirect(loginUriProvider.getLoginUri(getUri(request)).toASCIIString()); } public URI getUri(HttpServletRequest request) { StringBuffer builder = request.getRequestURL(); if (request.getQueryString() != null) { builder.append("?"); builder.append(request.getQueryString()); } return URI.create(builder.toString()); } /** * Generates an unencrypted token string with 4 parts separated by colons * <ul> * <li>username</li> * <li>created date</li> * <li>expiration date</li> * <li>random padding string</li> * </ul> * * @param username * @param ttl * @return */ public String <API key>(String username, Integer ttl) { return username + ":" + System.currentTimeMillis() + ":" + DateTime.now().plusDays(ttl).getMillis() + ":" + UUID.randomUUID().toString(); } public static String createRegexFromGlob(String line) { if (line.endsWith("**")) { String chopped = line.substring(0, line.length() - 2); if (!chopped.endsWith("/")) { throw new <API key>("Glob operator must be preceeded by a '/' character"); } String single = regexWildcard(<API key>(chopped.substring(0, chopped.length() - 1))); return regexWildcard(<API key>(chopped)) + ".*|" + single; } else { //can't support globs that aren't at the end, make sure there aren't any if (line.replaceAll("(\\*\\*)", "").length() != line.length()) { throw new <API key>("Glob operator (**) can only be at the end of a path"); } return regexWildcard(<API key>(line)); } } public static String <API key>(String line) { return line.replaceAll("\\.", "\\\\.").replaceAll("\\+", "\\\\+"); } public static String regexWildcard(String line) { return line.replaceAll("(\\*)", "[^/]*"); } }
using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace ShareX.UploadersLib { <summary> Inherited ListView to allow in-place editing of subitems </summary> public class ListViewEx : ListView { #region Interop structs, imports and constants <summary> MessageHeader for WM_NOTIFY </summary> [StructLayout(LayoutKind.Sequential)] private struct NMHDR { public IntPtr hwndFrom; public Int32 idFrom; public Int32 code; } [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wPar, IntPtr lPar); [DllImport("user32.dll", CharSet = CharSet.Ansi)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int len, ref int[] order); // ListView messages private const int LVM_FIRST = 0x1000; private const int <API key> = LVM_FIRST + 59; // Windows Messages that will abort editing private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int WM_SIZE = 0x05; private const int WM_NOTIFY = 0x4E; private const int HDN_FIRST = -300; private const int HDN_BEGINDRAG = HDN_FIRST - 10; private const int HDN_ITEMCHANGINGA = HDN_FIRST - 0; private const int HDN_ITEMCHANGINGW = HDN_FIRST - 20; #endregion Interop structs, imports and constants <summary> Required designer variable. </summary> private Container components; public event SubItemEventHandler SubItemClicked; public event SubItemEventHandler SubItemBeginEditing; public event <API key> SubItemEndEditing; public ListViewEx() { <API key> = false; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); FullRowSelect = true; View = View.Details; AllowColumnReorder = true; } <summary> Clean up any resources being used. </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { components = new Container(); } #endregion Component Designer generated code <summary> Is a double click required to start editing a cell? </summary> public bool <API key> { get; set; } <summary> Retrieve the order in which columns appear </summary> <returns>Current display order of column indices</returns> public int[] GetColumnOrder() { IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count); IntPtr res = SendMessage(Handle, <API key>, new IntPtr(Columns.Count), lPar); if (res.ToInt32() == 0) // Something went wrong { Marshal.FreeHGlobal(lPar); return null; } int[] order = new int[Columns.Count]; Marshal.Copy(lPar, order, 0, Columns.Count); Marshal.FreeHGlobal(lPar); return order; } <summary> Find ListViewItem and SubItem Index at position (x,y) </summary> <param name="x">relative to ListView</param> <param name="y">relative to ListView</param> <param name="item">Item at position (x,y)</param> <returns>SubItem index</returns> public int GetSubItemAt(int x, int y, out ListViewItem item) { item = GetItemAt(x, y); if (item != null) { int[] order = GetColumnOrder(); Rectangle lviBounds = item.GetBounds(ItemBoundsPortion.Entire); int subItemX = lviBounds.Left; foreach (int t in order) { ColumnHeader h = Columns[t]; if (x < subItemX + h.Width) { return h.Index; } subItemX += h.Width; } } return -1; } <summary> Get bounds for a SubItem </summary> <param name="Item">Target ListViewItem</param> <param name="SubItem">Target SubItem index</param> <returns>Bounds of SubItem (relative to ListView)</returns> public Rectangle GetSubItemBounds(ListViewItem Item, int SubItem) { int[] order = GetColumnOrder(); if (SubItem >= order.Length) throw new <API key>("SubItem " + SubItem + " out of range"); if (Item == null) throw new <API key>("Item"); Rectangle lviBounds = Item.GetBounds(ItemBoundsPortion.Entire); int subItemX = lviBounds.Left; ColumnHeader col; int i; for (i = 0; i < order.Length; i++) { col = Columns[order[i]]; if (col.Index == SubItem) break; subItemX += col.Width; } Rectangle subItemRect = new Rectangle(subItemX, lviBounds.Top, Columns[order[i]].Width, lviBounds.Height); return subItemRect; } protected override void WndProc(ref Message msg) { switch (msg.Msg) { // Look for WM_VSCROLL,WM_HSCROLL or WM_SIZE messages. case WM_VSCROLL: case WM_HSCROLL: case WM_SIZE: EndEditing(false); break; case WM_NOTIFY: // Look for WM_NOTIFY of events that might also change the // editor's position/size: Column reordering or resizing NMHDR h = (NMHDR)Marshal.PtrToStructure(msg.LParam, typeof(NMHDR)); if (h.code == HDN_BEGINDRAG || h.code == HDN_ITEMCHANGINGA || h.code == HDN_ITEMCHANGINGW) EndEditing(false); break; } base.WndProc(ref msg); } #region Initialize editing depending of <API key> property protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (<API key>) { return; } EditSubitemAt(new Point(e.X, e.Y)); } protected override void OnDoubleClick(EventArgs e) { base.OnDoubleClick(e); if (!<API key>) { return; } Point pt = PointToClient(Cursor.Position); EditSubitemAt(pt); } <summary> Fire SubItemClicked </summary> <param name="p">Point of click/doubleclick</param> private void EditSubitemAt(Point p) { ListViewItem item; int idx = GetSubItemAt(p.X, p.Y, out item); if (idx >= 0) { OnSubItemClicked(new SubItemEventArgs(item, idx)); } } #endregion Initialize editing depending of <API key> property #region In-place editing functions // The control performing the actual editing private Control _editingControl; // The LVI being edited private ListViewItem _editItem; // The SubItem being edited private int _editSubItem; protected void <API key>(SubItemEventArgs e) { if (SubItemBeginEditing != null) SubItemBeginEditing(this, e); } protected void OnSubItemEndEditing(<API key> e) { if (SubItemEndEditing != null) SubItemEndEditing(this, e); } protected void OnSubItemClicked(SubItemEventArgs e) { if (SubItemClicked != null) SubItemClicked(this, e); } <summary> Begin in-place editing of given cell </summary> <param name="c">Control used as cell editor</param> <param name="Item">ListViewItem to edit</param> <param name="SubItem">SubItem index to edit</param> public void StartEditing(Control c, ListViewItem Item, int SubItem) { <API key>(new SubItemEventArgs(Item, SubItem)); Rectangle rcSubItem = GetSubItemBounds(Item, SubItem); if (rcSubItem.X < 0) { // Left edge of SubItem not visible - adjust rectangle position and width rcSubItem.Width += rcSubItem.X; rcSubItem.X = 0; } if (rcSubItem.X + rcSubItem.Width > Width) { // Right edge of SubItem not visible - adjust rectangle width rcSubItem.Width = Width - rcSubItem.Left; } // Subitem bounds are relative to the location of the ListView! rcSubItem.Offset(Left, Top); // In case the editing control and the listview are on different parents, // account for different origins Point origin = new Point(0, 0); Point lvOrigin = Parent.PointToScreen(origin); Point ctlOrigin = c.Parent.PointToScreen(origin); rcSubItem.Offset(lvOrigin.X - ctlOrigin.X, lvOrigin.Y - ctlOrigin.Y); // Position and show editor c.Bounds = rcSubItem; c.Text = Item.SubItems[SubItem].Text; c.Visible = true; c.BringToFront(); c.Focus(); _editingControl = c; _editingControl.Leave += _editControl_Leave; _editingControl.KeyPress += <API key>; _editItem = Item; _editSubItem = SubItem; } private void _editControl_Leave(object sender, EventArgs e) { // cell editor losing focus EndEditing(true); } private void <API key>(object sender, KeyPressEventArgs e) { switch (e.KeyChar) { case (char)(int)Keys.Escape: { EndEditing(false); break; } case (char)(int)Keys.Enter: { EndEditing(true); break; } } } <summary> Accept or discard current value of cell editor control </summary> <param name="AcceptChanges">Use the _editingControl's Text as new SubItem text or discard changes?</param> public void EndEditing(bool AcceptChanges) { if (_editingControl == null) return; <API key> e = new <API key>( _editItem, // The item being edited _editSubItem, // The subitem index being edited AcceptChanges ? _editingControl.Text : // Use editControl text if changes are accepted _editItem.SubItems[_editSubItem].Text, // or the original subitem's text, if changes are discarded !AcceptChanges // Cancel? ); OnSubItemEndEditing(e); if (!string.IsNullOrEmpty(e.DisplayText)) { _editItem.SubItems[_editSubItem].Text = e.DisplayText; } _editingControl.Leave -= _editControl_Leave; _editingControl.KeyPress -= <API key>; _editingControl.Visible = false; _editingControl = null; _editItem = null; _editSubItem = -1; } #endregion In-place editing functions } <summary> Event Handler for SubItem events </summary> public delegate void SubItemEventHandler(object sender, SubItemEventArgs e); <summary> Event Handler for SubItemEndEditing events </summary> public delegate void <API key>(object sender, <API key> e); <summary> Event Args for SubItemClicked event </summary> public class SubItemEventArgs : EventArgs { public SubItemEventArgs(ListViewItem item, int subItem) { _subItemIndex = subItem; _item = item; } private int _subItemIndex = -1; private ListViewItem _item; public int SubItem { get { return _subItemIndex; } } public ListViewItem Item { get { return _item; } } } <summary> Event Args for <API key> event </summary> public class <API key> : SubItemEventArgs { private string _text = string.Empty; private bool _cancel = true; public <API key>(ListViewItem item, int subItem, string display, bool cancel) : base(item, subItem) { _text = display; _cancel = cancel; } public string DisplayText { get { return _text; } set { _text = value; } } public bool Cancel { get { return _cancel; } set { _cancel = value; } } } }
# p2p-adb # @theKos # kyle@kyleosborn.com # Registering command registerCommand "6:installAnti:Install/Uninstall AntiGuard" installAnti(){ adb shell pm list packages | grep io.kos.antiguard 2>/dev/null > /dev/null isInstalled=$? if [ $isInstalled -eq 0 ]; then adb uninstall io.kos.antiguard else adb install ./AntiGuard/AntiGuard.apk adb shell am start -S io.kos.antiguard/.unlock fi }
""" Unit tests for refactor.py. """ import sys import os import codecs import io import re import tempfile import shutil import unittest from lib2to3 import refactor, pygram, fixer_base from lib2to3.pgen2 import token TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") FIXER_DIR = os.path.join(TEST_DATA_DIR, "fixers") sys.path.append(FIXER_DIR) try: _DEFAULT_FIXERS = refactor.<API key>("myfixes") finally: sys.path.pop() _2TO3_FIXERS = refactor.<API key>("lib2to3.fixes") class TestRefactoringTool(unittest.TestCase): def setUp(self): sys.path.append(FIXER_DIR) def tearDown(self): sys.path.pop() def check_instances(self, instances, classes): for inst, cls in zip(instances, classes): if not isinstance(inst, cls): self.fail("%s are not instances of %s" % instances, classes) def rt(self, options=None, fixers=_DEFAULT_FIXERS, explicit=None): return refactor.RefactoringTool(fixers, options, explicit) def <API key>(self): rt = self.rt({"print_function" : True}) self.assertIs(rt.grammar, pygram.<API key>) self.assertIs(rt.driver.grammar, pygram.<API key>) def <API key>(self): rt = self.rt() self.assertFalse(rt.<API key>) rt = self.rt({"<API key>" : True}) self.assertTrue(rt.<API key>) def <API key>(self): contents = ["explicit", "first", "last", "parrot", "preorder"] non_prefixed = refactor.get_all_fix_names("myfixes") prefixed = refactor.get_all_fix_names("myfixes", False) full_names = refactor.<API key>("myfixes") self.assertEqual(prefixed, ["fix_" + name for name in contents]) self.assertEqual(non_prefixed, contents) self.assertEqual(full_names, ["myfixes.fix_" + name for name in contents]) def <API key>(self): run = refactor.<API key> fs = frozenset empty = fs() self.assertEqual(run(""), empty) self.assertEqual(run("from __future__ import print_function"), fs(("print_function",))) self.assertEqual(run("from __future__ import generators"), fs(("generators",))) self.assertEqual(run("from __future__ import generators, feature"), fs(("generators", "feature"))) inp = "from __future__ import generators, print_function" self.assertEqual(run(inp), fs(("generators", "print_function"))) inp ="from __future__ import print_function, generators" self.assertEqual(run(inp), fs(("print_function", "generators"))) inp = "from __future__ import (print_function,)" self.assertEqual(run(inp), fs(("print_function",))) inp = "from __future__ import (generators, print_function)" self.assertEqual(run(inp), fs(("generators", "print_function"))) inp = "from __future__ import (generators, nested_scopes)" self.assertEqual(run(inp), fs(("generators", "nested_scopes"))) inp = """from __future__ import generators from __future__ import print_function""" self.assertEqual(run(inp), fs(("generators", "print_function"))) invalid = ("from", "from 4", "from x", "from x 5", "from x im", "from x import", "from x import 4", ) for inp in invalid: self.assertEqual(run(inp), empty) inp = "'docstring'\nfrom __future__ import print_function" self.assertEqual(run(inp), fs(("print_function",))) inp = "'docstring'\n'somng'\nfrom __future__ import print_function" self.assertEqual(run(inp), empty) inp = "# comment\nfrom __future__ import print_function" self.assertEqual(run(inp), fs(("print_function",))) inp = "# comment\n'doc'\nfrom __future__ import print_function" self.assertEqual(run(inp), fs(("print_function",))) inp = "class x: pass\nfrom __future__ import print_function" self.assertEqual(run(inp), empty) def <API key>(self): class NoneFix(fixer_base.BaseFix): pass class FileInputFix(fixer_base.BaseFix): PATTERN = "file_input< any * >" class SimpleFix(fixer_base.BaseFix): PATTERN = "'name'" no_head = NoneFix({}, []) with_head = FileInputFix({}, []) simple = SimpleFix({}, []) d = refactor._get_headnode_dict([no_head, with_head, simple]) top_fixes = d.pop(pygram.python_symbols.file_input) self.assertEqual(top_fixes, [with_head, no_head]) name_fixes = d.pop(token.NAME) self.assertEqual(name_fixes, [simple, no_head]) for fixes in d.values(): self.assertEqual(fixes, [no_head]) def test_fixer_loading(self): from myfixes.fix_first import FixFirst from myfixes.fix_last import FixLast from myfixes.fix_parrot import FixParrot from myfixes.fix_preorder import FixPreorder rt = self.rt() pre, post = rt.get_fixers() self.check_instances(pre, [FixPreorder]) self.check_instances(post, [FixFirst, FixParrot, FixLast]) def test_naughty_fixers(self): self.assertRaises(ImportError, self.rt, fixers=["not_here"]) self.assertRaises(refactor.FixerError, self.rt, fixers=["no_fixer_cls"]) self.assertRaises(refactor.FixerError, self.rt, fixers=["bad_order"]) def <API key>(self): rt = self.rt() input = "def parrot(): pass\n\n" tree = rt.refactor_string(input, "<test>") self.assertNotEqual(str(tree), input) input = "def f(): pass\n\n" tree = rt.refactor_string(input, "<test>") self.assertEqual(str(tree), input) def test_refactor_stdin(self): class MyRT(refactor.RefactoringTool): def print_output(self, old_text, new_text, filename, equal): results.extend([old_text, new_text, filename, equal]) results = [] rt = MyRT(_DEFAULT_FIXERS) save = sys.stdin sys.stdin = io.StringIO("def parrot(): pass\n\n") try: rt.refactor_stdin() finally: sys.stdin = save expected = ["def parrot(): pass\n\n", "def cheese(): pass\n\n", "<stdin>", False] self.assertEqual(results, expected) def <API key>(self, test_file, fixers=_2TO3_FIXERS, options=None, mock_log_debug=None, actually_write=True): test_file = self.init_test_file(test_file) old_contents = self.read_file(test_file) rt = self.rt(fixers=fixers, options=options) if mock_log_debug: rt.log_debug = mock_log_debug rt.refactor_file(test_file) self.assertEqual(old_contents, self.read_file(test_file)) if not actually_write: return rt.refactor_file(test_file, True) new_contents = self.read_file(test_file) self.assertNotEqual(old_contents, new_contents) return new_contents def init_test_file(self, test_file): tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor") self.addCleanup(shutil.rmtree, tmpdir) shutil.copy(test_file, tmpdir) test_file = os.path.join(tmpdir, os.path.basename(test_file)) os.chmod(test_file, 0o644) return test_file def read_file(self, test_file): with open(test_file, "rb") as fp: return fp.read() def refactor_file(self, test_file, fixers=_2TO3_FIXERS): test_file = self.init_test_file(test_file) old_contents = self.read_file(test_file) rt = self.rt(fixers=fixers) rt.refactor_file(test_file, True) new_contents = self.read_file(test_file) return old_contents, new_contents def test_refactor_file(self): test_file = os.path.join(FIXER_DIR, "parrot_example.py") self.<API key>(test_file, _DEFAULT_FIXERS) def <API key>(self): test_file = os.path.join(FIXER_DIR, "parrot_example.py") debug_messages = [] def recording_log_debug(msg, *args): debug_messages.append(msg % args) self.<API key>(test_file, fixers=(), options={"<API key>": True}, mock_log_debug=recording_log_debug, actually_write=False) # Testing that it logged this message when write=False was passed is # sufficient to see that it did not bail early after "No changes". message_regex = r"Not writing changes to .*%s" % \ re.escape(os.sep + os.path.basename(test_file)) for message in debug_messages: if "Not writing changes" in message: self.assertRegex(message, message_regex) break else: self.fail("%r not matched in %r" % (message_regex, debug_messages)) def test_refactor_dir(self): def check(structure, expected): def mock_refactor_file(self, f, *args): got.append(f) save_func = refactor.RefactoringTool.refactor_file refactor.RefactoringTool.refactor_file = mock_refactor_file rt = self.rt() got = [] dir = tempfile.mkdtemp(prefix="2to3-test_refactor") try: os.mkdir(os.path.join(dir, "a_dir")) for fn in structure: open(os.path.join(dir, fn), "wb").close() rt.refactor_dir(dir) finally: refactor.RefactoringTool.refactor_file = save_func shutil.rmtree(dir) self.assertEqual(got, [os.path.join(dir, path) for path in expected]) check([], []) tree = ["nothing", "hi.py", ".dumb", ".after.py", "notpy.npy", "sappy"] expected = ["hi.py"] check(tree, expected) tree = ["hi.py", os.path.join("a_dir", "stuff.py")] check(tree, tree) def test_file_encoding(self): fn = os.path.join(TEST_DATA_DIR, "different_encoding.py") self.<API key>(fn) def <API key>(self): fn = os.path.join(TEST_DATA_DIR, "false_encoding.py") data = self.<API key>(fn) def test_bom(self): fn = os.path.join(TEST_DATA_DIR, "bom.py") data = self.<API key>(fn) self.assertTrue(data.startswith(codecs.BOM_UTF8)) def test_crlf_newlines(self): old_sep = os.linesep os.linesep = "\r\n" try: fn = os.path.join(TEST_DATA_DIR, "crlf.py") fixes = refactor.<API key>("lib2to3.fixes") self.<API key>(fn, fixes) finally: os.linesep = old_sep def test_crlf_unchanged(self): fn = os.path.join(TEST_DATA_DIR, "crlf.py") old, new = self.refactor_file(fn) self.assertIn(b"\r\n", old) self.assertIn(b"\r\n", new) def <API key>(self): rt = self.rt() doc = """ example() 42 """ out = rt.refactor_docstring(doc, "<test>") self.assertEqual(out, doc) doc = """ def parrot(): return 43 """ out = rt.refactor_docstring(doc, "<test>") self.assertNotEqual(out, doc) def test_explicit(self): from myfixes.fix_explicit import FixExplicit rt = self.rt(fixers=["myfixes.fix_explicit"]) self.assertEqual(len(rt.post_order), 0) rt = self.rt(explicit=["myfixes.fix_explicit"]) for fix in rt.post_order: if isinstance(fix, FixExplicit): break else: self.fail("explicit fixer not loaded")
<?php // Amazon S3 SDK v2.8.27 // http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region class <API key> extends <API key> { /** * @return array */ public function option_defaults() { return array( 's3accesskey' => '', 's3secretkey' => '', 's3bucket' => '', 's3region' => 'us-east-1', 's3base_url' => '', 's3ssencrypt' => '', 's3storageclass' => '', 's3dir' => trailingslashit( sanitize_file_name( get_bloginfo( 'name' ) ) ), 's3maxbackups' => 15, 's3syncnodelete' => TRUE, 's3multipart' => TRUE ); } /** * @param $jobid */ public function edit_tab( $jobid ) { ?> <h3 class="title"><?php esc_html_e( 'S3 Service', 'backwpup' ) ?></h3> <p></p> <table class="form-table"> <tr> <th scope="row"><label for="s3region"><?php esc_html_e( 'Select a S3 service', 'backwpup' ) ?></label></th> <td> <select name="s3region" id="s3region" title="<?php esc_html_e( 'Amazon S3 Region', 'backwpup' ); ?>"> <option value="us-east-1" <?php selected( 'us-east-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: US Standard', 'backwpup' ); ?></option> <option value="us-west-1" <?php selected( 'us-west-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: US West (Northern California)', 'backwpup' ); ?></option> <option value="us-west-2" <?php selected( 'us-west-2', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: US West (Oregon)', 'backwpup' ); ?></option> <option value="eu-west-1" <?php selected( 'eu-west-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: EU (Ireland)', 'backwpup' ); ?></option> <option value="eu-central-1" <?php selected( 'eu-central-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: EU (Germany)', 'backwpup' ); ?></option> <option value="ap-south-1" <?php selected( 'ap-south-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: Asia Pacific (Mumbai)', 'backwpup' ); ?></option> <option value="ap-northeast-1" <?php selected( 'ap-northeast-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: Asia Pacific (Tokyo)', 'backwpup' ); ?></option> <option value="ap-northeast-2" <?php selected( 'ap-northeast-2', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: Asia Pacific (Seoul)', 'backwpup' ); ?></option> <option value="ap-southeast-1" <?php selected( 'ap-southeast-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: Asia Pacific (Singapore)', 'backwpup' ); ?></option> <option value="ap-southeast-2" <?php selected( 'ap-southeast-2', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: Asia Pacific (Sydney)', 'backwpup' ); ?></option> <option value="sa-east-1" <?php selected( 'sa-east-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: South America (Sao Paulo)', 'backwpup' ); ?></option> <option value="cn-north-1" <?php selected( 'cn-north-1', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Amazon S3: China (Beijing)', 'backwpup' ); ?></option> <option value="google-storage" <?php selected( 'google-storage', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Google Storage: EU', 'backwpup' ); ?></option> <option value="google-storage-us" <?php selected( 'google-storage-us', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Google Storage: USA', 'backwpup' ); ?></option> <option value="google-storage-asia" <?php selected( 'google-storage-asia', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Google Storage: Asia', 'backwpup' ); ?></option> <option value="dreamhost" <?php selected( 'dreamhost', BackWPup_Option::get( $jobid, 's3region' ), TRUE ) ?>><?php esc_html_e( 'Dream Host Cloud Storage', 'backwpup' ); ?></option> </select> </td> </tr> <tr> <th scope="row"><label for="s3base_url"><?php esc_html_e( 'Or a S3 Server URL', 'backwpup' ) ?></label></th> <td> <input id="s3base_url" name="s3base_url" type="text" value="<?php echo esc_attr( BackWPup_Option::get( $jobid, 's3base_url' ) );?>" class="regular-text" autocomplete="off" /> </td> </tr> </table> <h3 class="title"><?php esc_html_e( 'S3 Access Keys', 'backwpup' ); ?></h3> <p></p> <table class="form-table"> <tr> <th scope="row"><label for="s3accesskey"><?php esc_html_e( 'Access Key', 'backwpup' ); ?></label></th> <td> <input id="s3accesskey" name="s3accesskey" type="text" value="<?php echo esc_attr( BackWPup_Option::get( $jobid, 's3accesskey' ) );?>" class="regular-text" autocomplete="off" /> </td> </tr> <tr> <th scope="row"><label for="s3secretkey"><?php esc_html_e( 'Secret Key', 'backwpup' ); ?></label></th> <td> <input id="s3secretkey" name="s3secretkey" type="password" value="<?php echo esc_attr( BackWPup_Encryption::decrypt( BackWPup_Option::get( $jobid, 's3secretkey' ) ) ); ?>" class="regular-text" autocomplete="off" /> </td> </tr> </table> <h3 class="title"><?php esc_html_e( 'S3 Bucket', 'backwpup' ); ?></h3> <p></p> <table class="form-table"> <tr> <th scope="row"><label for="s3bucketselected"><?php esc_html_e( 'Bucket selection', 'backwpup' ); ?></label></th> <td> <input id="s3bucketselected" name="s3bucketselected" type="hidden" value="<?php echo esc_attr( BackWPup_Option::get( $jobid, 's3bucket' ) ); ?>" /> <?php if ( BackWPup_Option::get( $jobid, 's3accesskey' ) && BackWPup_Option::get( $jobid, 's3secretkey' ) ) $this->edit_ajax( array( 's3accesskey' => BackWPup_Option::get( $jobid, 's3accesskey' ), 's3secretkey' => BackWPup_Encryption::decrypt(BackWPup_Option::get( $jobid, 's3secretkey' ) ), 's3bucketselected' => BackWPup_Option::get( $jobid, 's3bucket' ), 's3base_url' => BackWPup_Option::get( $jobid, 's3base_url' ), 's3region' => BackWPup_Option::get( $jobid, 's3region' ) ) ); ?> </td> </tr> <tr> <th scope="row"><label for="s3newbucket"><?php esc_html_e( 'Create a new bucket', 'backwpup' ); ?></label></th> <td> <input id="s3newbucket" name="s3newbucket" type="text" value="" class="small-text" autocomplete="off" /> </td> </tr> </table> <h3 class="title"><?php esc_html_e( 'S3 Backup settings', 'backwpup' ); ?></h3> <p></p> <table class="form-table"> <tr> <th scope="row"><label for="ids3dir"><?php esc_html_e( 'Folder in bucket', 'backwpup' ); ?></label></th> <td> <input id="ids3dir" name="s3dir" type="text" value="<?php echo esc_attr( BackWPup_Option::get( $jobid, 's3dir' ) ); ?>" class="regular-text" /> </td> </tr> <tr> <th scope="row"><?php esc_html_e( 'File deletion', 'backwpup' ); ?></th> <td> <?php if ( BackWPup_Option::get( $jobid, 'backuptype' ) === 'archive' ) { ?> <label for="ids3maxbackups"> <input id="ids3maxbackups" name="s3maxbackups" type="number" min="0" step="1" value="<?php echo esc_attr( BackWPup_Option::get( $jobid, 's3maxbackups' ) ); ?>" class="small-text" /> &nbsp;<?php esc_html_e( 'Number of files to keep in folder.', 'backwpup' ); ?> </label> <p><?php _e( '<strong>Warning</strong>: Files belonging to this job are now tracked. Old backup archives which are untracked will not be automatically deleted.', 'backwpup' ) ?></p> <?php } else { ?> <label for="ids3syncnodelete"> <input class="checkbox" value="1" type="checkbox" <?php checked( BackWPup_Option::get( $jobid, 's3syncnodelete' ), true ); ?> name="s3syncnodelete" id="ids3syncnodelete" /> &nbsp;<?php esc_html_e( 'Do not delete files while syncing to destination!', 'backwpup' ); ?> </label> <?php } ?> </td> </tr> <?php if ( BackWPup_Option::get( $jobid, 'backuptype' ) === 'archive' ) { ?> <tr> <th scope="row"><?php esc_html_e( 'Multipart Upload', 'backwpup' ); ?></th> <td> <label for="ids3multipart"><input class="checkbox" value="1" type="checkbox" <?php checked( BackWPup_Option::get( $jobid, 's3multipart' ), TRUE ); ?> name="s3multipart" id="ids3multipart" /> <?php esc_html_e( 'Use multipart upload for uploading a file', 'backwpup' ); ?></label> <p class="description"><?php esc_attr_e( 'Multipart splits file into multiple chunks while uploading. This is necessary for displaying the upload process and to transfer bigger files. Works without a problem on Amazon. Other services might have issues.', 'backwpup'); ?></p> </td> </tr> <?php } ?> </table> <h3 class="title"><?php esc_html_e( 'Amazon specific settings', 'backwpup' ); ?></h3> <p></p> <table class="form-table"> <tr> <th scope="row"><label for="ids3storageclass"><?php esc_html_e( 'Amazon: Storage Class', 'backwpup' ); ?></label></th> <td> <select name="s3storageclass" id="ids3storageclass" title="<?php esc_html_e( 'Amazon: Storage Class', 'backwpup' ); ?>"> <option value="" <?php selected( '', BackWPup_Option::get( $jobid, 's3storageclass' ), TRUE ) ?>><?php esc_html_e( 'Standard', 'backwpup' ); ?></option> <option value="STANDARD_IA" <?php selected( 'STANDARD_IA', BackWPup_Option::get( $jobid, 's3storageclass' ), TRUE ) ?>><?php esc_html_e( 'Standard-Infrequent Access', 'backwpup' ); ?></option> <option value="REDUCED_REDUNDANCY" <?php selected( 'REDUCED_REDUNDANCY', BackWPup_Option::get( $jobid, 's3storageclass' ), TRUE ) ?>><?php esc_html_e( 'Reduced Redundancy', 'backwpup' ); ?></option> </select> </td> </tr> <tr> <th scope="row"><label for="ids3ssencrypt"><?php esc_html_e( 'Server side encryption', 'backwpup' ); ?></label></th> <td> <input class="checkbox" value="AES256" type="checkbox" <?php checked( BackWPup_Option::get( $jobid, 's3ssencrypt' ), 'AES256' ); ?> name="s3ssencrypt" id="ids3ssencrypt" /> <?php esc_html_e( 'Save files encrypted (AES256) on server.', 'backwpup' ); ?> </td> </tr> </table> <?php } /** * @param string $args */ public function edit_ajax( $args = '' ) { $error = ''; $buckets_list = array(); if ( is_array( $args ) ) { $ajax = FALSE; } else { if ( ! current_user_can( 'backwpup_jobs_edit' ) ) { wp_die( -1 ); } check_ajax_referer( 'backwpup_ajax_nonce' ); $args = array(); $args[ 's3accesskey' ] = sanitize_text_field( $_POST[ 's3accesskey' ] ); $args[ 's3secretkey' ] = sanitize_text_field( $_POST[ 's3secretkey' ] ); $args[ 's3bucketselected' ] = sanitize_text_field( $_POST[ 's3bucketselected' ] ); $args[ 's3base_url' ] = esc_url_raw( $_POST[ 's3base_url' ] ); $args[ 's3region' ] = sanitize_text_field( $_POST[ 's3region' ] ); $ajax = TRUE; } echo '<span id="s3bucketerror" style="color:red;">'; if ( ! empty( $args[ 's3accesskey' ] ) && ! empty( $args[ 's3secretkey' ] ) ) { try { $s3 = Aws\S3\S3Client::factory( array( 'key' => $args[ 's3accesskey' ], 'secret' => BackWPup_Encryption::decrypt( $args[ 's3secretkey' ] ), 'region' => $args[ 's3region' ], 'base_url' => $this->get_s3_base_url( $args[ 's3region' ], $args[ 's3base_url' ]), 'scheme' => 'https', 'ssl.<API key>' => BackWPup::get_plugin_data( 'cacert' ) ) ); $buckets = $s3->listBuckets(); if ( ! empty( $buckets['Buckets'] ) ) { $buckets_list = $buckets['Buckets']; } while ( ! empty( $vaults['Marker'] ) ) { $buckets = $s3->listBuckets( array( 'marker' => $buckets['Marker'] ) ); if ( ! empty( $buckets['Buckets'] ) ) { $buckets_list = array_merge( $buckets_list, $buckets['Buckets'] ); } } } catch ( Exception $e ) { $error = $e->getMessage(); } } if ( empty( $args[ 's3accesskey' ] ) ) _e( 'Missing access key!', 'backwpup' ); elseif ( empty( $args[ 's3secretkey' ] ) ) _e( 'Missing secret access key!', 'backwpup' ); elseif ( ! empty( $error ) && $error == 'Access Denied' ) echo '<input type="text" name="s3bucket" id="s3bucket" value="' . esc_attr( $args[ 's3bucketselected' ] ) . '" >'; elseif ( ! empty( $error ) ) echo esc_html( $error ); elseif ( ! isset( $buckets ) || count( $buckets['Buckets'] ) < 1 ) _e( 'No bucket found!', 'backwpup' ); echo '</span>'; if ( !empty( $buckets_list ) ) { echo '<select name="s3bucket" id="s3bucket">'; foreach ( $buckets_list as $bucket ) { echo "<option " . selected( $args[ 's3bucketselected' ], esc_attr( $bucket['Name'] ), FALSE ) . ">" . esc_attr( $bucket['Name'] ) . "</option>"; } echo '</select>'; } if ( $ajax ) { die(); } } /** * @param $s3region * @param string $s3base_url * @return string */ protected function get_s3_base_url( $s3region, $s3base_url = '' ) { if ( ! empty( $s3base_url ) ) return $s3base_url; switch ( $s3region ) { case 'us-east-1': return 'https://s3.amazonaws.com'; case 'us-west-1': return 'https://s3-us-west-1.amazonaws.com'; case 'us-west-2': return 'https://s3-us-west-2.amazonaws.com'; case 'eu-west-1': return 'https://s3-eu-west-1.amazonaws.com'; case 'eu-central-1': return 'https://s3-eu-central-1.amazonaws.com'; case 'ap-south-1': return 'https://s3-ap-south-1.amazonaws.com'; case 'ap-northeast-1': return 'https://s3-ap-northeast-1.amazonaws.com'; case 'ap-northeast-2': return 'https://s3-ap-northeast-2.amazonaws.com'; case 'ap-southeast-1': return 'https://s3-ap-southeast-1.amazonaws.com'; case 'ap-southeast-2': return 'https://s3-ap-southeast-2.amazonaws.com'; case 'sa-east-1': return 'https://s3-sa-east-1.amazonaws.com'; case 'cn-north-1': return 'https://cn-north-1.amazonaws.com'; case 'google-storage': return 'https://storage.googleapis.com'; case 'google-storage-us': return 'https://storage.googleapis.com'; case 'google-storage-asia': return 'https://storage.googleapis.com'; case 'dreamhost': return 'https://objects-us-west-1.dream.io'; default: return ''; } } /** * @param $jobid * @return string */ public function edit_form_post_save( $jobid ) { BackWPup_Option::update( $jobid, 's3accesskey', sanitize_text_field( $_POST[ 's3accesskey' ] ) ); BackWPup_Option::update( $jobid, 's3secretkey', isset( $_POST[ 's3secretkey' ] ) ? BackWPup_Encryption::encrypt( $_POST[ 's3secretkey' ] ) : '' ); BackWPup_Option::update( $jobid, 's3base_url', isset( $_POST[ 's3base_url' ] ) ? esc_url_raw( $_POST[ 's3base_url' ] ) : '' ); BackWPup_Option::update( $jobid, 's3region', sanitize_text_field( $_POST[ 's3region' ] ) ); BackWPup_Option::update( $jobid, 's3storageclass', sanitize_text_field( $_POST[ 's3storageclass' ] ) ); BackWPup_Option::update( $jobid, 's3ssencrypt', ( isset( $_POST[ 's3ssencrypt' ] ) && $_POST[ 's3ssencrypt' ] === 'AES256' ) ? 'AES256' : '' ); BackWPup_Option::update( $jobid, 's3bucket', isset( $_POST[ 's3bucket' ] ) ? sanitize_text_field( $_POST[ 's3bucket' ] ) : '' ); $_POST[ 's3dir' ] = trailingslashit( str_replace( '//', '/', str_replace( '\\', '/', trim( sanitize_text_field( $_POST[ 's3dir' ] ) ) ) ) ); if ( substr( $_POST[ 's3dir' ], 0, 1 ) == '/' ) $_POST[ 's3dir' ] = substr( $_POST[ 's3dir' ], 1 ); if ( $_POST[ 's3dir' ] == '/' ) $_POST[ 's3dir' ] = ''; BackWPup_Option::update( $jobid, 's3dir', $_POST[ 's3dir' ] ); BackWPup_Option::update( $jobid, 's3maxbackups', ! empty( $_POST[ 's3maxbackups' ] ) ? absint( $_POST[ 's3maxbackups' ] ) : 0 ); BackWPup_Option::update( $jobid, 's3syncnodelete', ! empty( $_POST[ 's3syncnodelete' ] ) ); BackWPup_Option::update( $jobid, 's3multipart', ! empty( $_POST[ 's3multipart' ] ) ); //create new bucket if ( ! empty( $_POST[ 's3newbucket' ] ) ) { try { $s3 = Aws\S3\S3Client::factory( array( 'key' => sanitize_text_field( $_POST[ 's3accesskey' ] ), 'secret' => sanitize_text_field( $_POST[ 's3secretkey' ] ), 'region' => sanitize_text_field( $_POST[ 's3region' ] ), 'base_url' => $this->get_s3_base_url( sanitize_text_field( $_POST[ 's3region' ] ), esc_url_raw( $_POST[ 's3base_url' ] ) ), 'scheme' => 'https', 'ssl.<API key>' => BackWPup::get_plugin_data( 'cacert' ) ) ); // set bucket creation region if ( $_POST[ 's3region' ] === 'google-storage' ) { $region = 'EU'; } elseif ( $_POST[ 's3region' ] === 'google-storage-us' ) { $region = 'US'; } elseif ( $_POST[ 's3region' ] === 'google-storage-asia' ) { $region = 'ASIA'; } else { $region = sanitize_text_field( $_POST[ 's3region' ] ); } if ($s3->isValidBucketName( $_POST[ 's3newbucket' ] ) ) { $s3->createBucket( array( 'Bucket' => sanitize_text_field( $_POST[ 's3newbucket' ] ), 'LocationConstraint' => $region ) ); $s3->waitUntil( 'bucket_exists', array( 'Bucket' => $_POST[ 's3newbucket' ] ) ); BackWPup_Admin::message( sprintf( __( 'Bucket %1$s created.','backwpup'), sanitize_text_field( $_POST[ 's3newbucket' ] ) ) ); } else { BackWPup_Admin::message( sprintf( __( ' %s is not a valid bucket name.','backwpup'), sanitize_text_field( $_POST[ 's3newbucket' ] ) ), TRUE ); } } catch ( Aws\S3\Exception\S3Exception $e ) { BackWPup_Admin::message( $e->getMessage(), TRUE ); } BackWPup_Option::update( $jobid, 's3bucket', sanitize_text_field( $_POST[ 's3newbucket' ] ) ); } } /** * @param $jobdest * @param $backupfile */ public function file_delete( $jobdest, $backupfile ) { $files = get_site_transient( 'backwpup_'. strtolower( $jobdest ) ); list( $jobid, $dest ) = explode( '_', $jobdest ); if ( BackWPup_Option::get( $jobid, 's3accesskey' ) && BackWPup_Option::get( $jobid, 's3secretkey' ) && BackWPup_Option::get( $jobid, 's3bucket' ) ) { try { $s3 = Aws\S3\S3Client::factory( array( 'key' => BackWPup_Option::get( $jobid, 's3accesskey' ), 'secret' => BackWPup_Encryption::decrypt( BackWPup_Option::get( $jobid, 's3secretkey' ) ), 'region' => BackWPup_Option::get( $jobid, 's3region' ), 'base_url' => $this->get_s3_base_url( BackWPup_Option::get( $jobid, 's3region' ), BackWPup_Option::get( $jobid, 's3base_url' ) ), 'scheme' => 'https', 'ssl.<API key>' => BackWPup::get_plugin_data( 'cacert' ) ) ); $s3->deleteObject( array( 'Bucket' => BackWPup_Option::get( $jobid, 's3bucket' ), 'Key' => $backupfile ) ); //update file list foreach ( (array)$files as $key => $file ) { if ( is_array( $file ) && $file[ 'file' ] == $backupfile ) { unset( $files[ $key ] ); } } unset( $s3 ); } catch ( Exception $e ) { BackWPup_Admin::message( sprintf( __('S3 Service API: %s','backwpup'), $e->getMessage() ), TRUE ); } } set_site_transient( 'backwpup_'. strtolower( $jobdest ), $files, YEAR_IN_SECONDS ); } /** * @param $jobid * @param $get_file */ public function file_download( $jobid, $get_file ) { try { $s3 = Aws\S3\S3Client::factory( array( 'key' => BackWPup_Option::get( $jobid, 's3accesskey' ), 'secret' => BackWPup_Encryption::decrypt( BackWPup_Option::get( $jobid, 's3secretkey' ) ), 'region' => BackWPup_Option::get( $jobid, 's3region' ), 'base_url' => $this->get_s3_base_url( BackWPup_Option::get( $jobid, 's3region' ), BackWPup_Option::get( $jobid, 's3base_url' ) ), 'scheme' => 'https', 'ssl.<API key>' => BackWPup::get_plugin_data( 'cacert' ) ) ); $s3file = $s3->getObject( array( 'Bucket' => BackWPup_Option::get( $jobid, 's3bucket' ), 'Key' => $get_file ) ); } catch ( Exception $e ) { die( $e->getMessage() ); } if ( $s3file[ 'ContentLength' ] > 0 && ! empty( $s3file[ 'ContentType' ] ) ) { if ( $level = ob_get_level() ) { for ( $i = 0; $i < $level; $i ++ ) { ob_end_clean(); } } @set_time_limit( 300 ); nocache_headers(); header( 'Content-Description: File Transfer' ); header( 'Content-Type: ' . BackWPup_Job::get_mime_type( $get_file ) ); header( 'Content-Disposition: attachment; filename="' . basename( $get_file ) . '"' ); header( '<API key>: binary' ); header( 'Content-Length: ' . $s3file[ 'ContentLength' ] ); $body = $s3file->get( 'Body' ); $body->rewind(); while ( $filedata = $body->read( 1024 ) ) { echo $filedata; } die(); } } /** * @param $jobdest * @return mixed */ public function file_get_list( $jobdest ) { return get_site_transient( 'backwpup_' . strtolower( $jobdest ) ); } /** * @param $job_object BAckWPup_Job * @return bool */ public function job_run_archive( BackWPup_Job $job_object ) { $job_object->substeps_todo = 2 + $job_object->backup_filesize; if ( $job_object->steps_data[ $job_object->step_working ]['SAVE_STEP_TRY'] != $job_object->steps_data[ $job_object->step_working ][ 'STEP_TRY' ] ) $job_object->log( sprintf( __( '%d. Trying to send backup file to S3 Service&#160;&hellip;', 'backwpup' ), $job_object->steps_data[ $job_object->step_working ][ 'STEP_TRY' ] ), E_USER_NOTICE ); try { $s3 = Aws\S3\S3Client::factory( array( 'key' => $job_object->job[ 's3accesskey' ], 'secret' => BackWPup_Encryption::decrypt( $job_object->job[ 's3secretkey' ] ), 'region' => $job_object->job[ 's3region' ], 'base_url' => $this->get_s3_base_url( $job_object->job[ 's3region' ], $job_object->job[ 's3base_url' ] ), 'scheme' => 'https', 'ssl.<API key>' => BackWPup::get_plugin_data( 'cacert' ) ) ); if ( $job_object->steps_data[ $job_object->step_working ]['SAVE_STEP_TRY'] != $job_object->steps_data[ $job_object->step_working ][ 'STEP_TRY' ] && $job_object->substeps_done < $job_object->backup_filesize ) { if ( $s3->doesBucketExist( $job_object->job[ 's3bucket' ] ) ) { $bucketregion = $s3->getBucketLocation( array( 'Bucket' => $job_object->job[ 's3bucket' ] ) ); $job_object->log( sprintf( __( 'Connected to S3 Bucket "%1$s" in %2$s', 'backwpup' ), $job_object->job[ 's3bucket' ], $bucketregion->get( 'Location' ) ), E_USER_NOTICE ); } else { $job_object->log( sprintf( __( 'S3 Bucket "%s" does not exist!', 'backwpup' ), $job_object->job[ 's3bucket' ] ), E_USER_ERROR ); return TRUE; } if ( $job_object->job[ 's3multipart' ] && empty( $job_object->steps_data[ $job_object->step_working ][ 'UploadId' ] ) ) { //Check for aboded Multipart Uploads $job_object->log( __( 'Checking for not aborted multipart Uploads&#160;&hellip;', 'backwpup' ) ); $multipart_uploads = $s3-><API key>( array( 'Bucket' => $job_object->job[ 's3bucket' ], 'Prefix' => (string) $job_object->job[ 's3dir' ] ) ); $uploads = $multipart_uploads->get( 'Uploads' ); if ( ! empty( $uploads ) ) { foreach( $uploads as $upload ) { $s3-><API key>( array( 'Bucket' => $job_object->job[ 's3bucket' ], 'Key' => $upload[ 'Key' ], 'UploadId' => $upload[ 'UploadId' ] ) ); $job_object->log( sprintf( __( 'Upload for %s aborted.', 'backwpup' ), $upload[ 'Key' ] ) ); } } } //transfer file to S3 $job_object->log( __( 'Starting upload to S3 Service&#160;&hellip;', 'backwpup' ) ); } if ( ! $job_object->job[ 's3multipart' ] || $job_object->backup_filesize < 1048576 * 6 ) { //Prepare Upload if ( ! $up_file_handle = fopen( $job_object->backup_folder . $job_object->backup_file, 'rb' ) ) { $job_object->log( __( 'Can not open source file for transfer.', 'backwpup' ), E_USER_ERROR ); return FALSE; } $create_args = array(); $create_args[ 'Bucket' ] = $job_object->job[ 's3bucket' ]; $create_args[ 'ACL' ] = 'private'; //encrxption if ( ! empty( $job_object->job[ 's3ssencrypt' ] ) ) { $create_args[ '<API key>' ] = $job_object->job[ 's3ssencrypt' ]; } //Storage Class if ( ! empty( $job_object->job[ 's3storageclass' ] ) ) { $create_args[ 'StorageClass' ] = $job_object->job[ 's3storageclass' ]; } $create_args[ 'Metadata' ] = array( 'BackupTime' => date( 'Y-m-d H:i:s', $job_object->start_time ) ); $create_args[ 'Body' ] = $up_file_handle; $create_args[ 'Key' ] = $job_object->job[ 's3dir' ] . $job_object->backup_file; $create_args[ 'ContentType' ] = $job_object->get_mime_type( $job_object->backup_folder . $job_object->backup_file ); try { $s3->putObject( $create_args ); } catch ( Aws\Common\Exception\<API key> $e ) { $job_object->log( E_USER_ERROR, sprintf( __( 'S3 Service API: %s', 'backwpup' ), $e->getMessage() ), $e->getFile(), $e->getLine() ); return FALSE; } } else { //Prepare Upload if ( $file_handle = fopen( $job_object->backup_folder . $job_object->backup_file, 'rb' ) ) { fseek( $file_handle, $job_object->substeps_done ); try { if ( empty ( $job_object->steps_data[ $job_object->step_working ][ 'UploadId' ] ) ) { $args = array( 'ACL' => 'private', 'Bucket' => $job_object->job[ 's3bucket' ], 'ContentType' => $job_object->get_mime_type( $job_object->backup_folder . $job_object->backup_file ), 'Key' => $job_object->job[ 's3dir' ] . $job_object->backup_file ); if ( !empty( $job_object->job[ 's3ssencrypt' ] ) ) { $args[ '<API key>' ] = $job_object->job[ 's3ssencrypt' ]; } if ( !empty( $job_object->job[ 's3storageclass' ] ) ) { $args[ 'StorageClass' ] = empty( $job_object->job[ 's3storageclass' ] ) ? '' : $job_object->job[ 's3storageclass' ]; } $upload = $s3-><API key>( $args ); $job_object->steps_data[ $job_object->step_working ][ 'UploadId' ] = $upload->get( 'UploadId' ); $job_object->steps_data[ $job_object->step_working ][ 'Parts' ] = array(); $job_object->steps_data[ $job_object->step_working ][ 'Part' ] = 1; } while ( ! feof( $file_handle ) ) { $chunk_upload_start = microtime( TRUE ); $part_data = fread( $file_handle, 1048576 * 5 ); //5MB Minimum part size $part = $s3->uploadPart( array( 'Bucket' => $job_object->job[ 's3bucket' ], 'UploadId' => $job_object->steps_data[ $job_object->step_working ][ 'UploadId' ], 'Key' => $job_object->job[ 's3dir' ] . $job_object->backup_file, 'PartNumber' => $job_object->steps_data[ $job_object->step_working ][ 'Part' ], 'Body' => $part_data ) ); $chunk_upload_time = microtime( TRUE ) - $chunk_upload_start; $job_object->substeps_done = $job_object->substeps_done + strlen( $part_data ); $job_object->steps_data[ $job_object->step_working ][ 'Parts' ][] = array( 'ETag' => $part->get( 'ETag' ), 'PartNumber' => $job_object->steps_data[ $job_object->step_working ][ 'Part' ] ); $job_object->steps_data[ $job_object->step_working ][ 'Part' ]++; $time_remaining = $job_object->do_restart_time(); if ( $time_remaining < $chunk_upload_time ) $job_object->do_restart_time( TRUE ); $job_object->update_working_data(); } $s3-><API key>( array( 'Bucket' => $job_object->job[ 's3bucket' ], 'UploadId' => $job_object->steps_data[ $job_object->step_working ][ 'UploadId' ], 'Key' => $job_object->job[ 's3dir' ] . $job_object->backup_file, 'Parts' => $job_object->steps_data[ $job_object->step_working ][ 'Parts' ] ) ); } catch ( Exception $e ) { $job_object->log( E_USER_ERROR, sprintf( __( 'S3 Service API: %s', 'backwpup' ), $e->getMessage() ), $e->getFile(), $e->getLine() ); if ( ! empty( $job_object->steps_data[ $job_object->step_working ][ 'uploadId' ] ) ) $s3-><API key>( array( 'Bucket' => $job_object->job[ 's3bucket' ], 'UploadId' => $job_object->steps_data[ $job_object->step_working ][ 'uploadId' ], 'Key' => $job_object->job[ 's3dir' ] . $job_object->backup_file ) ); unset( $job_object->steps_data[ $job_object->step_working ][ 'UploadId' ] ); unset( $job_object->steps_data[ $job_object->step_working ][ 'Parts' ] ); unset( $job_object->steps_data[ $job_object->step_working ][ 'Part' ] ); $job_object->substeps_done = 0; if ( is_resource( $file_handle ) ) fclose( $file_handle ); return FALSE; } fclose( $file_handle ); } else { $job_object->log( __( 'Can not open source file for transfer.', 'backwpup' ), E_USER_ERROR ); return FALSE; } } $result = $s3->headObject( array( 'Bucket' => $job_object->job[ 's3bucket' ], 'Key' => $job_object->job[ 's3dir' ] . $job_object->backup_file) ); if ( $result->get( 'ContentLength' ) == filesize( $job_object->backup_folder . $job_object->backup_file ) ) { $job_object->substeps_done = 1 + $job_object->backup_filesize; $job_object->log( sprintf( __( 'Backup transferred to %s.', 'backwpup' ), $this->get_s3_base_url( $job_object->job[ 's3region' ], $job_object->job[ 's3base_url' ] ). '/' .$job_object->job[ 's3bucket' ] . '/' . $job_object->job[ 's3dir' ] . $job_object->backup_file ), E_USER_NOTICE ); if ( ! empty( $job_object->job[ 'jobid' ] ) ) BackWPup_Option::update( $job_object->job[ 'jobid' ], '<API key>', network_admin_url( 'admin.php' ) . '?page=backwpupbackups&action=downloads3&file=' . $job_object->job[ 's3dir' ] . $job_object->backup_file . '&jobid=' . $job_object->job[ 'jobid' ] ); } else { $job_object->log( sprintf( __( 'Cannot transfer backup to S3! (%1$d) %2$s', 'backwpup' ), $result->get( "status" ), $result->get( "Message" ) ), E_USER_ERROR ); } } catch ( Exception $e ) { $job_object->log( E_USER_ERROR, sprintf( __( 'S3 Service API: %s', 'backwpup' ), $e->getMessage() ), $e->getFile(), $e->getLine() ); return FALSE; } try { $backupfilelist = array(); $filecounter = 0; $files = array(); $args = array( 'Bucket' => $job_object->job[ 's3bucket' ], 'Prefix' => (string) $job_object->job[ 's3dir' ] ); $objects = $s3->getIterator('ListObjects', $args ); if ( is_object( $objects ) ) { foreach ( $objects as $object ) { $file = basename( $object[ 'Key' ] ); $changetime = strtotime( $object[ 'LastModified' ] ) + ( get_option( 'gmt_offset' ) * 3600 ); if ( $job_object->is_backup_archive( $file ) && $job_object->owns_backup_archive( $file ) == true ) $backupfilelist[ $changetime ] = $file; $files[ $filecounter ][ 'folder' ] = $this->get_s3_base_url( $job_object->job[ 's3region' ], $job_object->job[ 's3base_url' ] ). '/' .$job_object->job[ 's3bucket' ] . '/' . dirname( $object[ 'Key' ] ); $files[ $filecounter ][ 'file' ] = $object[ 'Key' ]; $files[ $filecounter ][ 'filename' ] = basename( $object[ 'Key' ] ); if ( ! empty( $object[ 'StorageClass' ] ) ) $files[ $filecounter ][ 'info' ] = sprintf( __('Storage Class: %s', 'backwpup' ), $object[ 'StorageClass' ] ); $files[ $filecounter ][ 'downloadurl' ] = network_admin_url( 'admin.php' ) . '?page=backwpupbackups&action=downloads3&file=' . $object[ 'Key' ] . '&jobid=' . $job_object->job[ 'jobid' ]; $files[ $filecounter ][ 'filesize' ] = $object[ 'Size' ]; $files[ $filecounter ][ 'time' ] = $changetime; $filecounter ++; } } if ( $job_object->job[ 's3maxbackups' ] > 0 && is_object( $s3 ) ) { //Delete old backups if ( count( $backupfilelist ) > $job_object->job[ 's3maxbackups' ] ) { ksort( $backupfilelist ); $numdeltefiles = 0; while ( $file = array_shift( $backupfilelist ) ) { if ( count( $backupfilelist ) < $job_object->job[ 's3maxbackups' ] ) break; //delete files on S3 $args = array( 'Bucket' => $job_object->job[ 's3bucket' ], 'Key' => $job_object->job[ 's3dir' ] . $file ); if ( $s3->deleteObject( $args ) ) { foreach ( $files as $key => $filedata ) { if ( $filedata[ 'file' ] == $job_object->job[ 's3dir' ] . $file ) unset( $files[ $key ] ); } $numdeltefiles ++; } else { $job_object->log( sprintf( __( 'Cannot delete backup from %s.', 'backwpup' ), $this->get_s3_base_url( $job_object->job[ 's3region' ], $job_object->job[ 's3base_url' ] ). '/' .$job_object->job[ 's3bucket' ] . '/' . $job_object->job[ 's3dir' ] . $file ), E_USER_ERROR ); } } if ( $numdeltefiles > 0 ) $job_object->log( sprintf( _n( 'One file deleted on S3 Bucket.', '%d files deleted on S3 Bucket', $numdeltefiles, 'backwpup' ), $numdeltefiles ), E_USER_NOTICE ); } } set_site_transient( 'backwpup_' . $job_object->job[ 'jobid' ] . '_s3', $files, YEAR_IN_SECONDS ); } catch ( Exception $e ) { $job_object->log( E_USER_ERROR, sprintf( __( 'S3 Service API: %s', 'backwpup' ), $e->getMessage() ), $e->getFile(), $e->getLine() ); return FALSE; } $job_object->substeps_done = 2 + $job_object->backup_filesize; return TRUE; } /** * @param $job_settings array * @return bool */ public function can_run( array $job_settings ) { if ( empty( $job_settings[ 's3accesskey' ] ) ) return FALSE; if ( empty( $job_settings[ 's3secretkey' ] ) ) return FALSE; if ( empty( $job_settings[ 's3bucket' ] ) ) return FALSE; return TRUE; } public function edit_inline_js() { ?> <script type="text/javascript"> jQuery(document).ready(function ($) { function awsgetbucket() { var data = { action: 'backwpup_dest_s3', s3accesskey: $('input[name="s3accesskey"]').val(), s3secretkey: $('input[name="s3secretkey"]').val(), s3bucketselected: $('input[name="s3bucketselected"]').val(), s3base_url: $('input[name="s3base_url"]').val(), s3region: $('#s3region').val(), _ajax_nonce: $('#backwpupajaxnonce').val() }; $.post(ajaxurl, data, function (response) { $('#s3bucketerror').remove(); $('#s3bucket').remove(); $('#s3bucketselected').after(response); }); } $('input[name="s3accesskey"]').backwpupDelayKeyup(function () { awsgetbucket(); }); $('input[name="s3secretkey"]').backwpupDelayKeyup(function () { awsgetbucket(); }); $('input[name="s3base_url"]').backwpupDelayKeyup(function () { awsgetbucket(); }); $('#s3region').change(function () { awsgetbucket(); }); }); </script> <?php } }
package com.cburch.logisim.gui.start; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cburch.logisim.circuit.Analyze; import com.cburch.logisim.circuit.Circuit; import com.cburch.logisim.circuit.CircuitState; import com.cburch.logisim.circuit.Propagator; import com.cburch.logisim.comp.Component; import com.cburch.logisim.data.Value; import com.cburch.logisim.file.FileStatistics; import com.cburch.logisim.file.LoadFailedException; import com.cburch.logisim.file.Loader; import com.cburch.logisim.file.LogisimFile; import com.cburch.logisim.instance.Instance; import com.cburch.logisim.instance.InstanceState; import com.cburch.logisim.proj.Project; import com.cburch.logisim.std.io.Keyboard; import com.cburch.logisim.std.io.Tty; import com.cburch.logisim.std.memory.Ram; import com.cburch.logisim.std.wiring.Pin; import com.cburch.logisim.tools.Library; import com.cburch.logisim.util.StringUtil; public class TtyInterface { // It's possible to avoid using the separate thread using // System.in.available(), // but this doesn't quite work because on some systems, the keyboard input // is not interactively echoed until System.in.read() is invoked. private static class StdinThread extends Thread { private LinkedList<char[]> queue; // of char[] public StdinThread() { queue = new LinkedList<char[]>(); } public char[] getBuffer() { synchronized (queue) { if (queue.isEmpty()) { return null; } else { return queue.removeFirst(); } } } @Override public void run() { InputStreamReader stdin = new InputStreamReader(System.in); char[] buffer = new char[32]; while (true) { try { int nbytes = stdin.read(buffer); if (nbytes > 0) { char[] add = new char[nbytes]; System.arraycopy(buffer, 0, add, 0, nbytes); synchronized (queue) { queue.addLast(add); } } } catch (IOException e) { } } } } private static int countDigits(int num) { int digits = 1; int lessThan = 10; while (num >= lessThan) { digits++; lessThan *= 10; } return digits; } private static void displaySpeed(long tickCount, long elapse) { double hertz = (double) tickCount / elapse * 1000.0; double precision; if (hertz >= 100) precision = 1.0; else if (hertz >= 10) precision = 0.1; else if (hertz >= 1) precision = 0.01; else if (hertz >= 0.01) precision = 0.0001; else precision = 0.0000001; hertz = (int) (hertz / precision) * precision; String hertzStr = hertz == (int) hertz ? "" + (int) hertz : "" + hertz; Object[] paramArray = { StringUtil.format(Strings.get("ttySpeedMsg")), hertzStr, tickCount, elapse }; logger.info("{}", paramArray); } private static void displayStatistics(LogisimFile file) { FileStatistics stats = FileStatistics.compute(file, file.getMainCircuit()); FileStatistics.Count total = stats.<API key>(); int maxName = 0; for (FileStatistics.Count count : stats.getCounts()) { int nameLength = count.getFactory().getDisplayName().length(); if (nameLength > maxName) maxName = nameLength; } String fmt = "%" + countDigits(total.getUniqueCount()) + "d\t" + "%" + countDigits(total.getRecursiveCount()) + "d\t"; String fmtNormal = fmt + "%-" + maxName + "s\t%s\n"; for (FileStatistics.Count count : stats.getCounts()) { Library lib = count.getLibrary(); String libName = lib == null ? "-" : lib.getDisplayName(); System.out.printf(fmtNormal, Integer.valueOf(count.getUniqueCount()), Integer .valueOf(count.getRecursiveCount()), count .getFactory().getDisplayName(), libName); } FileStatistics.Count totalWithout = stats.<API key>(); System.out.printf( fmt + "%s\n", Integer.valueOf(totalWithout.getUniqueCount()), Integer.valueOf(totalWithout.getRecursiveCount()), Strings.get("statsTotalWithout")); System.out.printf( fmt + "%s\n", Integer.valueOf(total.getUniqueCount()), Integer.valueOf(total.getRecursiveCount()), Strings.get("statsTotalWith")); } private static void displayTableRow(ArrayList<Value> prevOutputs, ArrayList<Value> curOutputs) { boolean shouldPrint = false; if (prevOutputs == null) { shouldPrint = true; } else { for (int i = 0; i < curOutputs.size(); i++) { Value a = prevOutputs.get(i); Value b = curOutputs.get(i); if (!a.equals(b)) { shouldPrint = true; break; } } } if (shouldPrint) { for (int i = 0; i < curOutputs.size(); i++) { if (i != 0) System.out.print("\t"); System.out.print(curOutputs.get(i)); } System.out.println(); } } private static void <API key>() { if (!lastIsNewline) { lastIsNewline = true; System.out.print('\n'); } } private static boolean loadRam(CircuitState circState, File loadFile) throws IOException { if (loadFile == null) return false; boolean found = false; for (Component comp : circState.getCircuit().getNonWires()) { if (comp.getFactory() instanceof Ram) { Ram ramFactory = (Ram) comp.getFactory(); InstanceState ramState = circState.getInstanceState(comp); ramFactory.loadImage(ramState, loadFile); found = true; } } for (CircuitState sub : circState.getSubstates()) { found |= loadRam(sub, loadFile); } return found; } private static boolean prepareForTty(CircuitState circState, ArrayList<InstanceState> keybStates) { boolean found = false; for (Component comp : circState.getCircuit().getNonWires()) { Object factory = comp.getFactory(); if (factory instanceof Tty) { Tty ttyFactory = (Tty) factory; InstanceState ttyState = circState.getInstanceState(comp); ttyFactory.sendToStdout(ttyState); found = true; } else if (factory instanceof Keyboard) { keybStates.add(circState.getInstanceState(comp)); found = true; } } for (CircuitState sub : circState.getSubstates()) { found |= prepareForTty(sub, keybStates); } return found; } public static void run(Startup args) { File fileToOpen = args.getFilesToOpen().get(0); Loader loader = new Loader(null); LogisimFile file; try { file = loader.openLogisimFile(fileToOpen, args.getSubstitutions()); } catch (LoadFailedException e) { logger.error("{}", Strings.get("ttyLoadError", fileToOpen.getName())); System.exit(-1); return; } int format = args.getTtyFormat(); if ((format & FORMAT_STATISTICS) != 0) { format &= ~FORMAT_STATISTICS; displayStatistics(file); } if (format == 0) { // no simulation remaining to perform, so just exit System.exit(0); } Project proj = new Project(file); Circuit circuit = file.getMainCircuit(); Map<Instance, String> pinNames = Analyze.getPinLabels(circuit); ArrayList<Instance> outputPins = new ArrayList<Instance>(); Instance haltPin = null; for (Map.Entry<Instance, String> entry : pinNames.entrySet()) { Instance pin = entry.getKey(); String pinName = entry.getValue(); if (!Pin.FACTORY.isInputPin(pin)) { outputPins.add(pin); if (pinName.equals("halt")) { haltPin = pin; } } } CircuitState circState = new CircuitState(proj, circuit); // we have to do our initial propagation before the simulation starts - // it's necessary to populate the circuit with substates. circState.getPropagator().propagate(); if (args.getLoadFile() != null) { try { boolean loaded = loadRam(circState, args.getLoadFile()); if (!loaded) { logger.error("{}", Strings.get("loadNoRamError")); System.exit(-1); } } catch (IOException e) { logger.error("{}: {}", Strings.get("loadIoError"), e.toString()); System.exit(-1); } } int ttyFormat = args.getTtyFormat(); int simCode = runSimulation(circState, outputPins, haltPin, ttyFormat); System.exit(simCode); } private static int runSimulation(CircuitState circState, ArrayList<Instance> outputPins, Instance haltPin, int format) { boolean showTable = (format & FORMAT_TABLE) != 0; boolean showSpeed = (format & FORMAT_SPEED) != 0; boolean showTty = (format & FORMAT_TTY) != 0; boolean showHalt = (format & FORMAT_HALT) != 0; ArrayList<InstanceState> keyboardStates = null; StdinThread stdinThread = null; if (showTty) { keyboardStates = new ArrayList<InstanceState>(); boolean ttyFound = prepareForTty(circState, keyboardStates); if (!ttyFound) { logger.error("{}", Strings.get("ttyNoTtyError")); System.exit(-1); } if (keyboardStates.isEmpty()) { keyboardStates = null; } else { stdinThread = new StdinThread(); stdinThread.start(); } } int retCode; long tickCount = 0; long start = System.currentTimeMillis(); boolean halted = false; ArrayList<Value> prevOutputs = null; Propagator prop = circState.getPropagator(); while (true) { ArrayList<Value> curOutputs = new ArrayList<Value>(); for (Instance pin : outputPins) { InstanceState pinState = circState.getInstanceState(pin); Value val = Pin.FACTORY.getValue(pinState); if (pin == haltPin) { halted |= val.equals(Value.TRUE); } else if (showTable) { curOutputs.add(val); } } if (showTable) { displayTableRow(prevOutputs, curOutputs); } if (halted) { retCode = 0; // normal exit break; } if (prop.isOscillating()) { retCode = 1; // abnormal exit break; } if (keyboardStates != null) { char[] buffer = stdinThread.getBuffer(); if (buffer != null) { for (InstanceState keyState : keyboardStates) { Keyboard.addToBuffer(keyState, buffer); } } } prevOutputs = curOutputs; tickCount++; prop.tick(); prop.propagate(); } long elapse = System.currentTimeMillis() - start; if (showTty) <API key>(); if (showHalt || retCode != 0) { if (retCode == 0) { logger.error("{}", Strings.get("ttyHaltReasonPin")); } else if (retCode == 1) { logger.error("{}", Strings.get("<API key>")); } } if (showSpeed) { displaySpeed(tickCount, elapse); } return retCode; } public static void sendFromTty(char c) { lastIsNewline = c == '\n'; System.out.print(c); } final static Logger logger = LoggerFactory.getLogger(TtyInterface.class); public static final int FORMAT_TABLE = 1; public static final int FORMAT_SPEED = 2; public static final int FORMAT_TTY = 4; public static final int FORMAT_HALT = 8; public static final int FORMAT_STATISTICS = 16; private static boolean lastIsNewline = true; }
#ifndef LGE_TOUCH_CORE_H #define LGE_TOUCH_CORE_H /* #define MT_PROTOCOL_A */ #define POWER_FW_UP_LOCK 0x01 #define POWER_SYSFS_LOCK 0x02 #define MAX_FINGER 5 #define MAX_BUTTON 4 #define FW_VER_INFO_NUM 4 #define <API key> 12 struct point { int x; int y; }; enum { TIME_SINCE_BOOTING = 0, DURATION_BET_PRESS, JITTER_VALUE, DIFF_FINGER_NUM, SUBTRACTION_TIME, <API key>, FORCE_CONT_TIME, LONG_PRESS_CNT, BUTTON_DURATION, BUTTON_INT_NUM, TIME_SINCE_REBASE, GHOST_VALUE_MAX }; struct touch_device_caps { u8 button_support; u16 y_button_boundary; u32 button_margin; /* percentage % */ u8 number_of_button; u32 button_name[MAX_BUTTON]; u8 is_width_supported; u8 <API key>; u8 is_id_supported; u32 max_width; u32 max_pressure; u32 max_id; u32 x_max; u32 y_max; u32 lcd_x; u32 lcd_y; u32 lcd_touch_ratio_x; u32 lcd_touch_ratio_y; u32 maker_id; u32 maker_id_gpio; u32 maker_id2_gpio; u16 <API key>[GHOST_VALUE_MAX]; }; struct <API key> { u32 palm_detect_mode; u8 operation_mode; /* interrupt = 1 , polling = 0; */ u8 key_type; /* none = 0, hard_touch_key = 1, virtual_key = 2 */ u8 report_mode; u8 delta_pos_threshold; u8 orientation; /* 0' = 0, 90' = 1, 180' = 2, 270' = 3 */ u32 report_period; u32 booting_delay; u32 reset_delay; u8 suspend_pwr; u8 resume_pwr; int <API key>; /* enable = 1, disable = 0 */ int jitter_curr_ratio; int <API key>; /* enable = 1, disable = 0 */ int <API key>; unsigned long irqflags; int ta_debouncing_count; int <API key>; int <API key>; int <API key>; }; struct touch_power_module { u8 use_regulator; u8 use_vio_regulator; char vdd[30]; int vdd_voltage; char vio[30]; int vio_voltage; int gpio_vdd_en; int (*power) (int on); }; struct touch_platform_data { u32 int_pin; u32 reset_pin; int panel_type; u8 panel_id; char knock_on_type; char maker[30]; u8 fw_version[FW_VER_INFO_NUM]; struct touch_device_caps *caps; u8 num_caps; struct <API key> *role; u8 num_role; struct touch_power_module *pwr; u8 num_pwr; const char *inbuilt_fw_name; const char *inbuilt_fw_name_id[4]; const char *panel_spec; const char *panel_spec_id[4]; u32 global_access_pixel; }; struct t_data { u16 id; u16 x_position; u16 y_position; u16 width_major; u16 width_minor; u16 width_orientation; u16 pressure; u8 status; }; struct b_data { u16 key_code; u16 state; }; struct touch_data { u8 total_num; u8 prev_total_num; u8 touch_count; u8 state; u8 palm; u8 prev_palm; struct t_data curr_data[MAX_FINGER]; struct t_data prev_data[MAX_FINGER]; struct b_data curr_button; struct b_data prev_button; }; struct fw_upgrade_info { const char *fw_path; u8 fw_force_upgrade; volatile u8 is_downloading; struct firmware *fw; }; struct touch_fw_info { struct fw_upgrade_info fw_upgrade; u8 ic_fw_identifier[31]; /* String */ u8 ic_fw_version[11]; /* String */ u8 update_fw_version[FW_VER_INFO_NUM]; }; struct rect { u16 left; u16 right; u16 top; u16 bottom; }; struct section_info { struct rect panel; struct rect button[MAX_BUTTON]; struct rect button_cancel[MAX_BUTTON]; u16 b_inner_width; u16 b_width; u16 b_margin; u16 b_height; u16 b_num; u16 b_name[MAX_BUTTON]; }; struct ghost_finger_ctrl { volatile u8 stage; int probe; int count; int min_count; int max_count; int ghost_check_count; int saved_x; int saved_y; int saved_last_x; int saved_last_y; int max_moved; int max_pressure; }; struct jitter_history_data { u16 x; u16 y; u16 pressure; int delta_x; int delta_y; }; struct jitter_filter_info { int id_mask; int adjust_margin; struct jitter_history_data his_data[10]; }; struct <API key> { u16 x; u16 y; u16 pressure; int count; int mod_x; int mod_y; int axis_x; int axis_y; int prev_total_num; }; struct <API key> { int ignore_pressure_gap; int touch_max_count; int delta_max; int max_pressure; int direction_count; int <API key>; u16 finish_filter; struct <API key> his_data; }; struct state_info { atomic_t power_state; atomic_t interrupt_state; atomic_t upgrade_state; atomic_t ta_state; atomic_t temperature_state; atomic_t proximity_state; atomic_t hallic_state; atomic_t uevent_state; }; struct lge_touch_data { void *h_touch; struct state_info state; atomic_t next_work; atomic_t device_init; u8 work_sync_err_cnt; u8 ic_init_err_cnt; volatile int curr_pwr_state; int int_pin_state; struct i2c_client *client; struct input_dev *input_dev; struct hrtimer timer; struct work_struct work; struct delayed_work work_init; struct delayed_work work_touch_lock; struct work_struct work_fw_upgrade; #if defined(CONFIG_FB) struct notifier_block fb_notifier_block; #endif #if defined(<API key>) struct early_suspend early_suspend; #endif struct touch_platform_data *pdata; struct touch_data ts_data; struct touch_fw_info fw_info; struct section_info st_info; struct kobject lge_touch_kobj; struct ghost_finger_ctrl gf_ctrl; struct jitter_filter_info jitter_filter; struct <API key> accuracy_filter; struct delayed_work work_gesture_wakeup; struct mutex irq_work_mutex; bool sd_status; int lockscreen; }; enum { TA_DISCONNECTED = 0, TA_CONNECTED, }; enum { PROXIMITY_FAR = 0, PROXIMITY_NEAR, }; enum { HALL_NONE = 0, HALL_COVERED, }; enum { UEVENT_IDLE = 0, UEVENT_BUSY, }; typedef enum error_type { NO_ERROR = 0, ERROR, IGNORE_EVENT, <API key>, } err_t; struct touch_device_driver { int (*probe) (struct lge_touch_data *lge_touch_ts);/* (struct i2c_client *client); us10_porting */ void (*remove) (struct i2c_client *client); int (*init) (struct i2c_client *client, struct touch_fw_info* info); int (*data) (struct i2c_client *client, struct touch_data* data); int (*power) (struct i2c_client *client, int power_ctrl); int (*ic_ctrl) (struct i2c_client *client, u8 code, u32 value); int (*fw_upgrade) (struct i2c_client *client, struct touch_fw_info *info); int (*sysfs) (struct i2c_client *client, char *buf, u8 code, struct touch_fw_info *fw_info); err_t (*suspend) (struct i2c_client *client); err_t (*resume) (struct i2c_client *client); err_t (*lpwg) (struct i2c_client *client, u32 code, u32 value, struct point *data); }; enum { POLLING_MODE = 0, INTERRUPT_MODE, HYBRIDE_MODE }; enum { POWER_OFF = 0, POWER_ON, POWER_SLEEP, POWER_WAKE }; enum { KEY_NONE = 0, TOUCH_HARD_KEY, TOUCH_SOFT_KEY, VIRTUAL_KEY, }; enum { <API key> = 0, REDUCED_REPORT_MODE, }; enum { RESET_NONE = 0, SOFT_RESET, PIN_RESET, VDD_RESET, }; enum { DOWNLOAD_COMPLETE = 0, UNDER_DOWNLOADING, }; enum { OP_NULL = 0, OP_RELEASE, OP_SINGLE, OP_MULTI, OP_LOCK, }; enum { KEY_NULL = 0, KEY_PANEL, KEY_BOUNDARY }; enum { DO_NOT_ANYTHING = 0, ABS_PRESS, ABS_RELEASE, BUTTON_PRESS, BUTTON_RELEASE, BUTTON_CANCEL, TOUCH_BUTTON_LOCK, TOUCH_ABS_LOCK }; enum { BUTTON_RELEASED = 0, BUTTON_PRESSED = 1, BUTTON_CANCLED = 0xff, }; enum { FINGER_RELEASED = 0, FINGER_PRESSED = 1, }; enum { KEYGUARD_RESERVED, KEYGUARD_ENABLE, }; enum { GHOST_STAGE_CLEAR = 0, GHOST_STAGE_1 = 1, GHOST_STAGE_2 = 2, GHOST_STAGE_3 = 4, GHOST_STAGE_4 = 8, }; enum { BASELINE_OPEN = 0, BASELINE_FIX, BASELINE_REBASE, }; enum { IC_CTRL_CODE_NONE = 0, IC_CTRL_BASELINE, IC_CTRL_READ, IC_CTRL_WRITE, IC_CTRL_RESET_CMD, IC_CTRL_REPORT_MODE, <API key>, }; /* For Error Handling * * DO_IF : execute 'do_work', and if the result is true, print 'error_log' and goto 'goto_error'. * DO_SAFE : execute 'do_work', and if the result is '< 0', print 'error_log' and goto 'goto_error' * ASSIGN : excute 'do_assign', and if the result is 'NULL', print 'error_log' and goto 'goto_error' * ERROR_IF : if the condition is true(ERROR), print 'string' and goto 'goto_error'. */ #define DO_IF(do_work, goto_error) \ do { \ if (do_work) { \ printk(KERN_INFO "[Touch E] Action Failed [%s %d] \n", __FUNCTION__, __LINE__); \ goto goto_error; \ } \ } while (0) #define DO_SAFE(do_work, goto_error) \ DO_IF(unlikely((do_work) < 0), goto_error) #define ASSIGN(do_assign, goto_error) \ do { \ if ((do_assign) == NULL) { \ printk(KERN_INFO "[Touch E] Assign Failed [%s %d] \n", __FUNCTION__, __LINE__); \ goto goto_error; \ } \ } while (0) #define ERROR_IF(cond, string, goto_error) \ do { \ if (cond) { \ TOUCH_ERR_MSG(string); \ goto goto_error; \ } \ } while (0) enum { <API key> = 1, <API key>, NOTIFY_PROXIMITY, NOTIFY_HALL_IC, }; enum { LPWG_NONE = 0, LPWG_DOUBLE_TAP, LPWG_MULTI_TAP, }; enum { LPWG_READ = 1, LPWG_ENABLE, LPWG_LCD_X, LPWG_LCD_Y, LPWG_ACTIVE_AREA_X1, LPWG_ACTIVE_AREA_X2, LPWG_ACTIVE_AREA_Y1, LPWG_ACTIVE_AREA_Y2, LPWG_TAP_COUNT, LPWG_REPLY, <API key>, LPWG_MODE_CHANGE, }; enum { DEBUG_NONE = 0, DEBUG_BASE_INFO = (1U << 0), DEBUG_TRACE = (1U << 1), DEBUG_GET_DATA = (1U << 2), DEBUG_ABS = (1U << 3), DEBUG_BUTTON = (1U << 4), DEBUG_FW_UPGRADE = (1U << 5), DEBUG_GHOST = (1U << 6), DEBUG_IRQ_HANDLE = (1U << 7), /* 128 */ DEBUG_POWER = (1U << 8), /* 256 */ DEBUG_JITTER = (1U << 9), /* 512 */ DEBUG_ACCURACY = (1U << 10), /* 1024 */ DEBUG_NOISE = (1U << 11), /* 2048 */ }; enum { TIME_ISR_START = 0, TIME_INT_INTERVAL, <API key>, <API key>, TIME_WORKQUEUE_END, <API key>, TIME_FW_UPGRADE_END, TIME_PROFILE_MAX, }; #ifdef <API key> enum{ <API key> = 0, <API key> = (1U << 0), <API key> = (1U << 1), <API key> = (1U << 2), <API key> = (1U << 3), <API key> = (1U << 4), <API key> = (1U << 5), }; #endif enum{ WORK_POST_COMPLATE = 0, WORK_POST_OUT, WORK_POST_ERR_RETRY, <API key>, WORK_POST_MAX, }; enum{ IGNORE_INTERRUPT = 100, NEED_TO_OUT, NEED_TO_INIT, }; enum{ <API key> = 0, <API key>, SYSFS_CHSTATUS_SHOW, SYSFS_RAWDATA_SHOW, SYSFS_DELTA_SHOW, <API key>, <API key>, }; enum{ EX_INIT, EX_FIRST_INT, EX_PREV_PRESS, EX_CURR_PRESS, <API key>, EX_BUTTON_PRESS_END, <API key>, <API key>, EX_CURR_INT, EX_PROFILE_MAX }; #define LGE_TOUCH_NAME "lge_touch" /* Debug Mask setting */ #define TOUCH_DEBUG_PRINT (1) #define TOUCH_ERROR_PRINT (1) #define TOUCH_INFO_PRINT (1) #if defined(TOUCH_INFO_PRINT) #define TOUCH_INFO_MSG(fmt, args...) \ printk(KERN_INFO "[Touch] " fmt, ##args); #else #define TOUCH_INFO_MSG(fmt, args...) do {} while (0) #endif #if defined(TOUCH_ERROR_PRINT) #define TOUCH_ERR_MSG(fmt, args...) \ printk(KERN_ERR "[Touch E] [%s %d] " \ fmt, __FUNCTION__, __LINE__, ##args); #else #define TOUCH_ERR_MSG(fmt, args...) do {} while (0) #endif #if defined(TOUCH_DEBUG_PRINT) #define TOUCH_DEBUG_MSG(fmt, args...) \ printk(KERN_INFO "[Touch D] [%s %d] " \ fmt, __FUNCTION__, __LINE__, ##args); #else #define TOUCH_DEBUG_MSG(fmt, args...) do {} while (0) #endif int <API key>(struct touch_device_driver *driver); void <API key>(void); void set_touch_handle(struct i2c_client *client, void *h_touch); void *get_touch_handle(struct i2c_client *client); void power_lock_(int value); void power_unlock_(int value); void send_uevent(char *string[2]); void send_uevent_lpwg(struct i2c_client *client, int type); int touch_i2c_read(struct i2c_client *client, u8 reg, int len, u8 *buf); int touch_i2c_write(struct i2c_client *client, u8 reg, int len, u8 *buf); int <API key>(struct i2c_client *client, u8 reg, u8 data); extern u32 touch_debug_mask; extern u32 <API key>; #endif
.x-progress-wrap { border:1px solid; overflow:hidden; } .x-progress-inner { height:18px; background:repeat-x; position:relative; } .x-progress-bar { height:18px; float:left; width:0; background: repeat-x left center; border-top:1px solid; border-bottom:1px solid; border-right:1px solid; } .x-progress-text { padding:1px 5px; overflow:hidden; position:absolute; left:0; text-align:center; } .<API key> { line-height:16px; } .ext-ie .<API key> { line-height:15px; } .ext-strict .ext-ie7 .<API key>{ width: 100%; }
namespace ACE.Server.Physics.Common { public class <API key> { public int Bitfield; public int ValidLocations; public static bool GetValidLocations(PhysicsDesc desc) { return false; } } }
#!/usr/bin/env python # -*- coding: utf-8 -*- # GuessIt - A library for guessing information from filenames # GuessIt is free software; you can redistribute it and/or modify it under # (at your option) any later version. # GuessIt is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from guessit.patterns import subtitle_exts import logging log = logging.getLogger(__name__) def process(mtree): # 1- try to promote language to subtitle language where it makes sense for node in mtree.nodes(): if 'language' not in node.guess: continue def promote_subtitle(): # pylint: disable=W0631 node.guess.set('subtitleLanguage', node.guess['language'], confidence=node.guess.confidence('language')) del node.guess['language'] # - if we matched a language in a file with a sub extension and that # the group is the last group of the filename, it is probably the # language of the subtitle # (eg: 'xxx.english.srt') if (mtree.node_at((-1,)).value.lower() in subtitle_exts and node == mtree.leaves()[-2]): promote_subtitle() # - if a language is in an explicit group just preceded by "st", # it is a subtitle language (eg: '...st[fr-eng]...') try: idx = node.node_idx previous = mtree.node_at((idx[0], idx[1] - 1)).leaves()[-1] if previous.value.lower()[-2:] == 'st': promote_subtitle() except IndexError: pass # 2- ", the" at the end of a series title should be prepended to it for node in mtree.nodes(): if 'series' not in node.guess: continue series = node.guess['series'] lseries = series.lower() if lseries[-4:] == ',the': node.guess['series'] = 'The ' + series[:-4] if lseries[-5:] == ', the': node.guess['series'] = 'The ' + series[:-5]
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) return; $GLOBALS[$GLOBALS['idx_lang']] = array( '<API key>' => 'Optimización e compresión', '<API key>' => 'Quere activar a compactación das follas de estilo(CSS) ?', # MODIF '<API key>' => 'Quere activar a compactación de scripts (javascript) ?', # MODIF '<API key>' => 'Quere activar a compactación do fluxo HTTP ?', # MODIF '<API key>' => 'Utiliser Google Closure Compiler [expérimental]', # NEW '<API key>' => 'Activer la compression des feuilles de styles (CSS)', # NEW '<API key>' => 'Activer la compression du HTML', # NEW 'item_compresseur_js' => 'Activer la compression des scripts (javascript)', # NEW '<API key>' => 'Atención para non activar estas opcións durante o desenvolvemento do seu web: os elementos compactados perden toda a súa lexibilidade.', '<API key>' => 'SPIP pode compactar os scripts javascript e as follas de estilo CSS, para rexistralos nas fichas estáticas ; iso acelera a presentación do web.', '<API key>' => 'SPIP pode comprimir automaticamente cada páxina que envía ao visitante do web. Esta regraxe permite optimizar o ancho de banda (o web é máis rápido ao seguirse unha ligazón de baixa velocidade), mais demanda máis potencia do servidor.', '<API key>' => 'Compactación de scripts e CSS', '<API key>' => 'Compactación do fluxo HTTP' # MODIF ); ?>
<?php require_once(ROOT_DIR . 'Pages/SecurePage.php'); require_once(ROOT_DIR . 'Presenters/Reservation/<API key>.php'); interface IReservationPage extends IPage { /** * Set the schedule period items to be used when presenting reservations * @param $startPeriods array|SchedulePeriod[] * @param $endPeriods array|SchedulePeriod[] */ function BindPeriods($startPeriods, $endPeriods); /** * Set the resources that can be reserved by this user * @param $resources array|ResourceDto[] */ function <API key>($resources); /** * @param $accessories array|AccessoryDto[] * @return void */ function <API key>($accessories); /** * @param $groups ResourceGroupTree */ function BindResourceGroups($groups); /** * @param SchedulePeriod $selectedStart * @param Date $startDate */ function SetSelectedStart(SchedulePeriod $selectedStart, Date $startDate); /** * @param SchedulePeriod $selectedEnd * @param Date $endDate */ function SetSelectedEnd(SchedulePeriod $selectedEnd, Date $endDate); /** * @param $<API key> Date */ function <API key>($<API key>); /** * @param UserDto $user */ function SetReservationUser(UserDto $user); /** * @param ResourceDto $resource */ function <API key>($resource); /** * @param int $scheduleId */ function SetScheduleId($scheduleId); /** * @param ReservationUserView[] $participants */ function SetParticipants($participants); /** * @param ReservationUserView[] $invitees */ function SetInvitees($invitees); /** * @param $accessories <API key>[]|array */ function SetAccessories($accessories); /** * @param $attachments <API key>[]|array */ function SetAttachments($attachments); /** * @param $canChangeUser */ function SetCanChangeUser($canChangeUser); /** * @param bool $<API key> */ function <API key>($<API key>); /** * @param bool $canShowUserDetails */ function ShowUserDetails($canShowUserDetails); /** * @param bool $shouldShow */ function <API key>($shouldShow); /** * @param bool $<API key> */ function <API key>($<API key>); /** * @param $attributes array|Attribute[] */ function SetCustomAttributes($attributes); /** * @param bool $isHidden */ function HideRecurrence($isHidden); } abstract class ReservationPage extends Page implements IReservationPage { protected $presenter; /** * @var <API key> */ protected $<API key>; /** * @var <API key> */ protected $<API key>; public function __construct($title = null) { parent::__construct($title); if (is_null($this-><API key>)) { $this-><API key> = new <API key>(); } $userRepository = new UserRepository(); $this-><API key> = new <API key>( new ScheduleRepository(), $userRepository, new ResourceService(new ResourceRepository(), $this-><API key>-><API key>(), new AttributeService(new AttributeRepository()), $userRepository), new <API key>(<API key>::Get<API key>()), new AttributeRepository(), ServiceLocator::GetServer()->GetUserSession() ); $this->presenter = $this->GetPresenter(); } /** * @return <API key> */ protected abstract function GetPresenter(); /** * @return string */ protected abstract function GetTemplateName(); /** * @return string */ protected abstract function <API key>(); public function PageLoad() { $this->presenter->PageLoad(); $this->Set('ReturnUrl', $this->GetLastPage(Pages::SCHEDULE)); $this->Set('ReservationAction', $this-><API key>()); $this->Set('MaxUploadSize', UploadedFile::GetMaxSize()); $this->Set('MaxUploadCount', UploadedFile::GetMaxUploadCount()); $this->Set('UploadsEnabled', Configuration::Instance()->GetSectionKey(ConfigSection::UPLOADS, ConfigKeys::<API key>, new BooleanConverter())); $this->Set('AllowParticipation', !Configuration::Instance()->GetSectionKey(ConfigSection::RESERVATION, ConfigKeys::<API key>, new BooleanConverter())); $remindersEnabled = Configuration::Instance()->GetSectionKey(ConfigSection::RESERVATION, ConfigKeys::<API key>, new BooleanConverter()); $emailEnabled = Configuration::Instance()->GetKey(ConfigKeys::ENABLE_EMAIL, new BooleanConverter()); $this->Set('RemindersEnabled', $remindersEnabled && $emailEnabled); $this->Set('RepeatEveryOptions', range(1, 20)); $this->Set('RepeatOptions', array( 'none' => array('key' => 'DoesNotRepeat', 'everyKey' => ''), 'daily' => array('key' => 'Daily', 'everyKey' => 'days'), 'weekly' => array('key' => 'Weekly', 'everyKey' => 'weeks'), 'monthly' => array('key' => 'Monthly', 'everyKey' => 'months'), 'yearly' => array('key' => 'Yearly', 'everyKey' => 'years'), ) ); $this->Set('DayNames', array( 0 => 'DaySundayAbbr', 1 => 'DayMondayAbbr', 2 => 'DayTuesdayAbbr', 3 => 'DayWednesdayAbbr', 4 => 'DayThursdayAbbr', 5 => 'DayFridayAbbr', 6 => 'DaySaturdayAbbr', ) ); $this->Display($this->GetTemplateName()); } public function BindPeriods($startPeriods, $endPeriods) { $this->Set('StartPeriods', $startPeriods); $this->Set('EndPeriods', $endPeriods); } public function <API key>($resources) { $this->Set('AvailableResources', $resources); } public function <API key>($shouldShow) { $this->Set('<API key>', $shouldShow); } public function <API key>($accessories) { $this->Set('<API key>', $accessories); } public function BindResourceGroups($groups) { $this->Set('<API key>', json_encode($groups->GetGroups())); } public function SetSelectedStart(SchedulePeriod $selectedStart, Date $startDate) { $this->Set('SelectedStart', $selectedStart); $this->Set('StartDate', $startDate); } public function SetSelectedEnd(SchedulePeriod $selectedEnd, Date $endDate) { $this->Set('SelectedEnd', $selectedEnd); $this->Set('EndDate', $endDate); } /** * @param UserDto $user * @return void */ public function SetReservationUser(UserDto $user) { $this->Set('ReservationUserName', $user->FullName()); $this->Set('UserId', $user->Id()); } /** * @param $resource ResourceDto * @return void */ public function <API key>($resource) { $this->Set('ResourceName', $resource->Name); $this->Set('ResourceId', $resource->Id); } public function SetScheduleId($scheduleId) { $this->Set('ScheduleId', $scheduleId); } public function <API key>($<API key>) { $this->Set('<API key>', $<API key>); } public function SetParticipants($participants) { $this->Set('Participants', $participants); } public function SetInvitees($invitees) { $this->Set('Invitees', $invitees); } public function SetAccessories($accessories) { $this->Set('Accessories', $accessories); } public function SetAttachments($attachments) { $this->Set('Attachments', $attachments); } public function SetCanChangeUser($canChangeUser) { $this->Set('CanChangeUser', $canChangeUser); } public function ShowUserDetails($canShowUserDetails) { $this->Set('ShowUserDetails', $canShowUserDetails); } public function <API key>($shouldShow) { $this->Set('ShowParticipation', $shouldShow); } public function <API key>($<API key>) { $this->Set('<API key>', $<API key>); } public function SetCustomAttributes($attributes) { $this->Set('Attributes', $attributes); } public function HideRecurrence($isHidden) { $this->Set('HideRecurrence', $isHidden); } }
// GazeTrackingLibrary for ITU GazeTracker // This program is free software; you can redistribute it and/or modify it // or (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // <author>Martin Tall</author> // <email>info@martintall.com</email> using System; using System.Windows; using System.Windows.Forms; using Emgu.CV.UI; using GazeTrackingLibrary; using GazeTrackingLibrary.Logging; using GTCommons.Enum; using GTSettings; namespace GazeTrackerUI.TrackerViewer { public partial class VideoImageControl { #region CONSTANTS private const int <API key> = 380; private const int <API key> = 200; #endregion //CONSTANTS #region Variables private VideoImageOverlay overlay; #endregion //FIELDS #region Constructor public VideoImageControl() { InitializeComponent(); VideoImageHeight = <API key>; VideoImageWidth = <API key>; pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; this.LayoutUpdated += <API key>; this.pictureBox.MouseEnter += <API key>; this.pictureBox.MouseLeave += <API key>; } void <API key>(object sender, EventArgs e) { if(overlay != null) overlay.<API key>.Visibility = Visibility.Collapsed; } void <API key>(object sender, EventArgs e) { if(overlay != null) overlay.<API key>.Visibility = Visibility.Visible; } void <API key>(object sender, EventArgs e) { if(overlay != null && this.IsVisible) { try { overlay.Width = this.Width; overlay.Height = this.Height; overlay.Top = this.PointToScreen(new Point(0, 0)).Y; overlay.Left = this.PointToScreen(new Point(0, 0)).X; } catch (Exception ex) { Console.Out.WriteLine("VideoImageControl: " + ex.Message); } } } #endregion //CONSTRUCTION #region Properties <summary> Gets the CV image box. </summary> <value>The CV image box.</value> public ImageBox CVImageBox { get { return pictureBox; } } <summary> Sets the width of the video image. </summary> <value>The width of the video image.</value> public int VideoImageWidth { set { pictureBox.Width = value; } get { return pictureBox.Width; } } <summary> Sets the height of the video image. </summary> <value>The height of the video image.</value> public int VideoImageHeight { set { pictureBox.Height = value; } get { return pictureBox.Height; } } public VideoImageOverlay Overlay { get { return this.overlay; } } public bool VideoOverlayTopMost { set { if(overlay != null) overlay.Topmost = value; } } <summary> Gets or sets a value indicating whether this instance is native resolution. </summary> <value> <c>true</c> if running at native resolution; otherwise, <c>false</c>. </value> //public bool IsNativeResolution // get { return this.isNativeResolution; } // set { this.isNativeResolution = value; } #endregion //PROPERTIES #region Public methods public void Start() { Tracker.Instance.OnProcessedFrame += <API key>; Settings.Instance.Visualization.IsDrawing = true; if(overlay == null) { overlay = new VideoImageOverlay(); overlay.Width = this.VideoImageWidth; overlay.Height = this.VideoImageHeight; overlay.Top = PointToScreen(new Point(0, 0)).Y; overlay.Left = PointToScreen(new Point(0, 0)).X; overlay.Show(); overlay.Topmost = true; } } public void Stop(bool stopAtServer) { // Unregister event listner for processed frame Tracker.Instance.OnProcessedFrame -= <API key>; // Turn of visualization (copying of newframe to visualization class, saves cpu and memory) if(stopAtServer) Settings.Instance.Visualization.IsDrawing = false; this.Dispatcher.BeginInvoke(new MethodInvoker(delegate { if (overlay == null) return; overlay.Topmost = false; })); } #endregion #region Eventhandler int drawImageOnCounter = 1; int imageCounter = 0; int fps = 0; private void <API key>(object sender, EventArgs args) { // Don't draw while calibrating to obtain maximum images if (Tracker.Instance.IsCalibrating) return; #region Skipping to conserve CPU on high framerates if (GTHardware.Camera.Instance.DeviceType != GTHardware.Camera.DeviceTypeEnum.DirectShow) { imageCounter++; // If fps changed by more than +-10, determine new skipping if (fps < GTHardware.Camera.Instance.Device.FPS - 10 || fps > GTHardware.Camera.Instance.Device.FPS + 10) { fps = GTHardware.Camera.Instance.Device.FPS; if (fps < 30) drawImageOnCounter = 1; else drawImageOnCounter = Convert.ToInt32(fps/24); // Target visualization @ 24 fps } if (imageCounter < drawImageOnCounter) return; imageCounter = 0; } #endregion try { if (pictureBox.InvokeRequired) pictureBox.BeginInvoke(new MethodInvoker(UpdateImage)); else UpdateImage(); } catch (Exception ex) { ErrorLogger.ProcessException(ex, false); } } #endregion #region Private methods private void UpdateImage() { pictureBox.Image = null; if (Settings.Instance.Visualization.VideoMode == VideoModeEnum.Processed) pictureBox.Image = Tracker.Instance.GetProcessedImage(); else pictureBox.Image = Tracker.Instance.GetGrayImage(); if (overlay != null) overlay.<API key>.Update(Tracker.Instance.FPSVideo, Tracker.Instance.FPSTracking); } #endregion } }
/*globals qq */ qq.UploadData = function(uploaderProxy) { "use strict"; var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {}; function getDataByIds(idOrIds) { if (qq.isArray(idOrIds)) { var entries = []; qq.each(idOrIds, function(idx, id) { entries.push(data[id]); }); return entries; } return data[idOrIds]; } function getDataByUuids(uuids) { if (qq.isArray(uuids)) { var entries = []; qq.each(uuids, function(idx, uuid) { entries.push(data[byUuid[uuid]]); }); return entries; } return data[byUuid[uuids]]; } function getDataByStatus(status) { var statusResults = [], statuses = [].concat(status); qq.each(statuses, function(index, statusEnum) { var statusResultIndexes = byStatus[statusEnum]; if (statusResultIndexes !== undefined) { qq.each(statusResultIndexes, function(i, dataIndex) { statusResults.push(data[dataIndex]); }); } }); return statusResults; } qq.extend(this, { /** * Adds a new file to the data cache for tracking purposes. * * @param spec Data that describes this file. Possible properties are: * * - uuid: Initial UUID for this file. * - name: Initial name of this file. * - size: Size of this file, omit if this cannot be determined * - status: Initial `qq.status` for this file. Omit for `qq.status.SUBMITTING`. * - batchId: ID of the batch this file belongs to * - proxyGroupId: ID of the proxy group associated with this file * * @returns {number} Internal ID for this file. */ addFile: function(spec) { var status = spec.status || qq.status.SUBMITTING; var id = data.push({ name: spec.name, originalName: spec.name, uuid: spec.uuid, size: spec.size || -1, status: status }) - 1; if (spec.batchId) { data[id].batchId = spec.batchId; if (byBatchId[spec.batchId] === undefined) { byBatchId[spec.batchId] = []; } byBatchId[spec.batchId].push(id); } if (spec.proxyGroupId) { data[id].proxyGroupId = spec.proxyGroupId; if (byProxyGroupId[spec.proxyGroupId] === undefined) { byProxyGroupId[spec.proxyGroupId] = []; } byProxyGroupId[spec.proxyGroupId].push(id); } data[id].id = id; byUuid[spec.uuid] = id; if (byStatus[status] === undefined) { byStatus[status] = []; } byStatus[status].push(id); uploaderProxy.onStatusChange(id, null, status); return id; }, retrieve: function(optionalFilter) { if (qq.isObject(optionalFilter) && data.length) { if (optionalFilter.id !== undefined) { return getDataByIds(optionalFilter.id); } else if (optionalFilter.uuid !== undefined) { return getDataByUuids(optionalFilter.uuid); } else if (optionalFilter.status) { return getDataByStatus(optionalFilter.status); } } else { return qq.extend([], data, true); } }, reset: function() { data = []; byUuid = {}; byStatus = {}; byBatchId = {}; }, setStatus: function(id, newStatus) { var oldStatus = data[id].status, <API key> = qq.indexOf(byStatus[oldStatus], id); byStatus[oldStatus].splice(<API key>, 1); data[id].status = newStatus; if (byStatus[newStatus] === undefined) { byStatus[newStatus] = []; } byStatus[newStatus].push(id); uploaderProxy.onStatusChange(id, oldStatus, newStatus); }, uuidChanged: function(id, newUuid) { var oldUuid = data[id].uuid; data[id].uuid = newUuid; byUuid[newUuid] = id; delete byUuid[oldUuid]; }, updateName: function(id, newName) { data[id].name = newName; }, updateSize: function(id, newSize) { data[id].size = newSize; }, // Only applicable if this file has a parent that we may want to reference later. setParentId: function(targetId, parentId) { data[targetId].parentId = parentId; }, getIdsInProxyGroup: function(id) { var proxyGroupId = data[id].proxyGroupId; if (proxyGroupId) { return byProxyGroupId[proxyGroupId]; } return []; }, getIdsInBatch: function(id) { var batchId = data[id].batchId; return byBatchId[batchId]; } }); }; qq.status = { SUBMITTING: "submitting", SUBMITTED: "submitted", REJECTED: "rejected", QUEUED: "queued", CANCELED: "canceled", PAUSED: "paused", UPLOADING: "uploading", UPLOAD_RETRYING: "retrying upload", UPLOAD_SUCCESSFUL: "upload successful", UPLOAD_FAILED: "upload failed", DELETE_FAILED: "delete failed", DELETING: "deleting", DELETED: "deleted" };
include $(TOPDIR)/rules.mk PKG_NAME:=stund PKG_VERSION:=0.96 PKG_RELEASE:=3 PKG_SOURCE:=$(PKG_NAME)_$(PKG_VERSION)_Aug13.tgz PKG_SOURCE_URL:=@SF/stun PKG_MD5SUM:=<API key> PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME) include $(INCLUDE_DIR)/package.mk define Package/stun/Default SECTION:=net CATEGORY:=Network DEPENDS:=+uclibcxx URL:=http://sourceforge.net/projects/stun endef define Package/stun/Default/description The STUN protocol (Simple Traversal of UDP through NATs) is described in the IETF RFC 3489, available at http: help clients behind NAT to tunnel incoming calls through. This server is the counterpart to help the client identify the NAT and have it open the proper ports for it. endef define Package/stund $(call Package/stun/Default) TITLE:=STUN server endef define Package/stund/description $(call Package/stun/Default/description) endef define Package/stun-client $(call Package/stun/Default) TITLE:=STUN test client endef define Package/stun-client/description $(call Package/stun/Default/description) endef define Build/Compile $(MAKE) -C $(PKG_BUILD_DIR) \ CXX="$(TARGET_CXX)" \ CFLAGS="$(TARGET_CFLAGS)" \ DESTDIR="$(PKG_INSTALL_DIR)" \ CXXFLAGS="$$$$CXXFLAGS -fno-builtin -fno-rtti -nostdinc++" \ CPPFLAGS="$$$$CPPFLAGS -I$(STAGING_DIR)/usr/include/uClibc++ $(TARGET_CPPFLAGS)" \ LDFLAGS="$$$$LDFLAGS $(TARGET_LDFLAGS) -nodefaultlibs -luClibc++ $(LIBGCC_S)" \ all endef define Package/stund/install $(INSTALL_DIR) $(1)/usr/sbin $(INSTALL_BIN) $(PKG_BUILD_DIR)/server $(1)/usr/sbin/stund $(INSTALL_DIR) $(1)/etc/init.d $(INSTALL_BIN) ./files/stund.init $(1)/etc/init.d/stund $(INSTALL_DIR) $(1)/etc/config $(INSTALL_DATA) ./files/stund.config $(1)/etc/config/stund endef define Package/stun-client/install $(INSTALL_DIR) $(1)/usr/sbin $(INSTALL_BIN) $(PKG_BUILD_DIR)/client $(1)/usr/sbin/stun-client endef $(eval $(call BuildPackage,stund)) $(eval $(call BuildPackage,stun-client))
package me.ccrama.redditslide; import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.text.method.Touch; import android.text.style.ClickableSpan; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; /** * Implementation of LinkMovementMethod to allow the loading of * a link clicked inside text inside an Android application * without exiting to an external browser. * * @author Isaac Whitfield * @version 25/08/2013 */ class <API key> extends LinkMovementMethod { @Override public boolean <API key>() { return true; } @Override public void initialize(TextView widget, Spannable text) { Selection.setSelection(text, text.length()); } @Override public void onTakeFocus(TextView view, Spannable text, int dir) { if ((dir & (View.FOCUS_FORWARD | View.FOCUS_DOWN)) != 0) { if (view.getLayout() == null) { // This shouldn't be null, but do something sensible if it is. Selection.setSelection(text, text.length()); } } else { Selection.setSelection(text, text.length()); } } @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.<API key>(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } else if (action == MotionEvent.ACTION_DOWN) { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } } return Touch.onTouchEvent(widget, buffer, event); } }
// and you are welcome to redistribute it under certain conditions; See #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using MoonSharp.Interpreter; using Power; using UnityEngine; [MoonSharpUserData] public class World : IXmlSerializable { // TODO: Should this be also saved with the world data? // If so - beginner task! public readonly string GameVersion = "<API key>"; public List<Character> characters; public List<Furniture> furnitures; public List<Room> rooms; public InventoryManager inventoryManager; public Material skybox; // Store all temperature information public Temperature temperature; // The pathfinding graph used to navigate our world map. public Path_TileGraph tileGraph; public Wallet Wallet; // TODO: Most likely this will be replaced with a dedicated // class for managing job queues (plural!) that might also // be semi-static or self initializing or some damn thing. // For now, this is just a PUBLIC member of World public JobQueue jobQueue; public JobQueue jobWaitingQueue; // A two-dimensional array to hold our tile data. private Tile[,] tiles; <summary> Initializes a new instance of the <see cref="World"/> class. </summary> <param name="width">Width in tiles.</param> <param name="height">Height in tiles.</param> public World(int width, int height) { // Creates an empty world. SetupWorld(width, height); int seed = UnityEngine.Random.Range(0, int.MaxValue); WorldGenerator.Generate(this, seed); Debug.ULogChannel("World", "Generated World"); // adding air to enclosed rooms foreach (Room room in this.rooms) { if (room.ID > 0) { room.ChangeGas("O2", 0.2f * room.GetSize()); room.ChangeGas("N2", 0.8f * room.GetSize()); } } // Make one character. CreateCharacter(GetTileAt(Width / 2, Height / 2)); } <summary> Default constructor, used when loading a world from a file. </summary> public World() { } public event Action<Furniture> OnFurnitureCreated; public event Action<Character> OnCharacterCreated; public event Action<Inventory> OnInventoryCreated; public event Action<Tile> OnTileChanged; public static World Current { get; protected set; } // The tile width of the world. public int Width { get; protected set; } // The tile height of the world public int Height { get; protected set; } public Syster PowerSystem { get; private set; } public Room GetOutsideRoom() { return rooms[0]; } public int GetRoomID(Room r) { return rooms.IndexOf(r); } public Room GetRoomFromID(int i) { if (i < 0 || i > rooms.Count - 1) { return null; } return rooms[i]; } public void AddRoom(Room r) { rooms.Add(r); Debug.ULogChannel("Rooms", "creating room:" + r.ID); } public int CountFurnitureType(string objectType) { int count = furnitures.Count(f => f.ObjectType == objectType); return count; } public void DeleteRoom(Room r) { if (r.IsOutsideRoom()) { Debug.ULogErrorChannel("World", "Tried to delete the outside room."); return; } Debug.ULogChannel("Rooms", "Deleting room:" + r.ID); // Remove this room from our rooms list. rooms.Remove(r); // All tiles that belonged to this room should be re-assigned to // the outside. r.<API key>(); } public void UpdateCharacters(float deltaTime) { // Change from a foreach due to the collection being modified while its being looped through for (int i = 0; i < characters.Count; i++) { characters[i].Update(deltaTime); } } public void Tick(float deltaTime) { foreach (Furniture f in furnitures) { f.Update(deltaTime); } // Progress temperature modelling temperature.Update(); PowerSystem.Update(deltaTime); } public Character CreateCharacter(Tile t) { return CreateCharacter(t, UnityEngine.Random.ColorHSV()); } public Character CreateCharacter(Tile t, Color color) { Debug.ULogChannel("World", "CreateCharacter"); Character c = new Character(t, color); // Adds a random name to the Character string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "Data"); filePath = System.IO.Path.Combine(filePath, "CharacterNames.txt"); string[] names = File.ReadAllLines(filePath); c.name = names[UnityEngine.Random.Range(0, names.Length - 1)]; characters.Add(c); if (OnCharacterCreated != null) { OnCharacterCreated(c); } return c; } <summary> A function for testing out the system. </summary> public void RandomizeTiles() { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { if (UnityEngine.Random.Range(0, 2) == 0) { tiles[x, y].Type = TileType.Empty; } else { tiles[x, y].Type = TileType.Floor; } } } } public void <API key>() { // Make a set of floors/walls to test pathfinding with. int l = (Width / 2) - 5; int b = (Height / 2) - 5; for (int x = l - 5; x < l + 15; x++) { for (int y = b - 5; y < b + 15; y++) { tiles[x, y].Type = TileType.Floor; if (x == l || x == (l + 9) || y == b || y == (b + 9)) { if (x != (l + 9) && y != (b + 4)) { PlaceFurniture("furn_SteelWall", tiles[x, y]); } } } } } <summary> Gets the tile data at x and y. </summary> <returns>The <see cref="Tile"/> or null if called with invalid arguments.</returns> <param name="x">The x coordinate.</param> <param name="y">The y coordinate.</param> public Tile GetTileAt(int x, int y) { if (x >= Width || x < 0 || y >= Height || y < 0) { return null; } return tiles[x, y]; } public Tile GetCenterTile() { return GetTileAt(Width / 2, Height / 2); } public Tile <API key>(int maxOffset) { return <API key>(maxOffset, Width / 2, Height / 2); } public Tile <API key>(int maxOffset, int centerX, int centerY) { for (int offset = 0; offset <= maxOffset; offset++) { int offsetX = 0; int offsetY = 0; Tile tile; // searching top & bottom line of the square for (offsetX = -offset; offsetX <= offset; offsetX++) { offsetY = offset; tile = GetTileAt(centerX + offsetX, centerY + offsetY); if (tile.Inventory == null) { return tile; } offsetY = -offset; tile = GetTileAt(centerX + offsetX, centerY + offsetY); if (tile.Inventory == null) { return tile; } } // searching left & rigth line of the square for (offsetY = -offset; offsetY <= offset; offsetY++) { offsetX = offset; tile = GetTileAt(centerX + offsetX, centerY + offsetY); if (tile.Inventory == null) { return tile; } offsetX = -offset; tile = GetTileAt(centerX + offsetX, centerY + offsetY); if (tile.Inventory == null) { return tile; } } } return null; } public Furniture PlaceFurniture(string objectType, Tile t, bool doRoomFloodFill = true) { // TODO: This function assumes 1x1 tiles -- change this later! if (PrototypeManager.Furniture.HasPrototype(objectType) == false) { Debug.ULogErrorChannel("World", "furniturePrototypes doesn't contain a proto for key: " + objectType); return null; } Furniture furn = Furniture.PlaceInstance(PrototypeManager.Furniture.GetPrototype(objectType), t); if (furn == null) { // Failed to place object -- most likely there was already something there. return null; } furn.Removed += OnFurnitureRemoved; furnitures.Add(furn); // Do we need to recalculate our rooms? if (doRoomFloodFill && furn.RoomEnclosure) { Room.DoRoomFloodFill(furn.Tile); } if (OnFurnitureCreated != null) { OnFurnitureCreated(furn); if (furn.MovementCost != 1) { // Since tiles return movement cost as their base cost multiplied // buy the furniture's movement cost, a furniture movement cost // of exactly 1 doesn't impact our pathfinding system, so we can // occasionally avoid invalidating pathfinding graphs. // InvalidateTileGraph(); // Reset the pathfinding system if (tileGraph != null) { tileGraph.<API key>(t); } } } return furn; } // This should be called whenever a change to the world // means that our old pathfinding info is invalid. public void InvalidateTileGraph() { tileGraph = null; } public bool <API key>(string furnitureType, Tile t) { return PrototypeManager.Furniture.GetPrototype(furnitureType).IsValidPosition(t); } public XmlSchema GetSchema() { return null; } public void WriteXml(XmlWriter writer) { // Save info here writer.<API key>("Width", Width.ToString()); writer.<API key>("Height", Height.ToString()); writer.WriteStartElement("Rooms"); foreach (Room r in rooms) { if (GetOutsideRoom() == r) { // Skip the outside room. Alternatively, should SetupWorld be changed to not create one? continue; } writer.WriteStartElement("Room"); r.WriteXml(writer); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Tiles"); for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { if (tiles[x, y].Type != TileType.Empty) { writer.WriteStartElement("Tile"); tiles[x, y].WriteXml(writer); writer.WriteEndElement(); } } } writer.WriteEndElement(); writer.WriteStartElement("Inventories"); foreach (string objectType in inventoryManager.inventories.Keys) { foreach (Inventory inv in inventoryManager.inventories[objectType]) { // If we don't have a tile, that means this is in a character's inventory (or some other non-tile location // which means we shouldn't save that Inventory here, the character will take care of saving and loading // the inventory properly. if (inv.tile != null) { writer.WriteStartElement("Inventory"); inv.WriteXml(writer); writer.WriteEndElement(); } } } writer.WriteEndElement(); writer.WriteStartElement("Furnitures"); foreach (Furniture furn in furnitures) { writer.WriteStartElement("Furniture"); furn.WriteXml(writer); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Characters"); foreach (Character c in characters) { writer.WriteStartElement("Character"); c.WriteXml(writer); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteElementString("Skybox", skybox.name); writer.WriteStartElement("Wallet"); foreach (Currency currency in Wallet.Currencies.Values) { writer.WriteStartElement("Currency"); currency.WriteXml(writer); writer.WriteEndElement(); } writer.WriteEndElement(); } public void ReadXml(XmlReader reader) { // Load info here Width = int.Parse(reader.GetAttribute("Width")); Height = int.Parse(reader.GetAttribute("Height")); SetupWorld(Width, Height); while (reader.Read()) { switch (reader.Name) { case "Rooms": ReadXml_Rooms(reader); break; case "Tiles": ReadXml_Tiles(reader); break; case "Inventories": ReadXml_Inventories(reader); break; case "Furnitures": ReadXml_Furnitures(reader); break; case "Characters": ReadXml_Characters(reader); break; case "Skybox": LoadSkybox(reader.ReadElementString("Skybox")); break; case "Wallet": ReadXml_Wallet(reader); break; } } // DEBUGGING ONLY! REMOVE ME LATER! // Create an Inventory Item Inventory inv = new Inventory("Steel Plate", 50, 50); Tile t = GetTileAt(Width / 2, Height / 2); inventoryManager.PlaceInventory(t, inv); if (OnInventoryCreated != null) { OnInventoryCreated(t.Inventory); } inv = new Inventory("Steel Plate", 50, 4); t = GetTileAt((Width / 2) + 2, Height / 2); inventoryManager.PlaceInventory(t, inv); if (OnInventoryCreated != null) { OnInventoryCreated(t.Inventory); } inv = new Inventory("Copper Wire", 50, 3); t = GetTileAt((Width / 2) + 1, (Height / 2) + 2); inventoryManager.PlaceInventory(t, inv); if (OnInventoryCreated != null) { OnInventoryCreated(t.Inventory); } } public void <API key>(Inventory inv) { if (OnInventoryCreated != null) { OnInventoryCreated(inv); } } public void OnFurnitureRemoved(Furniture furn) { furnitures.Remove(furn); } private void ReadXml_Wallet(XmlReader reader) { if (reader.ReadToDescendant("Currency")) { do { Currency c = new Currency { Name = reader.GetAttribute("Name"), ShortName = reader.GetAttribute("ShortName"), Balance = float.Parse(reader.GetAttribute("Balance")) }; Wallet.Currencies[c.Name] = c; } while (reader.ReadToNextSibling("Character")); } } private void LoadSkybox(string name = null) { DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(Application.dataPath, "Resources/Skyboxes")); if (!dirInfo.Exists) { dirInfo.Create(); } FileInfo[] files = dirInfo.GetFiles("*.mat", SearchOption.AllDirectories); if (files.Length > 0) { string resourcePath = string.Empty; FileInfo file = null; if (!string.IsNullOrEmpty(name)) { foreach (FileInfo fileInfo in files) { if (name.Equals(fileInfo.Name.Remove(fileInfo.Name.LastIndexOf(".")))) { file = fileInfo; break; } } } // Maybe we passed in a name that doesn't exist? Pick a random skybox. if (file == null) { // Get random file file = files[(int)(UnityEngine.Random.value * files.Length)]; } resourcePath = Path.Combine(file.DirectoryName.Substring(file.DirectoryName.IndexOf("Skyboxes")), file.Name); if (resourcePath.Contains(".")) { resourcePath = resourcePath.Remove(resourcePath.LastIndexOf(".")); } skybox = Resources.Load<Material>(resourcePath); RenderSettings.skybox = skybox; } else { Debug.ULogWarningChannel("World", "No skyboxes detected! Falling back to black."); } } private void SetupWorld(int width, int height) { // Setup furniture actions before any other things are loaded. new FurnitureActions(); jobQueue = new JobQueue(); jobWaitingQueue = new JobQueue(); // Set the current world to be this world. // TODO: Do we need to do any cleanup of the old world? Current = this; Width = width; Height = height; TileType.LoadTileTypes(); tiles = new Tile[Width, Height]; rooms = new List<Room>(); rooms.Add(new Room()); // Create the outside? for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { tiles[x, y] = new Tile(x, y); tiles[x, y].TileChanged += <API key>; tiles[x, y].Room = GetOutsideRoom(); // Rooms 0 is always going to be outside, and that is our default room } } CreateWallet(); characters = new List<Character>(); furnitures = new List<Furniture>(); inventoryManager = new InventoryManager(); PowerSystem = new Syster(); temperature = new Temperature(Width, Height); LoadSkybox(); } private void CreateWallet() { Wallet = new Wallet(); string dataPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Data"); string filePath = System.IO.Path.Combine(dataPath, "Currency.xml"); string xmlText = System.IO.File.ReadAllText(filePath); <API key>(xmlText); DirectoryInfo[] mods = WorldController.Instance.modsManager.GetMods(); foreach (DirectoryInfo mod in mods) { string xmlModFile = System.IO.Path.Combine(mod.FullName, "Currency.xml"); if (File.Exists(xmlModFile)) { string xmlModText = System.IO.File.ReadAllText(xmlModFile); <API key>(xmlModText); } } } private void <API key>(string xmlText) { XmlTextReader reader = new XmlTextReader(new StringReader(xmlText)); if (reader.ReadToDescendant("Currencies")) { try { Wallet.ReadXmlPrototype(reader); } catch (Exception e) { Debug.LogError("Error reading Currency " + Environment.NewLine + "Exception: " + e.Message + Environment.NewLine + "StackTrace: " + e.StackTrace); } } else { Debug.LogError("Did not find a 'Currencies' element in the prototype definition file."); } } // Gets called whenever ANY tile changes private void <API key>(Tile t) { if (OnTileChanged == null) { return; } OnTileChanged(t); // InvalidateTileGraph(); if (tileGraph != null) { tileGraph.<API key>(t); } } private void ReadXml_Tiles(XmlReader reader) { // We are in the "Tiles" element, so read elements until // we run out of "Tile" nodes. if (reader.ReadToDescendant("Tile")) { // We have at least one tile, so do something with it. do { int x = int.Parse(reader.GetAttribute("X")); int y = int.Parse(reader.GetAttribute("Y")); tiles[x, y].ReadXml(reader); } while (reader.ReadToNextSibling("Tile")); } } private void ReadXml_Inventories(XmlReader reader) { Debug.ULogChannel("World", "ReadXml_Inventories"); if (reader.ReadToDescendant("Inventory")) { do { int x = int.Parse(reader.GetAttribute("X")); int y = int.Parse(reader.GetAttribute("Y")); // Create our inventory from the file Inventory inv = new Inventory( reader.GetAttribute("objectType"), int.Parse(reader.GetAttribute("maxStackSize")), int.Parse(reader.GetAttribute("stackSize"))); inventoryManager.PlaceInventory(tiles[x, y], inv); } while (reader.ReadToNextSibling("Inventory")); } } private void ReadXml_Furnitures(XmlReader reader) { if (reader.ReadToDescendant("Furniture")) { do { int x = int.Parse(reader.GetAttribute("X")); int y = int.Parse(reader.GetAttribute("Y")); Furniture furn = PlaceFurniture(reader.GetAttribute("objectType"), tiles[x, y], false); furn.ReadXml(reader); } while (reader.ReadToNextSibling("Furniture")); } } private void ReadXml_Rooms(XmlReader reader) { if (reader.ReadToDescendant("Room")) { do { Room r = new Room(); rooms.Add(r); r.ReadXml(reader); } while (reader.ReadToNextSibling("Room")); } } private void ReadXml_Characters(XmlReader reader) { if (reader.ReadToDescendant("Character")) { do { Character character; int x = int.Parse(reader.GetAttribute("X")); int y = int.Parse(reader.GetAttribute("Y")); if (reader.GetAttribute("r") != null) { float r = float.Parse(reader.GetAttribute("r")); float b = float.Parse(reader.GetAttribute("b")); float g = float.Parse(reader.GetAttribute("g")); Color color = new Color(r, g, b, 1.0f); character = CreateCharacter(tiles[x, y], color); } else { character = CreateCharacter(tiles[x, y]); } character.name = reader.GetAttribute("name"); character.ReadXml(reader); if (reader.ReadToDescendant("Inventories")) { if (reader.ReadToDescendant("Inventory")) { do { // Create our inventory from the file Inventory inv = new Inventory( reader.GetAttribute("objectType"), int.Parse(reader.GetAttribute("maxStackSize")), int.Parse(reader.GetAttribute("stackSize"))); inventoryManager.PlaceInventory(character, inv); } while (reader.ReadToNextSibling("Inventory")); // One more read to step out of Inventories, so ReadToNextSibling will find sibling Character reader.Read(); } } } while (reader.ReadToNextSibling("Character")); } } }
#!/usr/bin/env python3 # vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab # This file is part of SmartHomeNG # SmartHomeNG is free software: you can redistribute it and/or modifyNode.js Design Patterns - Second Edition # (at your option) any later version. # SmartHomeNG is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # TO DO # - consolidate with plugin.py """ This library implements loading and starting of core modules of SmartHomeNG. The methods of the class Modules implement the API for modules. They can be used the following way: To call eg. **xxx()**, use the following syntax: .. code-block:: python from lib.module import Modules modules = Modules.get_instance() # to access a method (eg. enable_logic()): moddules.xxx() :Warning: This library is part of the core of SmartHomeNG. It **should not be called directly** from plugins! """ import logging #import threading import inspect import os import lib.config import lib.translation as translation from lib.constants import (KEY_CLASS_NAME, KEY_CLASS_PATH, KEY_INSTANCE,CONF_FILE) from lib.utils import Utils from lib.metadata import Metadata logger = logging.getLogger(__name__) _modules_instance = None # Pointer to the initialized instance of the Modules class (for use by static methods) class Modules(): """ Module loader class. Parses config file and creates an instance for each module. To start the modules, the start() method has to be called. :param smarthome: Instance of the smarthome master-object :param configfile: Basename of the module configuration file :type samrthome: object :type configfile: str """ _modules = [] _moduledict = {} def __init__(self, smarthome, configfile): self._sh = smarthome self._basedir = smarthome.get_basedir() # self._sh._moduledict = {} global _modules_instance if _modules_instance is not None: import inspect curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 4) logger.critical("A second 'modules' object has been created. There should only be ONE instance of class 'Modules'!!! Called from: {} ({})".format(calframe[1][1], calframe[1][3])) _modules_instance = self # read module configuration (from etc/module.yaml) _conf = lib.config.parse_basename(configfile, configtype='module') if _conf == {}: return for module in _conf: logger.debug("Modules, section: {}".format(module)) module_name, self.meta = self.<API key>(module, _conf[module]) if module_name != '' and self.meta is not None: if self.meta.<API key>() and self.meta.<API key>(): args = self._get_conf_args(_conf[module]) classname, classpath = self.<API key>(_conf[module], module_name) if not self.<API key>(module, classname): try: self._load_module(module, classname, classpath, args) except Exception as e: logger.exception("Module {0} exception: {1}".format(module, e)) else: logger.warning("Section '{}' ignored".format(module)) logger.info('Loaded Modules: {}'.format( str( self.return_modules() ) ) ) # clean up (module configuration from module.yaml) del(_conf) # clean up return def <API key>(self, module, mod_conf): """ Return the actual module name and the metadata instance :param mod_conf: loaded section of the module.yaml for the actual module :type mod_conf: dict :return: module_name and metadata_instance :rtype: string, object """ module_name = mod_conf.get('module_name','').lower() meta = None if module_name != '': module_dir = os.path.join(self._basedir, 'modules', module_name) if os.path.isdir(module_dir): meta = Metadata(self._sh, module_name, 'module') else: logger.warning("Section '{}': No module directory {} found".format(module, module_dir)) else: classpath = mod_conf.get(KEY_CLASS_PATH,'') if classpath != '': module_name = classpath.split('.')[len(classpath.split('.'))-1].lower() logger.info("Section '{}': module_name '{}' was extracted from classpath '{}'".format(module, module_name, classpath)) meta = Metadata(self._sh, module_name, 'module', classpath) else: logger.info("Section '{}': No attribute 'module_name' found in configuration".format(module)) return (module_name, meta) def _get_conf_args(self, mod_conf): """ Return the parameters/values for the actual module as args-dict :param mod_conf: loaded section of the module.yaml for the actual module :type mod_conf: dict :return: args = specified parameters and their values :rtype: dict """ args = {} for arg in mod_conf: if arg != KEY_CLASS_NAME and arg != KEY_CLASS_PATH and arg != KEY_INSTANCE: value = mod_conf[arg] if isinstance(value, str): value = "'{0}'".format(value) args[arg] = value return args def <API key>(self, mod_conf, module_name): """ Returns the classname and the classpath for the actual module :param mod_conf: loaded section of the module.yaml for the actual module :param module_name: Module name (to be used, for building classpass, if it is not specified in the configuration :type mod_conf: dict :type module_name: str :return: classname, classpass :rtype: str, str """ classname = self.meta.get_string('classname') if classname == '': classname = mod_conf.get(KEY_CLASS_NAME,'') try: classpath = mod_conf[KEY_CLASS_PATH] except: classpath = 'modules.' + module_name return (classname, classpath) def <API key>(self, module, classname): """ Returns True, if a module instance of the classname is already loaded by another configuration section :param module: Name of the configuration :param classname: Name of the class to check :type module: str :type classname: str :return: True, if module is already loaded :rtype: bool """ # give a warning if a module uses the same class twice duplicate = False for m in self._modules: if m.__class__.__name__ == classname: duplicate = True logger.warning("Modules, section '{}': Multiple module instances of class '{}' detected, additional instance not initialized".format(module, classname)) return duplicate def _load_module(self, name, classname, classpath, args): """ Module Loader. Loads one module defined by the parameters classname and classpath. Parameters defined in the configuration file are passed to this function as 'args' :param name: Section name in module configuration file (etc/module.yaml) :param classname: Name of the (main) class in the module :param classpath: Path to the Python file containing the class :param args: Parameter as specified in the configuration file (etc/module.yaml) :type name: str :type classname: str :type classpath: str :type args: dict :return: loaded module :rtype: object """ logger.debug('_load_module: Section {}, Module {}, classpath {}'.format( name, classname, classpath )) enabled = Utils.strip_quotes(args.get('enabled', 'true').lower()) if enabled == 'false': logger.warning("Not loading module {} from section '{}': Module is disabled".format(classname, name)) return logger.info("Loading module '{}': args = '{}'".format(name, args)) # Load an instance of the module try: exec("import {0}".format(classpath)) except Exception as e: logger.critical("Module '{}' ({}) exception during import of __init__.py: {}".format(name, classpath, e)) return None try: exec("self.loadedmodule = {0}.{1}.__new__({0}.{1})".format(classpath, classname)) except Exception as e: #logger.error("Module '{}' ({}) exception during initialization: {}".format(name, classpath, e)) pass # load module-specific translations translation.load_translations('module', classpath.replace('.', '/'), 'module/'+classpath.split('.')[1]) # get arguments defined in __init__ of module's class to self.args try: # exec("self.args = inspect.getargspec({0}.{1}.__init__)[0][1:]".format(classpath, classname)) exec("self.args = inspect.getfullargspec({0}.{1}.__init__)[0][1:]".format(classpath, classname)) except Exception as e: logger.critical("Module '{}' ({}) exception during call to __init__.py: {}".format(name, classpath, e)) return None #logger.warning("- self.args = '{}'".format(self.args)) # get list of argument used names, if they are defined in the module's class logger.info("Module '{}': args = '{}'".format(classname, str(args))) arglist = [name for name in self.args if name in args] argstring = ",".join(["{}={}".format(name, args[name]) for name in arglist]) self.loadedmodule._init_complete = False (module_params, params_ok, hide_params) = self.meta.check_parameters(args) if params_ok == True: if module_params != {}: # initialize parameters the old way argstring = ",".join(["{}={}".format(name, "'"+str(module_params.get(name,''))+"'") for name in arglist]) # initialize parameters the new way: Define a dict within the instance self.loadedmodule._parameters = module_params self.loadedmodule._metadata = self.meta # initialize the loaded instance of the module self.loadedmodule._init_complete = True # set to false by module, if an initalization error occurs exec("self.loadedmodule.__init__(self._sh{0}{1})".format("," if len(arglist) else "", argstring)) if self.loadedmodule._init_complete == True: try: code_version = self.loadedmodule.version except: code_version = None # if module code without version if self.meta.test_version(code_version): logger.info("Modules: Loaded module '{}' (class '{}') v{}: {}".format( name, str(self.loadedmodule.__class__.__name__), self.meta.get_version(), self.meta.get_mlstring('description') ) ) self._moduledict[name] = self.loadedmodule self._modules.append(self._moduledict[name]) return self.loadedmodule else: return None else: logger.error("Modules: Module '{}' initialization failed, module not loaded".format(classpath.split('.')[1])) return None # Following (static) methods of the class Modules implement the API for modules in shNG @staticmethod def get_instance(): """ Returns the instance of the Modules class, to be used to access the modules-api Use it the following way to access the api: .. code-block:: python from lib.module import Modules modules = Modules.get_instance() # to access a method (eg. xxx()): modules.xxx() :return: modules instance :rtype: object of None """ if _modules_instance == None: return None else: return _modules_instance def return_modules(self): """ Returns a list with the names of all loaded modules :return: list of module names :rtype: list """ l = [] for module_key in self._moduledict.keys(): l.append(module_key) return l def get_module(self, name): """ Returns the module object for the module named by the parameter or None, if the named module is not loaded :param name: Name of the module to return :type name: str :return: list of module names :rtype: object """ return self._moduledict.get(name) def start(self): """ Start all modules Call start routine of module in case the module wants to start any threads """ logger.info('Start Modules') for module in self.return_modules(): logger.debug('Starting {} Module'.format(module)) self.m = self.get_module(module) self.m.start() def stop(self): """ Stop all modules Call stop routine of module to clean up in case the module has started any threads """ logger.info('Stop Modules') module_list = self.return_modules() # stop modules in revered order (module started first is stopped last) module_list.reverse() for module in module_list: logger.debug('Stopping {} Module'.format(module)) self.m = self.get_module(module) try: self.m.stop() # except: # pass except Exception as e: logger.warning("Error while stopping module '{}'\n-> {}".format(module, e))