answer
stringlengths 15
1.25M
|
|---|
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Special targets provided by cmake.
# Disable implicit rules so canoncical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .<API key>
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/Bootstrap.cmk/cmake
# The command to remove a file.
RM = /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/Bootstrap.cmk/cmake -E remove -f
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@echo "Running interactive CMake command-line interface..."
../../Bootstrap.cmk/cmake -i .
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target install
install: preinstall
@echo "Install the project..."
../../bin/cmake -P cmake_install.cmake
.PHONY : install
# Special rule for the target install
install/fast: preinstall/fast
@echo "Install the project..."
../../bin/cmake -P cmake_install.cmake
.PHONY : install/fast
# Special rule for the target install/local
install/local: preinstall
@echo "Installing only the local directory..."
../../bin/cmake -<API key>=1 -P cmake_install.cmake
.PHONY : install/local
# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast
# Special rule for the target install/strip
install/strip: preinstall
@echo "Installing the project stripped..."
../../bin/cmake -<API key>=1 -P cmake_install.cmake
.PHONY : install/strip
# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast
# Special rule for the target <API key>
<API key>:
@echo "Available install components are: \"Unspecified\""
.PHONY : <API key>
# Special rule for the target <API key>
<API key>/fast: <API key>
.PHONY : <API key>/fast
# Special rule for the target package
package: preinstall
@echo "Run CPack packaging tool..."
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/bin/cpack --config ./CPackConfig.cmake
.PHONY : package
# Special rule for the target package
package/fast: package
.PHONY : package/fast
# Special rule for the target package_source
package_source:
@echo "Run CPack packaging tool for source..."
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/bin/cpack --config ./CPackSourceConfig.cmake /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/CPackSourceConfig.cmake
.PHONY : package_source
# Special rule for the target package_source
package_source/fast: package_source
.PHONY : package_source/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@echo "Running CMake to regenerate build system..."
../../Bootstrap.cmk/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target test
test:
@echo "Running tests..."
../../bin/ctest --<API key> $(ARGS)
.PHONY : test
# Special rule for the target test
test/fast: test
.PHONY : test/fast
# The main all target
all: <API key>
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(CMAKE_COMMAND) -E <API key> /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/CMakeFiles /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/Utilities/cmzlib/CMakeFiles/progress.marks
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f CMakeFiles/Makefile2 Utilities/cmzlib/all
$(CMAKE_COMMAND) -E <API key> /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f CMakeFiles/Makefile2 Utilities/cmzlib/clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f CMakeFiles/Makefile2 Utilities/cmzlib/preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f CMakeFiles/Makefile2 Utilities/cmzlib/preinstall
.PHONY : preinstall/fast
# clear depends
depend:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
# Convenience name for target.
Utilities/cmzlib/CMakeFiles/cmzlib.dir/rule:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f CMakeFiles/Makefile2 Utilities/cmzlib/CMakeFiles/cmzlib.dir/rule
.PHONY : Utilities/cmzlib/CMakeFiles/cmzlib.dir/rule
# Convenience name for target.
cmzlib: Utilities/cmzlib/CMakeFiles/cmzlib.dir/rule
.PHONY : cmzlib
# fast build rule for target.
cmzlib/fast:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/build
.PHONY : cmzlib/fast
# target to build an object file
adler32.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/adler32.o
.PHONY : adler32.o
# target to preprocess a source file
adler32.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/adler32.i
.PHONY : adler32.i
# target to generate assembly for a file
adler32.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/adler32.s
.PHONY : adler32.s
# target to build an object file
compress.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/compress.o
.PHONY : compress.o
# target to preprocess a source file
compress.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/compress.i
.PHONY : compress.i
# target to generate assembly for a file
compress.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/compress.s
.PHONY : compress.s
# target to build an object file
crc32.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/crc32.o
.PHONY : crc32.o
# target to preprocess a source file
crc32.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/crc32.i
.PHONY : crc32.i
# target to generate assembly for a file
crc32.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/crc32.s
.PHONY : crc32.s
# target to build an object file
deflate.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/deflate.o
.PHONY : deflate.o
# target to preprocess a source file
deflate.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/deflate.i
.PHONY : deflate.i
# target to generate assembly for a file
deflate.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/deflate.s
.PHONY : deflate.s
# target to build an object file
gzio.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/gzio.o
.PHONY : gzio.o
# target to preprocess a source file
gzio.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/gzio.i
.PHONY : gzio.i
# target to generate assembly for a file
gzio.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/gzio.s
.PHONY : gzio.s
# target to build an object file
inffast.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inffast.o
.PHONY : inffast.o
# target to preprocess a source file
inffast.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inffast.i
.PHONY : inffast.i
# target to generate assembly for a file
inffast.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inffast.s
.PHONY : inffast.s
# target to build an object file
inflate.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inflate.o
.PHONY : inflate.o
# target to preprocess a source file
inflate.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inflate.i
.PHONY : inflate.i
# target to generate assembly for a file
inflate.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inflate.s
.PHONY : inflate.s
# target to build an object file
inftrees.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inftrees.o
.PHONY : inftrees.o
# target to preprocess a source file
inftrees.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inftrees.i
.PHONY : inftrees.i
# target to generate assembly for a file
inftrees.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/inftrees.s
.PHONY : inftrees.s
# target to build an object file
trees.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/trees.o
.PHONY : trees.o
# target to preprocess a source file
trees.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/trees.i
.PHONY : trees.i
# target to generate assembly for a file
trees.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/trees.s
.PHONY : trees.s
# target to build an object file
uncompr.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/uncompr.o
.PHONY : uncompr.o
# target to preprocess a source file
uncompr.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/uncompr.i
.PHONY : uncompr.i
# target to generate assembly for a file
uncompr.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/uncompr.s
.PHONY : uncompr.s
# target to build an object file
zutil.o:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/zutil.o
.PHONY : zutil.o
# target to preprocess a source file
zutil.i:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/zutil.i
.PHONY : zutil.i
# target to generate assembly for a file
zutil.s:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(MAKE) -f Utilities/cmzlib/CMakeFiles/cmzlib.dir/build.make Utilities/cmzlib/CMakeFiles/cmzlib.dir/zutil.s
.PHONY : zutil.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... cmzlib"
@echo "... edit_cache"
@echo "... install"
@echo "... install/local"
@echo "... install/strip"
@echo "... <API key>"
@echo "... package"
@echo "... package_source"
@echo "... rebuild_cache"
@echo "... test"
@echo "... adler32.o"
@echo "... adler32.i"
@echo "... adler32.s"
@echo "... compress.o"
@echo "... compress.i"
@echo "... compress.s"
@echo "... crc32.o"
@echo "... crc32.i"
@echo "... crc32.s"
@echo "... deflate.o"
@echo "... deflate.i"
@echo "... deflate.s"
@echo "... gzio.o"
@echo "... gzio.i"
@echo "... gzio.s"
@echo "... inffast.o"
@echo "... inffast.i"
@echo "... inffast.s"
@echo "... inflate.o"
@echo "... inflate.i"
@echo "... inflate.s"
@echo "... inftrees.o"
@echo "... inftrees.i"
@echo "... inftrees.s"
@echo "... trees.o"
@echo "... trees.i"
@echo "... trees.s"
@echo "... uncompr.o"
@echo "... uncompr.i"
@echo "... uncompr.s"
@echo "... zutil.o"
@echo "... zutil.i"
@echo "... zutil.s"
.PHONY : help
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
<API key>:
cd /home/fdkit/GPL-AirCam-v1.2/openwrt/build_dir/host/cmake-2.8.4 && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : <API key>
|
{# This file was generated with the ext-templateevents:generate command. #}
{%- if <API key>.enable -%}
<a class="templateevents" title="3.1.0-b3&
{%- endif -%}
|
#ifndef <API key>
#define <API key>
#include <linux/mm.h>
#include <asm/glue.h>
#include <asm/shmparam.h>
#include <asm/cachetype.h>
#define CACHE_COLOUR(vaddr) ((vaddr & (SHMLBA - 1)) >> PAGE_SHIFT)
#undef _CACHE
#undef MULTI_CACHE
#if defined(CONFIG_CPU_CACHE_V3)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE v3
# endif
#endif
#if defined(CONFIG_CPU_CACHE_V4)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE v4
# endif
#endif
#if defined(CONFIG_CPU_ARM920T) || defined(CONFIG_CPU_ARM922T) || \
defined(CONFIG_CPU_ARM925T) || defined(CONFIG_CPU_ARM1020)
# define MULTI_CACHE 1
#endif
#if defined(CONFIG_CPU_FA526)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE fa
# endif
#endif
#if defined(CONFIG_CPU_ARM926T)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE arm926
# endif
#endif
#if defined(CONFIG_CPU_ARM940T)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE arm940
# endif
#endif
#if defined(CONFIG_CPU_ARM946E)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE arm946
# endif
#endif
#if defined(<API key>)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE v4wb
# endif
#endif
#if defined(CONFIG_CPU_XSCALE)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE xscale
# endif
#endif
#if defined(CONFIG_CPU_XSC3)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE xsc3
# endif
#endif
#if defined(CONFIG_CPU_MOHAWK)
# ifdef _CACHE
# define MULTI_CACHE 1
# else
# define _CACHE mohawk
# endif
#endif
#if defined(CONFIG_CPU_FEROCEON)
# define MULTI_CACHE 1
#endif
#if defined(CONFIG_CPU_V6)
//# ifdef _CACHE
# define MULTI_CACHE 1
//# else
//# define _CACHE v6
//# endif
#endif
#if defined(CONFIG_CPU_V7)
//# ifdef _CACHE
# define MULTI_CACHE 1
//# else
//# define _CACHE v7
//# endif
#endif
#if !defined(_CACHE) && !defined(MULTI_CACHE)
#error Unknown cache maintainence model
#endif
/*
* This flag is used to indicate that the page pointed to by a pte
* is dirty and requires cleaning before returning it to the user.
*/
#define PG_dcache_dirty PG_arch_1
struct cpu_cache_fns {
void (*flush_kern_all)(void);
void (*flush_user_all)(void);
void (*flush_user_range)(unsigned long, unsigned long, unsigned int);
void (*coherent_kern_range)(unsigned long, unsigned long);
void (*coherent_user_range)(unsigned long, unsigned long);
void (*<API key>)(void *);
void (*dma_inv_range)(const void *, const void *);
void (*dma_clean_range)(const void *, const void *);
void (*dma_flush_range)(const void *, const void *);
};
struct outer_cache_fns {
void (*inv_range)(unsigned long, unsigned long);
void (*clean_range)(unsigned long, unsigned long);
void (*flush_range)(unsigned long, unsigned long);
};
/*
* Select the calling method
*/
#ifdef MULTI_CACHE
extern struct cpu_cache_fns cpu_cache;
#define <API key> cpu_cache.flush_kern_all
#define <API key> cpu_cache.flush_user_all
#define <API key> cpu_cache.flush_user_range
#define <API key> cpu_cache.coherent_kern_range
#define <API key> cpu_cache.coherent_user_range
#define <API key> cpu_cache.<API key>
/*
* These are private to the dma-mapping API. Do not use directly.
* Their sole purpose is to ensure that data held in the cache
* is visible to DMA, or data written by DMA to system memory is
* visible to the CPU.
*/
#define dmac_inv_range cpu_cache.dma_inv_range
#define dmac_clean_range cpu_cache.dma_clean_range
#define dmac_flush_range cpu_cache.dma_flush_range
#else
#define <API key> __glue(_CACHE,<API key>)
#define <API key> __glue(_CACHE,<API key>)
#define <API key> __glue(_CACHE,<API key>)
#define <API key> __glue(_CACHE,<API key>)
#define <API key> __glue(_CACHE,<API key>)
#define <API key> __glue(_CACHE,<API key>)
extern void <API key>(void);
extern void <API key>(void);
extern void <API key>(unsigned long, unsigned long, unsigned int);
extern void <API key>(unsigned long, unsigned long);
extern void <API key>(unsigned long, unsigned long);
extern void <API key>(void *);
/*
* These are private to the dma-mapping API. Do not use directly.
* Their sole purpose is to ensure that data held in the cache
* is visible to DMA, or data written by DMA to system memory is
* visible to the CPU.
*/
#define dmac_inv_range __glue(_CACHE,_dma_inv_range)
#define dmac_clean_range __glue(_CACHE,_dma_clean_range)
#define dmac_flush_range __glue(_CACHE,_dma_flush_range)
extern void dmac_inv_range(const void *, const void *);
extern void dmac_clean_range(const void *, const void *);
extern void dmac_flush_range(const void *, const void *);
#endif
#ifdef CONFIG_OUTER_CACHE
extern struct outer_cache_fns outer_cache;
static inline void outer_inv_range(unsigned long start, unsigned long end)
{
if (outer_cache.inv_range)
outer_cache.inv_range(start, end);
}
static inline void outer_clean_range(unsigned long start, unsigned long end)
{
if (outer_cache.clean_range)
outer_cache.clean_range(start, end);
}
static inline void outer_flush_range(unsigned long start, unsigned long end)
{
if (outer_cache.flush_range)
outer_cache.flush_range(start, end);
}
#else
static inline void outer_inv_range(unsigned long start, unsigned long end)
{ }
static inline void outer_clean_range(unsigned long start, unsigned long end)
{ }
static inline void outer_flush_range(unsigned long start, unsigned long end)
{ }
#endif
/*
* Copy user data from/to a page which is mapped into a different
* processes address space. Really, we want to allow our "user
* space" model to handle this.
*/
#define copy_to_user_page(vma, page, vaddr, dst, src, len) \
do { \
memcpy(dst, src, len); \
flush_ptrace_access(vma, page, vaddr, dst, len, 1);\
} while (0)
#define copy_from_user_page(vma, page, vaddr, dst, src, len) \
do { \
memcpy(dst, src, len); \
} while (0)
/*
* Convert calls to our calling convention.
*/
#define flush_cache_all() <API key>()
#ifndef <API key>
static inline void flush_cache_mm(struct mm_struct *mm)
{
if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(mm)))
<API key>();
}
static inline void
flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end)
{
if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(vma->vm_mm)))
<API key>(start & PAGE_MASK, PAGE_ALIGN(end),
vma->vm_flags);
}
static inline void
flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn)
{
if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(vma->vm_mm))) {
unsigned long addr = user_addr & PAGE_MASK;
<API key>(addr, addr + PAGE_SIZE, vma->vm_flags);
}
}
static inline void
flush_ptrace_access(struct vm_area_struct *vma, struct page *page,
unsigned long uaddr, void *kaddr,
unsigned long len, int write)
{
if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(vma->vm_mm))) {
unsigned long addr = (unsigned long)kaddr;
<API key>(addr, addr + len);
}
}
#else
extern void flush_cache_mm(struct mm_struct *mm);
extern void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end);
extern void flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn);
extern void flush_ptrace_access(struct vm_area_struct *vma, struct page *page,
unsigned long uaddr, void *kaddr,
unsigned long len, int write);
#endif
#define flush_cache_dup_mm(mm) flush_cache_mm(mm)
/*
* <API key> is used when we want to ensure that the
* Harvard caches are synchronised for the user space address range.
* This is used for the ARM private sys_cacheflush system call.
*/
#define <API key>(vma,start,end) \
<API key>((start) & PAGE_MASK, PAGE_ALIGN(end))
/*
* Perform necessary cache operations to ensure that data previously
* stored within this range of addresses can be executed by the CPU.
*/
#define flush_icache_range(s,e) <API key>(s,e)
/*
* Perform necessary cache operations to ensure that the TLB will
* see data written in the specified area.
*/
#define clean_dcache_area(start,size) <API key>(start, size)
/*
* flush_dcache_page is used when the kernel has written to the page
* cache page at virtual address page->virtual.
*
* If this page isn't mapped (ie, page_mapping == NULL), or it might
* have userspace mappings, then we _must_ always clean + invalidate
* the dcache entries associated with the kernel mapping.
*
* Otherwise we can defer the operation, and clean the cache when we are
* about to change to user space. This is the same method as used on SPARC64.
* See update_mmu_cache for the user space part.
*/
extern void flush_dcache_page(struct page *);
extern void __flush_dcache_page(struct address_space *mapping, struct page *page);
static inline void __flush_icache_all(void)
{
#ifdef <API key>
extern void v6_icache_inval_all(void);
v6_icache_inval_all();
#else
#ifdef <API key>
asm("mcr p15, 0, %0, c7, c5, 0 @ invalidate I-cache\n"
:
: "r" (0));
#endif
asm("mcr p15, 0, %0, c7, c5, 0 @ invalidate I-cache\n"
:
: "r" (0));
#endif
asm("mcr p15, 0, %0, c7, c5, 4 @ ISB is required per ARM spec\n"
:
: "r" (0));
}
#define <API key>
static inline void flush_anon_page(struct vm_area_struct *vma,
struct page *page, unsigned long vmaddr)
{
extern void __flush_anon_page(struct vm_area_struct *vma,
struct page *, unsigned long);
if (PageAnon(page))
__flush_anon_page(vma, page, vmaddr);
}
#define <API key>
static inline void <API key>(struct page *page)
{
/* highmem pages are always flushed upon kunmap already */
if ((cache_is_vivt() || <API key>()) && !PageHighMem(page))
<API key>(page_address(page));
}
#define <API key>(mapping) \
spin_lock_irq(&(mapping)->tree_lock)
#define <API key>(mapping) \
spin_unlock_irq(&(mapping)->tree_lock)
#define <API key>(vma,page,addr,len) \
flush_dcache_page(page)
/*
* We don't appear to need to do anything here. In fact, if we did, we'd
* duplicate cache flushing elsewhere performed by flush_dcache_page().
*/
#define flush_icache_page(vma,page) do { } while (0)
static inline void <API key>(unsigned long phys, void __iomem *virt,
unsigned offset, size_t size)
{
const void *start = (void __force *)virt + offset;
dmac_inv_range(start, start + size);
}
/*
* flush_cache_vmap() is used when creating mappings (eg, via vmap,
* vmalloc, ioremap etc) in kernel space for pages. On non-VIPT
* caches, since the direct-mappings of these pages may contain cached
* data, we need to do a full cache flush to ensure that writebacks
* don't corrupt data placed into these pages via the new mappings.
*/
static inline void flush_cache_vmap(unsigned long start, unsigned long end)
{
if (!<API key>())
flush_cache_all();
else
/*
* set_pte_at() called from vmap_pte_range() does not
* have a DSB after cleaning the cache line.
*/
dsb();
}
static inline void flush_cache_vunmap(unsigned long start, unsigned long end)
{
if (!<API key>())
flush_cache_all();
}
#endif
|
<!DOCTYPE html PUBLIC "-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/js.cookie.js"></script>
<title>BenchmarkTest02509</title>
</head>
<body>
<form action="/benchmark/BenchmarkTest02509" method="GET" id="<API key>">
<div><label>Please enter your details:</label></div>
<br/>
<div><label>Username:</label></div>
<div><input type="text" id="username" name="username"></input></div>
<div><label>Password:</label></div>
<div><input type="text" id="password" name="password" value=""></input></div>
<div> </div>
<div><label>Parameter: vector <BR> Value:</label>
<input type="text" id="vector" name="vector" value="someSecret"></input></div>
<br/>
<div><input type="submit" value="Login" /></div>
</form>
</body>
</html>
|
/* vi: set sw=4 ts=4: */
//config:config NICE
//config: bool "nice (1.8 kb)"
//config: default y
//config: help
//config: nice runs a program with modified scheduling priority.
//applet:IF_NICE(APPLET_NOEXEC(nice, nice, BB_DIR_BIN, BB_SUID_DROP, nice))
//kbuild:lib-$(CONFIG_NICE) += nice.o
//usage:#define nice_trivial_usage
//usage: "[-n ADJUST] [PROG ARGS]"
//usage:#define nice_full_usage "\n\n"
//usage: "Change scheduling priority, run PROG\n"
//usage: "\n -n ADJUST Adjust priority by ADJUST"
#include <sys/resource.h>
#include "libbb.h"
int nice_main(int argc, char **argv) <API key>;
int nice_main(int argc, char **argv)
{
int old_priority, adjustment;
old_priority = getpriority(PRIO_PROCESS, 0);
if (!*++argv) { /* No args, so (GNU) output current nice value. */
printf("%d\n", old_priority);
<API key>(EXIT_SUCCESS);
}
adjustment = 10; /* Set default adjustment. */
if (argv[0][0] == '-') {
if (argv[0][1] == 'n') {
if (argv[0][2]) { /* -nNNNN (w/o space) */
argv[0] += 2; argv--; argc++;
}
} else { /* -NNN (NNN may be negative) == -n NNN */
argv[0] += 1; argv--; argc++;
}
if (argc < 4) { /* Missing priority and/or utility! */
bb_show_usage();
}
adjustment = xatoi_range(argv[1], INT_MIN/2, INT_MAX/2);
argv += 2;
}
{ /* Set our priority. */
int prio = old_priority + adjustment;
if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
<API key>("setpriority(%d)", prio);
}
}
BB_EXECVP_or_die(argv);
}
|
<?php
$gsa_agentstring = $vars['entity']->gsa_agentstring;
if (!$gsa_agentstring) { $vars['entity']->gsa_agentstring = 'gsa-crawler'; }
// agent string of the crawler
$<API key> = "<label>Federated Search GSA Agent-String</label>";
$<API key> = elgg_view('input/text', array(
'name' => 'params[gsa_agentstring]',
'value' => $vars['entity']->gsa_agentstring));
// parameters that needs to be passed in and redirect to intranet result page
$<API key> = "<label>Parameters for the GSA federated search page (Parameter name and Parameter value)</label>";
$gsa_param_key = elgg_view('input/text', array(
'name' => 'params[gsa_param_key]',
'value' => $vars['entity']->gsa_param_key));
$gsa_param_value = elgg_view('input/text', array(
'name' => 'params[gsa_param_value]',
'value' => $vars['entity']->gsa_param_value));
// for testing purposes
$gsa_user_test_label = "<label>Username to be tested (please leave empty in production)</label>";
$gsa_user_test = elgg_view('input/text', array(
'name' => 'params[gsa_test]',
'value' => $vars['entity']->gsa_test));
// css settings
$<API key> = "<label>CSS setting for pagination</label>";
$<API key> = elgg_view('input/text', array(
'name' => 'params[gsa_pagination]',
'value' => $vars['entity']->gsa_pagination));
// display to page
echo "<br/><br/>";
echo "<p>{$<API key>}{$<API key>}</p>";
echo "<p>{$<API key>}{$gsa_param_key}{$gsa_param_value}</p>";
echo "<p>{$gsa_user_test_label}{$gsa_user_test}</p>";
echo "<p>{$<API key>}{$<API key>}</p>";
|
#ifndef LDEMUL_H
#define LDEMUL_H
/* Forward declaration for ldemul_add_options() and others. */
struct option;
extern void ldemul_hll
(char *);
extern void ldemul_syslib
(char *);
extern void ldemul_after_parse
(void);
extern void ldemul_before_parse
(void);
extern void ldemul_after_open
(void);
extern void <API key>
(void);
extern void <API key>
(void);
extern void <API key>
(void);
extern char *<API key>
(int, char**);
extern void ldemul_choose_mode
(char *);
extern void <API key>
(FILE *);
extern void <API key>
(FILE *);
extern char *ldemul_get_script
(int *isfile);
extern void ldemul_finish
(void);
extern void ldemul_set_symbols
(void);
extern void <API key>
(void);
extern <API key> *ldemul_place_orphan
(asection *, const char *, int);
extern bfd_boolean ldemul_parse_args
(int, char **);
extern void ldemul_add_options
(int, char **, int, struct option **, int, struct option **);
extern bfd_boolean <API key>
(int);
extern bfd_boolean <API key>
(struct <API key> *);
extern bfd_boolean <API key>
(struct <API key> *);
extern bfd_boolean <API key>
(const char *, struct search_dirs *, struct <API key> *);
extern char *<API key>
(int, char**);
extern void after_parse_default
(void);
extern void after_open_default
(void);
extern void <API key>
(void);
extern void <API key>
(void);
extern void finish_default
(void);
extern void finish_default
(void);
extern void <API key>
(void);
extern void syslib_default
(char*);
extern void hll_default
(char*);
extern int <API key>
(char *, struct <API key> *);
extern struct <API key> *<API key>
(struct <API key> *);
typedef struct <API key> {
/* Run before parsing the command line and script file.
Set the architecture, maybe other things. */
void (*before_parse) (void);
/* Handle the SYSLIB (low level library) script command. */
void (*syslib) (char *);
/* Handle the HLL (high level library) script command. */
void (*hll) (char *);
/* Run after parsing the command line and script file. */
void (*after_parse) (void);
/* Run after opening all input files, and loading the symbols. */
void (*after_open) (void);
/* Run after allocating output sections. */
void (*after_allocation) (void);
/* Set the output architecture and machine if possible. */
void (*set_output_arch) (void);
/* Decide which target name to use. */
char * (*choose_target) (int, char**);
/* Run before allocating output sections. */
void (*before_allocation) (void);
/* Return the appropriate linker script. */
char * (*get_script) (int *isfile);
/* The name of this emulation. */
char *emulation_name;
/* The output format. */
char *target_name;
/* Run after assigning values from the script. */
void (*finish) (void);
/* Create any output sections needed by the target. */
void (*<API key>) (void);
/* Try to open a dynamic library. ARCH is an architecture name, and
is normally the empty string. ENTRY is the <API key>
that should be opened. */
bfd_boolean (*<API key>)
(const char *arch, struct search_dirs *,
struct <API key> *entry);
/* Place an orphan section. Return TRUE if it was placed, FALSE if
the default action should be taken. This field may be NULL, in
which case the default action will always be taken. */
<API key> *(*place_orphan)
(asection *, const char *, int);
/* Run after assigning parsing with the args, but before
reading the script. Used to initialize symbols used in the script. */
void (*set_symbols) (void);
/* Parse args which the base linker doesn't understand.
Return TRUE if the arg needs no further processing. */
bfd_boolean (*parse_args) (int, char **);
/* Hook to add options to parameters passed by the base linker to
getopt_long and getopt_long_only calls. */
void (*add_options)
(int, char **, int, struct option **, int, struct option **);
/* Companion to the above to handle an option. Returns TRUE if it is
one of our options. */
bfd_boolean (*handle_option) (int);
/* Run to handle files which are not recognized as object files or
archives. Return TRUE if the file was handled. */
bfd_boolean (*unrecognized_file)
(struct <API key> *);
/* Run to list the command line options which parse_args handles. */
void (* list_options) (FILE *);
/* Run to specially handle files which *are* recognized as object
files or archives. Return TRUE if the file was handled. */
bfd_boolean (*recognized_file)
(struct <API key> *);
/* Called when looking for libraries in a directory specified
via a linker command line option or linker script option.
Files that match the pattern "lib*.a" have already been scanned.
(For VMS files matching ":lib*.a" have also been scanned). */
int (* <API key>)
(char *, struct <API key> *);
/* Called when adding a new version pattern. PowerPC64-ELF uses
this hook to add a pattern matching ".foo" for every "foo". */
struct <API key> * (*new_vers_pattern)
(struct <API key> *);
} <API key>;
typedef enum {
<API key>,
default_mode_enum,
<API key>
} <API key>;
extern <API key> *ld_emulations[];
#endif
|
if not WeakAuras.IsCorrectVersion() then return end
local AddonName, Private = ...
local L = WeakAuras.L;
local root2 = math.sqrt(2);
local halfroot2 = root2/2;
local default = {
texture = "Interface\\Addons\\WeakAuras\\PowerAurasMedia\\Auras\\Aura3",
desaturate = false,
width = 200,
height = 200,
color = {1, 1, 1, 1},
blendMode = "BLEND",
textureWrapMode = "<API key>",
rotation = 0,
discrete_rotation = 0,
mirror = false,
rotate = true,
selfPoint = "CENTER",
anchorPoint = "CENTER",
anchorFrameType = "SCREEN",
xOffset = 0,
yOffset = 0,
frameStrata = 1
};
WeakAuras.regionPrototype.AddAlphaToDefault(default);
local screenWidth, screenHeight = math.ceil(GetScreenWidth() / 20) * 20, math.ceil(GetScreenHeight() / 20) * 20;
local properties = {
color = {
display = L["Color"],
setter = "Color",
type = "color",
},
desaturate = {
display = L["Desaturate"],
setter = "SetDesaturated",
type = "bool"
},
width = {
display = L["Width"],
setter = "SetRegionWidth",
type = "number",
min = 1,
softMax = screenWidth,
bigStep = 1,
default = 32
},
height = {
display = L["Height"],
setter = "SetRegionHeight",
type = "number",
min = 1,
softMax = screenHeight,
bigStep = 1,
default = 32
},
mirror = {
display = L["Mirror"],
setter = "SetMirror",
type = "bool"
}
}
WeakAuras.regionPrototype.AddProperties(properties, default);
local function create(parent)
local region = CreateFrame("FRAME", nil, UIParent);
region.regionType = "texture"
region:SetMovable(true);
region:SetResizable(true);
region:SetMinResize(1, 1);
local texture = region:CreateTexture();
texture:SetSnapToPixelGrid(false)
texture:<API key>(0)
region.texture = texture;
texture:SetAllPoints(region);
WeakAuras.regionPrototype.create(region);
return region;
end
local function modify(parent, region, data)
WeakAuras.regionPrototype.modify(parent, region, data);
WeakAuras.SetTextureOrAtlas(region.texture, data.texture, data.textureWrapMode, data.textureWrapMode);
region.texture:SetDesaturated(data.desaturate)
region:SetWidth(data.width);
region:SetHeight(data.height);
region.width = data.width;
region.height = data.height;
region.scalex = 1;
region.scaley = 1;
region.texture:SetBlendMode(data.blendMode);
--region.texture:SetRotation((data.rotation / 180) * math.pi);
local function GetRotatedPoints(degrees)
local angle = rad(135 - degrees);
local vx = math.cos(angle);
local vy = math.sin(angle);
return 0.5+vx,0.5-vy , 0.5-vy,0.5-vx , 0.5+vy,0.5+vx , 0.5-vx,0.5+vy
end
region.mirror = data.mirror
local function DoTexCoord()
local mirror_h, mirror_v = region.mirror_h, region.mirror_v;
if(region.mirror) then
mirror_h = not mirror_h;
end
local ulx,uly , llx,lly , urx,ury , lrx,lry;
if(data.rotate) then
ulx,uly , llx,lly , urx,ury , lrx,lry = GetRotatedPoints(region.rotation);
else
if(data.discrete_rotation == 0 or data.discrete_rotation == 360) then
ulx,uly , llx,lly , urx,ury , lrx,lry = 0,0 , 0,1 , 1,0 , 1,1;
elseif(data.discrete_rotation == 90) then
ulx,uly , llx,lly , urx,ury , lrx,lry = 1,0 , 0,0 , 1,1 , 0,1;
elseif(data.discrete_rotation == 180) then
ulx,uly , llx,lly , urx,ury , lrx,lry = 1,1 , 1,0 , 0,1 , 0,0;
elseif(data.discrete_rotation == 270) then
ulx,uly , llx,lly , urx,ury , lrx,lry = 0,1 , 1,1 , 0,0 , 1,0;
end
end
if(mirror_h) then
if(mirror_v) then
region.texture:SetTexCoord(lrx,lry , urx,ury , llx,lly , ulx,uly);
else
region.texture:SetTexCoord(urx,ury , lrx,lry , ulx,uly , llx,lly);
end
else
if(mirror_v) then
region.texture:SetTexCoord(llx,lly , ulx,uly , lrx,lry , urx,ury);
else
region.texture:SetTexCoord(ulx,uly , llx,lly , urx,ury , lrx,lry);
end
end
end
region.rotation = data.rotation;
DoTexCoord();
function region:Scale(scalex, scaley)
region.scalex = scalex;
region.scaley = scaley;
if(scalex < 0) then
region.mirror_h = true;
scalex = scalex * -1;
else
region.mirror_h = nil;
end
region:SetWidth(region.width * scalex);
if(scaley < 0) then
scaley = scaley * -1;
region.mirror_v = true;
else
region.mirror_v = nil;
end
region:SetHeight(region.height * scaley);
DoTexCoord();
end
function region:SetRegionWidth(width)
region.width = width;
region:Scale(region.scalex, region.scaley);
end
function region:SetRegionHeight(height)
region.height = height;
region:Scale(region.scalex, region.scaley);
end
function region:SetMirror(mirror)
region.mirror = mirror
DoTexCoord()
end
function region:Update()
if region.state.texture then
WeakAuras.SetTextureOrAtlas(region.texture, region.state.texture, data.textureWrapMode, data.textureWrapMode);
end
end
function region:Color(r, g, b, a)
region.color_r = r;
region.color_g = g;
region.color_b = b;
region.color_a = a;
if (r or g or b) then
a = a or 1;
end
region.texture:SetVertexColor(region.color_anim_r or r, region.color_anim_g or g, region.color_anim_b or b, region.color_anim_a or a);
end
function region:ColorAnim(r, g, b, a)
region.color_anim_r = r;
region.color_anim_g = g;
region.color_anim_b = b;
region.color_anim_a = a;
if (r or g or b) then
a = a or 1;
end
region.texture:SetVertexColor(r or region.color_r, g or region.color_g, b or region.color_b, a or region.color_a);
end
function region:GetColor()
return region.color_r or data.color[1], region.color_g or data.color[2],
region.color_b or data.color[3], region.color_a or data.color[4];
end
region:Color(data.color[1], data.color[2], data.color[3], data.color[4]);
function region:SetDesaturated(b)
region.texture:SetDesaturated(b);
end
if(data.rotate) then
function region:Rotate(degrees)
region.rotation = degrees;
DoTexCoord();
end
function region:GetRotation()
return region.rotation;
end
else
region.Rotate = nil;
region.GetRotation = nil;
end
WeakAuras.regionPrototype.modifyFinish(parent, region, data);
end
local function validate(data)
Private.<API key>(data, "subbackground")
end
WeakAuras.RegisterRegionType("texture", create, modify, default, properties, validate);
|
! This file created from test/mpi/f77/comm/commnamef.f with f77tof90
! -*- Mode: Fortran; -*-
!
! (C) 2003 by Argonne National Laboratory.
! See COPYRIGHT in top-level directory.
!
program main
use mpi
integer errs, ierr
integer comm(4), i, rlen, ln
integer ncomm
character*(MPI_MAX_OBJECT_NAME) inname(4), cname
logical MTestGetIntracomm
errs = 0
call mtest_init( ierr )
! Test the predefined communicators
do ln=1,MPI_MAX_OBJECT_NAME
cname(ln:ln) = 'X'
enddo
call mpi_comm_get_name( MPI_COMM_WORLD, cname, rlen, ierr )
do ln=MPI_MAX_OBJECT_NAME,1,-1
if (cname(ln:ln) .ne. ' ') then
if (ln .ne. rlen) then
errs = errs + 1
print *, 'result len ', rlen,' not equal to actual len ', &
& ln
endif
goto 110
endif
enddo
if (cname(1:rlen) .ne. 'MPI_COMM_WORLD') then
errs = errs + 1
print *, 'Did not get MPI_COMM_WORLD for world'
endif
110 continue
!
do ln=1,MPI_MAX_OBJECT_NAME
cname(ln:ln) = 'X'
enddo
call mpi_comm_get_name( MPI_COMM_SELF, cname, rlen, ierr )
do ln=MPI_MAX_OBJECT_NAME,1,-1
if (cname(ln:ln) .ne. ' ') then
if (ln .ne. rlen) then
errs = errs + 1
print *, 'result len ', rlen,' not equal to actual len ', &
& ln
endif
goto 120
endif
enddo
if (cname(1:rlen) .ne. 'MPI_COMM_SELF') then
errs = errs + 1
print *, 'Did not get MPI_COMM_SELF for world'
endif
120 continue
!
do i = 1, 4
if (MTestGetIntracomm( comm(i), 1, .true. )) then
ncomm = i
write( inname(i), '(a,i1)') 'myname',i
call mpi_comm_set_name( comm(i), inname(i), ierr )
else
goto 130
endif
enddo
130 continue
!
! Now test them all
do i=1, ncomm
call mpi_comm_get_name( comm(i), cname, rlen, ierr )
if (inname(i) .ne. cname) then
errs = errs + 1
print *, ' Expected ', inname(i), ' got ', cname
endif
call MTestFreeComm( comm(i) )
enddo
!
call mtest_finalize( errs )
call mpi_finalize( ierr )
end
|
package cmu.servercommunication;
/**
* GigaSight - CMU 2012
* @author Pieter Simoens
*
*/
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.<API key>;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import cmu.capture.FileStream;
import cmu.capture.MP4Stream;
import cmu.gigasight.CaptureActivity;
import android.util.Log;
public class FileUploader implements Runnable {
private static final String TAG = "FileUploader";
private static final int STATUS_OK = 0;
private static final int STATUS_ERROR = 1;
private static final int BUFFER_SIZE = 10240;
private BlockingQueue<FileStream> queue;
private MP4Stream STOP;
private Socket uploadSocket;
private DataInputStream in;
private DataOutputStream out;
private CaptureActivity cap;
public FileUploader(CaptureActivity cap) {
this.queue = new LinkedBlockingQueue<FileStream>();
this.cap = cap;
STOP = new MP4Stream(new File("STOP"));
}
public void start() {
new Thread(this).start();
}
public void upload(FileStream s) {
if(s.isRegistered()){
queue.add(s);
}
else{
Log.w(TAG,"Could not upload "+s.getFile().getName()+" because it is not registered on the server");
cap.onFileUploaded("Stream not registered on server, could not upload!");
}
}
public void stop() {
queue.add(STOP);
}
public void run() {
while (true) {
try {
FileStream element = queue.take();
if (element == STOP) {
Log.d(TAG, "End of fileUpload thread");
break;
} else {
Log.d(TAG, "Upload " + element.getServerLocation());
if(send(element)){
element.setUploaded();
cap.onFileUploaded("Upload completed of stream " + element.getServerLocation());
}
}
} catch (<API key> e) {
e.printStackTrace();
}
}
}
private boolean send(FileStream s) {
try {
Log.d(TAG,"Sending upload to server "+ServerSettings.serverIP+":"+ServerSettings.uploadPort);
uploadSocket = new Socket(ServerSettings.serverIP,
Integer.parseInt(ServerSettings.uploadPort));
in = new DataInputStream(uploadSocket.getInputStream());
out = new DataOutputStream(uploadSocket.getOutputStream());
// send length of ID and ID (e.g. /segment/200/400)
int length = s.getServerLocation().getBytes().length;
out.writeInt(length);
out.write(s.getServerLocation().getBytes());
out.flush();
// wait for OK from server before proceeding
if (!serverOK()) {
Log.i(TAG, "Aborting upload after error from server");
cleanUp();
return false;
}
// send fileSize
int fileSize = s.getFileSize();
out.writeInt(fileSize);
out.flush();
// wait for OK
if (!serverOK()) {
Log.i(TAG, "Aborting upload after error from server");
cleanUp();
return false;
}
// now do the actual upload
BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(s.getFile()));
byte[] buffer = new byte[BUFFER_SIZE];
int bytes_read = 0;
while ((bytes_read = bin.read(buffer)) != -1) {
if (bytes_read > 0) {
out.write(buffer, 0, bytes_read);
out.flush();
}
}
bin.close();
// wait for ok
if (!serverOK()) {
cleanUp();
return false;
}
Log.d(TAG,"Upload finished of file "+s.getFile().getName()+" to "+s.getServerLocation());
} catch (<API key> e) {
Log.e(TAG, e.getMessage());
cleanUp();
return false;
} catch (<API key> e) {
Log.e(TAG, e.getMessage());
cleanUp();
return false;
} catch (IOException e) {
Log.e(TAG, e.getMessage());
cleanUp();
return false;
}
cleanUp();
return true;
}
private boolean serverOK() {
int reply;
try {
reply = in.readInt();
if (reply == STATUS_ERROR)
return false;
else if (reply == STATUS_OK)
return true;
} catch (IOException e) {
Log.e(TAG, ""+e.getMessage());
return false;
}
return false;
}
private void cleanUp() {
try {
if (out != null)
out.close();
if (in != null)
in.close();
if (uploadSocket != null)
uploadSocket.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
}
|
<?php
/**
* Cache handler for route.
*/
namespace Drupal\at_base\Route;
use Drupal\at_base\Helper\ContentRender\<API key>;
class CacheHandler implements <API key> {
protected $options;
protected $callback;
/**
* Tell the proxy does not cache this page
*/
public function __destruct() {
if (!empty($this->options['id']) && user_is_anonymous()) {
$GLOBALS['conf']['cache'] = 0;
}
}
public function setOptions($options) {
$this->options = $options;
return $this;
}
public function setCallback($callback) {
$this->callback = $callback;
return $this;
}
protected function getCacheId() {
$o = &$this->options;
$o['id'] = isset($o['id']) ? $o['id'] : '';
$cid_parts = array($o['id']);
$cid_parts = array_merge($cid_parts, <API key>($o['type']));
return implode(':', $cid_parts);
}
public function render() {
$cachable = drupal_is_cli() || <API key>();
if (!$cachable) {
return call_user_func($this->callback);
}
$o = &$this->options;
if (!empty($o['type'])) {
switch ($o['type']) {
case DRUPAL_CACHE_CUSTOM:
case DRUPAL_NO_CACHE:
return call_user_func($this->callback);
default:
$o['id'] = $this->getCacheId();
break;
}
}
return at_cache($o, $this->callback);
}
}
|
#ifndef TPA2028_SPK_L_H
#define TPA2028_SPK_L_H
#define TPA2028_L_NAME "tpa2028_l"
#define TPA2028_I2C_ADDR ( 0x58 )
#define TPA2028_IOCTL_MAGIC 'u'
#define TPA2028_ENABLE _IOW(TPA2028_IOCTL_MAGIC, 0xE0, unsigned)
#define TPA2028_DISABLE _IOW(TPA2028_IOCTL_MAGIC, 0xE1, unsigned)
#define TPA2028_SET_REG _IOW(TPA2028_IOCTL_MAGIC, 0xE2, unsigned)
#define TPA2028_GET_REG _IOR(TPA2028_IOCTL_MAGIC, 0xE3, unsigned)
struct <API key> {
uint32_t gpio_tpa2028_en;
uint32_t boost_flag;
struct mutex boost_mutex;
};
#endif /* TPA2028_SPK_L_H */
|
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.model');
class FsssModelMainmenu extends JModelLegacy
{
function __construct()
{
parent::__construct();
$array = JRequest::getVar('cid', 0, '', 'array');
$this->setId((int)$array[0]);
}
function setId($id)
{
$this->_id = $id;
$this->_data = null;
}
function &getData()
{
if (empty( $this->_data )) {
$query = ' SELECT * FROM #__fss_main_menu '.
' WHERE id = '.FSSJ3Helper::getEscaped($this->_db,$this->_id);
$this->_db->setQuery( $query );
$this->_data = $this->_db->loadObject();
}
if (!$this->_data) {
$this->_data = new stdClass();
$this->_data->id = 0;
$this->_data->title = null;
$this->_data->description = null;
$this->_data->icon = null;
$this->_data->ordering = 0;
$this->_data->itemtype = 7;
$this->_data->link = "";
$this->_data->itemid = 0;
$this->_data->published = 1;
$this->_data->access = 1;
$this->_data->language = "*";
$this->_data->target = '';
$this->_data->translation = '';
$this->published = 1;
}
return $this->_data;
}
function store($data)
{
$row = $this->getTable();
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
function delete()
{
$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
$row = $this->getTable();
if (count( $cids )) {
foreach($cids as $cid) {
$this->_id = $cid;
$item = $this->getData();
if ($item->itemtype != 7)
{
$this->setError( "Unable to delete main items, please use the publish setting to hide them." );
return false;
}
if (!$row->delete( $cid )) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
}
return true;
}
function unpublish()
{
$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
$table = $this->getTable();
return $table->publish($cids, 0);
}
function publish()
{
$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
$table = $this->getTable();
return $table->publish($cids, 1);
}
function changeorder($direction)
{
$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
if (isset( $cid[0] ))
{
$row = $this->getTable();
$row->load( (int) $cid[0] );
$row->move($direction);
return true;
}
return false;
}
function saveorder()
{
$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );
$order = JRequest::getVar( 'order', array (0), 'post', 'array' );
$total = count($cid);
JArrayHelper::toInteger($cid, array(0));
JArrayHelper::toInteger($order, array(0));
// Instantiate an article table object
$row = $this->getTable();
// Update the ordering for items in the cid array
for ($i = 0; $i < $total; $i ++)
{
$row->load( (int) $cid[$i] );
if ($row->ordering != $order[$i]) {
$row->ordering = $order[$i];
if (!$row->store()) {
JError::raiseError( 500, $db->getErrorMsg() );
return false;
}
}
}
$row->reorder();
$row->reset();
return true;
}
}
|
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest02524")
public class BenchmarkTest02524 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String[] values = request.getParameterValues("vector");
String param;
if (values != null && values.length > 0)
param = values[0];
else param = "";
String bar = doSomething(param);
double value = java.lang.Math.random();
String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front.
String user = "Doug";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = param;
return bar;
}
}
|
// Practica Final, Clase GeneralTree, archivo .h
# ifndef GENERAL_TREE
# define GENERAL_TREE
# include <iostream>
# include <stdexcept> // Excepciones
using namespace std;
template <class T>
class GeneralTree{
private:
struct NodeP {
/**
*@brief Clave almacenada del tipo de dato *T*.
*
* En este campo se almacena la clave que le corresponde a este nodo.
*/
T key;
NodeP *leftc; // left child
NodeP *rightb; // right brother
NodeP *parent;
/**
* @brief Constructor por defecto.
*/
NodeP() : leftc(NULL), rightb(NULL), parent(NULL)
{}
NodeP(const T & key, NodeP * leftc, NodeP * rightb, NodeP * parent): key(key), leftc(leftc), rightb(rightb), parent(parent)
{}
};
NodeP *root;
void destroy(NodeP * n);
void copy(NodeP * origin, NodeP *& destination, NodeP * parent);
int sizeP(const NodeP * n) const;
bool areEqual(const NodeP * n1, const NodeP * n2) const;
void printTree(ostream & out, NodeP * n) const;
void readTree(istream& in, NodeP *& n, NodeP * parent);
public:
typedef struct NodeP * Node;
GeneralTree() : root(NULL)
{}
GeneralTree(const T& key) : root(new NodeP(key, NULL, NULL, NULL))
{}
GeneralTree(const GeneralTree<T> & other){
copy(other.root, root, NULL);
}
~GeneralTree(){
destroy(root);
}
GeneralTree<T> & operator=(const GeneralTree<T> & other);
inline void setRoot(const T & key){
destroy(root);
root = new NodeP(key, NULL, NULL, NULL);
}
inline const Node & getRoot() const{
return root;
}
Node & leftChild(const Node n) const{
if (n != NULL)
return n->leftc;
else
throw runtime_error("El nodo del que se pretende obtener el hijo de la izquierda es nulo");
}
/**
* @brief Devuelve el hermano situado a la derecha de un nodo dado.
* @param n Nodo del que se quiere obtener el hermano a la derecha.
* @pre *n* no es nulo
*
* En caso de no tener hermanos a la derecha se devuelve NULL.
*/
inline Node & rightBrother(const Node n) const{
if (n != NULL)
return n->rightb;
else
throw runtime_error("El nodo del que se pretende obtener el hermano a la derecha es nulo");
}
/**
* @brief Devuelve el nodo padre de un nodo dado.
* @param n Nodo del que se quiere obtener el padre.
* @pre *n* no es nulo.
*
* En caso de no tener padre se devuelve NULL.
*/
inline Node & parent(const Node n) const{
if (n != NULL)
return n->parent;
else
throw runtime_error("El nodo del que se pretende obtener su padre es nulo");
}
/**
* @brief Devuelve una referencia a la clave de un nodo dado.
* @param n Nodo del que se quiere obtener la clave.
* @pre *n* no es nulo
*/
inline T& key(const Node n){
if (n != NULL)
return n->key;
else
throw runtime_error("El nodo del que se pretende obtener su clave es nulo");
}
/**
* @brief Devuelve una referencia constante a la clave de un nodo dado.
* @param n Nodo del que se quiere obtener la clave.
* @pre *n* no es nulo
*/
inline const T& key(const Node n) const{
if (n != NULL)
return n->key;
else
throw runtime_error("El nodo del que se pretende obtener su clave es nulo");
}
void pruneSubtree(Node n, GeneralTree<T> & destination);
void pruneLeftChild(Node n, GeneralTree<T> & destination);
void pruneRightBrother(Node n, GeneralTree<T> & destination);
void insertLeftChild(Node n, GeneralTree<T> & tree);
void insertRightBrother(Node n, GeneralTree<T>& tree);
inline void clear(){
destroy(root);
root = NULL;
}
inline int size() const{
return sizeP(root);
}
inline bool empty() const{
return root == NULL;
}
inline bool operator==(const GeneralTree<T>& other) const{
return areEqual(root, other.root);
}
bool operator!=(const GeneralTree<T>& other) const{
return ! areEqual(root, other.root);
}
friend istream& operator>>(istream & in, GeneralTree<T> & other){
other.readTree(in, other.root, NULL);
return in;
}
friend ostream& operator<<(ostream & out, const GeneralTree<T> & other){
other.printTree(out, other.root);
return out;
}
class Iterator{
private:
Node it;
Node root;
int level;
public:
/**
* @brief Constructor por defecto.
*/
Iterator() : it(NULL), root(NULL), level(0)
{}
/**
* @brief Obtiene la etiqueta del nodo.
*/
inline T & operator*(){
return it->key;
}
/**
* @brief Obtiene el nodo actual.
*/
inline Node getNode() const{
return it;
}
/**
* @brief Obtiene el nivel del nodo actual.
*/
inline int getLevel() const{
return level;
}
Iterator & operator++();
inline bool operator==(const Iterator & i) const{
return root == i.root && it == i.it;
}
inline bool operator!=(const Iterator & i) const{
return root != i.root || it != i.it;
}
/**
* @brief Comprueba si el iterador es nulo o no.
*/
inline bool isNull() const{
return it == NULL;
}
friend class GeneralTree;
};
class ConstIterator{
private:
Node it;
Node root;
int level;
public:
/**
* @brief Constructor por defecto.
*/
ConstIterator() : it(NULL), root(NULL), level(0)
{}
/**
* @brief Obtiene la etiqueta del nodo.
*/
inline const T & operator*() const{
return it->key;
}
/**
* @brief Obtiene el nivel del nodo actual.
*/
inline int getLevel() const{
return level;
}
/**
* @brief Obtiene el nodo actual.
*/
inline const Node getNode() const{
return it;
}
ConstIterator & operator++();
inline bool operator==(const ConstIterator & i) const{
return root == i.root && it == i.it;
}
inline bool operator!=(const ConstIterator & i) const{
return root != i.root || it != i.it;
}
/**
* @brief Comprueba si el iterador es nulo o no.
*/
inline bool isNull() const{
return it == NULL;
}
friend class GeneralTree;
};
inline Iterator begin(){
Iterator begin;
begin.it = begin.root = root;
return begin;
}
inline ConstIterator begin() const{
ConstIterator begin;
begin.it = begin.root = root;
return begin;
}
/**
* @brief Devuelve un iterador apuntando al nodo nulo. Nivel 0.
*/
inline Iterator end(){
Iterator end;
end.it = NULL;
end.root = root;
return end;
}
/**
* @brief Devuelve un iterador constante apuntando al nodo nulo. Nivel 0.
*/
inline ConstIterator end() const{
ConstIterator end;
end.it = NULL;
end.root = root;
return end;
}
Iterator isChild(Node n, T key);
ConstIterator isChild(Node n, T key) const;
};
# include "GeneralTree.cpp"
# endif
|
package com.oracle.graal.nodes.java;
import jdk.vm.ci.meta.LocationIdentity;
import com.oracle.graal.graph.IterableNodeType;
import com.oracle.graal.graph.NodeClass;
import com.oracle.graal.nodeinfo.NodeInfo;
import com.oracle.graal.nodes.ValueNode;
import com.oracle.graal.nodes.extended.MonitorExit;
import com.oracle.graal.nodes.memory.MemoryCheckpoint;
import com.oracle.graal.nodes.spi.Lowerable;
import com.oracle.graal.nodes.spi.LoweringTool;
import com.oracle.graal.nodes.spi.Virtualizable;
import com.oracle.graal.nodes.spi.VirtualizerTool;
import com.oracle.graal.nodes.virtual.VirtualObjectNode;
/**
* The {@code MonitorExitNode} represents a monitor release. If it is the release of the monitor of
* a synchronized method, then the return value of the method will be referenced via the edge
* {@link #escapedReturnValue}, so that it will be materialized before releasing the monitor.
*/
@NodeInfo
public final class MonitorExitNode extends AccessMonitorNode implements Virtualizable, Lowerable, IterableNodeType, MonitorExit, MemoryCheckpoint.Single {
public static final NodeClass<MonitorExitNode> TYPE = NodeClass.create(MonitorExitNode.class);
/**
* Non-null for the monitor exit introduced due to a synchronized root method and null in all
* other cases.
*/
@OptionalInput ValueNode escapedReturnValue;
public MonitorExitNode(ValueNode object, MonitorIdNode monitorId, ValueNode escapedReturnValue) {
super(TYPE, object, monitorId);
this.escapedReturnValue = escapedReturnValue;
}
/**
* Return value is cleared when a synchronized method graph is inlined.
*/
public void <API key>() {
updateUsages(escapedReturnValue, null);
this.escapedReturnValue = null;
}
@Override
public LocationIdentity getLocationIdentity() {
return LocationIdentity.any();
}
@Override
public void lower(LoweringTool tool) {
tool.getLowerer().lower(this, tool);
}
@Override
public void virtualize(VirtualizerTool tool) {
ValueNode alias = tool.getAlias(object());
if (alias instanceof VirtualObjectNode) {
VirtualObjectNode virtual = (VirtualObjectNode) alias;
if (virtual.hasIdentity()) {
MonitorIdNode removedLock = tool.removeLock(virtual);
assert removedLock == getMonitorId() : "mismatch at " + this + ": " + removedLock + " vs. " + getMonitorId();
tool.delete();
}
}
}
}
|
package com.caucho.config.core;
import com.caucho.config.Config;
import com.caucho.config.ConfigException;
import com.caucho.config.SchemaBean;
import com.caucho.config.program.RecoverableProgram;
import com.caucho.config.type.FlowBean;
import com.caucho.config.types.FileSetType;
import com.caucho.loader.Environment;
import com.caucho.util.L10N;
import com.caucho.vfs.Depend;
import com.caucho.vfs.Path;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Imports values from a separate file.
*/
// XXX: FlowBean is from ioc/04c1 and server/1ac2
public class ResinImport extends ResinControl implements FlowBean
{
private static final L10N L = new L10N(ResinImport.class);
private static final Logger log
= Logger.getLogger(ResinImport.class.getName());
private Path _path;
private FileSetType _fileSet;
private boolean _isOptional;
private boolean _isRecover;
/**
* Sets the resin:import path.
*/
public void setPath(Path path)
{
if (path == null)
throw new <API key>(L.l("'path' may not be null for resin:import"));
_path = path;
}
/**
* Sets the resin:import fileset.
*/
public void setFileset(FileSetType fileSet)
{
_fileSet = fileSet;
}
/**
* Sets true if the path is optional.
*/
public void setOptional(boolean optional)
{
_isOptional = optional;
}
/**
* Sets true if the resin:import should recover from errors.
*/
public void setRecover(boolean isRecover)
{
_isRecover = isRecover;
}
@PostConstruct
public void init()
throws Exception
{
if (_path == null) {
if (_fileSet == null)
throw new ConfigException(L.l("'path' attribute missing from resin:import."));
}
else if (_path.canRead() && ! _path.isDirectory()) {
}
else if (_isOptional && ! _path.exists()) {
log.finer(L.l("resin:import '{0}' is not readable.", _path));
Environment.addDependency(new Depend(_path));
return;
}
else {
throw new ConfigException(L.l("Required file '{0}' can not be read for resin:import.",
_path.getNativePath()));
}
Object object = getObject();
String schema = null;
// Use the relax schema for beans with schema.
if (object instanceof SchemaBean) {
schema = ((SchemaBean) object).getSchema();
}
ArrayList<Path> paths;
if (_fileSet != null) {
paths = _fileSet.getPaths();
Environment.addDependency(new Depend(_fileSet.getDir()));
}
else {
paths = new ArrayList<Path>();
paths.add(_path);
}
for (int i = 0; i < paths.size(); i++) {
Path path = paths.get(i);
log.config(L.l("resin:import '{0}'", path.getNativePath()));
Environment.addDependency(new Depend(path));
String recoverAttr = RecoverableProgram.ATTR;
Object oldRecover = Config.getCurrentVar(recoverAttr);
try {
Config.setProperty(recoverAttr, _isRecover);
Config config = new Config();
// server/10hc
// config.setResinInclude(true);
config.configureBean(object, path, schema);
} catch (RuntimeException e) {
if (! _isRecover)
throw e;
log.log(Level.WARNING, e.toString(), e);
Environment.setConfigException(e);
} finally {
Config.setProperty(recoverAttr, oldRecover);
}
}
}
}
|
'use strict';
angular.module('openolitor-admin')
.controller('<API key>', ['$q', '$scope', '$rootScope', '$filter',
'ReportsModel', 'NgTableParams', '<API key>',
'<API key>', '$location', '<API key>', 'FilterQueryUtil', 'gettext',
function($q, $scope, $rootScope, $filter, ReportsModel, NgTableParams, <API key>,
<API key>, $location, <API key>, FilterQueryUtil, gettext) {
$rootScope.viewId = 'L-Rept';
$scope.entries = [];
$scope.filteredEntries = [];
$scope.loading = false;
$scope.model = {};
$scope.search = {
query: '',
queryQuery: '',
filterQuery: ''
};
$scope.hasData = function() {
return $scope.entries !== undefined;
};
if (!$scope.tableParams) {
//use default tableParams
$scope.tableParams = new NgTableParams({ // jshint ignore:line
page: 1,
count: 10,
sorting: {
name: 'asc'
}
}, {
filterDelay: 0,
groupOptions: {
isExpanded: true
},
getData: function(params) {
if (!$scope.entries) {
return;
}
// use build-in angular filter
var dataSet = $filter('filter')($scope.entries, $scope.search.queryQuery);
// also filter by ngtable filters
dataSet = $filter('filter')(dataSet, params.filter());
dataSet = params.sorting ?
$filter('orderBy')(dataSet, params.orderBy(), false, <API key>) :
dataSet;
$scope.filteredEntries = dataSet;
params.total(dataSet.length);
return dataSet.slice((params.page() - 1) * params.count(), params.page() * params.count());
}
});
}
function search() {
if ($scope.loading) {
return;
}
$scope.tableParams.reload();
$scope.loading = true;
$scope.entries = ReportsModel.query({
f: $scope.search.filterQuery
}, function() {
$scope.tableParams.reload();
$scope.loading = false;
$location.search('q', $scope.search.query);
});
}
search();
$scope.actions = [{
labelFunction: function() {
return gettext('Auswertung erstellen');
},
noEntityText: true,
iconClass: 'glyphicon glyphicon-plus',
onExecute: function() {
return $location.path('/reports/new');
}
}];
var existingQuery = $location.search().q;
if (existingQuery) {
$scope.search.query = existingQuery;
}
$scope.$watch('search.query', function() {
$scope.search.filterQuery = FilterQueryUtil.transform($scope.search
.query);
$scope.search.queryQuery = FilterQueryUtil.withoutFilters($scope.search
.query);
search();
}, true);
$scope.executeReport = function(report) {
$location.path('/reports/' + report.id + '/execute');
};
}
]);
|
// <API key>: GPL-2.0+
#include <common.h>
#include <dm.h>
#include <env.h>
#include <hang.h>
#include <image.h>
#include <init.h>
#include <log.h>
#include <mmc.h>
#include <axp_pmic.h>
#include <generic-phy.h>
#include <phy-sun4i-usb.h>
#include <asm/arch/clock.h>
#include <asm/arch/cpu.h>
#include <asm/arch/display.h>
#include <asm/arch/dram.h>
#include <asm/arch/gpio.h>
#include <asm/arch/mmc.h>
#include <asm/arch/prcm.h>
#include <asm/arch/spl.h>
#include <linux/delay.h>
#include <u-boot/crc.h>
#ifndef CONFIG_ARM64
#include <asm/armv7.h>
#endif
#include <asm/gpio.h>
#include <asm/io.h>
#include <u-boot/crc.h>
#include <env_internal.h>
#include <linux/libfdt.h>
#include <nand.h>
#include <net.h>
#include <spl.h>
#include <sy8106a.h>
#include <asm/setup.h>
#if defined <API key> && !(defined CONFIG_SPL_BUILD)
/* So that we can use pin names in Kconfig and sunxi_name_to_gpio() */
int soft_i2c_gpio_sda;
int soft_i2c_gpio_scl;
static int soft_i2c_board_init(void)
{
int ret;
soft_i2c_gpio_sda = sunxi_name_to_gpio(<API key>);
if (soft_i2c_gpio_sda < 0) {
printf("Error invalid soft i2c sda pin: '%s', err %d\n",
<API key>, soft_i2c_gpio_sda);
return soft_i2c_gpio_sda;
}
ret = gpio_request(soft_i2c_gpio_sda, "soft-i2c-sda");
if (ret) {
printf("Error requesting soft i2c sda pin: '%s', err %d\n",
<API key>, ret);
return ret;
}
soft_i2c_gpio_scl = sunxi_name_to_gpio(<API key>);
if (soft_i2c_gpio_scl < 0) {
printf("Error invalid soft i2c scl pin: '%s', err %d\n",
<API key>, soft_i2c_gpio_scl);
return soft_i2c_gpio_scl;
}
ret = gpio_request(soft_i2c_gpio_scl, "soft-i2c-scl");
if (ret) {
printf("Error requesting soft i2c scl pin: '%s', err %d\n",
<API key>, ret);
return ret;
}
return 0;
}
#else
static int soft_i2c_board_init(void) { return 0; }
#endif
<API key>;
void i2c_init_board(void)
{
#ifdef CONFIG_I2C0_ENABLE
#if defined(CONFIG_MACH_SUN4I) || \
defined(CONFIG_MACH_SUN5I) || \
defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
<API key>(SUNXI_GPB(0), SUN4I_GPB_TWI0);
<API key>(SUNXI_GPB(1), SUN4I_GPB_TWI0);
clock_twi_onoff(0, 1);
#elif defined(CONFIG_MACH_SUN6I)
<API key>(SUNXI_GPH(14), SUN6I_GPH_TWI0);
<API key>(SUNXI_GPH(15), SUN6I_GPH_TWI0);
clock_twi_onoff(0, 1);
#elif defined(<API key>)
<API key>(SUNXI_GPB(6), SUN8I_V3S_GPB_TWI0);
<API key>(SUNXI_GPB(7), SUN8I_V3S_GPB_TWI0);
clock_twi_onoff(0, 1);
#elif defined(CONFIG_MACH_SUN8I)
<API key>(SUNXI_GPH(2), SUN8I_GPH_TWI0);
<API key>(SUNXI_GPH(3), SUN8I_GPH_TWI0);
clock_twi_onoff(0, 1);
#elif defined(CONFIG_MACH_SUN50I)
<API key>(SUNXI_GPH(0), SUN50I_GPH_TWI0);
<API key>(SUNXI_GPH(1), SUN50I_GPH_TWI0);
clock_twi_onoff(0, 1);
#endif
#endif
#ifdef CONFIG_I2C1_ENABLE
#if defined(CONFIG_MACH_SUN4I) || \
defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
<API key>(SUNXI_GPB(18), SUN4I_GPB_TWI1);
<API key>(SUNXI_GPB(19), SUN4I_GPB_TWI1);
clock_twi_onoff(1, 1);
#elif defined(CONFIG_MACH_SUN5I)
<API key>(SUNXI_GPB(15), SUN5I_GPB_TWI1);
<API key>(SUNXI_GPB(16), SUN5I_GPB_TWI1);
clock_twi_onoff(1, 1);
#elif defined(CONFIG_MACH_SUN6I)
<API key>(SUNXI_GPH(16), SUN6I_GPH_TWI1);
<API key>(SUNXI_GPH(17), SUN6I_GPH_TWI1);
clock_twi_onoff(1, 1);
#elif defined(CONFIG_MACH_SUN8I)
<API key>(SUNXI_GPH(4), SUN8I_GPH_TWI1);
<API key>(SUNXI_GPH(5), SUN8I_GPH_TWI1);
clock_twi_onoff(1, 1);
#elif defined(CONFIG_MACH_SUN50I)
<API key>(SUNXI_GPH(2), SUN50I_GPH_TWI1);
<API key>(SUNXI_GPH(3), SUN50I_GPH_TWI1);
clock_twi_onoff(1, 1);
#endif
#endif
#ifdef CONFIG_I2C2_ENABLE
#if defined(CONFIG_MACH_SUN4I) || \
defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
<API key>(SUNXI_GPB(20), SUN4I_GPB_TWI2);
<API key>(SUNXI_GPB(21), SUN4I_GPB_TWI2);
clock_twi_onoff(2, 1);
#elif defined(CONFIG_MACH_SUN5I)
<API key>(SUNXI_GPB(17), SUN5I_GPB_TWI2);
<API key>(SUNXI_GPB(18), SUN5I_GPB_TWI2);
clock_twi_onoff(2, 1);
#elif defined(CONFIG_MACH_SUN6I)
<API key>(SUNXI_GPH(18), SUN6I_GPH_TWI2);
<API key>(SUNXI_GPH(19), SUN6I_GPH_TWI2);
clock_twi_onoff(2, 1);
#elif defined(CONFIG_MACH_SUN8I)
<API key>(SUNXI_GPE(12), SUN8I_GPE_TWI2);
<API key>(SUNXI_GPE(13), SUN8I_GPE_TWI2);
clock_twi_onoff(2, 1);
#elif defined(CONFIG_MACH_SUN50I)
<API key>(SUNXI_GPE(14), SUN50I_GPE_TWI2);
<API key>(SUNXI_GPE(15), SUN50I_GPE_TWI2);
clock_twi_onoff(2, 1);
#endif
#endif
#ifdef CONFIG_I2C3_ENABLE
#if defined(CONFIG_MACH_SUN6I)
<API key>(SUNXI_GPG(10), SUN6I_GPG_TWI3);
<API key>(SUNXI_GPG(11), SUN6I_GPG_TWI3);
clock_twi_onoff(3, 1);
#elif defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
<API key>(SUNXI_GPI(0), SUN7I_GPI_TWI3);
<API key>(SUNXI_GPI(1), SUN7I_GPI_TWI3);
clock_twi_onoff(3, 1);
#endif
#endif
#ifdef CONFIG_I2C4_ENABLE
#if defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
<API key>(SUNXI_GPI(2), SUN7I_GPI_TWI4);
<API key>(SUNXI_GPI(3), SUN7I_GPI_TWI4);
clock_twi_onoff(4, 1);
#endif
#endif
#ifdef CONFIG_R_I2C_ENABLE
#ifdef CONFIG_MACH_SUN50I
clock_twi_onoff(5, 1);
<API key>(SUNXI_GPL(8), SUN50I_GPL_R_TWI);
<API key>(SUNXI_GPL(9), SUN50I_GPL_R_TWI);
#else
clock_twi_onoff(5, 1);
<API key>(SUNXI_GPL(0), SUN8I_H3_GPL_R_TWI);
<API key>(SUNXI_GPL(1), SUN8I_H3_GPL_R_TWI);
#endif
#endif
}
#if defined(<API key>) && defined(<API key>)
enum env_location env_get_location(enum env_operation op, int prio)
{
switch (prio) {
case 0:
return ENVL_FAT;
case 1:
return ENVL_MMC;
default:
return ENVL_UNKNOWN;
}
}
#endif
#ifdef CONFIG_DM_MMC
static void mmc_pinmux_setup(int sdc);
#endif
/* add board specific code here */
int board_init(void)
{
__maybe_unused int id_pfr1, ret, satapwr_pin, macpwr_pin;
gd->bd->bi_boot_params = (PHYS_SDRAM_0 + 0x100);
#ifndef CONFIG_ARM64
asm volatile("mrc p15, 0, %0, c0, c1, 1" : "=r"(id_pfr1));
debug("id_pfr1: 0x%08x\n", id_pfr1);
/* Generic Timer Extension available? */
if ((id_pfr1 >> <API key>) & 0xf) {
uint32_t freq;
debug("Setting CNTFRQ\n");
/*
* CNTFRQ is a secure register, so we will crash if we try to
* write this from the non-secure world (read is OK, though).
* In case some bootcode has already set the correct value,
* we avoid the risk of writing to it.
*/
asm volatile("mrc p15, 0, %0, c14, c0, 0" : "=r"(freq));
if (freq != COUNTER_FREQUENCY) {
debug("arch timer frequency is %d Hz, should be %d, fixing ...\n",
freq, COUNTER_FREQUENCY);
#ifdef CONFIG_NON_SECURE
printf("arch timer frequency is wrong, but cannot adjust it\n");
#else
asm volatile("mcr p15, 0, %0, c14, c0, 0"
: : "r"(COUNTER_FREQUENCY));
#endif
}
}
#endif /* !CONFIG_ARM64 */
ret = axp_gpio_init();
if (ret)
return ret;
#ifdef CONFIG_SATAPWR
satapwr_pin = sunxi_name_to_gpio(CONFIG_SATAPWR);
gpio_request(satapwr_pin, "satapwr");
<API key>(satapwr_pin, 1);
/* Give attached sata device time to power-up to avoid link timeouts */
mdelay(500);
#endif
#ifdef CONFIG_MACPWR
macpwr_pin = sunxi_name_to_gpio(CONFIG_MACPWR);
gpio_request(macpwr_pin, "macpwr");
<API key>(macpwr_pin, 1);
#endif
#ifdef CONFIG_DM_I2C
/*
* Temporary workaround for enabling I2C clocks until proper sunxi DM
* clk, reset and pinctrl drivers land.
*/
i2c_init_board();
#endif
#ifdef CONFIG_DM_MMC
/*
* Temporary workaround for enabling MMC clocks until a sunxi DM
* pinctrl driver lands.
*/
mmc_pinmux_setup(<API key>);
#if <API key> != -1
mmc_pinmux_setup(<API key>);
#endif
#endif /* CONFIG_DM_MMC */
/* Uses dm gpio code so do this here and not in i2c_init_board() */
return soft_i2c_board_init();
}
/*
* On older SoCs the SPL is actually at address zero, so using NULL as
* an error value does not work.
*/
#define INVALID_SPL_HEADER ((void *)~0UL)
static struct boot_file_head * get_spl_header(uint8_t req_version)
{
struct boot_file_head *spl = (void *)(ulong)SPL_ADDR;
uint8_t spl_header_version = spl->spl_signature[3];
/* Is there really the SPL header (still) there? */
if (memcmp(spl->spl_signature, SPL_SIGNATURE, 3) != 0)
return INVALID_SPL_HEADER;
if (spl_header_version < req_version) {
printf("sunxi SPL version mismatch: expected %u, got %u\n",
req_version, spl_header_version);
return INVALID_SPL_HEADER;
}
return spl;
}
static const char *get_spl_dt_name(void)
{
struct boot_file_head *spl = get_spl_header(<API key>);
/* Check if there is a DT name stored in the SPL header. */
if (spl != INVALID_SPL_HEADER && spl->dt_name_offset)
return (char *)spl + spl->dt_name_offset;
return NULL;
}
int dram_init(void)
{
struct boot_file_head *spl = get_spl_header(<API key>);
if (spl == INVALID_SPL_HEADER)
gd->ram_size = get_ram_size((long *)PHYS_SDRAM_0,
PHYS_SDRAM_0_SIZE);
else
gd->ram_size = (phys_addr_t)spl->dram_size << 20;
if (gd->ram_size > <API key>)
gd->ram_size = <API key>;
return 0;
}
#if defined(CONFIG_NAND_SUNXI)
static void nand_pinmux_setup(void)
{
unsigned int pin;
for (pin = SUNXI_GPC(0); pin <= SUNXI_GPC(19); pin++)
<API key>(pin, SUNXI_GPC_NAND);
#if defined CONFIG_MACH_SUN4I || defined CONFIG_MACH_SUN7I
for (pin = SUNXI_GPC(20); pin <= SUNXI_GPC(22); pin++)
<API key>(pin, SUNXI_GPC_NAND);
#endif
/* sun4i / sun7i do have a PC23, but it is not used for nand,
* only sun7i has a PC24 */
#ifdef CONFIG_MACH_SUN7I
<API key>(SUNXI_GPC(24), SUNXI_GPC_NAND);
#endif
}
static void nand_clock_setup(void)
{
struct sunxi_ccm_reg *const ccm =
(struct sunxi_ccm_reg *)SUNXI_CCM_BASE;
setbits_le32(&ccm->ahb_gate0, (CLK_GATE_OPEN << <API key>));
#if defined CONFIG_MACH_SUN6I || defined CONFIG_MACH_SUN8I || \
defined CONFIG_MACH_SUN9I || defined CONFIG_MACH_SUN50I
setbits_le32(&ccm->ahb_reset0_cfg, (1 << <API key>));
#endif
setbits_le32(&ccm->nand0_clk_cfg, <API key> | AHB_DIV_1);
}
void board_nand_init(void)
{
nand_pinmux_setup();
nand_clock_setup();
#ifndef CONFIG_SPL_BUILD
sunxi_nand_init();
#endif
}
#endif
#ifdef CONFIG_MMC
static void mmc_pinmux_setup(int sdc)
{
unsigned int pin;
__maybe_unused int pins;
switch (sdc) {
case 0:
/* SDC0: PF0-PF5 */
for (pin = SUNXI_GPF(0); pin <= SUNXI_GPF(5); pin++) {
<API key>(pin, SUNXI_GPF_SDC0);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
break;
case 1:
pins = <API key>(CONFIG_MMC1_PINS);
#if defined(CONFIG_MACH_SUN4I) || defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
if (pins == SUNXI_GPIO_H) {
/* SDC1: PH22-PH-27 */
for (pin = SUNXI_GPH(22); pin <= SUNXI_GPH(27); pin++) {
<API key>(pin, SUN4I_GPH_SDC1);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
} else {
/* SDC1: PG0-PG5 */
for (pin = SUNXI_GPG(0); pin <= SUNXI_GPG(5); pin++) {
<API key>(pin, SUN4I_GPG_SDC1);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
}
#elif defined(CONFIG_MACH_SUN5I)
/* SDC1: PG3-PG8 */
for (pin = SUNXI_GPG(3); pin <= SUNXI_GPG(8); pin++) {
<API key>(pin, SUN5I_GPG_SDC1);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#elif defined(CONFIG_MACH_SUN6I)
/* SDC1: PG0-PG5 */
for (pin = SUNXI_GPG(0); pin <= SUNXI_GPG(5); pin++) {
<API key>(pin, SUN6I_GPG_SDC1);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#elif defined(CONFIG_MACH_SUN8I)
if (pins == SUNXI_GPIO_D) {
/* SDC1: PD2-PD7 */
for (pin = SUNXI_GPD(2); pin <= SUNXI_GPD(7); pin++) {
<API key>(pin, SUN8I_GPD_SDC1);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
} else {
/* SDC1: PG0-PG5 */
for (pin = SUNXI_GPG(0); pin <= SUNXI_GPG(5); pin++) {
<API key>(pin, SUN8I_GPG_SDC1);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
}
#endif
break;
case 2:
pins = <API key>(CONFIG_MMC2_PINS);
#if defined(CONFIG_MACH_SUN4I) || defined(CONFIG_MACH_SUN7I)
/* SDC2: PC6-PC11 */
for (pin = SUNXI_GPC(6); pin <= SUNXI_GPC(11); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#elif defined(CONFIG_MACH_SUN5I)
if (pins == SUNXI_GPIO_E) {
/* SDC2: PE4-PE9 */
for (pin = SUNXI_GPE(4); pin <= SUNXI_GPD(9); pin++) {
<API key>(pin, SUN5I_GPE_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
} else {
/* SDC2: PC6-PC15 */
for (pin = SUNXI_GPC(6); pin <= SUNXI_GPC(15); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
}
#elif defined(CONFIG_MACH_SUN6I)
if (pins == SUNXI_GPIO_A) {
/* SDC2: PA9-PA14 */
for (pin = SUNXI_GPA(9); pin <= SUNXI_GPA(14); pin++) {
<API key>(pin, SUN6I_GPA_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
} else {
/* SDC2: PC6-PC15, PC24 */
for (pin = SUNXI_GPC(6); pin <= SUNXI_GPC(15); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
<API key>(SUNXI_GPC(24), SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(SUNXI_GPC(24), SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(SUNXI_GPC(24), 2);
}
#elif defined(<API key>)
/* SDC2: PC6-PC15, PC24 */
for (pin = SUNXI_GPC(6); pin <= SUNXI_GPC(15); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
<API key>(SUNXI_GPC(24), SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(SUNXI_GPC(24), SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(SUNXI_GPC(24), 2);
#elif defined(CONFIG_MACH_SUN8I) || defined(CONFIG_MACH_SUN50I)
/* SDC2: PC5-PC6, PC8-PC16 */
for (pin = SUNXI_GPC(5); pin <= SUNXI_GPC(6); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
for (pin = SUNXI_GPC(8); pin <= SUNXI_GPC(16); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#elif defined(<API key>)
/* SDC2: PC4-PC14 */
for (pin = SUNXI_GPC(4); pin <= SUNXI_GPC(14); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#elif defined(CONFIG_MACH_SUN9I)
/* SDC2: PC6-PC16 */
for (pin = SUNXI_GPC(6); pin <= SUNXI_GPC(16); pin++) {
<API key>(pin, SUNXI_GPC_SDC2);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#endif
break;
case 3:
pins = <API key>(CONFIG_MMC3_PINS);
#if defined(CONFIG_MACH_SUN4I) || defined(CONFIG_MACH_SUN7I) || \
defined(<API key>)
/* SDC3: PI4-PI9 */
for (pin = SUNXI_GPI(4); pin <= SUNXI_GPI(9); pin++) {
<API key>(pin, SUNXI_GPI_SDC3);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
#elif defined(CONFIG_MACH_SUN6I)
if (pins == SUNXI_GPIO_A) {
/* SDC3: PA9-PA14 */
for (pin = SUNXI_GPA(9); pin <= SUNXI_GPA(14); pin++) {
<API key>(pin, SUN6I_GPA_SDC3);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
} else {
/* SDC3: PC6-PC15, PC24 */
for (pin = SUNXI_GPC(6); pin <= SUNXI_GPC(15); pin++) {
<API key>(pin, SUN6I_GPC_SDC3);
sunxi_gpio_set_pull(pin, SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(pin, 2);
}
<API key>(SUNXI_GPC(24), SUN6I_GPC_SDC3);
sunxi_gpio_set_pull(SUNXI_GPC(24), SUNXI_GPIO_PULL_UP);
sunxi_gpio_set_drv(SUNXI_GPC(24), 2);
}
#endif
break;
default:
printf("sunxi: invalid MMC slot %d for pinmux setup\n", sdc);
break;
}
}
int board_mmc_init(struct bd_info *bis)
{
__maybe_unused struct mmc *mmc0, *mmc1;
mmc_pinmux_setup(<API key>);
mmc0 = sunxi_mmc_init(<API key>);
if (!mmc0)
return -1;
#if <API key> != -1
mmc_pinmux_setup(<API key>);
mmc1 = sunxi_mmc_init(<API key>);
if (!mmc1)
return -1;
#endif
return 0;
}
#endif
#ifdef CONFIG_SPL_BUILD
static void <API key>(phys_addr_t dram_size)
{
struct boot_file_head *spl = get_spl_header(<API key>);
if (spl == INVALID_SPL_HEADER)
return;
/* Promote the header version for U-Boot proper, if needed. */
if (spl->spl_signature[3] < <API key>)
spl->spl_signature[3] = <API key>;
spl->dram_size = dram_size >> 20;
}
void sunxi_board_init(void)
{
int power_failed = 0;
#ifdef <API key>
power_failed = sy8106a_set_vout1(<API key>);
#endif
#if defined CONFIG_AXP152_POWER || defined CONFIG_AXP209_POWER || \
defined CONFIG_AXP221_POWER || defined CONFIG_AXP809_POWER || \
defined CONFIG_AXP818_POWER
power_failed = axp_init();
#if defined CONFIG_AXP221_POWER || defined CONFIG_AXP809_POWER || \
defined CONFIG_AXP818_POWER
power_failed |= axp_set_dcdc1(<API key>);
#endif
power_failed |= axp_set_dcdc2(<API key>);
power_failed |= axp_set_dcdc3(<API key>);
#if !defined(CONFIG_AXP209_POWER) && !defined(CONFIG_AXP818_POWER)
power_failed |= axp_set_dcdc4(<API key>);
#endif
#if defined CONFIG_AXP221_POWER || defined CONFIG_AXP809_POWER || \
defined CONFIG_AXP818_POWER
power_failed |= axp_set_dcdc5(<API key>);
#endif
#if defined CONFIG_AXP221_POWER || defined CONFIG_AXP809_POWER || \
defined CONFIG_AXP818_POWER
power_failed |= axp_set_aldo1(<API key>);
#endif
power_failed |= axp_set_aldo2(<API key>);
#if !defined(CONFIG_AXP152_POWER)
power_failed |= axp_set_aldo3(<API key>);
#endif
#ifdef CONFIG_AXP209_POWER
power_failed |= axp_set_aldo4(<API key>);
#endif
#if defined(CONFIG_AXP221_POWER) || defined(CONFIG_AXP809_POWER) || \
defined(CONFIG_AXP818_POWER)
power_failed |= axp_set_dldo(1, <API key>);
power_failed |= axp_set_dldo(2, <API key>);
#if !defined CONFIG_AXP809_POWER
power_failed |= axp_set_dldo(3, <API key>);
power_failed |= axp_set_dldo(4, <API key>);
#endif
power_failed |= axp_set_eldo(1, <API key>);
power_failed |= axp_set_eldo(2, <API key>);
power_failed |= axp_set_eldo(3, <API key>);
#endif
#ifdef CONFIG_AXP818_POWER
power_failed |= axp_set_fldo(1, <API key>);
power_failed |= axp_set_fldo(2, <API key>);
power_failed |= axp_set_fldo(3, <API key>);
#endif
#if defined CONFIG_AXP809_POWER || defined CONFIG_AXP818_POWER
power_failed |= axp_set_sw(IS_ENABLED(CONFIG_AXP_SW_ON));
#endif
#endif
printf("DRAM:");
gd->ram_size = sunxi_dram_init();
printf(" %d MiB\n", (int)(gd->ram_size >> 20));
if (!gd->ram_size)
hang();
<API key>(gd->ram_size);
/*
* Only clock up the CPU to full speed if we are reasonably
* assured it's being powered with suitable core voltage
*/
if (!power_failed)
clock_set_pll1(CONFIG_SYS_CLK_FREQ);
else
printf("Failed to set core voltage! Can't set CPU frequency\n");
}
#endif
#ifdef CONFIG_USB_GADGET
int <API key>(void)
{
struct udevice *dev;
struct phy phy;
int ret;
ret = uclass_get_device(<API key>, 0, &dev);
if (ret) {
pr_err("%s: Cannot find USB device\n", __func__);
return ret;
}
ret = <API key>(dev, "usb", &phy);
if (ret) {
pr_err("failed to get %s USB PHY\n", dev->name);
return ret;
}
ret = generic_phy_init(&phy);
if (ret) {
pr_debug("failed to init %s USB PHY\n", dev->name);
return ret;
}
ret = <API key>(&phy);
if (ret == 1) {
pr_err("A charger is plugged into the OTG\n");
return -ENODEV;
}
return ret;
}
#endif
#ifdef CONFIG_SERIAL_TAG
void get_board_serial(struct tag_serialnr *serialnr)
{
char *serial_string;
unsigned long long serial;
serial_string = env_get("serial
if (serial_string) {
serial = simple_strtoull(serial_string, NULL, 16);
serialnr->high = (unsigned int) (serial >> 32);
serialnr->low = (unsigned int) (serial & 0xffffffff);
} else {
serialnr->high = 0;
serialnr->low = 0;
}
}
#endif
/*
* Check the SPL header for the "sunxi" variant. If found: parse values
* that might have been passed by the loader ("fel" utility), and update
* the environment accordingly.
*/
static void parse_spl_header(const uint32_t spl_addr)
{
struct boot_file_head *spl = get_spl_header(<API key>);
if (spl == INVALID_SPL_HEADER)
return;
if (!spl->fel_script_address)
return;
if (spl->fel_uEnv_length != 0) {
/*
* data is expected in uEnv.txt compatible format, so "env
* import -t" the string(s) at fel_script_address right away.
*/
himport_r(&env_htab, (char *)(uintptr_t)spl->fel_script_address,
spl->fel_uEnv_length, '\n', H_NOCLEAR, 0, 0, NULL);
return;
}
/* otherwise assume .scr format (mkimage-type script) */
env_set_hex("fel_scriptaddr", spl->fel_script_address);
}
/*
* Note this function gets called multiple times.
* It must not make any changes to env variables which already exist.
*/
static void setup_environment(const void *fdt)
{
char serial_string[17] = { 0 };
unsigned int sid[4];
uint8_t mac_addr[6];
char ethaddr[16];
int i, ret;
ret = sunxi_get_sid(sid);
if (ret == 0 && sid[0] != 0) {
/*
* The single words 1 - 3 of the SID have quite a few bits
* which are the same on many models, so we take a crc32
* of all 3 words, to get a more unique value.
*
* Note we only do this on newer SoCs as we cannot change
* the algorithm on older SoCs since those have been using
* fixed mac-addresses based on only using word 3 for a
* long time and changing a fixed mac-address with an
* u-boot update is not good.
*/
#if !defined(CONFIG_MACH_SUN4I) && !defined(CONFIG_MACH_SUN5I) && \
!defined(CONFIG_MACH_SUN6I) && !defined(CONFIG_MACH_SUN7I) && \
!defined(<API key>) && !defined(<API key>)
sid[3] = crc32(0, (unsigned char *)&sid[1], 12);
#endif
/* Ensure the NIC specific bytes of the mac are not all 0 */
if ((sid[3] & 0xffffff) == 0)
sid[3] |= 0x800000;
for (i = 0; i < 4; i++) {
sprintf(ethaddr, "ethernet%d", i);
if (!fdt_get_alias(fdt, ethaddr))
continue;
if (i == 0)
strcpy(ethaddr, "ethaddr");
else
sprintf(ethaddr, "eth%daddr", i);
if (env_get(ethaddr))
continue;
/* Non OUI / registered MAC address */
mac_addr[0] = (i << 4) | 0x02;
mac_addr[1] = (sid[0] >> 0) & 0xff;
mac_addr[2] = (sid[3] >> 24) & 0xff;
mac_addr[3] = (sid[3] >> 16) & 0xff;
mac_addr[4] = (sid[3] >> 8) & 0xff;
mac_addr[5] = (sid[3] >> 0) & 0xff;
<API key>(ethaddr, mac_addr);
}
if (!env_get("serial
snprintf(serial_string, sizeof(serial_string),
"%08x%08x", sid[0], sid[3]);
env_set("serial#", serial_string);
}
}
}
int misc_init_r(void)
{
const char *spl_dt_name;
uint boot;
env_set("fel_booted", NULL);
env_set("fel_scriptaddr", NULL);
env_set("mmc_bootdev", NULL);
boot = <API key>();
/* determine if we are running in FEL mode */
if (boot == BOOT_DEVICE_BOARD) {
env_set("fel_booted", "1");
parse_spl_header(SPL_ADDR);
/* or if we booted from MMC, and which one */
} else if (boot == BOOT_DEVICE_MMC1) {
env_set("mmc_bootdev", "0");
} else if (boot == BOOT_DEVICE_MMC2) {
env_set("mmc_bootdev", "1");
}
/* Set fdtfile to match the FIT configuration chosen in SPL. */
spl_dt_name = get_spl_dt_name();
if (spl_dt_name) {
char *prefix = IS_ENABLED(CONFIG_ARM64) ? "allwinner/" : "";
char str[64];
snprintf(str, sizeof(str), "%s%s.dtb", prefix, spl_dt_name);
env_set("fdtfile", str);
}
setup_environment(gd->fdt_blob);
#ifdef CONFIG_USB_ETHER
usb_ether_init();
#endif
return 0;
}
int ft_board_setup(void *blob, struct bd_info *bd)
{
int __maybe_unused r;
/*
* Call setup_environment again in case the boot fdt has
* ethernet aliases the u-boot copy does not have.
*/
setup_environment(blob);
#ifdef <API key>
r = <API key>(blob);
if (r)
return r;
#endif
return 0;
}
#ifdef CONFIG_SPL_LOAD_FIT
static void set_spl_dt_name(const char *name)
{
struct boot_file_head *spl = get_spl_header(<API key>);
if (spl == INVALID_SPL_HEADER)
return;
/* Promote the header version for U-Boot proper, if needed. */
if (spl->spl_signature[3] < <API key>)
spl->spl_signature[3] = <API key>;
strcpy((char *)&spl->string_pool, name);
spl->dt_name_offset = offsetof(struct boot_file_head, string_pool);
}
int <API key>(const char *name)
{
const char *best_dt_name = get_spl_dt_name();
int ret;
#ifdef <API key>
if (best_dt_name == NULL)
best_dt_name = <API key>;
#endif
if (best_dt_name == NULL) {
/* No DT name was provided, so accept the first config. */
return 0;
}
#ifdef <API key>
if (strstr(best_dt_name, "-pine64-plus")) {
/* Differentiate the Pine A64 boards by their DRAM size. */
if ((gd->ram_size == 512 * 1024 * 1024))
best_dt_name = "sun50i-a64-pine64";
}
#endif
#ifdef <API key>
if (strstr(best_dt_name, "-pinephone")) {
/* Differentiate the PinePhone revisions by GPIO inputs. */
prcm_apb0_enable(PRCM_APB0_GATE_PIO);
sunxi_gpio_set_pull(SUNXI_GPL(6), SUNXI_GPIO_PULL_UP);
<API key>(SUNXI_GPL(6), SUNXI_GPIO_INPUT);
udelay(100);
/* PL6 is pulled low by the modem on v1.2. */
if (gpio_get_value(SUNXI_GPL(6)) == 0)
best_dt_name = "<API key>.2";
else
best_dt_name = "<API key>.1";
<API key>(SUNXI_GPL(6), SUNXI_GPIO_DISABLE);
sunxi_gpio_set_pull(SUNXI_GPL(6), <API key>);
prcm_apb0_disable(PRCM_APB0_GATE_PIO);
}
#endif
ret = strcmp(name, best_dt_name);
/*
* If one of the FIT configurations matches the most accurate DT name,
* update the SPL header to provide that DT name to U-Boot proper.
*/
if (ret == 0)
set_spl_dt_name(best_dt_name);
return ret;
}
#endif
|
import attr
from navmazing import NavigateToAttribute
from cfme.common import Taggable
from cfme.exceptions import ItemNotFound
from cfme.modeling.base import BaseCollection, BaseEntity, parent_of_type
from cfme.networks.views import <API key>, SecurityGroupView
from cfme.utils import version
from cfme.utils.appliance.implementations.ui import navigator, CFMENavigateStep, navigate_to
@attr.s
class SecurityGroup(Taggable, BaseEntity):
"""Class representing security group in sdn"""
in_version = ('5.8', version.LATEST)
category = 'networks'
string_name = 'SecurityGroup'
quad_name = None
db_types = ['SecurityGroup']
name = attr.ib()
@property
def provider(self):
from cfme.networks.provider import NetworkProvider
return parent_of_type(self, NetworkProvider)
@property
def network_provider(self):
""" Returns network provider """
# security group collection contains reference to provider
if self.provider:
return self.provider
# otherwise get provider name from ui
view = navigate_to(self, 'Details')
try:
prov_name = view.entities.relationships.get_text_of("Network Manager")
collection = self.appliance.collections.network_provider
return collection.instantiate(name=prov_name)
except ItemNotFound: # BZ 1480577
return None
@attr.s
class <API key>(BaseCollection):
""" Collection object for SecurityGroup object
Note: Network providers object are not implemented in mgmt
"""
ENTITY = SecurityGroup
def all(self):
if self.filters.get('parent'):
view = navigate_to(self.filters.get('parent'), 'SecurityGroups')
else:
view = navigate_to(self, 'All')
list_networks_obj = view.entities.get_all(surf_pages=True)
return [self.instantiate(name=s.name) for s in list_networks_obj]
@navigator.register(<API key>, 'All')
class All(CFMENavigateStep):
VIEW = SecurityGroupView
prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
def step(self):
self.prerequisite_view.navigation.select('Networks', 'Security Groups')
def resetter(self):
"""Reset the view"""
self.view.browser.refresh()
@navigator.register(SecurityGroup, 'Details')
class Details(CFMENavigateStep):
prerequisite = NavigateToAttribute('parent', 'All')
VIEW = <API key>
def step(self):
self.prerequisite_view.entities.get_entity(name=self.obj.name).click()
|
# -*- coding: utf-8 -*-
import wx
from outwiker.gui.testeddialog import TestedDialog
class OverwriteDialog(TestedDialog):
def __init__(self, *args, **kwds):
super(OverwriteDialog, self).__init__(*args, **kwds)
self.textLabel = wx.StaticText(self,
-1,
_("Overwrite file?"),
style=wx.ALIGN_CENTRE)
self.overwrite = wx.Button(self, -1, _("Overwrite"))
self.overwriteAll = wx.Button(self, -1, _("Overwrite all"))
self.skip = wx.Button(self, -1, _("Skip"))
self.skipAll = wx.Button(self, -1, _("Skip all"))
self.cancel = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.onOverwrite, self.overwrite)
self.Bind(wx.EVT_BUTTON, self.onOverwriteAll, self.overwriteAll)
self.Bind(wx.EVT_BUTTON, self.onSkip, self.skip)
self.Bind(wx.EVT_BUTTON, self.onSkipAll, self.skipAll)
self.ID_OVERWRITE = 1
self.ID_SKIP = 2
self.flag = 0
self.SetEscapeId(wx.ID_CANCEL)
self.Center(wx.BOTH)
def __set_properties(self):
self.SetTitle(_("Overwrite Files"))
self.overwrite.SetFocus()
self.overwrite.SetDefault()
def __do_layout(self):
sizer_1 = wx.FlexGridSizer(cols=1)
sizer_1.AddGrowableCol(0)
sizer_1.AddGrowableRow(1)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.textLabel,
flag=wx.ALL | wx.EXPAND | wx.<API key>,
border=10)
sizer_2.Add(self.overwrite, flag=wx.ALL, border=4)
sizer_2.Add(self.overwriteAll, flag=wx.ALL, border=4)
sizer_2.Add(self.skip, flag=wx.ALL, border=4)
sizer_2.Add(self.skipAll, flag=wx.ALL, border=4)
sizer_2.Add(self.cancel, flag=wx.ALL, border=4)
sizer_1.Add(sizer_2,
flag=wx.<API key> | wx.<API key> | wx.ALL,
border=4)
self.SetSizer(sizer_1)
self.Fit()
def ShowDialog(self, text):
if self.flag == 0:
self.textLabel.SetLabel(text)
self.Layout()
return self.ShowModal()
return self.flag
def onOverwrite(self, event):
self.EndModal(self.ID_OVERWRITE)
def onOverwriteAll(self, event):
self.flag = self.ID_OVERWRITE
self.EndModal(self.ID_OVERWRITE)
def onSkip(self, event):
self.EndModal(self.ID_SKIP)
def onSkipAll(self, event):
self.flag = self.ID_SKIP
self.EndModal(self.ID_SKIP)
|
# This file is part of CARPS.
# CARPS is free software: you can redistribute it and/or modify
# (at your option) any later version.
# CARPS is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
require "carps/util"
require "carps/ui"
require "carps/protocol/keyword"
require "openssl"
require "yaml"
module CARPS
# Clean the end of an email
# Strip the last end marker and any text after it
def clean_end blob
rb = blob.reverse
before, after = rb.split K.end.reverse, 2
if after
return after.reverse
end
nil
end
# Fetch security information from an email
def security_info blob
blob = clean_end blob
sig = nil
begin
sig, blob = find K.sig, blob
rescue
UI::warn "Message signature was malformed", blob
return nil
end
# If the digest is the hash of the message and the signature matches the digest then all is well
dig = Digest::MD5.digest blob
[[sig, dig], blob]
end
# Peers
class Peer < UserConfig
# Extend protocol for signed data
protoval :sig
# Create a new peer
def initialize addr
@addr = addr
end
def addr
@addr
end
# Tell this peer its key
def your_key key
@peer_key = key
end
# Perform a verification on an email
def verify mail
sig, dig = mail.crypt
begin
pass = @peer_key.sysverify dig, sig
rescue OpenSSL::PKey::DSAError => e
UI::warn "Someone sent you an invalid signature: #{e.message}"
return false
end
if pass
return true
else
UI::warn "Someone has attempted to spoof an email from #{mail.from}", mail.to_s
return false
end
end
# Save as YAML file in .peers
def save
y = emit.to_yaml
begin
write_file_in ".peers/", y
rescue StandardError => e
UI::warn "Could not save Peer in .peers/"
end
end
protected
# Emit this peer as a yaml document
def emit
{"addr" => @addr, "key" => @peer_key.to_pem}
end
def parse_yaml conf
key_pem = read_conf conf, "key"
@addr = read_conf conf, "addr"
[key_pem]
end
def load_resources key_pem
@peer_key = OpenSSL::PKey::DSA.new key_pem
end
end
end
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_25) on Wed Aug 08 22:38:31 NZST 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class moa.streams.FilteredStream (MOA: Massive Online Analysis 2012.08 API)
</TITLE>
<META NAME="date" CONTENT="2012-08-08">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class moa.streams.FilteredStream (MOA: Massive Online Analysis 2012.08 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../moa/streams/FilteredStream.html" title="class in moa.streams"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?moa/streams//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="FilteredStream.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>moa.streams.FilteredStream</B></H2>
</CENTER>
No usage of moa.streams.FilteredStream
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../moa/streams/FilteredStream.html" title="class in moa.streams"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?moa/streams//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="FilteredStream.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
Copyright &
</BODY>
</HTML>
|
/* Return to Masteria
[Lucky Lucky Monstory] Check Your Monster Cards
Made by Daenerys
*/
importPackage(Packages.tools.packet);
function start() {
qm.OpenUI(117);
qm.dispose();
}
|
Ext.ns('Deluge');
/**
* @class Deluge.EditTrackerWindow
* @extends Ext.Window
*/
Deluge.EditTrackersWindow = Ext.extend(Ext.Window, {
title: _('Edit Trackers'),
layout: 'fit',
width: 350,
height: 220,
plain: true,
closable: true,
resizable: true,
bodyStyle: 'padding: 5px',
buttonAlign: 'right',
closeAction: 'hide',
iconCls: '<API key>',
initComponent: function() {
Deluge.EditTrackersWindow.superclass.initComponent.call(this);
this.addButton(_('Cancel'), this.onCancelClick, this);
this.addButton(_('OK'), this.onOkClick, this);
this.addEvents('save');
this.on('show', this.onShow, this);
this.on('save', this.onSave, this);
this.addWindow = new Deluge.AddTrackerWindow();
this.addWindow.on('add', this.onAddTrackers, this);
this.editWindow = new Deluge.EditTrackerWindow();
this.list = new Ext.list.ListView({
store: new Ext.data.JsonStore({
root: 'trackers',
fields: [
'tier',
'url'
]
}),
columns: [{
header: _('Tier'),
width: .1,
dataIndex: 'tier'
}, {
header: _('Tracker'),
width: .9,
dataIndex: 'url'
}],
columnSort: {
sortClasses: ['', '']
},
stripeRows: true,
singleSelect: true,
listeners: {
'dblclick': {fn: this.<API key>, scope: this},
'selectionchange': {fn: this.onSelect, scope: this}
}
});
this.panel = this.add({
margins: '0 0 0 0',
items: [this.list],
autoScroll: true,
bbar: new Ext.Toolbar({
items: [
{
text: _('Up'),
iconCls: 'icon-up',
handler: this.onUpClick,
scope: this
}, {
text: _('Down'),
iconCls: 'icon-down',
handler: this.onDownClick,
scope: this
}, '->', {
text: _('Add'),
iconCls: 'icon-add',
handler: this.onAddClick,
scope: this
}, {
text: _('Edit'),
iconCls: 'icon-edit-trackers',
handler: this.onEditClick,
scope: this
}, {
text: _('Remove'),
iconCls: 'icon-remove',
handler: this.onRemoveClick,
scope: this
}
]
})
});
},
onAddClick: function() {
this.addWindow.show();
},
onAddTrackers: function(trackers) {
var store = this.list.getStore();
Ext.each(trackers, function(tracker) {
var duplicate = false, heightestTier = -1;
store.each(function(record) {
if (record.get('tier') > heightestTier) {
heightestTier = record.get('tier');
}
if (tracker == record.get('tracker')) {
duplicate = true;
return false;
}
}, this);
if (duplicate) return;
store.add(new store.recordType({'tier': heightestTier + 1, 'url': tracker}));
}, this);
},
onCancelClick: function() {
this.hide();
},
onEditClick: function() {
this.editWindow.show(this.list.getSelectedRecords()[0]);
},
onHide: function() {
this.list.getStore().removeAll();
},
<API key>: function(list, index, node, e) {
this.editWindow.show(this.list.getRecord(node));
},
onOkClick: function() {
var trackers = [];
this.list.getStore().each(function(record) {
trackers.push({
'tier': record.get('tier'),
'url': record.get('url')
})
}, this);
deluge.client.core.<API key>(this.torrentId, trackers, {
failure: this.onSaveFail,
scope: this
});
this.hide();
},
onRemoveClick: function() {
// Remove from the grid
this.list.getStore().remove(this.list.getSelectedRecords()[0]);
},
onRequestComplete: function(status) {
this.list.getStore().loadData(status);
this.list.getStore().sort('tier', 'ASC');
},
onSaveFail: function() {
},
onSelect: function(list) {
if (list.getSelectionCount()) {
this.panel.getBottomToolbar().items.get(4).enable();
}
},
onShow: function() {
this.panel.getBottomToolbar().items.get(4).disable();
var r = deluge.torrents.getSelected();
this.torrentId = r.id;
deluge.client.core.get_torrent_status(r.id, ['trackers'], {
success: this.onRequestComplete,
scope: this
});
},
onDownClick: function() {
var r = this.list.getSelectedRecords()[0];
if (!r) return;
r.set('tier', r.get('tier') + 1);
r.store.sort('tier', 'ASC');
r.store.commitChanges();
this.list.select(r.store.indexOf(r));
},
onUpClick: function() {
var r = this.list.getSelectedRecords()[0];
if (!r) return;
if (r.get('tier') == 0) return;
r.set('tier', r.get('tier') - 1);
r.store.sort('tier', 'ASC');
r.store.commitChanges();
this.list.select(r.store.indexOf(r));
}
});
|
<?php
namespace Jigoshop\Factory;
use Jigoshop\Core\Options;
use Jigoshop\Service\PaymentService as Service;
use WPAL\Wordpress;
class PaymentService
{
/** @var \WPAL\Wordpress */
private $wp;
/** @var \Jigoshop\Core\Options */
private $options;
public function __construct(Wordpress $wp, Options $options)
{
$this->wp = $wp;
$this->options = $options;
}
/**
* @return Service Tax service.
* @since 2.0
*/
public function getService()
{
$service = new Service();
switch ($this->options->get('advanced.cache')) {
// TODO: Add caching mechanisms
default:
$service = $this->wp->applyFilters('jigoshop\core\get_payment_service', $service);
}
return $service;
}
}
|
# encoding: utf-8
require 'data_mapper'
require 'slim'
module Assassins
class Game
def winner
alive = Player.all(:is_verified => true, :is_alive => true)
if (alive.count == 1)
alive[0]
else
nil
end
end
end
class App < Sinatra::Base
before do
@game = Game.first
if @game.nil?
@game = Game.new
@game.save
end
end
set(:game_state) do |*vals|
condition {(vals.include? game_state)}
end
helpers do
def game_state
if defined?(@game_state) && !@game_state.nil?
@game_state
else
if !@game.start_time.nil? && Time.now >= @game.start_time
if Player.count(:is_verified => true, :is_alive => true) == 1
@game_state = :postgame
else
@game_state = :ingame
end
else
@game_state = :pregame
end
end
end
end
get '/leaderboard', :game_state => [:ingame, :postgame] do
slim :leaderboard
end
end
end
# vim:set ts=2 sw=2 et:
|
package cern.colt.matrix.tdouble.impl;
import cern.colt.matrix.tdouble.DoubleMatrix2D;
import cern.jet.math.tdouble.DoubleFunctions;
/**
* Benchmarks the performance of matrices. Here are the results of some
* encouraging measurements. Note that all benchmarks only measure the time
* spent in accessing a matrix element; they exclude the loop itself.
* <p>
* <center>
* <table border cellpadding="3" cellspacing="0" align="center">
* <tr valign="middle" bgcolor="#33CC66" nowrap align="center">
* <td nowrap columnspan="7"><font size="+2">Iteration Performance [million method
* calls per second]</font><br>
* <font size="-1">Pentium Pro 200 Mhz, SunJDK 1.2.2, NT, java -classic,<br>
* 60 times repeating the same iteration </font></td>
* </tr>
* <tr valign="middle" bgcolor="#33CC66" nowrap align="center">
* <td nowrap><div align="left"> Element type</div></td>
* <td nowrap columnspan="6">Matrix2D type</td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td nowrap bgcolor="#FF9966" rowspan="2"><div align="left"> .</div></td>
* <td bgcolor="#FF9966" columnspan="2">
* <p>
* <tt>DenseDoubleMatrix2D</tt><br>
* 1000 x 1000
* </p>
* </td>
* <td bgcolor="#FF9966" columnspan="2"> </td>
* <td bgcolor="#FF9966" columnspan="2">
* <p>
* <tt><API key></tt><br>
* 100 x 1000,<br>
* <font size="-1"> minLoadFactor=0.2, maxLoadFactor=0.5, initialCapacity =
* 0</font>
* </p>
* </td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td bgcolor="#FF9966">getQuick</td>
* <td bgcolor="#FF9966">setQuick</td>
* <td bgcolor="#FF9966"> </td>
* <td bgcolor="#FF9966"> </td>
* <td bgcolor="#FF9966">getQuick</td>
* <td bgcolor="#FF9966">setQuick</td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td nowrap bgcolor="#FF9966">double</td>
* <td nowrap>5</td>
* <td nowrap>5</td>
* <td nowrap> </td>
* <td nowrap> </td>
* <td nowrap>1</td>
* <td nowrap>0.27</td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td nowrap bgcolor="#FF9966">int</td>
* <td nowrap>5</td>
* <td nowrap>5.5</td>
* <td nowrap> </td>
* <td nowrap> </td>
* <td nowrap>1</td>
* <td nowrap>0.3</td>
* </tr>
* </table>
* </center>
* <p align="left">
* As can be seen, sparse matrices are certainly not quite as quick as dense
* ones, but not really slow either. Considering their minimal footprint they
* can be a real alternative.
* <p>
* Comparing the OO abstractions to zero-abstraction primitive Java arrays may
* or may not be useful. Still, the table below provides some interesting
* information. For example, access to <tt>Type_T_Matrix2D</tt> is quicker than
* naive usage of <tt>Type_T_[]</tt>. Primitive arrays should only be considered
* if the optimized form can be applied. Note again that all benchmarks only
* measure the time spent in accessing a matrix element; they exclude the loop
* itself.
* <p>
* <center>
* <table border cellpadding="3" cellspacing="0" align="center" * width="617">
* <tr valign="middle" bgcolor="#33CC66" nowrap align="center">
* <td height="30" nowrap columnspan="7"><font size="+2">Iteration Performance
* [million element accesses per second]</font><br>
* <font size="-1">Pentium Pro 200 Mhz, SunJDK 1.2.2, NT, java -classic,<br>
* 200 times repeating the same iteration </font></td>
* </tr>
* <tr valign="middle" bgcolor="#33CC66" nowrap align="center">
* <td width="78" height="30" nowrap><div align="left"> Element type</div></td>
* <td height="30" nowrap columnspan="6"><div align="center">Matrix2D type = Java
* array <tt>double[][]</tt></div></td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td width="78" height="60" nowrap bgcolor="#FF9966" rowspan="2"><div
* align="left"> .</div></td>
* <td height="132" bgcolor="#FF9966" columnspan="2">
* <p>
* Unoptimized Form<br>
* 1000 x 1000<br>
* <div align="left"> <font size="-1">
*
* <pre>
* for (int row=0; row < rows; row++) {
* for (int col=0; col < columns; ) {
* value = m[row][col++];
* ...
* }
* }
* </pre>
*
* </font> </div>
* </td>
* <td height="132" bgcolor="#FF9966" columnspan="4">Optimized Form<br>
* 1000 x 1000 <div align="left"> <font size="-1">
*
* <pre>
* for (int row=0; row < rows; row++) {
* int[] r = matrix[row];
* for (int col=0; col < columns; ) {
* value = r[col++];
* ...
* }
* }
* </pre>
*
* </font> </div></td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td width="152" height="30" bgcolor="#FF9966">getting</td>
* <td width="144" height="30" bgcolor="#FF9966">setting</td>
* <td width="150" height="30" bgcolor="#FF9966">getting</td>
* <td width="138" height="30" bgcolor="#FF9966" columnspan="3">setting</td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td width="78" height="30" nowrap bgcolor="#FF9966">double</td>
* <td width="152" height="30" nowrap>1.6</td>
* <td width="144" height="30" nowrap>1.8</td>
* <td width="150" height="30" nowrap>18</td>
* <td width="138" height="30" nowrap columnspan="3">11</td>
* </tr>
* <tr valign="middle" bgcolor="#66CCFF" nowrap align="center">
* <td width="78" height="30" nowrap bgcolor="#FF9966">int</td>
* <td width="152" height="30" nowrap>1.5</td>
* <td width="144" height="30" nowrap>1.8</td>
* <td width="150" height="30" nowrap>28</td>
* <td width="138" height="30" nowrap columnspan="3">26</td>
* </tr>
* </table>
* </center> <left>
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*/
class BenchmarkMatrix2D {
/**
* Makes this class non instantiable, but still let's others inherit from
* it.
*/
protected BenchmarkMatrix2D() {
throw new RuntimeException("Non instantiable");
}
/**
* Runs a bench on matrices holding double elements.
*/
public static void doubleBenchmark(int runs, int rows, int columns, String kind, boolean print,
int initialCapacity, double minLoadFactor, double maxLoadFactor) {
System.out.println("benchmarking double matrix");
// certain loops need to be constructed so that the jitter can't
// optimize them away and we get fantastic numbers.
// this involves primarly read-loops
cern.colt.Timer timer1 = new cern.colt.Timer();
cern.colt.Timer timer2 = new cern.colt.Timer();
cern.colt.Timer timer3 = new cern.colt.Timer();
cern.colt.Timer timer4 = new cern.colt.Timer();
cern.colt.Timer emptyLoop = new cern.colt.Timer();
cern.colt.Timer emptyLoop2 = new cern.colt.Timer();
emptyLoop.start();
int dummy = 0;
for (int i = 0; i < runs; i++) {
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
dummy++;
}
}
}
emptyLoop.stop();
System.out.println(dummy); // !!! so that the jitter can't optimize
// away the whole loop
emptyLoop2.start();
dummy = 3;
double dummy2 = 0;
for (int i = 0; i < runs; i++) {
for (int value = 0, column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
dummy2 += dummy;
}
}
}
emptyLoop2.stop();
System.out.println(dummy2); // !!! so that the jitter can't optimize
// away the whole loop
long before = Runtime.getRuntime().freeMemory();
long size = (((long) rows) * columns) * runs;
DoubleMatrix2D matrix = null;
if (kind.equals("sparse"))
matrix = new <API key>(rows, columns, initialCapacity, minLoadFactor, maxLoadFactor);
else if (kind.equals("dense"))
matrix = new DenseDoubleMatrix2D(rows, columns);
// else if (kind.equals("denseArray")) matrix = new
// DoubleArrayMatrix2D(rows,columns);
else
throw new RuntimeException("unknown kind");
System.out.println("\nNow filling...");
// if (kind.equals("sparse"))
// ((<API key>)matrix).elements.hashCollisions = 0;
for (int i = 0; i < runs; i++) {
matrix.assign(0);
matrix.ensureCapacity(initialCapacity);
if (kind.equals("sparse"))
((<API key>) matrix).ensureCapacity(initialCapacity);
timer1.start();
int value = 0;
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
matrix.setQuick(row, column, value++);
}
}
timer1.stop();
}
timer1.display();
timer1.minus(emptyLoop).display();
System.out.println(size / timer1.minus(emptyLoop).seconds() + " elements / sec");
Runtime.getRuntime().gc(); // invite gc
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (<API key> exc) {
}
;
long after = Runtime.getRuntime().freeMemory();
System.out.println("KB needed=" + (before - after) / 1024);
System.out.println("bytes needed per non-zero=" + (before - after) / (double) matrix.cardinality());
if (print) {
System.out.println(matrix);
if (kind.equals("sparse"))
System.out.println("map=" + ((<API key>) matrix).elements());
}
/*
* if (kind.equals("sparse")) { int hashCollisions =
* ((<API key>)matrix).elements.hashCollisions;
* System.out.println("hashCollisions="+hashCollisions);
* System.out.println("--> "+ ((double)hashCollisions / (rows*columns)) +"
* hashCollisions/element on average."); }
*/
System.out.println("\nNow reading...");
// if (kind.equals("sparse"))
// ((<API key>)matrix).elements.hashCollisions = 0;
timer2.start();
double element = 0;
for (int i = 0; i < runs; i++) {
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
element += matrix.getQuick(row, column);
}
}
}
timer2.stop().display();
timer2.minus(emptyLoop2).display();
System.out.println(size / timer2.minus(emptyLoop2).seconds() + " elements / sec");
if (print)
System.out.println(matrix);
// if (kind.equals("sparse"))
// System.out.println("hashCollisions="+((<API key>)matrix).elements.hashCollisions);
System.out.println(element); // !!! so that the jitter can't optimize
// away the whole loop
System.out.println("\nNow reading view...");
DoubleMatrix2D view = matrix.viewPart(0, 0, rows, columns);
timer4.start();
element = 0;
for (int i = 0; i < runs; i++) {
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
element += view.getQuick(row, column);
}
}
}
timer4.stop().display();
timer4.minus(emptyLoop2).display();
System.out.println(size / timer4.minus(emptyLoop2).seconds() + " elements / sec");
if (print)
System.out.println(view);
// if (kind.equals("sparse"))
// System.out.println("hashCollisions="+((<API key>)view).elements.hashCollisions);
System.out.println(element); // !!! so that the jitter can't optimize
// away the whole loop
System.out.println("\nNow removing...");
before = Runtime.getRuntime().freeMemory();
// if (kind.equals("sparse"))
// ((<API key>)matrix).elements.hashCollisions = 0;
for (int i = 0; i < runs; i++) {
// initializing
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
matrix.setQuick(row, column, 1);
}
}
timer3.start();
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
matrix.setQuick(row, column, 0);
}
}
timer3.stop();
}
timer3.display();
timer3.minus(emptyLoop).display();
System.out.println(size / timer3.minus(emptyLoop).seconds() + " elements / sec");
Runtime.getRuntime().gc(); // invite gc
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (<API key> exc) {
}
;
after = Runtime.getRuntime().freeMemory();
System.out.println("KB needed=" + (before - after) / 1024);
System.out.println("KB free=" + (after / 1024));
if (print)
System.out.println(matrix);
// if (kind.equals("sparse"))
// System.out.println("hashCollisions"+((<API key>)matrix).elements.hashCollisions);
System.out.println("bye bye.");
}
/**
* Runs a bench on matrices holding double elements.
*/
public static void doubleBenchmarkMult(int runs, int rows, int columns, String kind, boolean print,
int initialCapacity, double minLoadFactor, double maxLoadFactor) {
System.out.println("benchmarking double matrix");
// certain loops need to be constructed so that the jitter can't
// optimize them away and we get fantastic numbers.
// this involves primarly read-loops
cern.colt.Timer timer1 = new cern.colt.Timer();
cern.colt.Timer timer2 = new cern.colt.Timer();
long size = (((long) rows) * columns) * runs;
DoubleMatrix2D matrix = null;
if (kind.equals("sparse"))
matrix = new <API key>(rows, columns, initialCapacity, minLoadFactor, maxLoadFactor);
else if (kind.equals("dense"))
matrix = new DenseDoubleMatrix2D(rows, columns);
// else if (kind.equals("denseArray")) matrix = new
// DoubleArrayMatrix2D(rows,columns);
else
throw new RuntimeException("unknown kind");
System.out.println("\nNow multiplying...");
matrix.assign(1);
// if (kind.equals("sparse"))
// ((<API key>)matrix).elements.hashCollisions = 0;
for (int i = 0; i < runs; i++) {
timer1.start();
matrix.assign(DoubleFunctions.mult(3));
timer1.stop();
}
timer1.display();
System.out.println(size / timer1.seconds() + " elements / sec");
if (print) {
System.out.println(matrix);
}
/*
* if (kind.equals("sparse")) { int hashCollisions =
* ((<API key>)matrix).elements.hashCollisions;
* System.out.println("hashCollisions="+hashCollisions);
* System.out.println("--> "+ ((double)hashCollisions / (rows*columns)) +"
* hashCollisions/element on average."); }
*/
System.out.println("\nNow multiplying2...");
matrix.assign(1);
// if (kind.equals("sparse"))
// ((<API key>)matrix).elements.hashCollisions = 0;
for (int i = 0; i < runs; i++) {
timer2.start();
matrix.assign(DoubleFunctions.mult(3));
timer2.stop();
}
timer2.display();
System.out.println(size / timer2.seconds() + " elements / sec");
if (print) {
System.out.println(matrix);
}
/*
* if (kind.equals("sparse")) { int hashCollisions =
* ((<API key>)matrix).elements.hashCollisions;
* System.out.println("hashCollisions="+hashCollisions);
* System.out.println("--> "+ ((double)hashCollisions / (rows*columns)) +"
* hashCollisions/element on average."); }
*/
System.out.println("bye bye.");
}
/**
* Runs a bench on matrices holding double elements.
*/
public static void <API key>(int runs, int rows, int columns, boolean print) {
// certain loops need to be constructed so that the jitter can't
// optimize them away and we get fantastic numbers.
// this involves primarly read-loops
cern.colt.Timer timer1 = new cern.colt.Timer();
cern.colt.Timer timer2 = new cern.colt.Timer();
cern.colt.Timer timer3 = new cern.colt.Timer();
cern.colt.Timer emptyLoop = new cern.colt.Timer();
cern.colt.Timer emptyLoop2 = new cern.colt.Timer();
emptyLoop.start();
int dummy = 0;
for (int i = 0; i < runs; i++) {
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
dummy++;
}
}
}
emptyLoop.stop();
System.out.println(dummy); // !!! so that the jitter can't optimize
// away the whole loop
emptyLoop2.start();
dummy = 3;
double dummy2 = 0;
for (int i = 0; i < runs; i++) {
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
dummy2 += dummy;
}
}
}
emptyLoop2.stop();
System.out.println(dummy2); // !!! so that the jitter can't optimize
// away the whole loop
long before = Runtime.getRuntime().freeMemory();
long size = (((long) rows) * columns) * runs;
double[][] matrix = new double[rows][columns];
System.out.println("\nNow filling...");
for (int i = 0; i < runs; i++) {
timer1.start();
int value = 0;
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
matrix[row][column] = value++;
}
}
timer1.stop();
}
timer1.display();
timer1.minus(emptyLoop).display();
System.out.println(size / timer1.minus(emptyLoop).seconds() + " elements / sec");
Runtime.getRuntime().gc(); // invite gc
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (<API key> exc) {
}
;
long after = Runtime.getRuntime().freeMemory();
System.out.println("KB needed=" + (before - after) / 1024);
if (print) {
DenseDoubleMatrix2D m = new DenseDoubleMatrix2D(rows, columns);
m.assign(matrix);
System.out.println(m);
}
System.out.println("\nNow reading...");
timer2.start();
double element = 0;
for (int i = 0; i < runs; i++) {
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
element += matrix[row][column];
}
}
}
timer2.stop().display();
timer2.minus(emptyLoop2).display();
System.out.println(size / timer2.minus(emptyLoop2).seconds() + " elements / sec");
if (print) {
DenseDoubleMatrix2D m = new DenseDoubleMatrix2D(rows, columns);
m.assign(matrix);
System.out.println(m);
}
System.out.println(element); // !!! so that the jitter can't optimize
// away the whole loop
System.out.println("\nNow removing...");
before = Runtime.getRuntime().freeMemory();
for (int i = 0; i < runs; i++) {
/*
* // initializing for (int column=0; column < columns; column++) {
* for (int row=0; row < rows; row++) {
* matrix.setQuick(row,column,1); } }
*/
timer3.start();
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
matrix[row][column] = 0;
}
}
timer3.stop();
}
timer3.display();
timer3.minus(emptyLoop).display();
System.out.println(size / timer3.minus(emptyLoop).seconds() + " elements / sec");
Runtime.getRuntime().gc(); // invite gc
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (<API key> exc) {
}
;
after = Runtime.getRuntime().freeMemory();
System.out.println("KB needed=" + (before - after) / 1024);
System.out.println("KB free=" + (after / 1024));
if (print) {
DenseDoubleMatrix2D m = new DenseDoubleMatrix2D(rows, columns);
m.assign(matrix);
System.out.println(m);
}
System.out.println("bye bye.");
}
/**
* Runs a bench on matrices holding double elements.
*/
public static void <API key>(int runs, int rows, int columns, boolean print) {
// certain loops need to be constructed so that the jitter can't
// optimize them away and we get fantastic numbers.
// this involves primarly read-loops
cern.colt.Timer timer1 = new cern.colt.Timer();
cern.colt.Timer timer2 = new cern.colt.Timer();
cern.colt.Timer timer3 = new cern.colt.Timer();
cern.colt.Timer emptyLoop = new cern.colt.Timer();
cern.colt.Timer emptyLoop2 = new cern.colt.Timer();
emptyLoop.start();
int dummy = 0;
for (int i = 0; i < runs; i++) {
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
dummy++;
}
}
}
emptyLoop.stop();
System.out.println(dummy); // !!! so that the jitter can't optimize
// away the whole loop
emptyLoop2.start();
dummy = 3;
double dummy2 = 0;
for (int i = 0; i < runs; i++) {
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
dummy2 += dummy;
}
}
}
emptyLoop2.stop();
System.out.println(dummy2); // !!! so that the jitter can't optimize
// away the whole loop
long before = Runtime.getRuntime().freeMemory();
long size = (((long) rows) * columns) * runs;
double[][] matrix = new double[rows][columns];
System.out.println("\nNow filling...");
for (int i = 0; i < runs; i++) {
timer1.start();
int value = 0;
for (int row = 0; row < rows; row++) {
double[] r = matrix[row];
for (int column = 0; column < columns; column++) {
r[column] = value++;
// matrix[row][column] = value++;
}
}
timer1.stop();
}
timer1.display();
timer1.minus(emptyLoop).display();
System.out.println(size / timer1.minus(emptyLoop).seconds() + " elements / sec");
Runtime.getRuntime().gc(); // invite gc
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (<API key> exc) {
}
;
long after = Runtime.getRuntime().freeMemory();
System.out.println("KB needed=" + (before - after) / 1024);
if (print) {
DenseDoubleMatrix2D m = new DenseDoubleMatrix2D(rows, columns);
m.assign(matrix);
System.out.println(m);
}
System.out.println("\nNow reading...");
timer2.start();
double element = 0;
for (int i = 0; i < runs; i++) {
for (int row = 0; row < rows; row++) {
double[] r = matrix[row];
for (int column = 0; column < columns; column++) {
element += r[column];
// element += matrix[row][column];
}
}
}
timer2.stop().display();
timer2.minus(emptyLoop2).display();
System.out.println(size / timer2.minus(emptyLoop2).seconds() + " elements / sec");
if (print) {
DenseDoubleMatrix2D m = new DenseDoubleMatrix2D(rows, columns);
m.assign(matrix);
System.out.println(m);
}
System.out.println(element); // !!! so that the jitter can't optimize
// away the whole loop
System.out.println("\nNow removing...");
before = Runtime.getRuntime().freeMemory();
for (int i = 0; i < runs; i++) {
timer3.start();
for (int row = 0; row < rows; row++) {
double[] r = matrix[row];
for (int column = 0; column < columns; column++) {
r[column] = 0;
// matrix[row][column] = 0;
}
}
timer3.stop();
}
timer3.display();
timer3.minus(emptyLoop).display();
System.out.println(size / timer3.minus(emptyLoop).seconds() + " elements / sec");
Runtime.getRuntime().gc(); // invite gc
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (<API key> exc) {
}
;
after = Runtime.getRuntime().freeMemory();
System.out.println("KB needed=" + (before - after) / 1024);
System.out.println("KB free=" + (after / 1024));
if (print) {
DenseDoubleMatrix2D m = new DenseDoubleMatrix2D(rows, columns);
m.assign(matrix);
System.out.println(m);
}
System.out.println("bye bye.");
}
/**
* Runs a bench on matrices holding int elements.
*/
public static void intBenchmark(int runs, int rows, int columns, String kind, boolean print, int initialCapacity,
double minLoadFactor, double maxLoadFactor) {
throw new InternalError();
/*
* // certain loops need to be constructed so that the jitter can't
* optimize them away and we get fantastic numbers. // this involves
* primarly read-loops
*
* cern.colt.Timer timer1 = new cern.colt.Timer(); cern.colt.Timer
* timer2 = new cern.colt.Timer(); cern.colt.Timer timer3 = new
* cern.colt.Timer(); cern.colt.Timer emptyLoop = new cern.colt.Timer();
* cern.colt.Timer emptyLoop2 = new cern.colt.Timer();
*
* emptyLoop.start(); int dummy = 0; for (int i=0; i<runs; i++) { for
* (int column=0; column < columns; column++) { for (int row=0; row <
* rows; row++) { dummy++; } } } emptyLoop.stop();
* System.out.println(dummy); // !!! so that the jitter can't optimize
* away the whole loop
*
* emptyLoop2.start(); dummy = 3; int dummy2 = 0; for (int i=0; i<runs;
* i++) { for (int value = 0, column=0; column < columns; column++) {
* for (int row=0; row < rows; row++) { dummy2 += dummy; } } }
* emptyLoop2.stop(); System.out.println(dummy2); // !!! so that the
* jitter can't optimize away the whole loop
*
* long before = Runtime.getRuntime().freeMemory(); long size =
* (((long)rows)*columns)*runs;
*
* AbstractIntMatrix2D matrix = null; if (kind.equals("sparse")) matrix =
* new
* SparseIntMatrix2D(rows,columns,initialCapacity,minLoadFactor,maxLoadFactor);
* else if (kind.equals("dense")) matrix = new
* DenseIntMatrix2D(rows,columns); //else if (kind.equals("denseArray"))
* matrix = new DoubleArrayMatrix2D(rows,columns); else throw new
* RuntimeException("unknown kind");
*
* System.out.println("\nNow filling..."); if (kind.equals("sparse"))
* ((SparseIntMatrix2D)matrix).elements.hashCollisions = 0; for (int
* i=0; i<runs; i++) { matrix.assign(0);
* matrix.ensureCapacity(initialCapacity); if (kind.equals("sparse"))
* ((SparseIntMatrix2D)matrix).ensureCapacity(initialCapacity);
* timer1.start(); int value = 0; for (int column=0; column < columns;
* column++) { for (int row=0; row < rows; row++) {
* matrix.setQuick(row,column,value++); } } timer1.stop(); }
* timer1.display(); timer1.minus(emptyLoop).display();
* System.out.println(size / timer1.minus(emptyLoop).seconds() +"
* elements / sec");
*
* Runtime.getRuntime().gc(); // invite gc try {
* Thread.currentThread().sleep(1000); } catch (<API key>
* exc) {}; long after = Runtime.getRuntime().freeMemory();
* System.out.println("KB needed="+(before-after) / 1024);
* System.out.println("bytes needed per non-zero="+(before-after) /
* (double)matrix.cardinality()); if (print) {
* System.out.println(matrix); if (kind.equals("sparse"))
* System.out.println("map="+((SparseIntMatrix2D)matrix).elements); } if
* (kind.equals("sparse")) { int hashCollisions =
* ((SparseIntMatrix2D)matrix).elements.hashCollisions;
* System.out.println("hashCollisions="+hashCollisions);
* System.out.println("--> "+ ((double)hashCollisions / (rows*columns)) +"
* probes/element on average."); }
*
* System.out.println("\nNow reading..."); if (kind.equals("sparse"))
* ((SparseIntMatrix2D)matrix).elements.hashCollisions = 0;
* timer2.start(); int element=0; for (int i=0; i<runs; i++) { for (int
* column=0; column < columns; column++) { for (int row=0; row < rows;
* row++) { element += matrix.getQuick(row,column); } } }
* timer2.stop().display(); timer2.minus(emptyLoop2).display();
* System.out.println(size / timer2.minus(emptyLoop2).seconds() +"
* elements / sec"); if (print) System.out.println(matrix); if
* (kind.equals("sparse"))
* System.out.println("hashCollisions="+((SparseIntMatrix2D)matrix).elements.hashCollisions);
* System.out.println(element); // !!! so that the jitter can't optimize
* away the whole loop
*
* System.out.println("\nNow removing..."); before =
* Runtime.getRuntime().freeMemory(); if (kind.equals("sparse"))
* ((SparseIntMatrix2D)matrix).elements.hashCollisions = 0; for (int
* i=0; i<runs; i++) { // initializing for (int column=0; column <
* columns; column++) { for (int row=0; row < rows; row++) {
* matrix.setQuick(row,column,1); } } timer3.start(); for (int column=0;
* column < columns; column++) { for (int row=0; row < rows; row++) {
* matrix.setQuick(row,column,0); } } timer3.stop(); } timer3.display();
* timer3.minus(emptyLoop).display(); System.out.println(size /
* timer3.minus(emptyLoop).seconds() +" elements / sec");
* Runtime.getRuntime().gc(); // invite gc try {
* Thread.currentThread().sleep(1000); } catch (<API key>
* exc) {}; after = Runtime.getRuntime().freeMemory();
* System.out.println("KB needed="+(before-after)/1024);
* System.out.println("KB free="+(after/1024));
*
* if (print) System.out.println(matrix); if (kind.equals("sparse"))
* System.out.println("hashCollisions="+((SparseIntMatrix2D)matrix).elements.hashCollisions);
*
*
* System.out.println("bye bye.");
*/
}
/**
* Runs a bench on matrices holding int elements.
*/
public static void <API key>(int runs, int rows, int columns, boolean print) {
throw new InternalError();
/*
* // certain loops need to be constructed so that the jitter can't
* optimize them away and we get fantastic numbers. // this involves
* primarly read-loops cern.colt.Timer timer1 = new cern.colt.Timer();
* cern.colt.Timer timer2 = new cern.colt.Timer(); cern.colt.Timer
* timer3 = new cern.colt.Timer(); cern.colt.Timer emptyLoop = new
* cern.colt.Timer(); cern.colt.Timer emptyLoop2 = new
* cern.colt.Timer();
*
* emptyLoop.start(); int dummy = 0; for (int i=0; i<runs; i++) { for
* (int column=0; column < columns; column++) { for (int row=0; row <
* rows; row++) { dummy++; } } } emptyLoop.stop();
* System.out.println(dummy); // !!! so that the jitter can't optimize
* away the whole loop
*
* emptyLoop2.start(); dummy = 3; int dummy2 = 0; for (int i=0; i<runs;
* i++) { for (int column=0; column < columns; column++) { for (int
* row=0; row < rows; row++) { dummy2 += dummy; } } } emptyLoop2.stop();
* System.out.println(dummy2); // !!! so that the jitter can't optimize
* away the whole loop
*
* long before = Runtime.getRuntime().freeMemory(); long size =
* (((long)rows)*columns)*runs;
*
* int[][] matrix = new int[rows][columns];
*
* System.out.println("\nNow filling..."); for (int i=0; i<runs; i++) {
* timer1.start(); int value = 0; for (int column=0; column < columns;
* column++) { for (int row=0; row < rows; row++) { matrix[row][column] =
* value++; } } timer1.stop(); } timer1.display();
* timer1.minus(emptyLoop).display(); System.out.println(size /
* timer1.minus(emptyLoop).seconds() +" elements / sec");
*
* Runtime.getRuntime().gc(); // invite gc try {
* Thread.currentThread().sleep(1000); } catch (<API key>
* exc) {}; long after = Runtime.getRuntime().freeMemory();
* System.out.println("KB needed="+(before-after) / 1024); if (print) {
* DenseIntMatrix2D m = new DenseIntMatrix2D(rows,columns);
* m.assign(matrix); System.out.println(m); }
*
* System.out.println("\nNow reading..."); timer2.start(); int
* element=0; for (int i=0; i<runs; i++) { for (int column=0; column <
* columns; column++) { for (int row=0; row < rows; row++) { element +=
* matrix[row][column]; } } } timer2.stop().display();
* timer2.minus(emptyLoop2).display(); System.out.println(size /
* timer2.minus(emptyLoop2).seconds() +" elements / sec"); if (print) {
* DenseIntMatrix2D m = new DenseIntMatrix2D(rows,columns);
* m.assign(matrix); System.out.println(m); }
* System.out.println(element); // !!! so that the jitter can't optimize
* away the whole loop
*
* System.out.println("\nNow removing..."); before =
* Runtime.getRuntime().freeMemory(); for (int i=0; i<runs; i++) {
* timer3.start(); for (int column=0; column < columns; column++) { for
* (int row=0; row < rows; row++) { matrix[row][column] = 0; } }
* timer3.stop(); } timer3.display(); timer3.minus(emptyLoop).display();
* System.out.println(size / timer3.minus(emptyLoop).seconds() +"
* elements / sec"); Runtime.getRuntime().gc(); // invite gc try {
* Thread.currentThread().sleep(1000); } catch (<API key>
* exc) {}; after = Runtime.getRuntime().freeMemory();
* System.out.println("KB needed="+(before-after)/1024);
* System.out.println("KB free="+(after/1024));
*
* if (print) { DenseIntMatrix2D m = new DenseIntMatrix2D(rows,columns);
* m.assign(matrix); System.out.println(m); }
*
* System.out.println("bye bye.");
*/
}
/**
* Runs a bench on matrices holding int elements.
*/
public static void <API key>(int runs, int rows, int columns, boolean print) {
throw new InternalError();
/*
* // certain loops need to be constructed so that the jitter can't
* optimize them away and we get fantastic numbers. // this involves
* primarly read-loops cern.colt.Timer timer1 = new cern.colt.Timer();
* cern.colt.Timer timer2 = new cern.colt.Timer(); cern.colt.Timer
* timer3 = new cern.colt.Timer(); cern.colt.Timer emptyLoop = new
* cern.colt.Timer(); cern.colt.Timer emptyLoop2 = new
* cern.colt.Timer();
*
* emptyLoop.start(); int dummy = 0; for (int i=0; i<runs; i++) { for
* (int column=0; column < columns; column++) { for (int row=0; row <
* rows; row++) { dummy++; } } } emptyLoop.stop();
* System.out.println(dummy); // !!! so that the jitter can't optimize
* away the whole loop
*
* int[][] matrix = new int[rows][columns]; emptyLoop2.start(); dummy =
* 3; int dummy2 = 7; System.out.println(dummy2); // !!! so that the
* jitter can't optimize away the whole loop for (int i=0; i<runs; i++) {
* for (int column=0; column < columns; column++) { for (int row=0; row <
* rows; row++) { dummy2 += dummy; //matrix[row][column]; } } }
* emptyLoop2.stop(); System.out.println(dummy2); // !!! so that the
* jitter can't optimize away the whole loop
*
* long before = Runtime.getRuntime().freeMemory(); long size =
* (((long)rows)*columns)*runs;
*
*
* System.out.println("\nNow filling..."); for (int i=0; i<runs; i++) {
* timer1.start(); int value = 0; for (int row=0; row < rows; row++) {
* int[] r = matrix[row]; for (int column=0; column < columns; column++) {
* r[column] = value++; //matrix[row][column] = value++; } }
* timer1.stop(); } timer1.display(); timer1.minus(emptyLoop).display();
* System.out.println(size / timer1.minus(emptyLoop).seconds() +"
* elements / sec");
*
* Runtime.getRuntime().gc(); // invite gc try {
* Thread.currentThread().sleep(1000); } catch (<API key>
* exc) {}; long after = Runtime.getRuntime().freeMemory();
* System.out.println("KB needed="+(before-after) / 1024); if (print) {
* DenseIntMatrix2D m = new DenseIntMatrix2D(rows,columns);
* m.assign(matrix); System.out.println(m); }
*
* System.out.println("\nNow reading..."); timer2.start(); int
* element=0; for (int i=0; i<runs; i++) { for (int row=0; row < rows;
* row++) { int[] r = matrix[row]; for (int column=0; column < columns;
* column++) { element += r[column]; //element += matrix[row][column]; } } }
* timer2.stop().display(); timer2.minus(emptyLoop2).display();
* System.out.println(size / timer2.minus(emptyLoop2).seconds() +"
* elements / sec"); if (print) { DenseIntMatrix2D m = new
* DenseIntMatrix2D(rows,columns); m.assign(matrix);
* System.out.println(m); } System.out.println(element); // !!! so that
* the jitter can't optimize away the whole loop
*
* System.out.println("\nNow removing..."); before =
* Runtime.getRuntime().freeMemory(); for (int i=0; i<runs; i++) {
* timer3.start(); for (int row=0; row < rows; row++) { int[] r =
* matrix[row]; for (int column=0; column < columns; column++) {
* r[column] = 0; //matrix[row][column] = 0; } } timer3.stop(); }
* timer3.display(); timer3.minus(emptyLoop).display();
* System.out.println(size / timer3.minus(emptyLoop).seconds() +"
* elements / sec"); Runtime.getRuntime().gc(); // invite gc try {
* Thread.currentThread().sleep(1000); } catch (<API key>
* exc) {}; after = Runtime.getRuntime().freeMemory();
* System.out.println("KB needed="+(before-after)/1024);
* System.out.println("KB free="+(after/1024));
*
* if (print) { DenseIntMatrix2D m = new DenseIntMatrix2D(rows,columns);
* m.assign(matrix); System.out.println(m); }
*
* System.out.println("bye bye.");
*/
}
/**
* Benchmarks various methods of this class.
*/
public static void main(String args[]) {
int runs = Integer.parseInt(args[0]);
int rows = Integer.parseInt(args[1]);
int columns = Integer.parseInt(args[2]);
// int size = Integer.parseInt(args[3]);
// boolean isSparse = args[4].equals("sparse");
String kind = args[3];
int initialCapacity = Integer.parseInt(args[4]);
double minLoadFactor = new Double(args[5]).doubleValue();
double maxLoadFactor = new Double(args[6]).doubleValue();
boolean print = args[7].equals("print");
String type = args[8];
String command = args[9];
if (type.equals("int")) {
if (kind.equals("primitive"))
<API key>(runs, rows, columns, print);
else if (kind.equals("primitiveOpt"))
<API key>(runs, rows, columns, print);
else
intBenchmark(runs, rows, columns, kind, print, initialCapacity, minLoadFactor, maxLoadFactor);
} else if (type.equals("double")) {
if (kind.equals("primitive"))
<API key>(runs, rows, columns, print);
else if (kind.equals("primitiveOpt"))
<API key>(runs, rows, columns, print);
else if (command.equals("mult"))
doubleBenchmarkMult(runs, rows, columns, kind, print, initialCapacity, minLoadFactor, maxLoadFactor);
else
doubleBenchmark(runs, rows, columns, kind, print, initialCapacity, minLoadFactor, maxLoadFactor);
}
}
}
|
#include "stateseditormodel.h"
#include "stateseditorview.h"
#include <QDebug>
#include <nodelistproperty.h>
#include <modelnode.h>
#include <bindingproperty.h>
#include <variantproperty.h>
#include <rewriterview.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagebox.h>
enum {
debug = false
};
namespace QmlDesigner {
StatesEditorModel::StatesEditorModel(StatesEditorView *view)
: QAbstractListModel(view),
m_statesEditorView(view),
m_updateCounter(0)
{
}
int StatesEditorModel::count() const
{
return rowCount();
}
QModelIndex StatesEditorModel::index(int row, int column, const QModelIndex &parent) const
{
if (m_statesEditorView.isNull())
return QModelIndex();
int internalNodeId = 0;
if (row > 0)
internalNodeId = m_statesEditorView->rootModelNode().nodeListProperty("states").at(row - 1).internalId();
return hasIndex(row, column, parent) ? createIndex(row, column, internalNodeId) : QModelIndex();
}
int StatesEditorModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid() || m_statesEditorView.isNull() || !m_statesEditorView->model())
return 0;
if (!m_statesEditorView->rootModelNode().hasNodeListProperty("states"))
return 1;
return m_statesEditorView->rootModelNode().nodeListProperty("states").count() + 1;
}
void StatesEditorModel::reset()
{
QAbstractListModel::beginResetModel();
QAbstractListModel::endResetModel();
}
QVariant StatesEditorModel::data(const QModelIndex &index, int role) const
{
if (index.parent().isValid() || index.column() != 0 || m_statesEditorView.isNull() || !m_statesEditorView-><API key>(index.internalId()))
return QVariant();
ModelNode stateNode;
if (index.internalId() > 0)
stateNode = m_statesEditorView-><API key>(index.internalId());
switch (role) {
case StateNameRole: {
if (index.row() == 0) {
return QString(tr("base state", "Implicit default state"));
} else {
if (stateNode.hasVariantProperty("name"))
return stateNode.variantProperty("name").value();
else
return QVariant();
}
}
case <API key>: {
static int randomNumber = 0;
randomNumber++;
if (index.row() == 0)
return QString("image://<API key>/baseState-%1").arg(randomNumber);
else
return QString("image://<API key>/%1-%2").arg(index.internalId()).arg(randomNumber);
}
case InternalNodeId: return index.internalId();
case HasWhenCondition: return stateNode.isValid() && stateNode.hasProperty("when");
case WhenConditionString: {
if (stateNode.isValid() && stateNode.hasBindingProperty("when"))
return stateNode.bindingProperty("when").expression();
else
return QString();
}
}
return QVariant();
}
QHash<int, QByteArray> StatesEditorModel::roleNames() const
{
static QHash<int, QByteArray> roleNames{
{StateNameRole, "stateName"},
{<API key>, "stateImageSource"},
{InternalNodeId, "internalNodeId"},
{HasWhenCondition, "hasWhenCondition"},
{WhenConditionString, "whenConditionString"}
};
return roleNames;
}
void StatesEditorModel::insertState(int stateIndex)
{
if (stateIndex >= 0) {
const int updateIndex = stateIndex + 1;
beginInsertRows(QModelIndex(), updateIndex, updateIndex);
endInsertRows();
emit dataChanged(index(updateIndex, 0), index(updateIndex, 0));
emit countChanged();
}
}
void StatesEditorModel::updateState(int beginIndex, int endIndex)
{
if (beginIndex >= 0 && endIndex >= 0)
emit dataChanged(index(beginIndex, 0), index(endIndex, 0));
}
void StatesEditorModel::removeState(int stateIndex)
{
if (stateIndex >= 0) {
const int updateIndex = stateIndex + 1;
beginRemoveRows(QModelIndex(), updateIndex, updateIndex);
endRemoveRows();
emit dataChanged(createIndex(updateIndex, 0), createIndex(updateIndex, 0));
emit countChanged();
}
}
void StatesEditorModel::renameState(int internalNodeId, const QString &newName)
{
if (newName == m_statesEditorView->currentStateName())
return;
if (newName.isEmpty() ||! m_statesEditorView->validStateName(newName)) {
Core::<API key>::warning(tr("Invalid state name"),
newName.isEmpty() ?
tr("The empty string as a name is reserved for the base state.") :
tr("Name already used in another state"));
} else {
m_statesEditorView->renameState(internalNodeId, newName);
}
}
void StatesEditorModel::setWhenCondition(int internalNodeId, const QString &condition)
{
m_statesEditorView->setWhenCondition(internalNodeId, condition);
}
void StatesEditorModel::resetWhenCondition(int internalNodeId)
{
m_statesEditorView->resetWhenCondition(internalNodeId);
}
QStringList StatesEditorModel::autoComplete(const QString &text, int pos, bool explicitComplete)
{
Model *model = m_statesEditorView->model();
if (model && model->rewriterView())
return model->rewriterView()->autoComplete(text, pos, explicitComplete);
return QStringList();
}
} // namespace QmlDesigner
|
YUI.add('recordset-base', function (Y, NAME) {
/**
* Provides a wrapper around a standard javascript object. Can be inserted into a Recordset instance.
*
* @class Record
*/
var Record = Y.Base.create('record', Y.Base, [], {
_setId: function() {
return Y.guid();
},
initializer: function() {
},
destructor: function() {
},
/**
* Retrieve a particular (or all) values from the object
*
* @param field {string} (optional) The key to retrieve the value from. If not supplied, the entire object is returned.
* @method getValue
* @public
*/
getValue: function(field) {
if (field === undefined) {
return this.get("data");
}
else {
return this.get("data")[field];
}
return null;
}
},
{
ATTRS: {
/**
* @description Unique ID of the record instance
* @attribute id
* @type string
*/
id: {
valueFn: "_setId"
},
/**
* @description The object stored within the record instance
* @attribute data
* @type object
*/
data: {
value: null
}
}
});
Y.Record = Record;
/**
The Recordset utility provides a standard way for dealing with
a collection of similar objects.
@module recordset
@main recordset
@submodule recordset-base
**/
var ArrayList = Y.ArrayList,
Lang = Y.Lang,
/**
The Recordset utility provides a standard way for dealing with
a collection of similar objects.
Provides the base Recordset implementation, which can be extended to add
additional functionality, such as custom indexing. sorting, and filtering.
@class Recordset
@extends Base
@uses ArrayList
@param config {Object} Configuration object with initial attribute values
@constructor
**/
Recordset = Y.Base.create('recordset', Y.Base, [], {
/**
* Publish default functions for events. Create the initial hash table.
*
* @method initializer
* @protected
*/
initializer: function() {
// The reason the conditional is needed is because of two scenarios:
// 1. Instantiating new Y.Recordset() will not go into the setter of "records", and so it is necessary to create this._items in the initializer.
// 2. Instantiating new Y.Recordset({records: [{...}]}) will call the setter of "records" and create this._items. In this case, we don't want that to be overwritten by [].
if (!this._items) {
this._items = [];
}
//set up event listener to fire events when recordset is modified in anyway
this.publish({
/**
* <p>At least one record is being added. Additional properties of
* the event are:</p>
* <dl>
* <dt>added</dt>
* <dd>Array of new records to be added</dd>
* <dt>index</dt>
* <dd>The insertion index in the Recordset's internal
* array</dd>
* </dl>
*
* <p>Preventing this event will cause the new records NOT to be
* added to the Recordset's internal collection.</p>
*
* @event add
* @preventable _defAddFn
*/
add: { defaultFn: this._defAddFn },
/**
* <p>At least one record is being removed. Additional properties of
* the event are:</p>
* <dl>
* <dt>removed</dt>
* <dd>Array of records to be removed</dd>
* <dt>range</dt>
* <dd>Number of records to be removed</dd>
* <dt>index</dt>
* <dd>The starting index in the Recordset's internal
* array from which to remove records</dd>
* </dl>
*
* <p>Preventing this event will cause the records NOT to be
* removed from the Recordset's internal collection.</p>
*
* @event remove
* @preventable _defRemoveFn
*/
remove: { defaultFn: this._defRemoveFn },
/**
* The Recordset is being flushed of all records.
*
* @event empty
* @preventable _defEmptyFn
*/
empty: { defaultFn: this._defEmptyFn },
/**
* <p>At least one record is being updated. Additional properties of
* the event are:</p>
* <dl>
* <dt>updated</dt>
* <dd>Array of records with updated values</dd>
* <dt>overwritten</dt>
* <dd>Array of current records that will be replaced</dd>
* <dt>index</dt>
* <dd>The starting index in the Recordset's internal
* array from which to update will apply</dd>
* </dl>
*
* <p>Preventing this event will cause the records NOT to be
* updated in the Recordset's internal collection.</p>
*
* @event update
* @preventable _defUpdateFn
*/
update: { defaultFn: this._defUpdateFn }
});
this._buildHashTable(this.get('key'));
this.after([
'recordsChange',
'add',
'remove',
'update',
'empty'], this._updateHash);
},
/**
* Returns the record with particular ID or index
*
* @method getRecord
* @param i {String, Number} The ID of the record if a string, or the index if a number.
* @return {Record} A Y.Record instance
*/
getRecord: function(i) {
if (Lang.isString(i)) {
return this.get('table')[i];
}
else if (Lang.isNumber(i)) {
return this._items[i];
}
return null;
},
/**
* Returns the record at a particular index
*
* @method getRecordByIndex
* @param i {Number} Index at which the required record resides
* @return {Record} A Y.Record instance
*/
getRecordByIndex: function(i) {
return this._items[i];
},
/**
* Returns a range of records beginning at particular index
*
* @method getRecordsByIndex
* @param index {Number} Index at which the required record resides
* @param range {Number} (Optional) Number of records to retrieve. The default is 1
* @return {Array} An array of Y.Record instances
*/
getRecordsByIndex: function(index, range) {
var i = 0,
returnedRecords = [];
//Range cannot take on negative values
range = (Lang.isNumber(range) && (range > 0)) ? range: 1;
for (; i < range; i++) {
returnedRecords.push(this._items[index + i]);
}
return returnedRecords;
},
/**
* Returns the length of the recordset
*
* @method getLength
* @return {Number} Number of records in the recordset
*/
getLength: function() {
return this.size();
},
/**
Gets an array of values for a data _key_ in the set's records. If no _key_
is supplied, the returned array will contain the full data object for each
record.
@method getValuesByKey
@param {String} [key] Data property to get from all records
@return {Array} An array of values for the given _key_ if supplied.
Otherwise, an array of each record's data hash.
**/
getValuesByKey: function(key) {
var i = 0,
len = this._items.length,
retVals = [];
for (; i < len; i++) {
retVals.push(this._items[i].getValue(key));
}
return retVals;
},
/**
* Adds one or more Records to the RecordSet at the given index. If index is null, then adds the Records to the end of the RecordSet.
*
* @method add
* @param {Record|Object|Array} oData A Y.Record instance, An object literal of data or an array of object literals
* @param [index] {Number} [index] Index at which to add the record(s)
* @return {Recordset} The updated recordset instance
*/
add: function(oData, index) {
var newRecords = [],
idx,
i = 0;
idx = (Lang.isNumber(index) && (index > -1)) ? index: this._items.length;
//Passing in array of object literals for oData
if (Lang.isArray(oData)) {
for (; i < oData.length; i++) {
newRecords[i] = this._changeToRecord(oData[i]);
}
} else if (Lang.isObject(oData)) {
newRecords[0] = this._changeToRecord(oData);
}
this.fire('add', {
added: newRecords,
index: idx
});
return this;
},
/**
Removes one or more Records to the RecordSet at the given index. If index
is null, then removes a single Record from the end of the RecordSet.
@method remove
@param {Number} [index] Index at which to remove the record(s) from
@param {Number} [range] Number of records to remove (including the one
at the index)
@return {Recordset} The updated recordset instance
**/
remove: function(index, range) {
var remRecords = [];
//Default is to only remove the last record - the length is always 1 greater than the last index
index = (index > -1) ? index: (this._items.length - 1);
range = (range > 0) ? range: 1;
remRecords = this._items.slice(index, (index + range));
this.fire('remove', {
removed: remRecords,
range: range,
index: index
});
//this._recordRemoved(remRecords, index);
//return ({data: remRecords, index:index});
return this;
},
/**
* Empties the recordset
*
* @method empty
* @return {Recordset} The updated recordset instance
*/
empty: function() {
this.fire('empty', {});
return this;
},
/**
Updates the recordset with the new records passed in. Overwrites existing
records when updating the index with the new records.
@method update
@param {Record|Object|Array} data A Y.Record instance, An object literal of
data or an array of object literals
@param {Number} [index] The index to start updating from.
@return {Recordset} The updated recordset instance
**/
update: function(data, index) {
var rec,
arr,
i = 0;
// Whatever is passed in, we are changing it to an array so that it can
// be easily iterated in the _defUpdateFn method
arr = (!(Lang.isArray(data))) ? [data] : data;
rec = this._items.slice(index, index + arr.length);
for (; i < arr.length; i++) {
arr[i] = this._changeToRecord(arr[i]);
}
this.fire('update', {
updated: arr,
overwritten: rec,
index: index
});
return this;
},
/**
* Default behavior for the "add" event. Adds Record instances starting from
* the index specified in `e.index`.
*
* @method _defAddFn
* @param {EventFacade} e The add event
* @private
*/
_defAddFn: function(e) {
this._items.splice.apply(this._items, [e.index, 0].concat(e.added));
},
/**
* Default behavior for the "remove" event. Removes Records from the
* internal array starting from `e.index`. By default, it will remove one
* Record. But if `e.range` is set, it will remove that many Records.
*
* @method _defRemoveFn
* @param {EventFacade} e The remove event
* @private
*/
_defRemoveFn: function(e) {
this._items.splice(e.index, e.range || 1);
},
/**
* Default behavior for the "update" event. Sets Record instances for each
* item in `e.updated` at indexes starting from `e.index`.
*
* @method _defUpdateFn
* @param {EventFacade} e The update event
* @private
*/
_defUpdateFn: function(e) {
for (var i = 0; i < e.updated.length; i++) {
this._items[e.index + i] = this._changeToRecord(e.updated[i]);
}
},
/**
* Default behavior for the "empty" event. Clears the internal array of
* Records.
*
* @method _defEmptyFn
* @param {EventFacade} e The empty event
* @private
*/
_defEmptyFn: function(e) {
this._items = [];
},
/**
Updates the internal hash table.
@method _defUpdateHash
@param {EventFacade} e Event triggering the hash table update
@private
**/
_updateHash: function (e) {
var handler = "_hash",
type = e.type.replace(/.*:/,''),
newHash;
// _hashAdd, _hashRemove, _hashEmpty, etc
// Not a switch or else if setup to allow for external expansion.
handler += type.charAt(0).toUpperCase() + type.slice(1);
newHash = this[handler] &&
this[handler](this.get('table'), this.get('key'), e);
if (newHash) {
this.set('table', newHash);
}
},
/**
Regenerates the hash table from the current internal array of Records.
@method _hashRecordsChange
@param {Object} hash The hash map before replacement
@param {String} key The key by which to add items to the hash
@param {Object} e The event or object containing the items to be added.
Items are expected to be stored in an array assigned to
the `added` property.
@return {Object} The updated hash map
@private
**/
_hashRecordsChange: function (hash, key, e) {
return this._buildHashTable(key);
},
/**
Builds a hash table from the current internal array of Records.
@method _buildHashTable
@param {String} key The Record key to hash the items by
@return {Object} A new hash map of Records keyed by each Records' key
@private
**/
_buildHashTable: function (key) {
return this._hashAdd({}, key, { added: this._items });
},
/**
Adds items to the hash table. Items are the values, and the keys are the
values of the item's attribute named in the `key` parameter.
@method _hashAdd
@param {Object} hash The hash map before adding items
@param {String} key The key by which to add the items to the hash
@param {Object} e The event or object containing the items to be added.
Items are expected to be stored in an array assigned to
the `added` property.
@return {Object} The updated hash map
@private
**/
_hashAdd: function(hash, key, e) {
var items = e.added,
i, len;
for (i = 0, len = e.added.length; i < len; ++i) {
hash[items[i].get(key)] = items[i];
}
return hash;
},
/**
Removes items from the hash table.
@method _hashRemove
@param {Object} hash The hash map before removing items
@param {String} key The key by which to remove the items from the hash
@param {Object} e The event or object containing the items to be removed.
Items are expected to be stored in an array assigned to
the `removed` property.
@return {Object} The updated hash map
@private
**/
_hashRemove: function(hash, key, e) {
for (var i = e.removed.length - 1; i >= 0; --i) {
delete hash[e.removed[i].get(key)];
}
return hash;
},
/**
Updates items in the hash table.
@method _hashUpdate
@param {Object} hash The hash map before updating items
@param {String} key The key by which to update the items to the hash
@param {Object} e The event or object containing the items to be updated.
Items are expected to be stored in an array assigned to
the `updated` property. Optionally, items can be
identified for being overwritten by including them in an
array assigned to the `overwritten` property.
@return {Object} The updated hash map
@private
**/
_hashUpdate: function (hash, key, e) {
if (e.overwritten && e.overwritten.length) {
hash = this._hashRemove(hash, key, { removed: e.overwritten });
}
return this._hashAdd(hash, key, { added: e.updated });
},
/**
Clears the hash table.
@method _hashEmpty
@param {Object} hash The hash map before adding items
@param {String} key The key by which to remove the items from the hash
@param {Object} e The event or object containing the items to be removed.
Items are expected to be stored in an array assigned to
the `removed` property.
@return {Object} An empty hash
@private
**/
_hashEmpty: function() {
return {};
},
/**
* Sets up the hashtable with all the records currently in the recordset
*
* @method _initHashTable
* @private
*/
_initHashTable: function() {
return this._hashAdd({}, this.get('key'), { added: this._items || [] });
},
/**
* Helper method - it takes an object bag and converts it to a Y.Record
*
* @method _changeToRecord
* @param obj {Object|Record} Any objet literal or Y.Record instance
* @return {Record} A Record instance.
* @private
*/
_changeToRecord: function(obj) {
return (obj instanceof Y.Record) ? obj : new Y.Record({ data: obj });
},
/**
Ensures the value being set is an array of Record instances. If array items
are raw object data, they are turned into Records.
@method _setRecords
@param {Record[]|Object[]} items The Records or data Objects to store as
Records.
@return {Record[]}
**/
_setRecords: function (items) {
if (!Y.Lang.isArray(items)) {
return Y.Attribute.INVALID_VALUE;
}
var records = [],
i, len;
// FIXME: This should use the flyweight pattern if possible
for (i = 0, len = items.length; i < len; ++i) {
records[i] = this._changeToRecord(items[i]);
}
return (this._items = records);
}
}, {
ATTRS: {
/**
* An array of Records that the Recordset is storing. Passing an array
* of raw record data is also accepted. The data for each item will be
* wrapped in a Record instance.
*
* @attribute records
* @type {Record[]}
*/
records: {
// TODO: necessary? valueFn?
lazyAdd: false,
getter: function() {
// give them a copy, not the internal object
return Y.Array(this._items);
},
setter: "_setRecords"
},
/**
A hash table where the ID of the record is the key, and the record
instance is the value.
@attribute table
@type object
**/
table: {
valueFn: '_initHashTable'
},
/**
The ID to use as the key in the hash table.
@attribute key
@type string
**/
key: {
value: 'id',
readOnly: true
}
}
});
Y.augment(Recordset, ArrayList);
Y.Recordset = Recordset;
}, '3.9.0pr1', {"requires": ["base", "arraylist"]});
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>RebeccaAIML: C:/rebecca/include/rebecca/CallBacks.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.5 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li id="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul></div>
<div class="nav">
<a class="el" href="<API key>.html">include</a> » <a class="el" href="<API key>.html">rebecca</a></div>
<h1>CallBacks.h</h1><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="preprocessor">#ifndef REBECCA_CALLBACKS_H</span>
<a name="l00002"></a>00002 <span class="preprocessor"></span><span class="preprocessor">#define REBECCA_CALLBACKS_H</span>
<a name="l00003"></a>00003 <span class="preprocessor"></span>
<a name="l00024"></a>00024
<a name="l00025"></a>00025 <span class="comment">//To get the REBECA_EXPORT macro</span>
<a name="l00026"></a>00026 <span class="preprocessor">#include <rebecca/exports.h></span>
<a name="l00027"></a>00027
<a name="l00028"></a>00028 <span class="comment">//See AimlFacade for the explanation of this namespace</span>
<a name="l00029"></a>00029 <span class="keyword">namespace </span>rebecca
<a name="l00030"></a>00030 {
<a name="l00031"></a>00031 <span class="comment">//See AimlFacade for the explanation of this namespace</span>
<a name="l00032"></a>00032 <span class="keyword">namespace </span>impl
<a name="l00033"></a>00033 {
<a name="l00034"></a>00034
<a name="l00060"></a><a class="code" href="<API key>.html">00060</a> <span class="keyword">class </span>REBECCA_EXPORT CallBacks
<a name="l00061"></a>00061 {
<a name="l00062"></a>00062 <span class="keyword">public</span>:
<a name="l00063"></a>00063
<a name="l00064"></a>00064 <span class="comment">/*</span>
<a name="l00065"></a>00065 <span class="comment"> * Informative callbacks</span>
<a name="l00066"></a>00066 <span class="comment"> *</span>
<a name="l00067"></a>00067 <span class="comment"> */</span>
<a name="l00068"></a>00068
<a name="l00087"></a><a class="code" href="<API key>.html#<API key>">00087</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> storeGossip(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> gossip) { }
<a name="l00088"></a>00088
<a name="l00103"></a><a class="code" href="<API key>.html#<API key>">00103</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> categoryLoaded() { }
<a name="l00104"></a>00104
<a name="l00122"></a><a class="code" href="<API key>.html#<API key>">00122</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> filePreLoad(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> fileName) { }
<a name="l00123"></a>00123
<a name="l00141"></a><a class="code" href="<API key>.html#<API key>">00141</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> filePostLoad(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> fileName) { }
<a name="l00142"></a>00142
<a name="l00163"></a><a class="code" href="<API key>.html#<API key>">00163</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> symbolicReduction(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> symbol) { }
<a name="l00164"></a>00164
<a name="l00180"></a><a class="code" href="<API key>.html#<API key>">00180</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>() { }
<a name="l00181"></a>00181
<a name="l00182"></a>00182 <span class="comment">/*</span>
<a name="l00183"></a>00183 <span class="comment"> * XML Parse Errors</span>
<a name="l00184"></a>00184 <span class="comment"> *</span>
<a name="l00185"></a>00185 <span class="comment"> */</span>
<a name="l00186"></a>00186
<a name="l00198"></a><a class="code" href="<API key>.html#<API key>">00198</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> XMLParseError(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00199"></a>00199
<a name="l00211"></a><a class="code" href="<API key>.html#<API key>">00211</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> XMLParseWarning(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00212"></a>00212
<a name="l00224"></a><a class="code" href="<API key>.html#<API key>">00224</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> XMLParseFatalError(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00225"></a>00225
<a name="l00226"></a>00226 <span class="comment">/*</span>
<a name="l00227"></a>00227 <span class="comment"> * AIML tag Errors</span>
<a name="l00228"></a>00228 <span class="comment"> *</span>
<a name="l00229"></a>00229 <span class="comment"> */</span>
<a name="l00230"></a>00230
<a name="l00244"></a><a class="code" href="<API key>.html#<API key>">00244</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>() { }
<a name="l00245"></a>00245
<a name="l00259"></a><a class="code" href="<API key>.html#<API key>">00259</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>() { }
<a name="l00260"></a>00260
<a name="l00274"></a><a class="code" href="<API key>.html#<API key>">00274</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> starTagSizeExceeded() { }
<a name="l00275"></a>00275
<a name="l00293"></a><a class="code" href="<API key>.html#<API key>">00293</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00294"></a>00294
<a name="l00308"></a><a class="code" href="<API key>.html#<API key>">00308</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>() { }
<a name="l00309"></a>00309
<a name="l00327"></a><a class="code" href="<API key>.html#<API key>">00327</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00328"></a>00328
<a name="l00342"></a><a class="code" href="<API key>.html#<API key>">00342</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> thatTagSizeExceeded() { }
<a name="l00343"></a>00343
<a name="l00361"></a><a class="code" href="<API key>.html#<API key>">00361</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00362"></a>00362
<a name="l00380"></a><a class="code" href="<API key>.html#<API key>">00380</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00381"></a>00381
<a name="l00399"></a><a class="code" href="<API key>.html#<API key>">00399</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <API key>(<span class="keyword">const</span> <span class="keywordtype">char</span> * <span class="keyword">const</span> message) { }
<a name="l00400"></a>00400
<a name="l00406"></a><a class="code" href="<API key>.html#<API key>">00406</a> <span class="keyword">virtual</span> ~CallBacks() { }
<a name="l00407"></a>00407 };
<a name="l00408"></a>00408
<a name="l00409"></a>00409
<a name="l00410"></a>00410 } <span class="comment">//end namespace impl</span>
<a name="l00411"></a>00411
<a name="l00412"></a>00412 <span class="comment">//expose CallBacks to Rebecca namespace </span>
<a name="l00413"></a>00413 <span class="keyword">using</span> <a class="code" href="<API key>.html">rebecca::impl::CallBacks</a>;
<a name="l00414"></a>00414
<a name="l00415"></a>00415 } <span class="comment">//end namespace rebecca</span>
<a name="l00416"></a>00416
<a name="l00417"></a>00417 <span class="preprocessor">#endif</span>
<a name="l00418"></a>00418 <span class="preprocessor"></span>
</pre></div><hr size="1"><address style="align: right;"><small>Generated on Mon Apr 10 00:39:51 2006 for RebeccaAIML by
<a href="http:
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.5 </small></address>
</body>
</html>
|
/**
* @class
* @extends ve.dm.Selection
* @constructor
*/
ve.dm.NullSelection = function VeDmNullSelection( doc ) {
// Parent constructor
ve.dm.NullSelection.super.call( this, doc );
};
/* Inheritance */
OO.inheritClass( ve.dm.NullSelection, ve.dm.Selection );
/* Static Properties */
ve.dm.NullSelection.static.name = 'null';
/* Static Methods */
/**
* @inheritdoc
*/
ve.dm.NullSelection.static.newFromHash = function ( doc ) {
return new ve.dm.NullSelection( doc );
};
/* Methods */
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.toJSON = function () {
return {
type: this.constructor.static.name
};
};
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.getDescription = function () {
return 'Null';
};
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.clone = function () {
return new this.constructor( this.getDocument() );
};
ve.dm.NullSelection.prototype.collapseToStart = ve.dm.NullSelection.prototype.clone;
ve.dm.NullSelection.prototype.collapseToEnd = ve.dm.NullSelection.prototype.clone;
ve.dm.NullSelection.prototype.collapseToFrom = ve.dm.NullSelection.prototype.clone;
ve.dm.NullSelection.prototype.collapseToTo = ve.dm.NullSelection.prototype.clone;
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.isCollapsed = function () {
return true;
};
ve.dm.NullSelection.prototype.<API key> = ve.dm.NullSelection.prototype.clone;
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.getRanges = function () {
return [];
};
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.getCoveringRange = function () {
return null;
};
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.equals = function ( other ) {
return other instanceof ve.dm.NullSelection &&
this.getDocument() === other.getDocument();
};
/**
* @inheritdoc
*/
ve.dm.NullSelection.prototype.isNull = function () {
return true;
};
/* Registration */
ve.dm.selectionFactory.register( ve.dm.NullSelection );
|
<?php
namespace HeVinci\CompetencyBundle\Tests\Repository;
use HeVinci\CompetencyBundle\Util\RepositoryTestCase;
class ScaleRepositoryTest extends RepositoryTestCase
{
private $repo;
protected function setUp(): void
{
parent::setUp();
$this->repo = $this->om->getRepository('<API key>:Scale');
}
public function testFindWithStatus()
{
$s1 = $this->persistScale('s1');
$s2 = $this->persistScale('s2');
$s3 = $this->persistScale('s3');
$level = $this->persistLevel('l1', $s1);
$c1 = $this->persistCompetency('c1', null, $s1);
$c2 = $this->persistCompetency('c2', null, $s1);
$this->persistCompetency('c3', null, $s2);
$a1 = $this->persistAbility('a1');
$a2 = $this->persistAbility('a2');
$a3 = $this->persistAbility('a3');
$this->persistLink($c1, $a1, $level);
$this->persistLink($c1, $a2, $level);
$this->persistLink($c2, $a3, $level);
$this->om->flush();
$expected = [
['id' => $s1->getId(), 'name' => 's1', 'competencies' => 2, 'abilities' => 3],
['id' => $s2->getId(), 'name' => 's2', 'competencies' => 1, 'abilities' => 0],
['id' => $s3->getId(), 'name' => 's3', 'competencies' => 0, 'abilities' => 0],
];
$this->assertEquals($expected, $this->repo->findWithStatus());
}
public function <API key>()
{
$scale = $this->persistScale('s1');
$c1 = $this->persistCompetency('c1', null, $scale);
$this->persistCompetency('c2', $c1);
$this->persistCompetency('c3', null, $scale);
$this->persistCompetency('c4', null, $scale);
$this->om->flush();
$this->assertEquals(3, $this->repo->findCompetencyCount($scale));
}
public function <API key>()
{
$scale = $this->persistScale('s1');
$level = $this->persistLevel('l1', $scale);
$c1 = $this->persistCompetency('c1', null, $scale);
$c2 = $this->persistCompetency('c2', $c1);
$a1 = $this->persistAbility('a1');
$a2 = $this->persistAbility('a2');
$a3 = $this->persistAbility('a3');
$this->persistLink($c1, $a1, $level);
$this->persistLink($c1, $a2, $level);
$this->persistLink($c2, $a3, $level);
$this->om->flush();
$this->assertEquals(3, $this->repo->findAbilityCount($scale));
}
}
|
# -*- coding: utf-8 -*-
# This file is part of FIFE.
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# This library is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# You should have received a copy of the GNU Lesser General Public
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from fife.extensions import pychan
import fife.extensions.pychan.widgets as widgets
class InputDialog(object):
"""
Input supplies a text box for entering data. The result is passed to onEntry.
onEntry - the function to call when a input is complete. Accepts one argument: a string of text.
"""
def __init__(self, prompt, onEntry, onCancel):
self._callback = onEntry
self._cancelCallback = onCancel
self._widget = pychan.loadXML('gui/input.xml')
self._widget.mapEvents({
'okButton' : self._complete,
'cancelButton' : self._cancel
})
self._widget.<API key>({
'prompt' : prompt
})
self._widget.show()
def _complete(self):
self._callback(self._widget.collectData('inputBox'))
self._widget.hide()
def _cancel(self):
self._cancelCallback()
self._widget.hide()
|
import pygame
import os, sys
from pygame.locals import *
import socketserver
import socket
def min(a, b):
return a if a < b else b
''' Load an animation strip.'''
def load_strip(filename, nframes, width=None, height=None, colorkey=None):
full_image, full_rect = load_image(filename, width=width, height=height)
sub_images = []
for i in range(nframes):
sub_w, sub_h = full_image.get_size()[0]/nframes, full_image.get_size()[1]
sub_image = pygame.Surface((sub_w, sub_h))
sub_image.blit(full_image, (-i * sub_w, 0, sub_w, sub_h))
if colorkey:
sub_image.set_colorkey(colorkey)
sub_rect = sub_image.get_rect()
sub_images.append((sub_image, sub_rect))
return sub_images
def load_image(filename, width=None, height=None):
fullpath = os.path.join('img', filename)
try:
image = pygame.image.load(fullpath)
except pygame.error:
print('Cannot load image:', fullpath)
raise SystemError
image = image.convert_alpha()
# Resize image if specified
if width and height:
image = pygame.transform.scale(image, (width, height))
if width:
ratio = width/image.get_size()[0]
image = pygame.transform.scale(image, (int(width), int(image.get_size()[1] * ratio)))
elif height:
ratio = height/image.get_size()[1]
image = pygame.transform.scale(image, (int(image.get_size()[0] * ratio), int(height)))
return image, image.get_rect()
def load_music(filename):
fullpath = os.path.join('snd', filename)
return pygame.mixer.Sound(fullpath)
|
#ifndef <API key>
#define <API key>
#include <common/types.h>
#include <gdt.h>
namespace myos
{
struct CPUState
{
common::uint32_t eax;
common::uint32_t ebx;
common::uint32_t ecx;
common::uint32_t edx;
common::uint32_t esi;
common::uint32_t edi;
common::uint32_t ebp;
/*
common::uint32_t gs;
common::uint32_t fs;
common::uint32_t es;
common::uint32_t ds;
*/
common::uint32_t error;
common::uint32_t eip;
common::uint32_t cs;
common::uint32_t eflags;
common::uint32_t esp;
common::uint32_t ss;
} __attribute__((packed));
class Task
{
friend class TaskManager;
private:
common::uint8_t stack[4096]; // 4 KiB
CPUState* cpustate;
public:
Task(<API key> *gdt, void entrypoint());
~Task();
};
class TaskManager
{
private:
Task* tasks[256];
int numTasks;
int currentTask;
public:
TaskManager();
~TaskManager();
bool AddTask(Task* task);
CPUState* Schedule(CPUState* cpustate);
};
}
#endif
|
package info.papdt.blacklight.ui.common;
import android.content.Intent;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.<API key>;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.<API key>;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import info.papdt.blacklight.R;
import info.papdt.blacklight.cache.file.FileCacheManager;
import info.papdt.blacklight.support.AsyncTask;
import info.papdt.blacklight.support.PermissionUtility;
import info.papdt.blacklight.support.Utility;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import static info.papdt.blacklight.BuildConfig.DEBUG;
public abstract class AbsImageActivity<C> extends AbsActivity /*implements OnPhotoTapListener*/
{
private static final String TAG = AbsImageActivity.class.getSimpleName();
private ImageAdapter mAdapter;
private ViewPager mPager;
private C mApiCache;
private TextView mPage;
protected boolean[] mLoaded;
protected abstract C buildApiCache();
protected abstract String saveLargePic(int current);
protected abstract Object[] doDownload(Object[] params);
protected abstract int getCount();
protected C getApiCache() {
return mApiCache;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
mLayout = R.layout.image_activity;
super.onCreate(savedInstanceState);
// ActionBar
mToolbar.bringToFront();
mToolbar.<API key>(getResources().getDrawable(R.drawable.action_gradient));
getSupportActionBar().setTitle("");
findViewById(R.id.image_container).<API key>(R.color.black);
mApiCache = buildApiCache();
int def = getIntent().getIntExtra("defaultId", 0);
// Initialize the adapter
mAdapter = new ImageAdapter();
mLoaded = new boolean[mAdapter.getCount()];
// Page indicator
mPage = (TextView) findViewById(R.id.image_page);
mPage.setText((def + 1) + " / " + mAdapter.getCount());
mPager = (ViewPager) findViewById(R.id.image_pager);
mPager.<API key>(new <API key>() {
@Override
public void onPageSelected(int page) {
mPage.setText((page + 1) + " / " + mAdapter.getCount());
}
});
mPager.setAdapter(mAdapter);
mPager.<API key>(1);
mPager.setCurrentItem(def);
ViewCompat.setTransitionName(mPager, "model");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image, menu);
return true;
}
@Override
public boolean <API key>(final MenuItem item) {
final int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
} else if (id == R.id.save || id == R.id.share) {
final int current = mPager.getCurrentItem();
if (!mLoaded[current]) {
Toast.makeText(this, R.string.not_loaded, Toast.LENGTH_SHORT).show();
} else {
PermissionUtility.storage(this, new Runnable() {
@Override
public void run() {
String path = saveLargePic(current);
if (id == R.id.save) {
if (path == null) {
Toast.makeText(AbsImageActivity.this, R.string.save_failed, Toast.LENGTH_SHORT).show();
} else {
String msg = String.format(getResources().getString(R.string.saved_to), path);
Toast.makeText(AbsImageActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
if (id == R.id.share) {
if (path != null) {
File f = new File(path);
Uri u = Uri.fromFile(f);
ShareActionProvider share = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_STREAM,u);
|
// <API key>.h
// NIMKit
#ifndef <API key>
#define <API key>
#import "<API key>.h"
@class NIMMessage;
@class NIMMessageModel;
@interface <API key> : NSObject
@property (nonatomic,copy) NSArray *indexpaths;
@property (nonatomic,copy) NSArray *messageModels;
@end
@protocol <API key> <NSObject>
- (NSArray *)items;
- (<API key> *)addMessageModels:(NSArray *)models;
- (<API key> *)insertMessageModels:(NSArray *)models;
- (<API key> *)deleteMessageModel:(NIMMessageModel *)model;
- (<API key> *)updateMessageModel:(NIMMessageModel *)model;
- (NIMMessageModel *)findModel:(NIMMessage *)message;
- (NSInteger)indexAtModelArray:(NIMMessageModel *)model;
- (NSArray *)deleteModels:(NSRange)range;
- (void)resetMessages:(void(^)(NSError *error))handler;
- (void)<API key>:(void(^)(NSInteger index, NSArray *messages , NSError *error))handler;
- (void)<API key>:(NSArray *)messages;
- (NSDictionary *)checkReceipt;
- (void)sendMessageReceipt:(NSArray *)messages;
- (void)cleanCache;
@end
@protocol NIMSessionLayout <NSObject>
- (void)update:(NSIndexPath *)indexPath;
- (void)insert:(NSArray *)indexPaths animated:(BOOL)animated;
- (void)remove:(NSArray *)indexPaths;
- (BOOL)<API key>;
- (void)layoutConfig:(NIMMessageModel *)model;
- (void)reloadTable;
- (void)resetLayout;
- (void)changeLayout:(CGFloat)inputViewHeight;
- (void)layoutAfterRefresh;
@end
@interface <API key>(Interactor)
- (void)setInteractor:(id<<API key>>) interactor;
- (void)setTableDelegate:(id<UITableViewDelegate, <API key>>) tableDelegate;
@end
#endif /* <API key> */
|
import React, {Component} from 'react'
import { Link } from 'react-router'
import EventListener from '<API key>'
import styles from './Blip.css'
class Blip extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.nameInput.focus()
}
render() {
const { params, deleteBlip, editBlip, blips } = this.props
var index = 0
for(var i = 0; i < blips.length; i++) {
if(blips[i].blipID === params.blipID) {
index = i
}
}
return(
<div className={styles.main}>
<div className={styles.header}>
<div className={styles.id} >BLIP ID: { params.blipID }</div>
<Link to={'/design'}><button className={styles.escbutton}>esc</button></Link>
<Link to={'/design'}><button className={styles.delbutton} onClick={() => this.handleDelete(index)} >del</button></Link>
</div>
<textarea className={styles.text} ref={(input) => { this.nameInput = input }} value={blips[index].text} onChange={(e) => editBlip(params.blipID, e.target.value)} />
</div>
)
}
handleDelete(index) {
// TODO:
// setup user confirmation component to delete blip
this.props.deleteBlip(index)
}
}
export default Blip
|
/* Project name: nstd - non-standard general library */
/* File Name: <API key>.cpp */
/* Description: solving equations for monotonic functions */
/* Email: vlasov at academ.org */
#pragma once
namespace nstd {
namespace equation {
template<class F>
inline bool
Monotonic :: solve (const Real y, Real& x, F f, const Interval interval, const Real precision)
{
typedef F Function;
return solve<Function, Real> (y, x, f, interval, precision);
}
template<class F>
inline bool
Monotonic :: solve (const Real y, Real& x, F f, const Real precision)
{
const Interval interval;
typedef F Function;
return solve<Function, Real> (y, x, f, interval, precision);
}
template<class F>
inline bool
Monotonic :: solve (const Real y, Integer& x, F f, const Interval interval)
{
typedef F Function;
return solve<Function, Integer> (y, x, f, interval, 1);
}
template<class F>
inline bool
Monotonic :: solve (const Real y, Integer& x, F f)
{
const Interval interval;
typedef F Function;
return solve<Function, Integer> (y, x, f, interval, 1);
}
template<class F, class N>
bool
Monotonic :: solve (const Real y, N& x, F f, const Interval interval, const Real precision)
{
typedef N Number;
Number x_down = 0;
Number x_up = 1;
for (int i = 0; i < MAX_DIGIT; ++ i) {
const Real y_up = f (x_up);
if (y < y_up) {
#ifdef <API key>
std :: cout << "iteration break" << i << ": " << std :: endl;
std :: cout << "x_down = " << x_down << ", ";
std :: cout << "x_up = " << x_up << ", ";
std :: cout << "y_up = " << y_up << std :: endl;
std :: cout << std :: endl;
#endif
break;
}
x_down = x_up;
if (interval.contains (x_up * 2)) {
x_up *= 2;
} else {
x_up = interval.getHigh().getValue();
x = x_up;
return true;
}
#ifdef <API key>
std :: cout << "iteration " << i << ": " << std :: endl;
std :: cout << "x_down = " << x_down << ", ";
std :: cout << "x_up = " << x_up << ", ";
std :: cout << "y_up = " << y_up << std :: endl;
std :: cout << std :: endl;
#endif
}
#ifdef <API key>
std :: cout << std :: endl;
std :: cout << "finally" << std :: endl;
std :: cout << "
std :: cout << "x_down = " << x_down << std :: endl;
std :: cout << "x_up = " << x_up << std :: endl;
std :: cout << "
#endif
Real y_up = f (x_up);
Real y_down = f (x_down);
int i = 0;
while (fabs (x_up - x_down) > precision) {
const Number x_mid = (x_up + x_down) / 2;
const Real y_mid = f (x_mid);
if (y < y_mid) {
y_up = y_mid;
x_up = x_mid;
} else {
y_down = y_mid;
x_down = x_mid;
}
#ifdef <API key>
std :: cout << "iteration " << i ++ << ": " << std :: endl;
std :: cout << "x_up = " << x_up << ", ";
std :: cout << "y_up = " << y_up << std :: endl;
std :: cout << "x_down = " << x_down << ", ";
std :: cout << "y_down = " << y_up << std :: endl;
std :: cout << "x_mid = " << x_mid << ", ";
std :: cout << "y_mid = " << y_mid << std :: endl;
std :: cout << std :: endl;
#endif
}
#ifdef <API key>
std :: cout << std :: endl;
std :: cout << "finally" << std :: endl;
std :: cout << "
std :: cout << "x_down = " << x_down << ", ";
std :: cout << "y_down = " << y_down << std :: endl;
std :: cout << "
#endif
x = x_down;
return true;
}
}
}
|
#!/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
import json
import time
EXAMPLES = '''
# Create new Block Storage
- <API key>:
state: present
command: create
api_token: <TOKEN>
region: nyc1
block_size: 10
volume_name: nyc1-block-storage
# Delete Block Storage
- <API key>:
state: absent
command: create
api_token: <TOKEN>
region: nyc1
volume_name: nyc1-block-storage
# Attach Block Storage to a Droplet
- <API key>:
state: present
command: attach
api_token: <TOKEN>
volume_name: nyc1-block-storage
region: nyc1
droplet_id: <ID>
# Detach Block Storage from a Droplet
- <API key>:
state: absent
command: attach
api_token: <TOKEN>
volume_name: nyc1-block-storage
region: nyc1
droplet_id: <ID>
'''
RETURN = '''
id:
description: Unique identifier of a Block Storage volume returned during creation.
returned: changed
type: string
sample: "<API key>"
'''
class <API key>(Exception):
pass
class Response(object):
def __init__(self, resp, info):
self.body = None
if resp:
self.body = resp.read()
self.info = info
@property
def json(self):
if self.body:
return json.loads(self.body)
elif "body" in self.info:
return json.loads(self.info["body"])
else:
return None
@property
def status_code(self):
return self.info["status"]
class Rest(object):
def __init__(self, module, headers):
self.module = module
self.headers = headers
self.baseurl = 'https://api.digitalocean.com/v2'
def _url_builder(self, path):
if path[0] == '/':
path = path[1:]
return '%s/%s' % (self.baseurl, path)
def send(self, method, path, data=None, headers=None):
url = self._url_builder(path)
data = self.module.jsonify(data)
resp, info = fetch_url(self.module, url, data=data, headers=self.headers, method=method)
return Response(resp, info)
def get(self, path, data=None, headers=None):
return self.send('GET', path, data, headers)
def put(self, path, data=None, headers=None):
return self.send('PUT', path, data, headers)
def post(self, path, data=None, headers=None):
return self.send('POST', path, data, headers)
def delete(self, path, data=None, headers=None):
return self.send('DELETE', path, data, headers)
class DOBlockStorage(object):
def __init__(self, module):
api_token = module.params['api_token'] or \
os.environ['DO_API_TOKEN'] or os.environ['DO_API_KEY']
self.module = module
self.rest = Rest(module, {'Authorization': 'Bearer {}'.format(api_token),
'Content-type': 'application/json'})
def get_key_or_fail(self, k):
v = self.module.params[k]
if v is None:
self.module.fail_json(msg='Unable to load %s' % k)
return v
def <API key>(self, action_id):
url = 'actions/{}'.format(action_id)
end_time = time.time() + self.module.params['timeout']
while time.time() < end_time:
time.sleep(2)
response = self.rest.get(url)
status = response.status_code
json = response.json
if status == 200:
if json['action']['status'] == 'completed':
return True
elif json['action']['status'] == 'errored':
raise <API key>(json['message'])
raise <API key>('Unable to reach api.digitalocean.com')
def <API key>(self, volume_name, region):
url = 'volumes?name={}®ion={}'.format(volume_name, region)
response = self.rest.get(url)
status = response.status_code
json = response.json
if status == 200:
volumes = json['volumes']
if len(volumes)>0:
droplet_ids = volumes[0]['droplet_ids']
if len(droplet_ids)>0:
return droplet_ids[0]
return None
else:
raise <API key>(json['message'])
def <API key>(self, method, volume_name, region, droplet_id):
data = {
'type' : method,
'volume_name' : volume_name,
'region' : region,
'droplet_id' : droplet_id
}
response = self.rest.post('volumes/actions', data=data)
status = response.status_code
json = response.json
if status == 202:
return self.<API key>(json['action']['id'])
elif status == 200:
return True
elif status == 422:
return False
else:
raise <API key>(json['message'])
def <API key>(self):
block_size = self.get_key_or_fail('block_size')
volume_name = self.get_key_or_fail('volume_name')
region = self.get_key_or_fail('region')
description = self.module.params['description']
data = {
'size_gigabytes' : block_size,
'name' : volume_name,
'description' : description,
'region' : region
}
response = self.rest.post("volumes", data=data)
status = response.status_code
json = response.json
if status == 201:
self.module.exit_json(changed=True, id=json['volume']['id'])
elif status == 409 and json['id'] == 'already_exists':
self.module.exit_json(changed=False)
else:
raise <API key>(json['message'])
def <API key>(self):
volume_name = self.get_key_or_fail('volume_name')
region = self.get_key_or_fail('region')
url = 'volumes?name={}®ion={}'.format(volume_name, region)
attached_droplet_id = self.<API key>(volume_name, region)
if attached_droplet_id != None:
self.<API key>('detach', volume_name, region, attached_droplet_id)
response = self.rest.delete(url)
status = response.status_code
json = response.json
if status == 204:
self.module.exit_json(changed=True)
elif status == 404:
self.module.exit_json(changed=False)
else:
raise <API key>(json['message'])
def <API key>(self):
volume_name = self.get_key_or_fail('volume_name')
region = self.get_key_or_fail('region')
droplet_id = self.get_key_or_fail('droplet_id')
attached_droplet_id = self.<API key>(volume_name, region)
if attached_droplet_id != None:
if attached_droplet_id==droplet_id:
self.module.exit_json(changed=False)
else:
self.<API key>('detach', volume_name, region, attached_droplet_id)
changed_status = self.<API key>('attach', volume_name, region, droplet_id)
self.module.exit_json(changed=changed_status)
def <API key>(self):
volume_name = self.get_key_or_fail('volume_name')
region = self.get_key_or_fail('region')
droplet_id = self.get_key_or_fail('droplet_id')
changed_status = self.<API key>('detach', volume_name, region, droplet_id)
self.module.exit_json(changed=changed_status)
def handle_request(module):
block_storage = DOBlockStorage(module)
command = module.params['command']
state = module.params['state']
if command == 'create':
if state == 'present':
block_storage.<API key>()
elif state == 'absent':
block_storage.<API key>()
elif command == 'attach':
if state =='present':
block_storage.<API key>()
elif state == 'absent':
block_storage.<API key>()
def main():
module = AnsibleModule(
argument_spec=dict(
state = dict(choices=['present', 'absent'], required=True),
command = dict(choices=['create', 'attach'], required=True),
api_token = dict(aliases=['API_TOKEN'], no_log=True),
block_size = dict(type='int'),
volume_name = dict(type='str', required=True),
description = dict(type='str'),
region = dict(type='str', required=True),
droplet_id = dict(type='int'),
timeout = dict(type='int', default=10),
),
)
try:
handle_request(module)
except <API key>:
e = get_exception()
module.fail_json(msg=e.message)
except KeyError:
e = get_exception()
module.fail_json(msg='Unable to load %s' % e.message)
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__':
main()
|
#include <websites.h>
WebsiteInfo youtube = {
"youtube",
"^(?i)(https?://)?(\\w+\\.)?youtube\\.com/watch\\?(.*&)?v=(?-i)(?<video_id>[\\w\\d-]{11})(?i)([^\\w\\d-].*)?$",
"<iframe width=\"425\" height=\"240\" src=\"http:
NULL
};
|
#ifndef _RMAFILES_H_
#define _RMAFILES_H_
/*
* Forward declarations of some interfaces defined here-in.
*/
typedef _INTERFACE IRMAFileObject IRMAFileObject;
typedef _INTERFACE IRMAFileResponse IRMAFileResponse;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE IRMAFileStat IRMAFileStat;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE IRMAFileExists IRMAFileExists;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE IRMAFileMimeMapper IRMAFileMimeMapper;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE IRMABroadcastMapper IRMABroadcastMapper;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE IRMABuffer IRMABuffer;
typedef _INTERFACE IRMAPacket IRMAPacket;
typedef _INTERFACE IRMAValues IRMAValues;
typedef _INTERFACE IRMAMetaCreation IRMAMetaCreation;
typedef _INTERFACE IRMAAuthenticator IRMAAuthenticator;
typedef _INTERFACE IRMARequest IRMARequest;
typedef _INTERFACE IRMAFileRename IRMAFileRename;
typedef _INTERFACE IRMADirHandler IRMADirHandler;
typedef _INTERFACE <API key> <API key>;
typedef _INTERFACE IRMAFileRemove IRMAFileRemove;
/****************************************************************************
* Defines:
* PN_FILE_XXXX
* Purpose:
* Flags for opening file objects
*/
#define PN_FILE_READ 1
#define PN_FILE_WRITE 2
#define PN_FILE_BINARY 4
#define PN_FILE_NOTRUNC 8
/****************************************************************************
* Defines:
* RMA_FILEADVISE_XXXX
* Purpose:
* Flags for file object Advise method
*/
#define <API key> 1
#if defined(_UNIX) || defined(_WINDOWS)
#include <sys/stat.h>
/*
* This is a subset of standard stat()/fstat() values that both Unix and
* Windows support (or at least define).
*
* These flags are returned from <API key>::StatDone() in the
* ulMode argument.
*/
#define PN_S_IFMT S_IFMT
#define PN_S_IFDIR S_IFDIR
#define PN_S_IFCHR S_IFCHR
#define PN_S_IFIFO S_IFIFO
#define PN_S_IFREG S_IFREG
#else
/* Macintosh */
#define PN_S_IFMT 0170000
#define PN_S_IFDIR 0040000
#define PN_S_IFCHR 0020000
#define PN_S_IFIFO 0010000
#define PN_S_IFREG 0100000
#endif
/****************************************************************************
*
* Interface:
*
* IRMAFileObject
*
* Purpose:
*
* Object that exports file control API
*
* IID_IRMAFileObject:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMAFileObject, 0x00000200, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileObject
DECLARE_INTERFACE_(IRMAFileObject, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileObject methods
*/
/************************************************************************
* Method:
* IRMAFileObject::Init
* Purpose:
* Associates a file object with the file response object it should
* notify of operation completness. This method should also check
* for validity of the object (for example by opening it if it is
* a local file).
*/
STDMETHOD(Init) (THIS_
ULONG32 ulFlags,
IRMAFileResponse* pFileResponse) PURE;
/************************************************************************
* Method:
* IRMAFileObject::GetFilename
* Purpose:
* Returns the filename (without any path information) associated
* with a file object.
*
* Note: The returned pointer's lifetime expires as soon as the
* caller returns from a function which was called from the RMA
* core (i.e. when you return control to the RMA core)
*
*/
STDMETHOD(GetFilename) (THIS_
REF(const char*) /*OUT*/ pFilename) PURE;
/************************************************************************
* Method:
* IRMAFileObject::Close
* Purpose:
* Closes the file resource and releases all resources associated
* with the object.
*/
STDMETHOD(Close) (THIS) PURE;
/************************************************************************
* Method:
* IRMAFileObject::Read
* Purpose:
* Reads a buffer of data of the specified length from the file
* and asynchronously returns it to the caller via the
* IRMAFileResponse interface passed in to Init.
*/
STDMETHOD(Read) (THIS_
ULONG32 ulCount) PURE;
/************************************************************************
* Method:
* IRMAFileObject::Write
* Purpose:
* Writes a buffer of data to the file and asynchronously notifies
* the caller via the IRMAFileResponse interface passed in to Init,
* of the completeness of the operation.
*/
STDMETHOD(Write) (THIS_
IRMABuffer* pBuffer) PURE;
/************************************************************************
* Method:
* IRMAFileObject::Seek
* Purpose:
* Seeks to an offset in the file and asynchronously notifies
* the caller via the IRMAFileResponse interface passed in to Init,
* of the completeness of the operation.
* If the bRelative flag is TRUE, it is a relative seek; else
* an absolute seek.
*/
STDMETHOD(Seek) (THIS_
ULONG32 ulOffset,
BOOL bRelative) PURE;
/************************************************************************
* Method:
* IRMAFileObject::Advise
* Purpose:
* To pass information to the File Object advising it about usage
* heuristics.
*/
STDMETHOD(Advise) (THIS_
ULONG32 ulInfo) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMAFileResponse
*
* Purpose:
*
* Object that exports file response API
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000201, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileResponse
DECLARE_INTERFACE_(IRMAFileResponse, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileResponse methods
*/
/************************************************************************
* Method:
* IRMAFileResponse::InitDone
* Purpose:
* Notification interface provided by users of the IRMAFileObject
* interface. This method is called by the IRMAFileObject when the
* initialization of the file is complete. If the file is not valid
* for the file system, the status PNR_FAILED should be
* returned.
*/
STDMETHOD(InitDone) (THIS_
PN_RESULT status) PURE;
/************************************************************************
* Method:
* IRMAFileResponse::CloseDone
* Purpose:
* Notification interface provided by users of the IRMAFileObject
* interface. This method is called by the IRMAFileObject when the
* close of the file is complete.
*/
STDMETHOD(CloseDone) (THIS_
PN_RESULT status) PURE;
/************************************************************************
* Method:
* IRMAFileResponse::ReadDone
* Purpose:
* Notification interface provided by users of the IRMAFileObject
* interface. This method is called by the IRMAFileObject when the
* last read from the file is complete and a buffer is available.
*/
STDMETHOD(ReadDone) (THIS_
PN_RESULT status,
IRMABuffer* pBuffer) PURE;
/************************************************************************
* Method:
* IRMAFileResponse::WriteDone
* Purpose:
* Notification interface provided by users of the IRMAFileObject
* interface. This method is called by the IRMAFileObject when the
* last write to the file is complete.
*/
STDMETHOD(WriteDone) (THIS_
PN_RESULT status) PURE;
/************************************************************************
* Method:
* IRMAFileResponse::SeekDone
* Purpose:
* Notification interface provided by users of the IRMAFileObject
* interface. This method is called by the IRMAFileObject when the
* last seek in the file is complete.
*/
STDMETHOD(SeekDone) (THIS_
PN_RESULT status) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Object that allows a Controller to communicate with a specific
* File System plug-in session
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000202, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
/************************************************************************
* Method:
* <API key>::GetFileSystemInfo
* Purpose:
* Returns information vital to the instantiation of file system
* plugin.
*
* pShortName should be a short, human readable name in the form
* of "company-fsname". For example: pShortName = "pn-local".
*/
STDMETHOD(GetFileSystemInfo) (THIS_
REF(const char*) /*OUT*/ pShortName,
REF(const char*) /*OUT*/ pProtocol) PURE;
STDMETHOD(InitFileSystem) (THIS_
IRMAValues* pOptions) PURE;
STDMETHOD(CreateFile) (THIS_
IUnknown** /*OUT*/ ppFileObject) PURE;
/*
* The following method is deprecated and should return PNR_NOTIMPL
*/
STDMETHOD(CreateDir) (THIS_
IUnknown** /*OUT*/ ppDirObject) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMAFileStat
*
* Purpose:
*
* Gets information about a specific File object
*
* IID_IRMAFileStat:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMAFileStat, 0x00000205, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileStat
DECLARE_INTERFACE_(IRMAFileStat, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileStat methods
*/
STDMETHOD(Stat) (THIS_
<API key>* pFileStatResponse
) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Returns information about a specific File object
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000206, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileStat methods
*/
STDMETHOD(StatDone) (THIS_
PN_RESULT status,
UINT32 ulSize,
UINT32 ulCreationTime,
UINT32 ulAccessTime,
UINT32 ulModificationTime,
UINT32 ulMode) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Gives out File Objects based on URLs
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000207, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
#define <API key> <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
STDMETHOD(Init) (THIS_
<API key>* <API key>
) PURE;
/* GetFileObject attempts to locate an existing file via the DoesExist
* method in each file system's objects, and returns that object through
* FSManagerResponse->FileObjectReady
*/
STDMETHOD(GetFileObject) (THIS_
IRMARequest* pRequest,
IRMAAuthenticator* pAuthenticator) PURE;
/* GetNewFileObject is similar to GetFileObject except that no DoesExist
* checks are done. The first file system that matches the mount point
* or protocol for the path in the request object creates the file
* which is then returned through FileObjectReady. This is especially
* useful for those who wish to open a brand new file for writing.
*/
STDMETHOD(GetNewFileObject) (THIS_
IRMARequest* pRequest,
IRMAAuthenticator* pAuthenticator) PURE;
STDMETHOD(<API key>) (THIS_
IUnknown* pOriginalObject,
const char* pPath) PURE;
/*
* The following method is deprecated and should return PNR_NOTIMPL
*/
STDMETHOD(GetDirObjectFromURL) (THIS_
const char* pURL) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Gives out File System objects based on URLs
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000208, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
/************************************************************************
* Method:
* <API key>::InitDone
* Purpose:
*/
STDMETHOD(InitDone) (THIS_
PN_RESULT status) PURE;
STDMETHOD(FileObjectReady) (THIS_
PN_RESULT status,
IUnknown* pObject) PURE;
/*
* The following method is deprecated and should return PNR_NOTIMPL
*/
STDMETHOD(DirObjectReady) (THIS_
PN_RESULT status,
IUnknown* pDirObject) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMAFileExists
*
* Purpose:
*
* Checks for the existense of a file. Must be implemented.
*
* IID_IRMAFileExists:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMAFileExists, 0x00000209, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileExists
DECLARE_INTERFACE_(IRMAFileExists, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileExists methods
*/
/************************************************************************
* Method:
* IRMAFileExists::DoesExist
* Purpose:
*/
STDMETHOD(DoesExist) (THIS_
const char* pPath,
<API key>* pFileResponse) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Response interface for IRMAFileExists. Must be implemented.
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x0000020a, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileExists
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
STDMETHOD(DoesExistDone) (THIS_
BOOL bExist) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMAFileMimeMapper
*
* Purpose:
*
* Allows you to specify a mime type for a specific file.
* Optional interface.
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x0000020b, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileMimeMapper
DECLARE_INTERFACE_(IRMAFileMimeMapper, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileMimeMapper methods
*/
/************************************************************************
* Method:
* IRMAFileMimeMapper::FindMimeType
* Purpose:
*/
STDMETHOD(FindMimeType) (THIS_
const char* pURL,
<API key>* pMimeMapperResponse
) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Response interface for IRMAFileMimeMapper.
* Optional interface.
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x0000020c, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
/************************************************************************
* Method:
* <API key>::MimeTypeFound
* Purpose:
* Notification interface provided by users of the IRMAFileMimeMapper
* interface. This method is called by the IRMAFileObject when the
* initialization of the file is complete, and the Mime type is
* available for the request file. If the file is not valid for the
* file system, the status PNR_FAILED should be returned,
* with a mime type of NULL. If the file is valid but the mime type
* is unknown, then the status PNR_OK should be returned with
* a mime type of NULL.
*
*/
STDMETHOD(MimeTypeFound) (THIS_
PN_RESULT status,
const char* pMimeType) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMABroadcastMapper
*
* Purpose:
*
* Associates a file with a broadcast format plugin.
* Implementation only required by broadcast plugin file systems.
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x0000020d, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMABroadcastMapper
DECLARE_INTERFACE_(IRMABroadcastMapper, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMABroadcastMapper methods
*/
/************************************************************************
* Method:
* IRMABroadcastMapper::FindBroadcastType
* Purpose:
*/
STDMETHOD(FindBroadcastType) (THIS_
const char* pURL,
<API key>* <API key>) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Response interface for IRMABroadcastMapper.
* Implementation only required by broadcast plugin file systems.
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x0000020e, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
/************************************************************************
* Method:
* <API key>::BroadcastTypeFound
* Purpose:
* Notification interface provided by users of the IRMABroadcastMapper
* interface. This method is called by the File Object when the
* initialization of the file is complete, and the broadcast type is
* available for the request file. If the file is not valid for the
* file system, the status PNR_FAILED should be returned,
* with the broadcast type set to NULL.
*
*/
STDMETHOD(BroadcastTypeFound) (THIS_
PN_RESULT status,
const char* pBroadcastType) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Gives out File Objects based on filenames and relative "paths"
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x0000020f, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
#define <API key> <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> method
*/
/************************************************************************
* Method:
* <API key>::<API key>
* Purpose:
* To get another FileObject from the same pool.
*/
STDMETHOD(<API key>) (THIS_
<API key>*) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Gives out File Objects based on filenames and relative "paths"
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000210, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
#define <API key> <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> method
*/
/************************************************************************
* Method:
* <API key>::FileObjectReady
* Purpose:
* To return another FileObject from the same pool.
*/
STDMETHOD(FileObjectReady) (THIS_
PN_RESULT status,
IUnknown* ppUnknown) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Set and Get a file object's authenticator object.
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000211, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
#define <API key> <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
STDMETHOD(SetAuthenticator) (THIS_
IRMAAuthenticator* pAuthenticator) PURE;
STDMETHOD(GetAuthenticator) (THIS_
REF(IRMAAuthenticator*) pAuthenticator) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMARequestHandler
*
* Purpose:
*
* Object to manage IRMARequest objects
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000212, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMARequestHandler
#define <API key> <API key>
DECLARE_INTERFACE_(IRMARequestHandler, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/************************************************************************
* Method:
* IRMARequestHandler::SetRequest
* Purpose:
* Associates an IRMARequest with an object
*/
STDMETHOD(SetRequest) (THIS_
IRMARequest* pRequest) PURE;
/************************************************************************
* Method:
* IRMARequestHandler::GetRequest
* Purpose:
* Gets the IRMARequest object associated with an object
*/
STDMETHOD(GetRequest) (THIS_
REF(IRMARequest*) /*OUT*/ pRequest) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMARequestContext
*
* Purpose:
*
* Object to manage the context of the Request
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000217, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMARequestContext
#define <API key> <API key>
DECLARE_INTERFACE_(IRMARequestContext, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMARequestContext methods
*/
/************************************************************************
* Method:
* IRMARequestContext::SetUserContext
* Purpose:
* Sets the Authenticated users Context.
*/
STDMETHOD(SetUserContext)
(
THIS_
IUnknown* pIUnknownNewContext
) PURE;
/************************************************************************
* Method:
* IRMARequestContext::GetUserContext
* Purpose:
* Gets the Authenticated users Context.
*/
STDMETHOD(GetUserContext)
(
THIS_
REF(IUnknown*) <API key>
) PURE;
/************************************************************************
* Method:
* IRMARequestContext::SetRequester
* Purpose:
* Sets the Object that made the request.
*/
STDMETHOD(SetRequester)
(
THIS_
IUnknown* <API key>
) PURE;
/************************************************************************
* Method:
* IRMARequestContext::GetRequester
* Purpose:
* Gets the Object that made the request.
*/
STDMETHOD(GetRequester)
(
THIS_
REF(IUnknown*) <API key>
) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMARequest
*
* Purpose:
*
* Object to manage the RFC822 headers sent by the client
*
* IID_IRMARequest:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMARequest, 0x00000213, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMARequest
#define CLSID_IRMARequest IID_IRMARequest
DECLARE_INTERFACE_(IRMARequest, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMARequest methods
*/
/************************************************************************
* Method:
* IRMARequest::SetRequestHeaders
* Purpose:
* Sets the headers that will be sent in the RFC822 header section
* of the request message
*/
STDMETHOD(SetRequestHeaders) (THIS_
IRMAValues* pRequestHeaders) PURE;
/************************************************************************
* Method:
* IRMARequest::GetRequestHeaders
* Purpose:
* Gets the headers that were sent in the RFC822 header section
* of the request message
*/
STDMETHOD(GetRequestHeaders) (THIS_
REF(IRMAValues*) pRequestHeaders) PURE;
/************************************************************************
* Method:
* IRMARequest::SetResponseHeaders
* Purpose:
* Sets the headers that will be returned in the RFC822 header
* section of the response message
*/
STDMETHOD(SetResponseHeaders) (THIS_
IRMAValues* pResponseHeaders) PURE;
/************************************************************************
* Method:
* IRMARequest::GetResponseHeaders
* Purpose:
* Gets the headers that were returned in the RFC822 header section
* of the response message
*/
STDMETHOD(GetResponseHeaders) (THIS_
REF(IRMAValues*) pResponseHeaders) PURE;
/************************************************************************
* Method:
* IRMARequest::SetURL
* Purpose:
* Sets the fully qualified path associated with a file object.
* Note: On the server, this path does not include the file system
* mount point.
*/
STDMETHOD(SetURL) (THIS_
const char* pURL) PURE;
/************************************************************************
* Method:
* IRMARequest::GetURL
* Purpose:
* Returns the fully qualified path associated with a file object.
* Note: On the server, this path does not include the file system
* mount point.
*
* Note: The returned pointer's lifetime expires as soon as the
* caller returns from a function which was called from the RMA
* core (i.e. when you return control to the RMA core)
*/
STDMETHOD(GetURL) (THIS_
REF(const char*) pURL) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMAFileRename
*
* Purpose:
*
* Interface to allow renaming of files. Query off of the File Object.
* Not all filesystem plugins implement this feature.
*
* IID_IRMAFileRename:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMAFileRename, 0x00000214, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileRename
DECLARE_INTERFACE_(IRMAFileRename, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileRename methods
*/
/************************************************************************
* Method:
* IRMAFileRename::Rename
* Purpose:
* Renames a file to a new name.
*/
STDMETHOD(Rename) (THIS_
const char* pNewFileName) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMADirHandler
*
* Purpose:
*
* Object that exports directory handler API
*
* IID_IRMADirHandler:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMADirHandler, 0x00000215, 0x901, 0x11d1, 0x8b, 0x6, 0x0, 0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMADirHandler
DECLARE_INTERFACE_(IRMADirHandler, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMADirHandler methods
*/
/************************************************************************
* Method:
* IRMADirHandler::InitDirHandler
* Purpose:
* Associates a directory handler with the directory handler
* response, it should notify of operation completness.
*/
STDMETHOD(InitDirHandler) (THIS_
<API key>* pDirResponse) PURE;
/************************************************************************
* Method:
* IRMADirHandler::CloseDirHandler
* Purpose:
* Closes the directory handler resource and releases all resources
* associated with the object.
*/
STDMETHOD(CloseDirHandler) (THIS) PURE;
/************************************************************************
* Method:
* IRMADirHandler::MakeDir
* Purpose:
* Create the directory
*/
STDMETHOD(MakeDir) (THIS) PURE;
/************************************************************************
* Method:
* IRMADirHandler::ReadDir
* Purpose:
* Get a dump of the directory
*/
STDMETHOD(ReadDir) (THIS) PURE;
};
/****************************************************************************
*
* Interface:
*
* <API key>
*
* Purpose:
*
* Object that exports the directory handler response API
*
* <API key>:
*
* {<API key>}
*
*/
DEFINE_GUID(<API key>, 0x00000216, 0x901, 0x11d1, 0x8b, 0x6, 0x0, 0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE <API key>
DECLARE_INTERFACE_(<API key>, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* <API key> methods
*/
/************************************************************************
* Method:
* <API key>::InitDirHandlerDone
* Purpose:
* Notification interface provided by users of the IRMADirHandler
* interface. This method is called by the IRMADirHandler when the
* initialization of the object is complete.
*/
STDMETHOD(InitDirHandlerDone) (THIS_
PN_RESULT status) PURE;
/************************************************************************
* Method:
* <API key>::CloseDirHandlerDone
* Purpose:
* Notification interface provided by users of the IRMADirHandler
* interface. This method is called by the IRMADirHandler when the
* close of the directory is complete.
*/
STDMETHOD(CloseDirHandlerDone) (THIS_
PN_RESULT status) PURE;
/************************************************************************
* Method:
* IRMADirHandler::MakeDirDone
* Purpose:
* Notification interface provided by users of the IRMADirHandler
* interface. This method is called by the IRMADirHandler when the
* attempt to create the directory is complete.
*/
STDMETHOD(MakeDirDone) (THIS_
PN_RESULT status) PURE;
/************************************************************************
* Method:
* IRMADirHandler::ReadDirDone
* Purpose:
* Notification interface provided by users of the IRMADirHandler
* interface. This method is called by the IRMADirHandler when the
* read from the directory is complete and a buffer is available.
*/
STDMETHOD(ReadDirDone) (THIS_
PN_RESULT status,
IRMABuffer* pBuffer) PURE;
};
/****************************************************************************
*
* Interface:
*
* IRMAFileRemove
*
* Purpose:
*
* Interface to allow removing of files. Query off of the File Object.
* Not all filesystem plugins implement this feature.
*
* IID_IRMAFileRemove:
*
* {<API key>}
*
*/
DEFINE_GUID(IID_IRMAFileRemove, 0x0000021A, 0x901, 0x11d1, 0x8b, 0x6, 0x0,
0xa0, 0x24, 0x40, 0x6d, 0x59);
#undef INTERFACE
#define INTERFACE IRMAFileRemove
DECLARE_INTERFACE_(IRMAFileRemove, IUnknown)
{
/*
* IUnknown methods
*/
STDMETHOD(QueryInterface) (THIS_
REFIID riid,
void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef) (THIS) PURE;
STDMETHOD_(ULONG,Release) (THIS) PURE;
/*
* IRMAFileRemove methods
*/
/************************************************************************
* Method:
* IRMAFileRemove::Remove
* Purpose:
* Removes a file from the file system.
*/
STDMETHOD(Remove) (THIS) PURE;
};
#endif /* _RMAFILES_H_ */
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
using System;
using System.Collections.Generic;
using ClearCanvas.Common.Serialization;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Enterprise.Core;
using ClearCanvas.Enterprise.Core.Modelling;
using ClearCanvas.Healthcare;
using ClearCanvas.Enterprise.Common;
using ClearCanvas.Ris.Application.Common;
using ClearCanvas.Common;
using System.Text.RegularExpressions;
namespace ClearCanvas.Ris.Application.Services
{
public class TextQueryHelper
{
public static PersonName[] ParsePersonNames(string query)
{
// define a term as anything starting with a letter, and followed by letters, hyphen (-) or apostrophe (')
// we allow hyphens for hyphenated surnames (wyatt-jones)
// allow apostrophe for names like O'Leary
var termDefinition = new Regex(@"\b[A-Za-z][A-Za-z'\-]*\b");
var terms = ParseTerms(query, termDefinition);
var names = new List<PersonName>();
for (var i = 0; i < terms.Length; i++)
{
var name = new PersonName {FamilyName = string.Join(" ", terms, 0, i + 1)};
if (i < terms.Length - 1)
{
name.GivenName = string.Join(" ", terms, i + 1, terms.Length - i - 1);
}
names.Add(name);
}
return names.ToArray();
}
public static string[] ParseIdentifiers(string query)
{
// define an identifier as anything containing at least 1 digit, and any other alpha-digit chars
var termDefinition = new Regex(@"\b[A-Za-z\d]*\d[A-Za-z\d]*\b");
return ParseTerms(query, termDefinition);
}
public static string[] ParsePhoneNumbers(string query)
{
// define a phone number as anything containing only one or more digits
var termDefinition = new Regex(@"\b\d+\b");
var <API key> = query.Replace("(", "").Replace(")", "").Replace("-", "");
return ParseTerms(<API key>, termDefinition);
}
public static string[] ParseTerms(string query)
{
var termDefinition = new Regex(@"\w+");
return ParseTerms(query, termDefinition);
}
public static string[] ParseTerms(string query, Regex termDefinition)
{
var matches = termDefinition.Matches(query);
return CollectionUtils.Map(matches, (Match m) => m.Value).ToArray();
}
}
public class TextQueryHelper<TDomainItem, TSearchCriteria, TSummary> : TextQueryHelper
where TSearchCriteria : SearchCriteria
where TSummary : DataContractBase
{
public delegate bool <API key>(TSearchCriteria[] where, int threshold);
public delegate IList<TDomainItem> DoQueryDelegate(TSearchCriteria[] where, SearchResultPage page);
private readonly Converter<TextQueryRequest, TSearchCriteria[]> <API key>;
private readonly Converter<TDomainItem, TSummary> _summaryAssembler;
private readonly DoQueryDelegate _queryCallback;
private readonly <API key> <API key>;
<summary>
Protected constructor for subclasses.
</summary>
protected TextQueryHelper()
{
}
<summary>
Public constructor allows direct use of this class without the need to create a subclass.
</summary>
<param name="criteriaBuilder"></param>
<param name="summaryAssembler"></param>
<param name="countCallback"></param>
<param name="queryCallback"></param>
public TextQueryHelper(
Converter<TextQueryRequest, TSearchCriteria[]> criteriaBuilder,
Converter<TDomainItem, TSummary> summaryAssembler,
<API key> countCallback,
DoQueryDelegate queryCallback)
{
<API key> = criteriaBuilder;
_summaryAssembler = summaryAssembler;
<API key> = countCallback;
_queryCallback = queryCallback;
}
public TextQueryResponse<TSummary> Query(TextQueryRequest request)
{
Platform.<API key>(request, "request");
Platform.CheckArgumentRange(request.<API key>, 0, 1000, "<API key>");
if (!ValidateRequest(request))
return new TextQueryResponse<TSummary>(true, new List<TSummary>());
var where = BuildCriteria(request);
// augment criteria to exclude de-activated items if specified
if (!request.IncludeDeactivated && AttributeUtils.HasAttribute<<API key>>(typeof(TDomainItem)))
{
var propertyName = AttributeUtils.GetAttribute<<API key>>(typeof(TDomainItem)).PropertyName;
var c = new SearchCondition<bool>(propertyName);
c.EqualTo(false);
CollectionUtils.ForEach(where, w => w.SetSubCriteria(c));
}
// if a specificity threshold was specified, apply it now
if (request.<API key> > 0)
{
// eliminate query that would return too many results
if (!TestSpecificity(where, request.<API key>))
return new TextQueryResponse<TSummary>(true, new List<TSummary>());
}
// execute query
var matches = DoQuery(where, request.Page);
return new TextQueryResponse<TSummary>(false,
CollectionUtils.Map(matches, (TDomainItem entity) => AssembleSummary(entity)));
}
protected virtual bool ValidateRequest(TextQueryRequest request)
{
// default validation - just ensure the text is not empty
return request.TextQuery != null && request.TextQuery.Trim().Length > 0;
}
protected virtual TSearchCriteria[] BuildCriteria(TextQueryRequest request)
{
if (<API key> == null)
throw new <API key>("Method must be overridden or a delegate supplied.");
return <API key>(request);
}
protected virtual bool TestSpecificity(TSearchCriteria[] where, int threshold)
{
if (<API key> == null)
throw new <API key>("Method must be overridden or a delegate supplied.");
return <API key>(where, threshold);
}
protected virtual IList<TDomainItem> DoQuery(TSearchCriteria[] where, SearchResultPage page)
{
if (_queryCallback == null)
throw new <API key>("Method must be overridden or a delegate supplied.");
return _queryCallback(where, page);
}
protected virtual TSummary AssembleSummary(TDomainItem domainItem)
{
if (_summaryAssembler == null)
throw new <API key>("Method must be overridden or a delegate supplied.");
return _summaryAssembler(domainItem);
}
<summary>
Applies specified string value to specified condition, if the value is non-empty, using partial matching.
</summary>
<param name="condition"></param>
<param name="value"></param>
protected static void ApplyStringCriteria(ISearchCondition<string> condition, string value)
{
ApplyStringCriteria(condition, value, false);
}
<summary>
Applies specified string value to specified condition, if the value is non-empty.
</summary>
<param name="condition"></param>
<param name="value"></param>
<param name="exactMatch"></param>
protected static void ApplyStringCriteria(ISearchCondition<string> condition, string value, bool exactMatch)
{
if (value == null)
return;
value = value.Trim();
if (string.IsNullOrEmpty(value))
return;
if (exactMatch)
condition.EqualTo(value);
else
condition.StartsWith(value);
}
}
}
|
using System;
using Popolo.<API key>;
using Popolo.Weather;
using Popolo.Numerics;
namespace Popolo.ThermalLoad
{
<summary>Air flow window class</summary>
public class AirFlowWindow
{
#region constant
private readonly double CPA = MoistAir.GetSpecificHeat(0.015);
#endregion
#region instance variables
<summary>has boundary conditions related to matrix changed or not.</summary>
private bool <API key> = true;
<summary>has boundary conditions not related to matrix changed or not.</summary>
private bool hasBoundaryChanged = true;
<summary>Inlet air temperature of air flow window.</summary>
private double inletAirTemperature;
<summary>glass pane of interior side[m]</summary>
private GlassPanes.Pane interiorGlassPane;
<summary>glass pnae of exterior side[m]</summary>
private GlassPanes.Pane exteriorGlassPane;
<summary></summary>
private double <API key> = 25;
<summary></summary>
private double <API key> = 25;
<summary>Interior side film coefficient [W/(m2K)]</summary>
private double <API key> = 9.3d;
<summary>Exterior side film coefficient [W/(m2K)]</summary>
private double <API key> = 21.0d;
<summary>Solar absorption [-] at exterior glass</summary>
private double <API key> = 0;
<summary>Solar absorption [-] at blind</summary>
private double <API key> = 0;
<summary>Solar absorption [-] at interior glass</summary>
private double <API key> = 0;
<summary></summary>
private double wi3, we3;
<summary>inside temperature[C]</summary>
private double itemp;
<summary>outside temperature[C]</summary>
private double otemp;
<summary>convective heat transfer coefficient [W/(m2K)] at interior air gap</summary>
private double <API key>;
<summary>convective heat transfer coefficient [W/(m2K)] at exterior air gap</summary>
private double <API key>;
<summary>radiative heat transfer coefficient [W/(m2K)] at interior air gap</summary>
private double <API key>;
<summary>radiative heat transfer coefficient [W/(m2K)] at exterior air gap</summary>
private double <API key>;
<summary>sun</summary>
private ImmutableSun sun;
#endregion
#region properties
<summary>Incline of exterior side.</summary>
public ImmutableIncline OutSideIncline
{
get;
private set;
}
<summary>Gets or Sets temperature [C] around interior glass.</summary>
public double IndoorTemperature
{
get
{
return itemp;
}
set
{
hasBoundaryChanged = true;
itemp = value;
}
}
<summary>Gets or Sets temperature [C] around exterior glass.</summary>
public double OutdoorTemperature
{
get
{
return otemp;
}
set
{
hasBoundaryChanged = true;
otemp = value;
}
}
<summary>Gets the interior side air gap thickness [m]</summary>
public double InteriorAirGap
{
private set;
get;
}
<summary>Gets the exterior side air gap thickness [m]</summary>
public double ExteriorAirGap
{
private set;
get;
}
<summary>Gets the width [m] of the air flow window</summary>
public double WindowWidth
{
private set;
get;
}
<summary>Gets the height [m] of the air flow window</summary>
public double WindowHeight
{
private set;
get;
}
<summary>Gets the air flow volume [CMH] at interior side.</summary>
public double <API key>
{
private set;
get;
}
<summary>Gets the air flow volume [CMH] at exterior side.</summary>
public double <API key>
{
private set;
get;
}
<summary>Gets the air flow volume [m/s] at interior side.</summary>
public double <API key>
{
private set;
get;
}
<summary>Gets the air flow volume [m/s] at exterior side.</summary>
public double <API key>
{
private set;
get;
}
<summary>Sets and Gets interior side film coefficient [W/(m2K)].</summary>
public double <API key>
{
get
{
return <API key>;
}
set
{
if (0 < value)
{
<API key> = value;
<API key> = true;
}
}
}
<summary>Sets and Gets exterior side film coefficient [W/(m2K)].</summary>
public double <API key>
{
get
{
return <API key>;
}
set
{
if (0 < value)
{
<API key> = value;
<API key> = true;
}
}
}
<summary>Sets or Gets sun.</summary>
public ImmutableSun Sun
{
get
{
return sun;
}
set
{
sun = value;
hasBoundaryChanged = true;
}
}
<summary>Gets the nocturnal radiation [W/m2]</summary>
public double NocturnalRadiation
{
get;
private set;
}
#endregion
#region instance variables for numeric calculation
<summary>Matrix A</summary>
private Matrix aMatrix = new Matrix(3, 3);
<summary>Inverse Matrix B</summary>
private Matrix bMatrix = new Matrix(3, 3);
<summary>Matrix T</summary>
private Vector tVector = new Vector(3);
<summary>Matrix Z</summary>
private Vector zVector = new Vector(3);
#endregion
#region constructor
<summary>Constructor</summary>
<param name="interiorGlassPane">glass pane of interior side</param>
<param name="interiorAirGap">interior side air gap thickness[m]</param>
<param name="exteriorGlassPane">glass pnae of exterior side</param>
<param name="exteriorAirGap">exterior side air gap thickness[m]</param>
<param name="windowWidth">width [m] of the air flow window</param>
<param name="windowHeight">height [m] of the air flow window</param>
<param name="outsideIncline"></param>
public AirFlowWindow(GlassPanes.Pane interiorGlassPane, double interiorAirGap,
GlassPanes.Pane exteriorGlassPane, double exteriorAirGap,double windowWidth, double windowHeight,
ImmutableIncline outsideIncline)
{
//initialize temperatures.
tVector.SetValue(25);
this.interiorGlassPane = interiorGlassPane;
this.exteriorGlassPane = exteriorGlassPane;
this.ExteriorAirGap = exteriorAirGap;
this.InteriorAirGap = interiorAirGap;
this.WindowWidth = windowWidth;
this.WindowHeight = windowHeight;
SetBlind(0.75, 0.07);
this.OutSideIncline = outsideIncline;
}
#endregion
#region public methods (Setting boundary conditions)
<summary>Set nocturnal radiation[W/m2] at window surface</summary>
<param name="nocturnalRadiation">nocturnal radiation[W/m2] at window surface</param>
public void <API key>(double nocturnalRadiation)
{
if (this.NocturnalRadiation != nocturnalRadiation)
{
this.NocturnalRadiation = nocturnalRadiation;
hasBoundaryChanged = true;
}
}
<summary>Set inlet air temperature of air flow window.</summary>
<param name="inletAirTemperature">temperature of inlet air</param>
public void <API key>(double inletAirTemperature)
{
if (this.inletAirTemperature != inletAirTemperature)
{
this.inletAirTemperature = inletAirTemperature;
<API key> = true;
}
}
<summary>Sets the air flow volume [CMH].</summary>
<param name="airFlowVolume">The air flow volume [CMH].</param>
public void SetAirFlowVolume(double airFlowVolume)
{
double iaf = InteriorAirGap / (InteriorAirGap + ExteriorAirGap) * airFlowVolume;
SetAirFlowVolume(iaf, airFlowVolume - iaf);
}
<summary>Sets the air flow volume [CMH].</summary>
<param name="<API key>">The air flow volume [CMH] at interior side</param>
<param name="<API key>">The air flow volume [CMH] at exterior side</param>
public void SetAirFlowVolume(double <API key>, double <API key>)
{
this.<API key> = <API key>;
this.<API key> = <API key>;
<API key> = <API key> / (InteriorAirGap * WindowWidth) / 3600d; //interior side velocity [m/s]
<API key> = <API key> / (ExteriorAirGap * WindowWidth) / 3600d; //exterior side velocity [m/s]
<API key> = true;
}
<summary>Sets the transmittance, reflectance and absorptance of the blind</summary>
<param name="transmittance">transmittance of the blind</param>
<param name="reflectance">reflectance of the blind</param>
public void SetBlind(double transmittance, double reflectance)
{
double xr;
double absorptance = 1d - transmittance - reflectance;
if (transmittance < 0 || reflectance < 0 || absorptance < 0) throw new Exception("Transmittance, Reflectance and Absorptance must take value between 0 to 1");
//calculate solar absorptance
double <API key> = interiorGlassPane.<API key>;
double overallReflectance = interiorGlassPane.<API key>;
<API key> = interiorGlassPane.<API key>;
xr = transmittance / (1d - reflectance * overallReflectance);
<API key> *= xr;
<API key> = absorptance + absorptance * overallReflectance * xr;
overallReflectance = reflectance + transmittance * overallReflectance * xr;
<API key> *= xr;
xr = exteriorGlassPane.<API key> / (1d - exteriorGlassPane.<API key> * overallReflectance);
<API key> *= xr;
<API key> *= xr;
<API key> = exteriorGlassPane.<API key> + exteriorGlassPane.<API key> * overallReflectance * xr;
overallReflectance = exteriorGlassPane.<API key> + exteriorGlassPane.<API key> * overallReflectance * xr;
<API key> *= xr;
<API key> = true;
}
#endregion
#region public methods (Getting state)
<summary>Gets temperature[C] of the blind</summary>
<returns>temperature[C] of the blind</returns>
public double GetBlindTemperature()
{
//update matirx if boundary conditions have changed
updateMatrix();
//update state
updateState();
return tVector.GetValue(1);
}
<summary>Gets temperature[C] of the interior glass</summary>
<returns>temperature[C] of the interior glass</returns>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
//update state
updateState();
return tVector.GetValue(2);
}
<summary>Gets temperature[C] of the exterior glass</summary>
<returns>temperature[C] of the exterior glass</returns>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
//update state
updateState();
return tVector.GetValue(0);
}
<summary>Gets the average temperature[C] of exterior air flow</summary>
<returns>average temperature[C] of exterior air flow</returns>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
//update state
updateState();
if (<API key> <= 0) return (tVector.GetValue(0) + tVector.GetValue(1)) * 0.5;
else return (tVector.GetValue(0) + tVector.GetValue(1)) * 0.5 * (1 - we3) + we3 * inletAirTemperature;
}
<summary>Gets the average temperature[C] of interior air flow</summary>
<returns>average temperature[C] of interior air flow</returns>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
//update state
updateState();
if (<API key> <= 0) return (tVector.GetValue(1) + tVector.GetValue(2)) * 0.5;
else return (tVector.GetValue(1) + tVector.GetValue(2)) * 0.5 * (1 - wi3) + wi3 * inletAirTemperature;
}
<summary>Gets the convective heat transfer coefficient [W/(m2K)] at interior air gap.</summary>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
return <API key>;
}
<summary>Gets the convective heat transfer coefficient [W/(m2K)] at exterior air gap.</summary>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
return <API key>;
}
<summary>Gets the radiative heat transfer coefficient [W/(m2K)] at interior air gap.</summary>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
return <API key>;
}
<summary>Gets the radiative heat transfer coefficient [W/(m2K)] at exterior air gap.</summary>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
return <API key>;
}
<summary>Gets the outlet air flow temperature [C]</summary>
<returns>outlet air flow temperature [C]</returns>
public double <API key>()
{
//update matirx if boundary conditions have changed
updateMatrix();
//update state
updateState();
double teo, tio;
double dens = 1.293 / (1 + inletAirTemperature / 273.15);
if (<API key> <= 0) teo = 0;
else
{
double tes = 0.5 * (tVector.GetValue(0) + tVector.GetValue(1));
double whe = (2 * <API key>) / (CPA * <API key> / 3.6d * dens);
double eps = 1 - Math.Exp(-whe);
teo = tes - (tes - inletAirTemperature) * Math.Exp(-whe);
}
if (<API key> <= 0) tio = 0;
else
{
double tis = 0.5 * (tVector.GetValue(1) + tVector.GetValue(2));
double whi = (2 * <API key>) / (CPA * <API key> / 3.6d * dens);
double eps = 1 - Math.Exp(-whi);
tio = tis - (tis - inletAirTemperature) * Math.Exp(-whi);
}
double eRate = <API key> / (<API key> + <API key>);
return teo * eRate + tio * (1 - eRate);
}
<summary>Gets heat removal by airflow [W/m2]</summary>
<returns>heat removal by airflow [W/m2]</returns>
public double <API key>()
{
double outT = <API key>();
double dens = 1.293 / (1 + inletAirTemperature / 273.15);
return (outT - inletAirTemperature) * (<API key> + <API key>) * dens * CPA / 3.6;
}
#endregion
#region private methods
private void updateState()
{
if (!hasBoundaryChanged) return;
//if (sunRev == sun.Revision) return;
//debug
double albedo = 0.5;
double shadowRate = 0;
double emissivity = 0.9;
//debug
//Calculate coefficients for glass
double cosineDN = OutSideIncline.<API key>(sun);
if (cosineDN < 0.01) cosineDN = 0.01;
double idn = cosineDN * sun.<API key>;
double id = OutSideIncline.<API key> * sun.<API key> +
(1 - OutSideIncline.<API key>) * albedo * sun.<API key>;
double charac = <API key>(cosineDN);
double radiation = (1d - shadowRate) * idn * charac + 0.91 * id;
double od = OutdoorTemperature - NocturnalRadiation * emissivity * OutSideIncline.<API key> / <API key>;
double kiw = 1 / (1 / interiorGlassPane.<API key> + 1 / <API key>);
double kew = 1 / (1 / exteriorGlassPane.<API key> + 1 / <API key>);
zVector.SetValue(0, <API key> * radiation
// - NocturnalRadiation * emissivity * OutSideIncline.<API key> +
+kew * od + <API key> * we3 * inletAirTemperature);
zVector.SetValue(1, <API key> * radiation +
<API key> * we3 * inletAirTemperature + <API key> * wi3 * inletAirTemperature);
zVector.SetValue(2, <API key> * radiation +
kiw * IndoorTemperature + <API key> * wi3 * inletAirTemperature);
//Blas.DGemv(Blas.TransposeType.NoTranspose, 1, bMatrix, zVector, 0, ref tVector);
bMatrix.VectorProduct(zVector, ref tVector, 1, 0);
hasBoundaryChanged = false;
//DEBUG
double sum1 = <API key> * radiation +
<API key> * (<API key>() - tVector.GetValue(0)) +
<API key> * (tVector.GetValue(1) - tVector.GetValue(0)) +
kew * (OutdoorTemperature - tVector.GetValue(0));
double sum2 = <API key> * radiation +
<API key> * (<API key>() - tVector.GetValue(1)) +
<API key> * (tVector.GetValue(0) - tVector.GetValue(1)) +
<API key> * (<API key>() - tVector.GetValue(1)) +
<API key> * (tVector.GetValue(2) - tVector.GetValue(1));
double sum3 = <API key> * radiation +
<API key> * (<API key>() - tVector.GetValue(2)) +
<API key> * (tVector.GetValue(1) - tVector.GetValue(2)) +
kiw * (IndoorTemperature - tVector.GetValue(2));
}
<summary>Update the matrix</summary>
private void updateMatrix()
{
if (!<API key>) return;
//Update heat transfer coefficients
<API key>();
double dens = 1.293 / (1 + inletAirTemperature / 273.15);
//interior side
double whi, epwi, wi1;
if (<API key> <= 0)
{
whi = 0;
epwi = 0;
wi1 = 0.5;
wi3 = 0;
}
else
{
whi = (2 * <API key>) / (CPA * <API key> / 3.6d * dens);
epwi = 1 - Math.Exp(-whi);
wi1 = (1 - epwi / whi) * 0.5;
wi3 = epwi / whi;
}
double kiw = 1 / (1 / interiorGlassPane.<API key> + 1 / <API key>);
//exterior side
double whe, epwe, we1;
if (<API key> <= 0)
{
whe = 0;
epwe = 0;
we1 = 0.5;
we3 = 0;
}
else
{
whe = (2 * <API key>) / (CPA * <API key> / 3.6d * dens);
epwe = 1 - Math.Exp(-whe);
we1 = (1 - epwe / whe) * 0.5;
we3 = epwe / whe;
}
double kew = 1 / (1 / exteriorGlassPane.<API key> + 1 / <API key>);
//make matrix A
aMatrix.SetValue(0, 0, <API key> * (1 - we1) + <API key> + kew);
aMatrix.SetValue(0, 1, -(<API key> * we1 + <API key>));
aMatrix.SetValue(0, 2, 0);
aMatrix.SetValue(1, 0, -(<API key> + <API key> * we1));
aMatrix.SetValue(1, 1, <API key> * (1 - we1) + <API key> +
<API key> * (1 - wi1) + <API key>);
aMatrix.SetValue(1, 2, -(<API key> + <API key> * wi1));
aMatrix.SetValue(2, 0, 0);
aMatrix.SetValue(2, 1, -(<API key> * wi1 + <API key>));
aMatrix.SetValue(2, 2, <API key> * (1 - wi1) + <API key> + kiw);
//calculate inverse matrix A- with LU decomposition
aMatrix.GetInverse(ref bMatrix);
<API key> = false;
hasBoundaryChanged = true;
}
<summary>update overall heat transfer coefficient of air gaps</summary>
private void <API key>()
{
//calculate convective heat transfer coefficients
<API key> = <API key>(tVector.GetValue(2), <API key>, <API key>);
<API key> = <API key>(tVector.GetValue(0), <API key>, <API key>);
//calculate radiative heat transfer coefficients
<API key> = (4 * 5.67e-8) / (1 / 0.9 + 1 / 0.9 - 1) * Math.Pow((tVector.GetValue(1) + tVector.GetValue(2)) / 2d + 273.15, 3);
<API key> = (4 * 5.67e-8) / (1 / 0.9 + 1 / 0.9 - 1) * Math.Pow((tVector.GetValue(0) + tVector.GetValue(1)) / 2d + 273.15, 3);
}
<summary>Calculate a convective heat transfer coefficient</summary>
<param name="surfaceTemperature">temperature of surface (blind or glass)</param>
<param name="airTemperature">temperature of air</param>
<param name="airVelocity">velocity of air</param>
<returns>convective heat transfer coefficient</returns>
private double <API key>(double surfaceTemperature, double airTemperature, double airVelocity)
{
//return 11.2 * airVelocity - 0.05;//
double aveTemp = (surfaceTemperature + airTemperature) * 0.5;
//Thermodynamic properties of air (interior side).
double dvis = MoistAir.GetDynamicViscosity(aveTemp); //Dynamic Viscosity [m2/s]
double tcd = MoistAir.<API key>(aveTemp); //Thermal conductivity [W/(mK)]
double des = 1.293 / (1 + aveTemp / 273.15); //Density [kg/m3]
double tds = tcd / des / CPA / 1000; //Thermal diffusivity [m2/s]
double exc = MoistAir.<API key>(aveTemp); //Expansion coefficient [1/K]
//Calculate Prandtl number
double prtl = dvis / tds;
//natural convection
if (airVelocity <= 0)
{
//Calculate Grashof number
double dt = Math.Abs(surfaceTemperature - airTemperature);
double grs = (9.8 * Math.Pow(des, 2) * exc * dt * Math.Pow(WindowHeight, 3)) / Math.Pow(dvis, 2);
//Calculate convective heat transfer coefficients [W/(m2 K)]
double grpr = grs * prtl;
if (grpr < 1e9) return 0.56 * Math.Pow(grpr, 0.25) * tcd / WindowHeight;
else return 0.13 * Math.Pow(grpr, 1 / 3d) * tcd / WindowHeight;
}
//forced convection
else
{
//Calculate Reynolds number
double rey = airVelocity * WindowHeight / dvis;
//Calculate convective heat transfer coefficients [W/(m2 K)]
if (rey < 500000) return 0.664 * Math.Pow(prtl, 1d / 3d) * Math.Pow(rey, 0.5) * tcd / WindowHeight;
else return 0.037 * Math.Pow(prtl, 1d / 3d) * Math.Pow(rey, 0.8) * tcd / WindowHeight;
}
}
<summary>[-]</summary>
<param name="cosineIncidentAngle">cosθ</param>
<returns>[-]</returns>
public double <API key>(double cosineIncidentAngle)
{
double[] <API key> = new double[] { 3.4167, -4.389, 2.4948, -0.5224 };
double ci = cosineIncidentAngle;
double val = 0;
for (int i = <API key>.Length - 1; 0 <= i; i
{
val = ci * (val + <API key>[i]);
}
return Math.Max(0, Math.Min(1, val));
}
#endregion
}
}
|
# rtlsdr_scan
# A frequency scanning GUI for the OsmoSDR rtl-sdr library at
# This program is free software: you can redistribute it and/or modify
# the Free Software Foundation, 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
import datetime
import json
from math import radians, sin, cos, asin, sqrt
import math
import os
import socket
import sys
from threading import Thread
import time
import urllib
import serial.tools.list_ports
from constants import SAMPLE_RATE, TIMESTAMP_FILE
class RemoteControl(object):
def __init__(self):
self.connected = False
self.socket = None
def __connect(self):
if not self.connected:
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(1)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.connect(('localhost', 3382))
self.connected = True
except socket.error:
self.connected = False
def __thread(self, command):
self.__connect()
if self.connected:
try:
self.socket.send(json.dumps(command))
self.socket.send('\r\n')
except socket.error:
self.socket.close()
self.connected = False
def __send(self, command):
thread = Thread(target=self.__thread, args=(command,))
thread.daemon = True
thread.start()
def tune(self, frequency):
command = {'Command': 'Set',
'Method': 'Frequency',
'Value': frequency}
self.__send(command)
def get_script_dir():
if not hasattr(sys, 'frozen'):
scriptDir = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
scriptDir = sys._MEIPASS
return scriptDir
def get_resdir():
scriptDir = get_script_dir()
if os.path.isdir(os.path.join(scriptDir, 'res')):
resDir = os.path.join(scriptDir, 'res')
else:
resDir = os.path.join(scriptDir, '..', 'res')
return resDir
def get_resource_path(resource):
return os.path.join(get_resdir(), resource)
def limit(value, minimum, maximum):
return max(min(maximum, value), minimum)
def level_to_db(level):
return 10 * math.log10(level)
def db_to_level(dB):
return math.pow(10, dB / 10.0)
def next_2_to_pow(val):
val -= 1
val |= val >> 1
val |= val >> 2
val |= val >> 4
val |= val >> 8
val |= val >> 16
return val + 1
def calc_samples(dwell):
samples = dwell * SAMPLE_RATE
samples = next_2_to_pow(int(samples))
return samples
def calc_real_dwell(dwell):
samples = calc_samples(dwell)
dwellReal = samples / SAMPLE_RATE
return (int)(dwellReal * 1000.0) / 1000.0
def nearest(value, values):
offset = [abs(value - v) for v in values]
return values[offset.index(min(offset))]
def haversine(lat1, lat2, lon1, lon2):
lat1, lat2, lon1, lon2 = map(radians, [lat1, lat2, lon1, lon2])
dlon = lon1 - lon2
dlat = lat1 - lat2
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
b = asin(sqrt(a))
return 2 * b * 6371000
def format_precision(settings, freq=None, level=None,
units=True, fancyUnits=False):
textFreq = None
textLevel = None
if freq is not None:
prec = settings.precisionFreq
width = 4 + prec
textFreq = '{:{width}.{prec}f}'.format(freq, width=width, prec=prec)
if units or fancyUnits:
textFreq += " MHz"
if level is not None:
prec = settings.precisionLevel
width = 4 + prec
textLevel = '{:.{prec}f}'.format(level, width=width, prec=prec)
if fancyUnits:
textLevel += r" $\mathsf{{dB/\sqrt{{Hz}}}}$"
elif units:
textLevel += " dB/Hz"
if textFreq and textLevel:
return (textFreq, textLevel)
if textFreq:
return textFreq
if textLevel:
return textLevel
return None
def format_time(timeStamp, withDate=False):
if timeStamp <= 1:
return 'Unknown'
if withDate:
return time.strftime('%c', time.localtime(timeStamp))
return time.strftime('%H:%M:%S', time.localtime(timeStamp))
def format_iso_time(timeStamp):
dt = datetime.datetime.utcfromtimestamp(timeStamp)
return dt.isoformat() + 'Z'
def <API key>():
scriptDir = get_script_dir()
timeStamp = str(int(time.time()))
f = open(os.path.join(scriptDir, TIMESTAMP_FILE), 'w')
f.write(timeStamp)
f.close()
def <API key>(asSeconds=False):
scriptDir = get_script_dir()
f = open(os.path.join(scriptDir, TIMESTAMP_FILE), 'r')
timeStamp = int(f.readline())
f.close()
if asSeconds:
return timeStamp
else:
return format_time(timeStamp, True)
def <API key>():
f = urllib.urlopen('https://raw.github.com/EarToEarOak/RTLSDR-Scanner/master/src/version-timestamp')
timeStamp = int(f.readline())
f.close()
return timeStamp
def get_serial_ports():
ports = [port[0] for port in serial.tools.list_ports.comports()]
if len(ports) == 0:
if os.name == 'nt':
ports.append('COM1')
else:
ports.append('/dev/ttyS0')
return ports
def limit_to_ascii(text):
return ''.join([i if ord(i) < 128 else '' for i in text])
if __name__ == '__main__':
print 'Please run rtlsdr_scan.py'
exit(1)
|
package com.oocl.mnlbc.service;
public class AddUserSvc {
public boolean fieldEmpty(String field) {
if(field != null && !field.equals("")){
return false;
}
return true;
}
}
|
# $Id: Tree.pm 16123 2009-09-17 12:57:27Z cjfields $
# BioPerl module for Bio::Tree::Tree
# Please direct questions and support issues to <bioperl-l@bioperl.org>
# Cared for by Jason Stajich <jason@bioperl.org>
# You may distribute this module under the same terms as perl itself
# POD documentation - main docs before the code
=head1 NAME
Bio::Tree::Tree - An Implementation of TreeI interface.
=head1 SYNOPSIS
# like from a TreeIO
my $treeio = Bio::TreeIO->new(-format => 'newick', -file => 'treefile.dnd');
my $tree = $treeio->next_tree;
my @nodes = $tree->get_nodes;
my $root = $tree->get_root_node;
=head1 DESCRIPTION
This object holds handles to Nodes which make up a tree.
=head1 IMPLEMENTATION NOTE
This implementation of Bio::Tree::Tree contains Bio::Tree:::NodeI; mainly linked
via the root node. As NodeI can potentially contain circular references (as
nodes will need to refer to both parent and child nodes), Bio::Tree::Tree will
remove those circular references when the object is garbage-collected. This has
some side effects; primarily, one must keep the Tree in scope or have at least
one reference to it if working with nodes. The fix is to count the references to
the nodes and if it is greater than expected retain all of them, but it requires
an additional prereq and thus may not be worth the effort. This only shows up
in minor edge cases, though (see Bug #2869).
Example of issue:
# tree is not assigned to a variable, so passes from memory after
# root node is passed
my $root = Bio::TreeIO->new(-format => 'newick', -file => 'foo.txt')->next_tree
->get_root_node;
# gets nothing, as all Node links are broken when Tree is garbage-collected above
my @descendents = $root->get_all_Descendents;
=head1 FEEDBACK
=head2 Mailing Lists
User feedback is an integral part of the evolution of this and other
Bioperl modules. Send your comments and suggestions preferably to
the Bioperl mailing list. Your participation is much appreciated.
bioperl-l@bioperl.org - General discussion
http://bioperl.org/wiki/Mailing_lists - About the mailing lists
=head2 Support
Please direct usage questions or support issues to the mailing list:
I<bioperl-l@bioperl.org>
rather than to the module maintainer directly. Many experienced and
reponsive experts will be able look at the problem and quickly
address it. Please include a thorough description of the problem
with code and data examples if at all possible.
=head2 Reporting Bugs
Report bugs to the Bioperl bug tracking system to help us keep track
of the bugs and their resolution. Bug reports can be submitted via
the web:
http://bugzilla.open-bio.org/
=head1 AUTHOR - Jason Stajich
Email jason@bioperl.org
=head1 CONTRIBUTORS
Aaron Mackey amackey@virginia.edu
Sendu Bala bix@sendu.me.uk
Mark A. Jensen maj@fortinbras.us
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _
=cut
# Let the code begin...
package Bio::Tree::Tree;
use strict;
# Object preamble - inherits from Bio::Root::Root
use base qw(Bio::Root::Root Bio::Tree::TreeI Bio::Tree::TreeFunctionsI);
=head2 new
Title : new
Usage : my $obj = Bio::Tree::Tree->new();
Function: Builds a new Bio::Tree::Tree object
Returns : Bio::Tree::Tree
Args : -root => L<Bio::Tree::NodeI> object which is the root
OR
-node => L<Bio::Tree::NodeI> object from which the root will be
determined
-nodelete => boolean, whether or not to try and cleanup all
the nodes when this this tree goes out
of scope.
-id => optional tree ID
-score => optional tree score value
=cut
sub new {
my($class,@args) = @_;
my $self = $class->SUPER::new(@args);
$self->{'_rootnode'} = undef;
$self->{'_maxbranchlen'} = 0;
$self-><API key>(\&cleanup_tree);
my ($root,$node,$nodel,$id,$score)= $self->_rearrange([qw(ROOT NODE NODELETE
ID SCORE)], @args);
if ($node && ! $root) {
$self->throw("Must supply a Bio::Tree::NodeI") unless ref($node) && $node->isa('Bio::Tree::NodeI');
my @lineage = $self->get_lineage_nodes($node);
$root = shift(@lineage) || $node;
# to stop us pulling in entire database of a Bio::Taxon when we later do
# get_nodes() or similar, specifically set ancestor() for each node
if ($node->isa('Bio::Taxon')) {
push(@lineage, $node) unless $node eq $root;
my $ancestor = $root;
foreach my $lineage_node (@lineage) {
$lineage_node->ancestor($ancestor);
} continue { $ancestor = $lineage_node; }
}
}
if ($root) {
$self->set_root_node($root);
}
$self->nodelete($nodel || 0);
$self->id($id) if defined $id;
$self->score($score) if defined $score;
return $self;
}
=head2 nodelete
Title : nodelete
Usage : $obj->nodelete($newval)
Function: Get/Set Boolean whether or not to delete the underlying
nodes when it goes out of scope. By default this is false
meaning trees are cleaned up.
Returns : boolean
Args : on set, new boolean value
=cut
sub nodelete{
my $self = shift;
return $self->{'nodelete'} = shift if @_;
return $self->{'nodelete'};
}
=head2 get_nodes
Title : get_nodes
Usage : my @nodes = $tree->get_nodes()
Function: Return list of Bio::Tree::NodeI objects
Returns : array of Bio::Tree::NodeI objects
Args : (named values) hash with one value
order => 'b|breadth' first order or 'd|depth' first order
=cut
sub get_nodes{
my ($self, @args) = @_;
my ($order, $sortby) = $self->_rearrange([qw(ORDER SORTBY)],@args);
$order ||= 'depth';
$sortby ||= 'none';
my $node = $self->get_root_node || return;
if ($order =~ m/^b|(breadth)$/oi) {
my @children = ($node);
for (@children) {
push @children, $_->each_Descendent($sortby);
}
return @children;
}
if ($order =~ m/^d|(depth)$/oi) {
# this is depth-first search I believe
my @children = ($node,$node->get_all_Descendents($sortby));
return @children;
}
}
=head2 get_root_node
Title : get_root_node
Usage : my $node = $tree->get_root_node();
Function: Get the Top Node in the tree, in this implementation
Trees only have one top node.
Returns : Bio::Tree::NodeI object
Args : none
=cut
sub get_root_node{
my ($self) = @_;
return $self->{'_rootnode'};
}
=head2 set_root_node
Title : set_root_node
Usage : $tree->set_root_node($node)
Function: Set the Root Node for the Tree
Returns : Bio::Tree::NodeI
Args : Bio::Tree::NodeI
=cut
sub set_root_node{
my $self = shift;
if( @_ ) {
my $value = shift;
if( defined $value &&
! $value->isa('Bio::Tree::NodeI') ) {
$self->warn("Trying to set the root node to $value which is not a Bio::Tree::NodeI");
return $self->get_root_node;
}
$self->{'_rootnode'} = $value;
}
return $self->get_root_node;
}
=head2 total_branch_length
Title : total_branch_length
Usage : my $size = $tree->total_branch_length
Function: Returns the sum of the length of all branches
Returns : real
Args : none
=cut
sub total_branch_length { shift->subtree_length }
=head2 subtree_length
Title : subtree_length
Usage : my $subtree_size = $tree->subtree_length($internal_node)
Function: Returns the sum of the length of all branches in a subtree
under the node. Calculates the size of the whole tree
without an argument (but only if root node is defined)
Returns : real or undef
Args : Bio::Tree::NodeI object, defaults to the root node
=cut
sub subtree_length {
my $tree = shift;
my $node = shift || $tree->get_root_node;
return unless $node;
my $sum = 0;
for ( $node->get_all_Descendents ) {
$sum += $_->branch_length || 0;
}
return $sum;
}
=head2 id
Title : id
Usage : my $id = $tree->id();
Function: An id value for the tree
Returns : scalar
Args : [optional] new value to set
=cut
sub id{
my ($self,$val) = @_;
if( defined $val ) {
$self->{'_treeid'} = $val;
}
return $self->{'_treeid'};
}
=head2 score
Title : score
Usage : $obj->score($newval)
Function: Sets the associated score with this tree
This is a generic slot which is probably best used
for log likelihood or other overall tree score
Returns : value of score
Args : newvalue (optional)
=cut
sub score{
my ($self,$val) = @_;
if( defined $val ) {
$self->{'_score'} = $val;
}
return $self->{'_score'};
}
# decorated interface TreeI Implements this
=head2 height
Title : height
Usage : my $height = $tree->height
Function: Gets the height of tree - this LOG_2($number_nodes)
WARNING: this is only true for strict binary trees. The TreeIO
system is capable of building non-binary trees, for which this
method will currently return an incorrect value!!
Returns : integer
Args : none
=head2 number_nodes
Title : number_nodes
Usage : my $size = $tree->number_nodes
Function: Returns the number of nodes in the tree
Returns : integer
Args : none
=cut
=head2 as_text
Title : as_text
Usage : my $tree_as_string = $tree->as_text($format)
Function: Returns the tree as a string representation in the
desired format (currently 'newick', 'nhx', or
'tabtree')
Returns : scalar string
Args : format type as specified by Bio::TreeIO
Note : This method loads the Bio::TreeIO::$format module
on the fly, and commandeers the _write_tree_Helper
routine therein to create the tree string.
=cut
sub as_text {
my $self = shift;
my $format = shift;
my @parms;
my $iomod = "Bio::TreeIO::$format";
$self->_load_module($iomod);
# following currently not really necessary, but who knows?
my $io = $iomod->new(-format=>$format, -file=>File::Spec->devnull());
no strict "refs";
my $iowtH = *{$iomod."::_write_tree_Helper"}{CODE};
use strict "refs";
for ($format) {
/newick/ && do {
@parms = ( $io->bootstrap_style, $io->order_by, 0 );
last;
};
/nhx/ && do {
@parms = ( 0 );
last;
};
/tabtree/ && do {
@parms = ( "" );
last;
};
# default
$self->throw("as_text does not allow format '$format'")
}
# newline_each_node...
my $data = [$iowtH->($self->get_root_node, @parms)];
if ($format eq 'tabtree') {
return $$data[0]."\n";
}
else {
return join(",", @$data).";\n";
}
}
=head2 Methods for associating Tag/Values with a Tree
These methods associate tag/value pairs with a Tree
=head2 set_tag_value
Title : set_tag_value
Usage : $tree->set_tag_value($tag,$value)
$tree->set_tag_value($tag,@values)
Function: Sets a tag value(s) to a tree. Replaces old values.
Returns : number of values stored for this tag
Args : $tag - tag name
$value - value to store for the tag
=cut
sub set_tag_value{
my ($self,$tag,@values) = @_;
if( ! defined $tag || ! scalar @values ) {
$self->warn("cannot call set_tag_value with an undefined value");
}
$self->remove_tag ($tag);
map { push @{$self->{'_tags'}->{$tag}}, $_ } @values;
return scalar @{$self->{'_tags'}->{$tag}};
}
=head2 add_tag_value
Title : add_tag_value
Usage : $tree->add_tag_value($tag,$value)
Function: Adds a tag value to a tree
Returns : number of values stored for this tag
Args : $tag - tag name
$value - value to store for the tag
=cut
sub add_tag_value{
my ($self,$tag,$value) = @_;
if( ! defined $tag || ! defined $value ) {
$self->warn("cannot call add_tag_value with an undefined value");
}
push @{$self->{'_tags'}->{$tag}}, $value;
return scalar @{$self->{'_tags'}->{$tag}};
}
=head2 remove_tag
Title : remove_tag
Usage : $tree->remove_tag($tag)
Function: Remove the tag and all values for this tag
Returns : boolean representing success (0 if tag does not exist)
Args : $tag - tagname to remove
=cut
sub remove_tag {
my ($self,$tag) = @_;
if( exists $self->{'_tags'}->{$tag} ) {
$self->{'_tags'}->{$tag} = undef;
delete $self->{'_tags'}->{$tag};
return 1;
}
return 0;
}
=head2 remove_all_tags
Title : remove_all_tags
Usage : $tree->remove_all_tags()
Function: Removes all tags
Returns : None
Args : None
=cut
sub remove_all_tags{
my ($self) = @_;
$self->{'_tags'} = {};
return;
}
=head2 get_all_tags
Title : get_all_tags
Usage : my @tags = $tree->get_all_tags()
Function: Gets all the tag names for this Tree
Returns : Array of tagnames
Args : None
=cut
sub get_all_tags{
my ($self) = @_;
my @tags = sort keys %{$self->{'_tags'} || {}};
return @tags;
}
=head2 get_tag_values
Title : get_tag_values
Usage : my @values = $tree->get_tag_values($tag)
Function: Gets the values for given tag ($tag)
Returns : Array of values or empty list if tag does not exist
Args : $tag - tag name
=cut
sub get_tag_values{
my ($self,$tag) = @_;
return wantarray ? @{$self->{'_tags'}->{$tag} || []} :
(@{$self->{'_tags'}->{$tag} || []})[0];
}
=head2 has_tag
Title : has_tag
Usage : $tree->has_tag($tag)
Function: Boolean test if tag exists in the Tree
Returns : Boolean
Args : $tag - tagname
=cut
sub has_tag {
my ($self,$tag) = @_;
return exists $self->{'_tags'}->{$tag};
}
# -- private internal methods --
sub cleanup_tree {
my $self = shift;
unless( $self->nodelete ) {
for my $node ($self->get_nodes(-order => 'b', -sortby => 'none')) {
#$node->ancestor(undef);
#$node = undef;
$node->node_cleanup;
undef $node;
}
}
$self->{'_rootnode'} = undef;
}
1;
|
package buildcraftAdditions.items.itemBlocks;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import buildcraftAdditions.BuildcraftAdditions;
import buildcraftAdditions.utils.Utils;
public class ItemBlockKEB extends ItemBlock {
public ItemBlockKEB(Block block) {
super(block);
}
@Override
public String <API key>(ItemStack stack) {
if (BuildcraftAdditions.proxy.getPlayer().getDisplayName().equals("corjaantje")) {
if (stack.stackTagCompound != null && stack.stackTagCompound.getBoolean("creative"))
return "Creative Kebab Extreme Bakery";
return "Kebab Extreme Bakery";
}
if (stack.stackTagCompound != null && stack.stackTagCompound.getBoolean("creative"))
return Utils.localize("tile.blockKEBT1Creative.name");
return super.<API key>(stack);
}
}
|
-- $Header: /tmp/libdirac/tmp.stZoy15380/dirac/DIRAC3/DIRAC/<API key>/DB/JobDB.sql,v 1.22 2009/08/26 09:39:53 rgracian Exp $
-- Schema definition for the JobDB database - the main database of the DIRAC
-- Workload Management System
-- When installing via dirac tools, the following is not needed (still here for reference)
-- DROP DATABASE IF EXISTS JobDB;
-- CREATE DATABASE JobDB;
-- Database owner definition
-- USE mysql;
-- DELETE FROM user WHERE user='Dirac';
-- Must set passwords for database user by replacing "must_be_set".
-- GRANT SELECT,INSERT,LOCK TABLES,UPDATE,DELETE,CREATE,DROP,ALTER,REFERENCES ON JobDB.* TO Dirac@localhost IDENTIFIED BY 'must_be_set';
-- GRANT SELECT,INSERT,LOCK TABLES,UPDATE,DELETE,CREATE,DROP,ALTER,REFERENCES ON JobDB.* TO Dirac@'%' IDENTIFIED BY 'must_be_set';
-- FLUSH PRIVILEGES;
USE JobDB;
DROP TABLE IF EXISTS `JobJDLs`;
CREATE TABLE `JobJDLs` (
`JobID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`JDL` MEDIUMBLOB NOT NULL,
`JobRequirements` BLOB NOT NULL,
`OriginalJDL` MEDIUMBLOB NOT NULL,
PRIMARY KEY (`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `Jobs`;
CREATE TABLE `Jobs` (
`JobID` INT(11) UNSIGNED NOT NULL DEFAULT 0,
`JobType` VARCHAR(32) NOT NULL DEFAULT 'user',
`DIRACSetup` VARCHAR(32) NOT NULL DEFAULT 'test',
`JobGroup` VARCHAR(32) NOT NULL DEFAULT '00000000',
`JobSplitType` ENUM('Single','Master','Subjob','DAGNode') NOT NULL DEFAULT 'Single',
`MasterJobID` INT(11) UNSIGNED NOT NULL DEFAULT 0,
`Site` VARCHAR(100) NOT NULL DEFAULT 'ANY',
`JobName` VARCHAR(128) NOT NULL DEFAULT 'Unknown',
`Owner` VARCHAR(32) NOT NULL DEFAULT 'Unknown',
`OwnerDN` VARCHAR(255) NOT NULL DEFAULT 'Unknown',
`OwnerGroup` VARCHAR(128) NOT NULL DEFAULT 'Unknown',
`SubmissionTime` DATETIME DEFAULT NULL,
`RescheduleTime` DATETIME DEFAULT NULL,
`LastUpdateTime` DATETIME DEFAULT NULL,
`StartExecTime` DATETIME DEFAULT NULL,
`HeartBeatTime` DATETIME DEFAULT NULL,
`EndExecTime` DATETIME DEFAULT NULL,
`Status` VARCHAR(32) NOT NULL DEFAULT 'Received',
`MinorStatus` VARCHAR(128) NOT NULL DEFAULT 'Unknown',
`ApplicationStatus` VARCHAR(255) DEFAULT 'Unknown',
`<API key>` INT(11) NOT NULL DEFAULT 0,
`UserPriority` INT(11) NOT NULL DEFAULT 0,
`SystemPriority` INT(11) NOT NULL DEFAULT 0,
`RescheduleCounter` INT(11) NOT NULL DEFAULT 0,
`VerifiedFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`DeletedFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`KilledFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`FailedFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`ISandboxReadyFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`OSandboxReadyFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`RetrievedFlag` ENUM('True','False') NOT NULL DEFAULT 'False',
`AccountedFlag` ENUM('True','False','Failed') NOT NULL DEFAULT 'False',
PRIMARY KEY (`JobID`),
FOREIGN KEY (`JobID`) REFERENCES `JobJDLs`(`JobID`),
KEY `JobType` (`JobType`),
KEY `DIRACSetup` (`DIRACSetup`),
KEY `JobGroup` (`JobGroup`),
KEY `JobSplitType` (`JobSplitType`),
KEY `Site` (`Site`),
KEY `Owner` (`Owner`),
KEY `OwnerDN` (`OwnerDN`),
KEY `OwnerGroup` (`OwnerGroup`),
KEY `Status` (`Status`),
KEY `MinorStatus` (`MinorStatus`),
KEY `ApplicationStatus` (`ApplicationStatus`),
KEY `StatusSite` (`Status`,`Site`),
KEY `LastUpdateTime` (`LastUpdateTime`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `InputData`;
CREATE TABLE `InputData` (
`JobID` INT(11) UNSIGNED NOT NULL,
`LFN` VARCHAR(255) NOT NULL DEFAULT '',
`Status` VARCHAR(32) NOT NULL DEFAULT 'AprioriGood',
PRIMARY KEY (`JobID`,`LFN`),
FOREIGN KEY (`JobID`) REFERENCES `Jobs`(`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `JobParameters`;
CREATE TABLE `JobParameters` (
`JobID` INT(11) UNSIGNED NOT NULL,
`Name` VARCHAR(100) NOT NULL,
`Value` BLOB NOT NULL,
PRIMARY KEY (`JobID`,`Name`),
FOREIGN KEY (`JobID`) REFERENCES `Jobs`(`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `OptimizerParameters`;
CREATE TABLE `OptimizerParameters` (
`JobID` INT(11) UNSIGNED NOT NULL,
`Name` VARCHAR(100) NOT NULL,
`Value` MEDIUMBLOB NOT NULL,
PRIMARY KEY (`JobID`,`Name`),
FOREIGN KEY (`JobID`) REFERENCES `Jobs`(`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `AtticJobParameters`;
CREATE TABLE `AtticJobParameters` (
`JobID` INT(11) UNSIGNED NOT NULL,
`Name` VARCHAR(100) NOT NULL,
`Value` BLOB NOT NULL,
`RescheduleCycle` INT(11) UNSIGNED NOT NULL,
PRIMARY KEY (`JobID`,`Name`,`RescheduleCycle`),
FOREIGN KEY (`JobID`) REFERENCES `Jobs`(`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `SiteMask`;
CREATE TABLE `SiteMask` (
`Site` VARCHAR(64) NOT NULL,
`Status` VARCHAR(64) NOT NULL,
`LastUpdateTime` DATETIME NOT NULL,
`Author` VARCHAR(255) NOT NULL,
`Comment` BLOB NOT NULL,
PRIMARY KEY (`Site`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `SiteMaskLogging`;
CREATE TABLE `SiteMaskLogging` (
`Site` VARCHAR(64) NOT NULL,
`Status` VARCHAR(64) NOT NULL,
`UpdateTime` DATETIME NOT NULL,
`Author` VARCHAR(255) NOT NULL,
`Comment` BLOB NOT NULL,
PRIMARY KEY (`Site`,`UpdateTime`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `<API key>`;
CREATE TABLE `<API key>` (
`JobID` INT(11) UNSIGNED NOT NULL,
`Name` VARCHAR(100) NOT NULL,
`Value` BLOB NOT NULL,
`HeartBeatTime` DATETIME NOT NULL,
PRIMARY KEY (`JobID`,`Name`,`HeartBeatTime`),
FOREIGN KEY (`JobID`) REFERENCES `Jobs`(`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `JobCommands`;
CREATE TABLE `JobCommands` (
`JobID` INT(11) UNSIGNED NOT NULL,
`Command` VARCHAR(100) NOT NULL,
`Arguments` VARCHAR(100) NOT NULL,
`Status` VARCHAR(64) NOT NULL DEFAULT 'Received',
`ReceptionTime` DATETIME NOT NULL,
`ExecutionTime` DATETIME DEFAULT NULL,
PRIMARY KEY (`JobID`,`Arguments`,`ReceptionTime`),
FOREIGN KEY (`JobID`) REFERENCES `Jobs`(`JobID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
|
package coderslagoon.trupax.lib.io.filesystem.udf;
import java.util.Arrays;
import coderslagoon.baselib.util.BinUtils;
import coderslagoon.baselib.util.BytePtr;
public class DString {
public static String read(byte[] buf, int ofs, int len) throws UDFException {
int end = ofs + len - 1;
int sz = buf[end] & 0xff;
if (0 == sz) {
// if zero then all must be zero or else
for (; ofs < end; ofs++) {
if (buf[ofs] != 0) {
throw new UDFException("zero string problem");
}
}
return "";
}
if (sz > len - 1) {
throw new UDFException("invalid dstring length " + sz);
}
for (int i = ofs + sz; i < end; i++) {
if (0 != buf[i]) {
throw new UDFException("nonzero found in dstring void");
}
}
return <API key>(new BytePtr(buf, ofs, sz));
}
final static int COMPRESSION_ID_8BIT = 8;
final static int <API key> = 16;
public static void write(String str, byte[] buf, int ofs, int len) throws UDFException {
if (str.length() > 127) {
throw new UDFException("string is too long");
}
if (len < str.length() * 2 + 2) {
try {
throw new Exception();
}
catch (Exception e) {
e.printStackTrace();
}
throw new UDFException("buffer too small (%d) for string '%s'", len, str);
}
if (0 == str.length()) {
Arrays.fill(buf, ofs, ofs + len, (byte)0);
return;
}
int last = ofs + len - 1;
buf[ofs++] = <API key>;
for (char c : str.toCharArray()) {
BinUtils.writeInt16BE((short)c, buf, ofs);
ofs += 2;
}
if (ofs < last) {
java.util.Arrays.fill(buf, ofs, last, (byte)0);
}
buf[last] = (byte)((str.length() << 1) + 1);
}
// NOTE: this method should just be used for debugging, it does not honor
// any character sets; consider it to be a prototype for now in that
// regard, or as a tool to take zero padded character bytes and
// convert them into a string (hoping that it is ASCII or UTF-8)
public static String readChars(BytePtr data) throws UDFException {
boolean done = false;
int len = 0;
for (int i = 0, c = data.len; i < c; i++) {
if (done) {
if (0 != data.at(i)) {
// inconsistent padding = we might have picked up garbage
throw new UDFException("inconsistent padding");
}
}
else if (0 == data.at(i)) {
done = true;
}
else {
len++;
}
}
return new String(data.buf, data.ofs, len);
}
/**
* Reads compressed Unicode characters, either via method 8 or 16.
* @param data The raw data. First byte is the compression ID.
* @return The uncompressed string.
* @throws UDFException If the data is corrupted or the compression unknown.
*/
public static String <API key>(BytePtr data) throws UDFException {
if (!data.isValid()) {
throw new UDFException("invalid compressed unicode element (%s)", data);
}
if (0 == data.len) {
return "";
}
int cid = data.at(0) & 0x0ff;
char[] result;
byte[] buf = data.buf;
int i = data.ofs + 1;
switch(cid) {
case 8: {
result = new char[data.len - 1];
for (int c = data.end(), j = 0; i < c; i++, j++) {
result[j] = (char)(0xff & buf[i]);
}
break;
}
case <API key>: {
int len = data.len - 1;
if (0 != (len & 1)) {
throw new UDFException("truncated 16bit Unicode string. length is %d", len);
}
result = new char[len >> 1];
for (int c = data.end(), j = 0; i < c; i += 2, j++) {
result[j] = (char)BinUtils.readInt16BE(buf, i);
}
break;
}
case 254:
case 255: {
if (UDF.Compliance.is(UDF.Compliance.VISTA)) {
return "///deleted///";
}
}
default: {
throw new UDFException("invalid Unicode compression ID %d", cid);
}
}
return new String(result);
}
public static boolean needsUnicode(CharSequence cs) {
for (int i = 0, c = cs.length(); i < c; i++) {
if (0 != (0x0ff00 & cs.charAt(i))) {
return true;
}
}
return false;
}
public static int <API key>(CharSequence cs) {
return 1 + cs.length() * (needsUnicode(cs) ? 2 : 1);
}
public static BytePtr <API key>(CharSequence cs) {
int len = cs.length();
boolean unicode = needsUnicode(cs);
byte[] result;
if (unicode) {
result = new byte[1 + (len << 1)];
result[0] = <API key>;
for (int i = 0, ofs = 1; i < len; i++, ofs += 2) {
BinUtils.writeInt16BE((short)cs.charAt(i), result, ofs);
}
}
else {
result = new byte[1 + len];
result[0] = COMPRESSION_ID_8BIT;
for (int i = 0; i < len; i++) {
result[i + 1] = (byte)cs.charAt(i);
}
}
return new BytePtr(result);
}
}
|
<?php
/* {{{ proto string array_to_insql(array elements)
Returns a string of a SQL fragment to klugde around
mysql's lack of nested SELECTS. */
function array_to_insql($array) {
if (count($array))
return("IN (".ereg_replace("([^,]+)","'\\1'",join(",",$array)).")");
return 'IS NULL';
}
/* {{{ proto string <API key>(int survey_id, int section)
Returns a string of a SQL fragment to limit questions to
specified section. */
function <API key>($sid, $section, $table = '') {
if(!empty($table))
$table .= '.';
$sql = "
SELECT position
FROM question
WHERE survey_id='${sid}' AND
type_id='99' AND
deleted='N'
ORDER BY position,id";
$result = mysql_query($sql);
$num_sections = mysql_num_rows($result) + 1;
if($section > $num_sections)
return(''); // invalid section
$ret = array("${table}survey_id='${sid}'", "${table}deleted='N'");
if($section>1 && $num_sections>1)
array_push($ret, "${table}position>" . mysql_result($result,$section-2,0));
if($section<$num_sections && $num_sections>1)
array_push($ret, "${table}position<" . mysql_result($result,$section-1,0));
mysql_free_result($result);
return('WHERE ' . join(' AND ',$ret) . ' ');
}
/* {{{ proto array <API key>()
Returns an associative array of bools indicating if each
question type has answer choices. */
function <API key>() {
$has_choices = array();
$sql = 'SELECT id, has_choices FROM question_type ORDER BY id';
$result = mysql_query($sql);
while(list($tid,$answ) = mysql_fetch_row($result)) {
if($answ == 'Y')
$has_choices[$tid]=1;
else
$has_choices[$tid]=0;
}
mysql_free_result($result);
return($has_choices);
}
/* {{{ proto array <API key>()
Returns an associative array of bools indicating the
table the responses are stored in. */
function <API key>() {
$sql = 'SELECT id, response_table FROM question_type ORDER BY id';
$result = mysql_query($sql);
$response_table = array();
while(list($tid,$answ) = mysql_fetch_row($result)) {
$response_table[$tid]=$answ;
}
mysql_free_result($result);
return($response_table);
}
function sql_to_array_assoc($sql){
$array = array();
$rs = mysql_query($sql);
if (!$rs) {
echo("<br>\nInvalid query: $sql <br>\n" . mysql_error());
}
while($row = mysql_fetch_assoc($rs)){
$array[] = $row;
}
mysql_free_result($rs);
return $array;
}
function sql_to_array($sql, $col_num = 2){
$list_array = array();
$rs = mysql_query($sql);
if (!$rs) {
echo("<br>\nInvalid query: $sql <br>\n" . mysql_error());
}
if($col_num == 2){
while(list($id, $val) = mysql_fetch_row($rs)){
$list_array[$id] = $val;
}
} else if($col_num == 1){
while(list($val) = mysql_fetch_row($rs)){
$list_array[] = $val;
}
}
mysql_free_result($rs);
return $list_array;
}
function sql_to_assoc($sql){
$array = null;
$rs = mysql_query($sql);
if (!$rs) {
echo("<br>\nInvalid query: $sql <br>\n" . mysql_error());
}
if(mysql_num_rows($rs) == 1){
$row = mysql_fetch_assoc($rs);
$array = $row;
}
mysql_free_result($rs);
return $array;
}
function sql_exe($sql){
// echo($sql."<br>\n");
$str = '';
$rs = mysql_query($sql);
if (!$rs) {
echo("<br>\nInvalid query: $sql <br>\n" . mysql_error());
}
while($row = mysql_fetch_row($rs)){
$str = $row[0];
};
mysql_free_result($rs);
return $str;
}
function sqlWildcard($fieldName, $fieldValue, $operator = "AND"){
$fieldValue = trim($fieldValue);
$fieldValue = _addslashes($fieldValue);
$fieldValue = str_replace("_", "\\_", $fieldValue);
$fieldValue = str_replace("%", "\%", $fieldValue);
$fieldValue = str_replace("*", "%", $fieldValue);
if(!empty($fieldValue)){
$fieldValue = " ".$operator." $fieldName LIKE '".$fieldValue."'";
}
return $fieldValue;
}
function <API key>($sid, $type) {
$operators = array();
if(!empty($sid)){
$sql = "SELECT oid FROM eoperator_right WHERE sid = '$sid' and type='$type'";
$result = mysql_query($sql);
while (list($oId) = mysql_fetch_row($result)) {
array_push($operators, array($oId));
}
mysql_free_result($result);
}
return $operators;
}
function <API key>($sid) {
$grp = array();
if(!empty($sid)){
$sql = "SELECT oid FROM org_right WHERE sid = '$sid'";
$result = mysql_query($sql);
while (list($oId) = mysql_fetch_row($result)) {
array_push($grp, array($oId));
}
mysql_free_result($result);
}
return $grp;
}
function <API key>($user_id, &$user_name, &$dept_name){
$sql="select s.Fullname, d.dept_desc from v_survey_user s, dept_list d where s.Dept_ID = d.dept_id and s.User_id='$user_id'";
$rs = mysql_query($sql);
if(mysql_num_rows($rs) > 0){
$row = mysql_fetch_array($rs);
$user_name = $row[0];
$dept_name = $row[1];
} else {
$user_name = "-";
$dept_name = "-";
}
}
function implode_with_keys($glue, $array) {
$output = array();
foreach( $array as $key => $item )
array_push($output, $key);
return implode($glue, $output);
}
function get_rate($currency_id, $date = ''){
$rate = sql_exe("SELECT rate FROM currency_rate WHERE curr_type_id ='$currency_id' and date >= '$date' ORDER BY date LIMIT 0, 1");
//$sql = "SELECT rate FROM currency_rate WHERE curr_type_id ='$currency_id' and date <= '$date' ORDER BY date DESC LIMIT 0, 1";
if(empty($rate)) $rate = sql_exe("SELECT rate FROM currency_rate WHERE curr_type_id ='$currency_id' and date <= '$date' ORDER BY date DESC LIMIT 0, 1");
if(empty($rate)){
$rate = 1;
}
return $rate;
}
function <API key>($sql_f){
$sql_v = array();
for($i = 0; $i < sizeof($sql_f); $i++){
global ${$sql_f[$i]};
if(isset(${$sql_f[$i]})){
array_push($sql_v, ${$sql_f[$i]});
} else {
array_push($sql_v, "");
}
}
return $sql_v;
}
function gen_insert_sql($sql_f, $sql_v){
for($i = 0; $i < sizeof($sql_v); $i++){
if($sql_v[$i] === null){
$sql_v[$i] = 'NULL';
} else {
$sql_v[$i] = "'"._addslashes($sql_v[$i])."'";
}
}
$sql = "(".join(",", $sql_f).") values ";
$sql .= "(".join(",", $sql_v).")";
return $sql;
}
function gen_update_sql($sql_f, $sql_v){
for($i = 0; $i < sizeof($sql_v); $i++){
if($sql_v[$i] === null){
$sql_v[$i] = 'NULL';
} else {
$sql_v[$i] = "'"._addslashes($sql_v[$i])."'";
}
}
$sql = "set ".$sql_f[0]."=".$sql_v[0];
for($i = 1; $i < sizeof($sql_v); $i++){
$sql .= ",".$sql_f[$i]."=".$sql_v[$i];
}
return $sql;
}
function <API key>($related_tables, $fk_value, &$msg, $table_desc){
$exist = false;
for($i = 0; $i < sizeof($related_tables); $i++){
$related_table = $related_tables[$i];
$table = $related_table[0];
$field = $related_table[1];
$desc = $related_table[2];
$condition = '';
if(count($related_table) >= 4) $condition = " and ".$related_table[3];
$related_exist = (intval(sql_exe("select count(*) from $table where $field = '$fk_value'".$condition)) > 0);
if($related_exist){
if(!$exist){
$msg .= "Deletion failure. The $table_desc is NOT empty.Please delete related records in the $table_desc:<br>\n";
} else {
$msg .= "<br>\n";
}
$msg .= "<span class='errMsgSm'>- ".$desc."</span>\n";
$exist = true;
}
}
return $exist;
}
function del_related_table($related_tables, $fk_value){
for($i = 0; $i < sizeof($related_tables); $i++){
$related_table = $related_tables[$i];
$table = $related_table[0];
$field = $related_table[1];
$condition = '';
if(count($related_table) >= 3) $condition = " and ".$related_table[2];
$sql = "delete from $table where $field = '"._addslashes($fk_value)."'".$condition;
mysql_query($sql);
}
}
function del_table_by_id($table_name, $pk_field, $pk_value, &$msg, $table_desc = '', $related_tables = array(), $auto_del_tables = array(), $condition=''){
$delete_ok = true;
// check any related records
if(<API key>($related_tables, $pk_value, $msg, $table_desc)){
// error related table exist
$delete_ok = false;
} else {
// no related table, can be deleted
if($condition != '') $condition = " and ".$condition;
mysql_query("delete from $table_name where $pk_field = '$pk_value'".$condition);
if(mysql_affected_rows() == 1){
$msg .= "Delete success";
$delete_ok = true;
del_related_table($auto_del_tables, $pk_value);
}
}
return $delete_ok;
}
function get_db_max_id($table_name, $id_field_name, $condition = ""){
$sql = "select max($id_field_name) from $table_name";
if(!empty($condition)){
$sql .= " where $condition";
}
$max_id = sql_exe($sql);
if(empty($max_id)) $max_id = 0;
return $max_id;
}
function <API key>($size){
$sort_order_select = array();
for($i = 1; $i <= $size ; $i++){
$sort_order_select[$i] = $i;
}
return $sort_order_select;
}
function sort_order($table_name, $id_field_name, $sort_field_name, $fr_order, $to_order, $condition = ''){
if(!empty($table_name)
&& !empty($id_field_name)
&& !empty($sort_field_name)
&& !empty($fr_order)
&& !empty($to_order)){
// $group_id = intval($group_id);
$fr_order = intval($fr_order);
$to_order = intval($to_order);
if($fr_order == $to_order) return ; // return if "number of from" == "number of to"
$ori_condition = '';
if(!empty($condition)){
$ori_condition = " and ($condition)";
$condition = " where ($condition)";
}
$new_id = 0;
$new_order = 0;
if($fr_order > $to_order){
//$sql = "select $id_field_name, $sort_field_name from $table_name $condition order by $sort_field_name limit ".($to_order -1).", ".($fr_order - $to_order + 1);
$sql = "select $id_field_name, $sort_field_name from $table_name $condition order by $sort_field_name LIMIT 0, $fr_order";
$rs = mysql_query($sql);
$i = 0;
$curr_row = 0;
while($row = mysql_fetch_row($rs)){
$curr_row++;
if($curr_row < $to_order) continue;
if($i == 0) $new_order = $row[1];
$new_id = $row[0];
$sql2 = "update $table_name set $sort_field_name=".(intval($row[1])+1)." where $id_field_name='"._addslashes($row[0])."'".$ori_condition;
//echo("<br> $sql2");
mysql_query($sql2);
$i++;
}
} else {
//$sql = "select $id_field_name, $sort_field_name from $table_name $condition order by $sort_field_name limit ".($fr_order -1).", ".($to_order - $fr_order + 1);
$sql = "select $id_field_name, $sort_field_name from $table_name $condition order by $sort_field_name LIMIT 0, $to_order";
$rs = mysql_query($sql);
$curr_row = 0;
$i = 0;
while($row = mysql_fetch_row($rs)){
$curr_row++;
if($curr_row < $fr_order) continue;
if($i == 0) $new_id = $row[0];
$new_order = $row[1];
//echo("update $table_name set $sort_field_name=".(intval($row[1])-1)." where $id_field_name=".$row[0]."<br>\n");
mysql_query("update $table_name set $sort_field_name=".(intval($row[1])-1)." where $id_field_name='"._addslashes($row[0])."'".$ori_condition);
$i++;
}
}
mysql_query("update $table_name set $sort_field_name=".$new_order." where $id_field_name='"._addslashes($new_id)."'".$ori_condition);
}
}
function saveContactChange($form_no){
$slashed_form_no = _addslashes($form_no);
$sql = "select count(*) from contact_info where form_no='$slashed_form_no'";
$existing_count = intval(sql_exe($sql));
if($existing_count > 0){
$sql = "delete from contact_info where form_no='$slashed_form_no'";
mysql_query($sql);
dbLog($sql);
}
$sql_f = array("form_no");
$sql_v = array($form_no);
for($i = 1; $i <= 4; $i++){
$sql_f[] = "<API key>".$i;
$sql_f[] = "<API key>".$i;
$sql_f[] = "contact_info_post_".$i;
$sql_f[] = "contact_info_email_".$i;
$sql_v[] = getPost("<API key>".$i);
$sql_v[] = getPost("<API key>".$i);
$sql_v[] = getPost("contact_info_post_".$i);
$sql_v[] = getPost("contact_info_email_".$i);
}
$sql = "insert into contact_info ".gen_insert_sql($sql_f, $sql_v);
mysql_query($sql);
$mysql_affected_rows = mysql_affected_rows();
dbLog($sql);
if($mysql_affected_rows != 1) die("error: $sql");
}
function <API key>($form_no){
$error_found = "";
$check_fields = array("<API key>" => "English Name", "<API key>"=>"Chinese Name", "contact_info_post"=>"Post", "contact_info_email"=>"Email");
$contact_obj = sql_to_assoc("select * from contact_info where form_no='"._addslashes($form_no)."'");
for($i = 1; $i <= 4; $i++){
foreach($check_fields as $c_f=> $c_title){
if($contact_obj[$c_f."_".$i] != getPost($c_f."_".$i)){
$error_found = "Contact Persion ($i) $c_title not match (".$contact_obj[$c_f."_".$i].")";
break;
}
}
if($error_found != "") break;
}
return $error_found;
}
?>
|
# -*- coding: utf-8 -*-
from module.plugins.internal.DeadCrypter import DeadCrypter
class FilebeerInfoFolder(DeadCrypter):
__name__ = "FilebeerInfoFolder"
__type__ = "crypter"
__pattern__ = r"http://(?:www\.)?filebeer\.info/(\d+~f).*"
__version__ = "0.02"
__description__ = """Filebeer.info Folder Plugin"""
__author_name__ = ("zoidberg")
__author_mail__ = ("zoidberg@mujmail.cz")
|
// Unarmed
class I_MRAP_03_F;
class Inegal_VAB_Unarmed: I_MRAP_03_F {
scope = 2;
side = 0;
faction = "UKSF_Inegal";
displayName = "VAB Unarmed";
editorPreview = QPATHTOEF(common,data\previews\Inegal_VAB_Unarmed.jpg);
crew = "Inegal_Crew_C";
typicalCargo[] = {
"Inegal_Crew_C"
};
<API key>[] = { "\a3\soft_f_beta\MRAP_03\Data\mrap_03_ext_co.paa", "\a3\data_f\vehicles\turret_co.paa" };
class TransportMagazines {};
class TransportItems {};
class TransportWeapons {};
class TransportBackpacks {};
};
class <API key>: Inegal_VAB_Unarmed {
displayName = "VAB Unarmed (Diablerie)";
crew = "Inegal_Diablerie_Se";
typicalCargo[] = {
"Inegal_Diablerie_Se"
};
};
// HMG
class I_MRAP_03_hmg_F;
class Inegal_VAB_HMG: I_MRAP_03_hmg_F {
scope = 2;
side = 0;
faction = "UKSF_Inegal";
displayName = "VAB HMG";
editorPreview = QPATHTOEF(common,data\previews\Inegal_VAB_HMG.jpg);
crew = "Inegal_F";
typicalCargo[] = {
"Inegal_F"
};
<API key>[] = { "\a3\soft_f_beta\MRAP_03\Data\mrap_03_ext_co.paa", "\a3\data_f\vehicles\turret_co.paa" };
class TransportMagazines {};
class TransportItems {};
class TransportWeapons {};
class TransportBackpacks {};
};
class Inegal_VAB_D_HMG: Inegal_VAB_HMG {
displayName = "VAB HMG (Diablerie)";
crew = "Inegal_Diablerie_Se";
typicalCargo[] = {
"Inegal_Diablerie_Se"
};
};
// GMG
class I_MRAP_03_gmg_F;
class Inegal_VAB_GMG: I_MRAP_03_gmg_F {
scope = 2;
side = 0;
faction = "UKSF_Inegal";
displayName = "VAB GMG";
editorPreview = QPATHTOEF(common,data\previews\Inegal_VAB_GMG.jpg);
crew = "Inegal_F";
typicalCargo[] = {
"Inegal_F"
};
<API key>[] = { "\a3\soft_f_beta\MRAP_03\Data\mrap_03_ext_co.paa", "\a3\data_f\vehicles\turret_co.paa" };
class TransportMagazines {};
class TransportItems {};
class TransportWeapons {};
class TransportBackpacks {};
};
class Inegal_VAB_D_GMG: Inegal_VAB_GMG {
displayName = "VAB GMG (Diablerie)";
crew = "Inegal_Diablerie_Se";
typicalCargo[] = {
"Inegal_Diablerie_Se"
};
};
|
nav>.sf-menu {
z-index: 990;
text-align: left;
position: relative;
float: right;
}
nav {
margin: 0;
position:relative;
padding: 0;
float: right;
width: 100%;
}
.sf-menu ul {
position:absolute;
top:-999px;
display:none;
}
.sf-menu li {
float:left;
position:relative;
}
.sf-menu>li {
display: block;
position: relative;
float: left;
text-transform: uppercase;
}
.sf-menu>li+li {
margin-left:1px;
}
.sf-menu>li>ul>li {
float: none;
position: static;
}
.sf-menu>li>a{
display: block;
text-align: center;
position: relative;
color: #3d3d3d;
font: 400 13px/80px 'Lato', sans-serif;
text-transform: uppercase;
text-decoration: none;
padding: 0 13px;
letter-spacing: -.1px;
}
.sf-menu>li>a:hover,
.sf-menu>li.current>a {
position: relative;
text-decoration: none;
background: #fff;
color: #ff6536;
}
.sf-menu>li>a.sf-with-ul:after {
position: absolute;
content: '';
left: 46%;
top: 83px;
width: 8px;
background: url(../images/arrow_menu.png) 0 0 no-repeat;
height: 5px;
pointer-events: none;
z-index: 999;
display: block;
}
.sf-menu>li>ul>li>a.sf-with-ul:after {
content: '';
position: absolute;
display: none;
width: 7px;
height: 6px;
right: 20px;
bottom: 11px;
pointer-events: none;
z-index: 999;
}
.sf-with-ul:after {background-position: 0 bottom;}
.sf-menu li ul {
position: absolute;
z-index: 999;
top: 80px;
left: 0;
padding: 0;
width: 162px;
background: #999999;
}
.sf-menu li ul li{
position: relative;
text-align: left;
float: none !important;
cursor: default;
line-height: 39px;
padding-left: 13px;
padding-bottom: 1px;
}
.sf-menu li ul li+li {
border-top: 1px #565656;
line-height: 20px;
padding-bottom: 20px;
}
.sf-menu li ul li a{
position: relative;
text-transform: uppercase;
z-index: 999;
display: inline;
color: #cccccc;
font: normal 11px/14px 'Lato';
padding: 0;
text-decoration: none;
}
.sf-menu>li>ul>li>a.sf-with-ul:after {
position: absolute;
content: '';
right: -50px;
width: 9px;
background: url(../images/arrow_menu.png) 0 0px no-repeat;
height: 5px;
top: 4px;
pointer-events: none;
z-index: 999;
display: block;
}
.sf-menu li li a:hover {
text-decoration: none;
color: #fff;
}
.sf-menu li ul li ul{
position: absolute;
left: 163px;
top: 0px;
background: #999999;
padding: 0;
}
.sf-menu li ul li ul li a {
color: #cccccc;
}
.sf-menu li ul li a:hover {
color: #fff;
}
@media only screen and (max-width: 1199px) {
}
@media only screen and (max-width: 995px) {
.sf-menu > li > a {
font-size: 16px;
padding-left: 10px;
padding-right: 10px;
}
.bottom_menu ul li a {font-size: 13px;}
}
@media only screen and (max-width: 767px) {
header nav{
border: none !important;
float:none !important;
font:12px/15px Arial, Helvetica, sans-serif;
text-transform:uppercase;
color:#927c67;
margin: 0 auto;
}
header nav ul {border: none;}
.sf-menu {
display:none !important;
float: none;
}
#mm0{
font: 400 12px/15px 'Arial', Helvetica, sans-serif;
background: #fff;
padding: 1px 0;
color:#000;
width:100%;
margin: 10px auto 20px;
float: none;
outline: none;
border: 2px solid #000;
}
}
|
import components from './components'
export default { components }
|
package org.structr.bolt;
import java.util.Iterator;
import java.util.Map;
abstract class <API key><T> implements Iterable<T> {
private Iterable<T> result = null;
private CypherQuery query = null;
private Iterator<T> current = null;
private BoltDatabaseService db = null;
protected abstract Iterable<T> fetchData(final BoltDatabaseService db, final String statement, final Map<String, Object> data);
public <API key>(final BoltDatabaseService db, final CypherQuery query) {
this.query = query;
this.db = db;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int remaining = 0;
@Override
public boolean hasNext() {
if (current == null || !current.hasNext()) {
// fetch more?
if (remaining == 0) {
// reset count
remaining = query.pageSize();
final String statement = query.getStatement(true);
final Map<String, Object> params = query.getParameters();
result = fetchData(db, statement, params);
if (result != null) {
current = result.iterator();
// advance page
query.nextPage();
// does the next result have elements?
if (!current.hasNext()) {
// no more elements
return false;
}
}
}
}
return current != null && current.hasNext();
}
@Override
public T next() {
remaining
return current.next();
}
};
}
public CypherQuery getQuery() {
return query;
}
}
|
#include "messageprocessor.h"
#include <QVariant>
#include <QTextCursor>
#include <definitions/messagedataroles.h>
#include <definitions/messagewriterorders.h>
#include <definitions/<API key>.h>
#include <utils/logger.h>
#define SHC_MESSAGE "/message"
MessageProcessor::MessageProcessor()
{
FXmppStreams = NULL;
FStanzaProcessor = NULL;
FNotifications = NULL;
}
MessageProcessor::~MessageProcessor()
{
}
void MessageProcessor::pluginInfo(IPluginInfo *APluginInfo)
{
APluginInfo->name = tr("Message Manager");
APluginInfo->description = tr("Allows other modules to send and receive messages");
APluginInfo->version = "1.0";
APluginInfo->author = "Potapov S.A. aka Lion";
APluginInfo->homePage = "http:
APluginInfo->dependences.append(XMPPSTREAMS_UUID);
APluginInfo->dependences.append(<API key>);
}
bool MessageProcessor::initConnections(IPluginManager *APluginManager, int &AInitOrder)
{
Q_UNUSED(AInitOrder);
IPlugin *plugin = APluginManager->pluginInterface("IXmppStreams").value(0,NULL);
if (plugin)
{
FXmppStreams = qobject_cast<IXmppStreams *>(plugin->instance());
if (FXmppStreams)
{
connect(FXmppStreams->instance(),SIGNAL(added(IXmppStream *)),SLOT(onXmppStreamAdded(IXmppStream *)));
connect(FXmppStreams->instance(),SIGNAL(removed(IXmppStream *)),SLOT(onXmppStreamRemoved(IXmppStream *)));
connect(FXmppStreams->instance(),SIGNAL(jidChanged(IXmppStream *, const Jid &)),SLOT(<API key>(IXmppStream *, const Jid &)));
}
}
plugin = APluginManager->pluginInterface("IStanzaProcessor").value(0,NULL);
if (plugin)
{
FStanzaProcessor = qobject_cast<IStanzaProcessor *>(plugin->instance());
}
plugin = APluginManager->pluginInterface("INotifications").value(0,NULL);
if (plugin)
{
FNotifications = qobject_cast<INotifications *>(plugin->instance());
if (FNotifications)
{
connect(FNotifications->instance(),SIGNAL(<API key>(int)), SLOT(<API key>(int)));
connect(FNotifications->instance(),SIGNAL(notificationRemoved(int)), SLOT(<API key>(int)));
}
}
return FStanzaProcessor!=NULL && FXmppStreams!=NULL;
}
bool MessageProcessor::initObjects()
{
insertMessageWriter(<API key>,this);
insertMessageWriter(<API key>,this);
return true;
}
bool MessageProcessor::stanzaReadWrite(int AHandlerId, const Jid &AStreamJid, Stanza &AStanza, bool &AAccept)
{
if (FActiveStreams.value(AStreamJid) == AHandlerId)
{
Message message(AStanza);
AAccept = sendMessage(AStreamJid,message,IMessageProcessor::DirectionIn) || AAccept;
}
return false;
}
void MessageProcessor::writeTextToMessage(int AOrder, Message &AMessage, QTextDocument *ADocument, const QString &ALang)
{
if (AOrder == <API key>)
{
AMessage.setBody(prepareBodyForSend(ADocument->toPlainText()),ALang);
}
}
void MessageProcessor::writeMessageToText(int AOrder, Message &AMessage, QTextDocument *ADocument, const QString &ALang)
{
if (AOrder == <API key>)
{
QTextCursor cursor(ADocument);
cursor.insertHtml(<API key>(AMessage.body(ALang)));
}
else if (AOrder == <API key>)
{
QRegExp regexp("\\b((https?|ftp)://|www\\.|xmpp:|magnet:|mailto:)\\S+\\b");
regexp.setCaseSensitivity(Qt::CaseInsensitive);
for (QTextCursor cursor = ADocument->find(regexp); !cursor.isNull(); cursor = ADocument->find(regexp,cursor))
{
QString link = cursor.selectedText();
if (QUrl(link).scheme().isEmpty())
link.prepend("http:
QTextCharFormat linkFormat = cursor.charFormat();
linkFormat.setAnchor(true);
linkFormat.setAnchorHref(link);
cursor.setCharFormat(linkFormat);
}
}
}
QList<Jid> MessageProcessor::activeStreams() const
{
return FActiveStreams.keys();
}
bool MessageProcessor::isActiveStream(const Jid &AStreamJid) const
{
return FActiveStreams.contains(AStreamJid);
}
void MessageProcessor::appendActiveStream(const Jid &AStreamJid)
{
if (FStanzaProcessor && AStreamJid.isValid() && !FActiveStreams.contains(AStreamJid))
{
IStanzaHandle shandle;
shandle.handler = this;
shandle.order = SHO_DEFAULT;
shandle.direction = IStanzaHandle::DirectionIn;
shandle.streamJid = AStreamJid;
shandle.conditions.append(SHC_MESSAGE);
FActiveStreams.insert(shandle.streamJid,FStanzaProcessor->insertStanzaHandle(shandle));
emit <API key>(AStreamJid);
}
}
void MessageProcessor::removeActiveStream(const Jid &AStreamJid)
{
if (FStanzaProcessor && FActiveStreams.contains(AStreamJid))
{
FStanzaProcessor->removeStanzaHandle(FActiveStreams.take(AStreamJid));
foreach(int notifyId, FNotifyId2MessageId.keys())
{
INotification notify = FNotifications->notificationById(notifyId);
if (AStreamJid == notify.data.value(NDR_STREAM_JID).toString())
removeMessageNotify(FNotifyId2MessageId.value(notifyId));
}
emit activeStreamRemoved(AStreamJid);
}
}
bool MessageProcessor::sendMessage(const Jid &AStreamJid, Message &AMessage, int ADirection)
{
if (processMessage(AStreamJid,AMessage,ADirection))
{
if (ADirection == IMessageProcessor::DirectionOut)
{
Stanza stanza = AMessage.stanza(); // Ignore changes in StanzaProcessor
if (FStanzaProcessor && FStanzaProcessor->sendStanzaOut(AStreamJid,stanza))
{
displayMessage(AStreamJid,AMessage,ADirection);
emit messageSent(AMessage);
return true;
}
}
else
{
displayMessage(AStreamJid,AMessage,ADirection);
emit messageReceived(AMessage);
return true;
}
}
return false;
}
bool MessageProcessor::processMessage(const Jid &AStreamJid, Message &AMessage, int ADirection)
{
if (ADirection == IMessageProcessor::DirectionIn)
AMessage.setTo(AStreamJid.full());
else
AMessage.setFrom(AStreamJid.full());
if (AMessage.data(MDR_MESSAGE_ID).isNull())
AMessage.setData(MDR_MESSAGE_ID,newMessageId());
AMessage.setData(<API key>,ADirection);
bool hooked = false;
QMapIterator<int,IMessageEditor *> it(FMessageEditors);
ADirection == DirectionIn ? it.toFront() : it.toBack();
while (!hooked && (ADirection==DirectionIn ? it.hasNext() : it.hasPrevious()))
{
ADirection == DirectionIn ? it.next() : it.previous();
hooked = it.value()->messageReadWrite(it.key(), AStreamJid, AMessage, ADirection);
}
return !hooked;
}
bool MessageProcessor::displayMessage(const Jid &AStreamJid, Message &AMessage, int ADirection)
{
Q_UNUSED(AStreamJid);
IMessageHandler *handler = findMessageHandler(AMessage,ADirection);
if (handler)
{
if (handler->messageDisplay(AMessage,ADirection))
{
notifyMessage(handler,AMessage,ADirection);
return true;
}
}
return false;
}
QList<int> MessageProcessor::notifiedMessages() const
{
return FNotifiedMessages.keys();
}
Message MessageProcessor::notifiedMessage(int AMesssageId) const
{
return FNotifiedMessages.value(AMesssageId);
}
int MessageProcessor::notifyByMessage(int AMessageId) const
{
return FNotifyId2MessageId.key(AMessageId,-1);
}
int MessageProcessor::messageByNotify(int ANotifyId) const
{
return FNotifyId2MessageId.value(ANotifyId,-1);
}
void MessageProcessor::showNotifiedMessage(int AMessageId)
{
IMessageHandler *handler = FHandlerForMessage.value(AMessageId,NULL);
if (handler)
handler->messageShowWindow(AMessageId);
}
void MessageProcessor::removeMessageNotify(int AMessageId)
{
int notifyId = FNotifyId2MessageId.key(AMessageId);
if (notifyId > 0)
{
FNotifiedMessages.remove(AMessageId);
FNotifyId2MessageId.remove(notifyId);
FHandlerForMessage.remove(AMessageId);
FNotifications->removeNotification(notifyId);
emit <API key>(AMessageId);
}
}
void MessageProcessor::textToMessage(Message &AMessage, const QTextDocument *ADocument, const QString &ALang) const
{
QTextDocument *documentCopy = ADocument->clone();
QMapIterator<int,IMessageWriter *> it(FMessageWriters);
it.toBack();
while (it.hasPrevious())
{
it.previous();
it.value()->writeTextToMessage(it.key(),AMessage,documentCopy,ALang);
}
delete documentCopy;
}
void MessageProcessor::messageToText(QTextDocument *ADocument, const Message &AMessage, const QString &ALang) const
{
Message messageCopy = AMessage;
QMapIterator<int,IMessageWriter *> it(FMessageWriters);
it.toFront();
while (it.hasNext())
{
it.next();
it.value()->writeMessageToText(it.key(),messageCopy,ADocument,ALang);
}
}
bool MessageProcessor::createMessageWindow(const Jid &AStreamJid, const Jid &AContactJid, Message::MessageType AType, int AShowMode) const
{
for (QMultiMap<int, IMessageHandler *>::const_iterator it = FMessageHandlers.constBegin(); it!=FMessageHandlers.constEnd(); ++it)
if (it.value()->messageShowWindow(it.key(),AStreamJid,AContactJid,AType,AShowMode))
return true;
return false;
}
QMultiMap<int, IMessageHandler *> MessageProcessor::messageHandlers() const
{
return FMessageHandlers;
}
void MessageProcessor::<API key>(int AOrder, IMessageHandler *AHandler)
{
if (AHandler && !FMessageHandlers.contains(AOrder,AHandler))
FMessageHandlers.insertMulti(AOrder,AHandler);
}
void MessageProcessor::<API key>(int AOrder, IMessageHandler *AHandler)
{
if (FMessageHandlers.contains(AOrder,AHandler))
FMessageHandlers.remove(AOrder,AHandler);
}
QMultiMap<int, IMessageWriter *> MessageProcessor::messageWriters() const
{
return FMessageWriters;
}
void MessageProcessor::insertMessageWriter(int AOrder, IMessageWriter *AWriter)
{
if (AWriter && !FMessageWriters.contains(AOrder,AWriter))
FMessageWriters.insertMulti(AOrder,AWriter);
}
void MessageProcessor::removeMessageWriter(int AOrder, IMessageWriter *AWriter)
{
if (FMessageWriters.contains(AOrder,AWriter))
FMessageWriters.remove(AOrder,AWriter);
}
QMultiMap<int, IMessageEditor *> MessageProcessor::messageEditors() const
{
return FMessageEditors;
}
void MessageProcessor::insertMessageEditor(int AOrder, IMessageEditor *AEditor)
{
if (AEditor && !FMessageEditors.contains(AOrder,AEditor))
FMessageEditors.insertMulti(AOrder,AEditor);
}
void MessageProcessor::removeMessageEditor(int AOrder, IMessageEditor *AEditor)
{
if (FMessageEditors.contains(AOrder,AEditor))
FMessageEditors.remove(AOrder,AEditor);
}
int MessageProcessor::newMessageId()
{
static int messageId = 1;
return messageId++;
}
IMessageHandler *MessageProcessor::findMessageHandler(const Message &AMessage, int ADirection)
{
for (QMultiMap<int, IMessageHandler *>::const_iterator it = FMessageHandlers.constBegin(); it!=FMessageHandlers.constEnd(); ++it)
if (it.value()->messageCheck(it.key(),AMessage,ADirection))
return it.value();
return NULL;
}
void MessageProcessor::notifyMessage(IMessageHandler *AHandler, const Message &AMessage, int ADirection)
{
if (FNotifications && AHandler)
{
INotification notify = AHandler->messageNotify(FNotifications, AMessage, ADirection);
if (notify.kinds > 0)
{
int notifyId = FNotifications->appendNotification(notify);
int messageId = AMessage.data(MDR_MESSAGE_ID).toInt();
FNotifiedMessages.insert(messageId,AMessage);
FNotifyId2MessageId.insert(notifyId,messageId);
FHandlerForMessage.insert(messageId,AHandler);
emit <API key>(messageId);
}
}
}
QString MessageProcessor::prepareBodyForSend(const QString &AString) const
{
QString result = AString;
result.remove(QChar::Null);
result.remove(QChar::<API key>);
return result;
}
QString MessageProcessor::<API key>(const QString &AString) const
{
QString result = Qt::escape(AString);
result.replace('\n',"<br>");
result.replace(" "," ");
result.replace('\t'," ");
return result;
}
void MessageProcessor::<API key>(int ANotifyId)
{
if (FNotifyId2MessageId.contains(ANotifyId))
showNotifiedMessage(FNotifyId2MessageId.value(ANotifyId));
}
void MessageProcessor::<API key>(int ANotifyId)
{
if (FNotifyId2MessageId.contains(ANotifyId))
removeMessageNotify(FNotifyId2MessageId.value(ANotifyId));
}
void MessageProcessor::onXmppStreamAdded(IXmppStream *AXmppStream)
{
appendActiveStream(AXmppStream->streamJid());
}
void MessageProcessor::onXmppStreamRemoved(IXmppStream *AXmppStream)
{
removeActiveStream(AXmppStream->streamJid());
}
void MessageProcessor::<API key>(IXmppStream *AXmppStream, const Jid &ABefore)
{
if (FActiveStreams.contains(ABefore))
{
int handleId = FActiveStreams.take(ABefore);
FActiveStreams.insert(AXmppStream->streamJid(),handleId);
}
}
Q_EXPORT_PLUGIN2(<API key>, MessageProcessor)
|
package github.daneren2005.dsub.view.compat;
import android.support.v7.app.<API key>;
import android.support.v7.app.<API key>;
import android.support.v7.app.<API key>;
public class <API key> extends <API key> {
@Override
public <API key> <API key>() {
return new <API key>();
}
@Override
public <API key> <API key>() {
return new <API key>();
}
}
|
package com.risevision.ui.client.common.widgets.demographics;
import com.risevision.ui.client.common.widgets.<API key>;
public class <API key> extends <API key> {
public <API key>() {
super();
loadData();
}
private void loadData() {
addItem("Consulting", "consulting");
addItem("Creative Design", "creativeDesign");
addItem("Advertising Sales and Management", "advertising");
addItem("Web Design and Development", "webDesign");
addItem("Installation", "installation");
addItem("Training", "training");
addItem("Support", "support");
addItem("Service", "service");
addItem("Display Sales", "displaySales");
addItem("Computer Sales", "computerSales");
addOther();
}
}
|
<?php defined('SYSPATH') or die('No direct script access.');?>
<div class="page-header">
<?if ($category!==NULL):?>
<h1><?=$category->translate_name()?></h1>
<?elseif ($location!==NULL):?>
<h1><?=$location->translate_name()?></h1>
<?else:?>
<h1><?=_e('Listings')?></h1>
<?endif?>
</div>
<div class="well blog-description" id="recomentadion">
<?if (Controller::$image!==NULL AND Theme::get('<API key>')!=1):?>
<img src="<?=Controller::$image?>" class="img-responsive" alt="<?=($category!==NULL) ? HTML::chars($category->translate_name()) : (($location!==NULL AND $category===NULL) ? HTML::chars($location->translate_name()) : NULL)?>">
<?endif?>
<p>
<?if ($category!==NULL):?>
<?=$category-><API key>()?>
<?elseif ($location!==NULL):?>
<?=$location-><API key>()?>
<?endif?>
</p>
<?if (Core::config('advertisement.only_admin_post')!=1 AND (core::config('advertisement.parent_category')==1)):?>
<i class="glyphicon glyphicon-pencil"></i>
<a title="<?=__('New Advertisement')?>"
href="<?=Route::url('post_new')?>?category=<?=($category!==NULL)?$category->seoname:''?>&location=<?=($location!==NULL)?$location->seoname:''?>">
<?=_e('Publish new advertisement')?>
</a>
<?endif?>
</div><!--end of recomentadion
<?if(core::count($ads)):?>
<div class="btn-group pull-right">
<?if(core::config('general.auto_locate')):?>
<button
class="btn btn-sm btn-default <?=core::request('userpos') == 1 ? 'active' : NULL?>"
id="myLocationBtn"
type="button"
data-toggle="modal"
data-target="#myLocation"
data-marker-title="<?=__('My Location')?>"
data-marker-error="<?=__('Cannot determine address at this location.')?>"
data-href="?<?=http_build_query(['userpos' => 1] + Request::current()->query())?>">
<i class="glyphicon <API key>"></i> <?=sprintf(__('%s from you'), i18n::format_measurement(Core::cookie('mydistance', Core::config('advertisement.<API key>', 2))))?>
</button>
<?endif?>
<?if (core::config('advertisement.map')==1):?>
<a href="
class="btn btn-default btn-sm"
data-toggle="modal" data-target="#listingMap">
<span class="glyphicon glyphicon-globe"></span> <?=_e('Map')?>
</a>
<?endif?>
<div class="btn-group">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?=_e('Show').' '.core::request('items_per_page').' '._e('items per page')?> <span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu" id="show-list">
<li><a href="?<?=http_build_query(['items_per_page' => '5'] + Request::current()->query())?>"> 5 <?=_e('per page')?></a></li>
<li><a href="?<?=http_build_query(['items_per_page' => '10'] + Request::current()->query())?>"> 10 <?=_e('per page')?></a></li>
<li><a href="?<?=http_build_query(['items_per_page' => '20'] + Request::current()->query())?>"> 20 <?=_e('per page')?></a></li>
<li><a href="?<?=http_build_query(['items_per_page' => '50'] + Request::current()->query())?>"> 50 <?=_e('per page')?></a></li>
<li><a href="?<?=http_build_query(['items_per_page' => '100'] + Request::current()->query())?>">100 <?=_e('per page')?></a></li>
</ul>
</div>
<button type="button" id="sort" data-sort="<?=core::request('sort',core::config('advertisement.sort_by'))?>" class="btn btn-info btn-sm dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-list-alt"></span> <?=_e('Sort')?> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" id="sort-list">
<li><a href="?<?=http_build_query(['sort' => 'title-asc'] + Request::current()->query())?>"><?=_e('Name (A-Z)')?></a></li>
<li><a href="?<?=http_build_query(['sort' => 'title-desc'] + Request::current()->query())?>"><?=_e('Name (Z-A)')?></a></li>
<?if(core::config('advertisement.price')!=FALSE):?>
<li><a href="?<?=http_build_query(['sort' => 'price-asc'] + Request::current()->query())?>"><?=_e('Price (Low)')?></a></li>
<li><a href="?<?=http_build_query(['sort' => 'price-desc'] + Request::current()->query())?>"><?=_e('Price (High)')?></a></li>
<?endif?>
<li><a href="?<?=http_build_query(['sort' => 'featured'] + Request::current()->query())?>"><?=_e('Featured')?></a></li>
<li><a href="?<?=http_build_query(['sort' => 'favorited'] + Request::current()->query())?>"><?=_e('Favorited')?></a></li>
<?if(core::config('general.auto_locate')):?>
<li><a href="?<?=http_build_query(['sort' => 'distance'] + Request::current()->query())?>" id="sort-distance"><?=_e('Distance')?></a></li>
<?endif?>
<li><a href="?<?=http_build_query(['sort' => 'published-desc'] + Request::current()->query())?>"><?=_e('Newest')?></a></li>
<li><a href="?<?=http_build_query(['sort' => 'published-asc'] + Request::current()->query())?>"><?=_e('Oldest')?></a></li>
</ul>
</div>
<div class="clearfix"></div>
<?foreach($ads as $ad ):?>
<?if($ad->featured >= Date::unix2mysql(time())):?>
<article class="list well clearfix featured ">
<span class="label label-danger pull-right"><?=_e('Featured')?></span>
<?else:?>
<article class="list well clearfix">
<?endif?>
<div class="pull-right favorite" id="fav-<?=$ad->id_ad?>">
<?if (Auth::instance()->logged_in()):?>
<?$fav = Model_Favorite::is_favorite($user,$ad);?>
<a data-id="fav-<?=$ad->id_ad?>" class="add-favorite <?=($fav)?'remove-favorite':''?>" title="<?=__('Add to Favorites')?>" href="<?=Route::url('oc-panel', array('controller'=>'profile', 'action'=>'favorites','id'=>$ad->id_ad))?>">
<i class="glyphicon glyphicon-heart<?=($fav)?'':'-empty'?>"></i>
</a>
<?else:?>
<a data-toggle="modal" data-dismiss="modal" href="<?=Route::url('oc-panel',array('directory'=>'user','controller'=>'auth','action'=>'login'))?>#login-modal">
<i class="glyphicon <API key>"></i>
</a>
<?endif?>
</div>
<?if($ad->id_location != 1):?>
<a href="<?=Route::url('list',array('location'=>$ad->location->seoname))?>" title="<?=HTML::chars($ad->location->translate_name())?>">
<span class="label label-default"><?=$ad->location->translate_name()?></span>
</a>
<?endif?>
<h2>
<a title="<?=HTML::chars($ad->title)?>" href="<?=Route::url('ad', array('controller'=>'ad','category'=>$ad->category->seoname,'seotitle'=>$ad->seotitle))?>">
<?=$ad->title?>
</a>
</h2>
<div class="picture">
<a class="pull-left" title="<?=HTML::chars($ad->title)?>" href="<?=Route::url('ad', array('controller'=>'ad','category'=>$ad->category->seoname,'seotitle'=>$ad->seotitle))?>">
<figure>
<?if($ad->get_first_image() !== NULL):?>
<img src="<?=Core::imagefly($ad->get_first_image(),150,150)?>" alt="<?=HTML::chars($ad->title)?>" />
<?elseif(( $icon_src = $ad->category->get_icon() )!==FALSE ):?>
<img src="<?=Core::imagefly($icon_src,150,150)?>" class="img-responsive" alt="<?=HTML::chars($ad->title)?>" />
<?elseif(( $icon_src = $ad->location->get_icon() )!==FALSE ):?>
<img src="<?=Core::imagefly($icon_src,150,150)?>" class="img-responsive" alt="<?=HTML::chars($ad->title)?>" />
<?else:?>
<img data-src="holder.js/150x150?<?=str_replace('+', ' ', http_build_query(array('text' => $ad->category->translate_name(), 'size' => 14, 'auto' => 'yes')))?>" class="img-responsive" alt="<?=HTML::chars($ad->title)?>">
<?endif?>
</figure>
</a>
</div>
<ul>
<?if (core::request('sort') == 'distance' AND Model_User::get_userlatlng()) :?>
<li><b><?=_e('Distance');?>:</b> <?=i18n::format_measurement($ad->distance)?></li>
<?endif?>
<?if ($ad->published!=0){?>
<li><b><?=_e('Publish Date');?>:</b> <?=Date::format($ad->published, core::config('general.date_format'))?></li>
<? }?>
<?if ($ad->price!=0){?>
<li class="price"><?=_e('Price');?>: <b><span class="price-curry"><?=i18n::money_format( $ad->price, $ad->currency() )?></span></b></li>
<?}?>
<?if ($ad->price==0 AND core::config('advertisement.free')==1){?>
<li class="price"><?=_e('Price');?>: <b><?=_e('Free');?></b></li>
<?}?>
</ul>
<?if(core::config('advertisement.description')!=FALSE):?>
<p><?=Text::limit_chars(Text::removebbcode($ad->description), 255, NULL, TRUE);?></p>
<?endif?>
<a title="<?=HTML::chars($ad->seotitle);?>" href="<?=Route::url('ad', array('controller'=>'ad','category'=>$ad->category->seoname,'seotitle'=>$ad->seotitle))?>"><i class="glyphicon glyphicon-share"></i><?=_e('Read more')?></a>
<?if ($user !== NULL AND ($user->is_admin() OR $user->is_moderator())):?>
<br />
<div class="toolbar btn btn-primary btn-xs"><i class="glyphicon glyphicon-cog"></i>
<div id="<API key><?=$ad->id_ad?>" class="hide <API key>">
<a class="btn btn-primary btn-xs" href="<?=Route::url('oc-panel', array('controller'=>'myads','action'=>'update','id'=>$ad->id_ad))?>"><i class="glyphicon glyphicon-edit"></i> <?=_e("Edit");?></a> |
<a class="btn btn-primary btn-xs" href="<?=Route::url('oc-panel', array('controller'=>'ad','action'=>'deactivate','id'=>$ad->id_ad))?>"
onclick="return confirm('<?=__('Deactivate?')?>');"><i class="glyphicon glyphicon-off"></i><?=_e("Deactivate");?>
</a> |
<a class="btn btn-primary btn-xs" href="<?=Route::url('oc-panel', array('controller'=>'ad','action'=>'spam','id'=>$ad->id_ad))?>"
onclick="return confirm('<?=__('Spam?')?>');"><i class="glyphicon glyphicon-fire"></i><?=_e("Spam");?>
</a> |
<a class="btn btn-primary btn-xs" href="<?=Route::url('oc-panel', array('controller'=>'ad','action'=>'delete','id'=>$ad->id_ad))?>"
onclick="return confirm('<?=__('Delete?')?>');"><i class="glyphicon glyphicon-remove"></i><?=_e("Delete");?>
</a>
</div>
</div>
<?elseif($user !== NULL && $user->id_user == $ad->id_user):?>
<br/>
<div class="toolbar btn btn-primary btn-xs"><i class="glyphicon glyphicon-cog"></i>
<div id="<API key><?=$ad->id_ad?>" class="hide <API key>">
<a class="btn btn-primary btn-xs" href="<?=Route::url('oc-panel', array('controller'=>'myads','action'=>'update','id'=>$ad->id_ad))?>"><i class="glyphicon glyphicon-edit"></i><?=_e("Edit");?></a> |
<a class="btn btn-primary btn-xs" href="<?=Route::url('oc-panel', array('controller'=>'myads','action'=>'deactivate','id'=>$ad->id_ad))?>"
onclick="return confirm('<?=__('Deactivate?')?>');"><i class="glyphicon glyphicon-off"></i><?=_e("Deactivate");?>
</a>
</div>
</div>
<?endif?>
</article>
<?endforeach?>
<div class="clearfix"></div>
<div class="text-center">
<?=$pagination?>
</div>
<?elseif (core::count($ads) == 0):?>
<?if(core::config('general.auto_locate') AND core::request('userpos') == 1):?>
<div class="btn-group pull-right">
<button
class="btn btn-sm btn-default <?=core::request('userpos') == 1 ? 'active' : NULL?>"
id="myLocationBtn"
type="button"
data-toggle="modal"
data-target="#myLocation"
data-href="?<?=http_build_query(['userpos' => 1] + Request::current()->query())?>">
<i class="glyphicon <API key>"></i> <?=sprintf(__('%s from you'), i18n::format_measurement(Core::config('advertisement.<API key>', 1)))?>
</button>
</div>
<div class="clearfix"></div>
<?endif?>
<!-- Case when we dont have ads for specific category / location -->
<div class="page-header">
<h3><?=_e('We do not have any advertisements in this category')?></h3>
</div>
<?endif?>
<?if(core::config('general.auto_locate')):?>
<div class="modal fade" id="myLocation" tabindex="-1" role="dialog" aria-labelledby="myLocationLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-distance btn-default dropdown-toggle" data-toggle="dropdown">
<span class="label-icon"><?=i18n::format_measurement(Core::cookie('mydistance', Core::config('advertisement.<API key>', 2)))?></span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-left" role="menu">
<li>
<a href="#" data-value="2"><?=i18n::format_measurement(2)?></a>
</li>
<li>
<a href="#" data-value="5"><?=i18n::format_measurement(5)?></a>
</li>
<li>
<a href="#" data-value="10"><?=i18n::format_measurement(10)?></a>
</li>
<li>
<a href="#" data-value="20"><?=i18n::format_measurement(20)?></a>
</li>
<li>
<a href="#" data-value="50"><?=i18n::format_measurement(50)?></a>
</li>
<li>
<a href="#" data-value="250"><?=i18n::format_measurement(250)?></a>
</li>
<li>
<a href="#" data-value="500"><?=i18n::format_measurement(500)?></a>
</li>
</ul>
</div>
<input type="hidden" name="distance" id="myDistance" value="<?=Core::cookie('mydistance', Core::config('advertisement.<API key>', 2))?>" disabled>
<input type="hidden" name="latitude" id="myLatitude" value="" disabled>
<input type="hidden" name="longitude" id="myLongitude" value="" disabled>
<?=FORM::input('myAddress', Request::current()->post('address'), array('class'=>'form-control', 'id'=>'myAddress', 'placeholder'=>__('Where do you want to search?')))?>
<span class="input-group-btn">
<button id="setMyLocation" class="btn btn-default" type="button"><?=_e('Ok')?></button>
</span>
</div>
<br>
<div id="mapCanvas"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><?=_e('Close')?></button>
<?if (core::request('userpos') == 1) :?>
<a class="btn btn-danger" href="?<?=http_build_query(['userpos' => NULL] + Request::current()->query())?>"><?=_e('Remove')?></a>
<?endif?>
</div>
</div>
</div>
</div>
<?if (core::config('advertisement.map')==1):?>
<?=View::factory('pages/ad/listing_map', compact('ads'))?>
<?endif?>
<?endif?>
|
<?php
function my_callrates() {
global $dbh, $db_name, $db_table_name, $group_by_field, $where, $result_limit, $graph_col_title, $<API key>;
$my_call_rates = array(
"Городские" => "(dst LIKE '2%' OR dst LIKE '7%') and (LENGTH(dst)=7)",
"Мобильные" => "(dst LIKE '89%') and (LENGTH(dst)=11)",
"Область" => "(dst LIKE '8351%') and (LENGTH(dst)=11)",
"Столицы" => "(dst LIKE '8495%' OR dst LIKE '8499%' OR dst LIKE '8812%') and (LENGTH(dst)=11)",
"Россия" => "(dst LIKE '8%') and (dst NOT LIKE '89%' and dst NOT LIKE '79%' and dst NOT LIKE '8351%' and dst NOT LIKE '8495%' and dst NOT LIKE '8499%' and dst NOT LIKE '8812%' and dst NOT LIKE '8800%') and (LENGTH(dst)=11)",
);
$<API key> = __DIR__ . '/' . $<API key>;
$my_bill_tototal_q = "SELECT $group_by_field AS group_by_field FROM $db_name.$db_table_name $where GROUP BY group_by_field ORDER BY group_by_field ASC LIMIT $result_limit";
$my_callrates_total = array();
foreach ( array_keys($my_call_rates) as $key ) {
$my_call_rates_total["$key"] = 0;
}
$my_call_rates_total["summ"] = 0;
echo '<p class="center title">Детализация звонков - Расход денежных средств</p><table class="cdr">
<tr>
<th>'.$graph_col_title.'</th>
<th colspan=5>Направление</th>
</tr>
<tr><th> </th>';
foreach ( array_keys($my_call_rates) as $key ) {
echo "<th>$key</th>";
}
echo "<th>Итого</th></tr>";
try {
$sth = $dbh->query($my_bill_tototal_q);
if (!$sth) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$result = $sth->fetchAll(PDO::FETCH_NUM);
$sth = NULL;
foreach ( $result as $row ) {
$summ = 0;
echo "<tr class=\"record\">";
echo '<td style="text-align:center;">'. $row[0] ."</td>";
foreach ( array_keys($my_call_rates) as $key ) {
$my_bill_ch_q = "SELECT dst, billsec FROM $db_name.$db_table_name $where and $group_by_field = '". $row[0] ."' and " . $my_call_rates["$key"];
$summ_local = 0;
$sth2 = $dbh->query($my_bill_ch_q);
if (!$sth2) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
while ($bill_row = $sth2->fetch(PDO::FETCH_NUM)) {
$rates = callrates( $bill_row[0], $bill_row[1], $<API key> );
$summ_local += $rates[4];
}
$sth2 = NULL;
$my_call_rates_total["$key"] += $summ_local;
$summ += $summ_local;
formatMoney($summ_local);
}
$my_call_rates_total["summ"] += $summ;
formatMoney($summ);
echo "</tr>";
}
}
catch (PDOException $e) {
print $e->getMessage();
}
echo "<tr class=\"chart_data total\">";
echo "<td>Всего</td>";
foreach ( array_keys($my_call_rates_total) as $key ) {
formatMoney($my_call_rates_total["$key"]);
}
echo "</tr>";
echo "</table>";
}
?>
|
# 2008-2018 H. Turgut Uyar <uyar@tekir.org>
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from __future__ import absolute_import, division, print_function, unicode_literals
from imdb.utils import <API key>
from .piculet import Path, Rule, Rules, reducers
from .searchMovieParser import <API key>
from .utils import analyze_imdbid
class <API key>(<API key>):
"""A parser for the company search page."""
rules = [
Rule(
key='data',
extractor=Rules(
foreach='//td[@class="result_text"]',
rules=[
Rule(
key='link',
extractor=Path('./a/@href', reduce=reducers.first)
),
Rule(
key='name',
extractor=Path('./a/text()')
),
Rule(
key='notes',
extractor=Path('./text()')
)
],
transform=lambda x: (
analyze_imdbid(x.get('link')),
<API key>(x.get('name') + x.get('notes', ''), stripNotes=True)
)
)
)
]
_OBJECTS = {
'<API key>': ((<API key>,), {'kind': 'company'})
}
|
/**
* @file IAR/ARMCMx/chcore_v7m.c
* @brief ARMv7-M architecture port code.
*
* @addtogroup IAR_ARMCMx_V7M_CORE
* @{
*/
#include "ch.h"
/* Port interrupt handlers. */
/**
* @brief System Timer vector.
* @details This interrupt is used as system tick.
* @note The timer must be initialized in the startup code.
*/
CH_IRQ_HANDLER(SysTickVector) {
CH_IRQ_PROLOGUE();
chSysLockFromIsr();
chSysTimerHandlerI();
chSysUnlockFromIsr();
CH_IRQ_EPILOGUE();
}
#if !<API key> || defined(__DOXYGEN__)
/**
* @brief SVC vector.
* @details The SVC vector is used for exception mode re-entering after a
* context switch.
* @note The PendSV vector is only used in advanced kernel mode.
*/
void SVCallVector(void) {
struct extctx *ctxp;
/* Current PSP value.*/
ctxp = (struct extctx *)__get_PSP();
/* Discarding the current exception context and positioning the stack to
point to the real one.*/
ctxp++;
#if CORTEX_USE_FPU
/* Restoring the special register SCB_FPCCR.*/
SCB_FPCCR = (uint32_t)ctxp->fpccr;
SCB_FPCAR = SCB_FPCAR + sizeof (struct extctx);
#endif
__set_PSP((unsigned long)ctxp);
<API key>();
}
#endif /* !<API key> */
#if <API key> || defined(__DOXYGEN__)
/**
* @brief PendSV vector.
* @details The PendSV vector is used for exception mode re-entering after a
* context switch.
* @note The PendSV vector is only used in compact kernel mode.
*/
void PendSVVector(void) {
struct extctx *ctxp;
/* Current PSP value.*/
ctxp = (struct extctx *)__get_PSP();
/* Discarding the current exception context and positioning the stack to
point to the real one.*/
ctxp++;
#if CORTEX_USE_FPU
/* Restoring the special register SCB_FPCCR.*/
SCB_FPCCR = (uint32_t)ctxp->fpccr;
SCB_FPCAR = SCB_FPCAR + sizeof (struct extctx);
#endif
__set_PSP((unsigned long)ctxp);
}
#endif /* <API key> */
/* Port exported functions. */
/**
* @brief Port-related initialization code.
*/
void _port_init(void) {
/* Initialization of the vector table and priority related settings.*/
SCB_VTOR = CORTEX_VTOR_INIT;
SCB_AIRCR = AIRCR_VECTKEY | AIRCR_PRIGROUP(<API key>);
#if CORTEX_USE_FPU
{
/* Initializing the FPU context save in lazy mode.*/
SCB_FPCCR = FPCCR_ASPEN | FPCCR_LSPEN;
/* CP10 and CP11 set to full access.*/
SCB_CPACR |= 0x00F00000;
/* Enables FPU context save/restore on exception entry/exit (FPCA bit).*/
__set_CONTROL(__get_CONTROL() | 4);
/* FPSCR and FPDSCR initially zero.*/
__set_FPSCR(0);
SCB_FPDSCR = 0;
}
#endif
/* Initialization of the system vectors used by the port.*/
<API key>(HANDLER_SVCALL,
<API key>(<API key>));
<API key>(HANDLER_PENDSV,
<API key>(<API key>));
<API key>(HANDLER_SYSTICK,
<API key>(<API key>));
}
/**
* @brief Exception exit redirection to <API key>().
*/
void _port_irq_epilogue(void) {
port_lock_from_isr();
if ((SCB_ICSR & ICSR_RETTOBASE) != 0) {
struct extctx *ctxp;
/* Current PSP value.*/
ctxp = (struct extctx *)__get_PSP();
/* Adding an artificial exception return context, there is no need to
populate it fully.*/
ctxp
__set_PSP((unsigned long)ctxp);
ctxp->xpsr = (regarm_t)0x01000000;
/* The exit sequence is different depending on if a preemption is
required or not.*/
if (<API key>()) {
/* Preemption is required we need to enforce a context switch.*/
ctxp->pc = (regarm_t)<API key>;
#if CORTEX_USE_FPU
/* Triggering a lazy FPU state save.*/
(void)__get_FPSCR();
#endif
}
else {
/* Preemption not required, we just need to exit the exception
atomically.*/
ctxp->pc = (regarm_t)_port_exit_from_isr;
}
#if CORTEX_USE_FPU
{
uint32_t fpccr;
/* Saving the special register SCB_FPCCR into the reserved offset of
the Cortex-M4 exception frame.*/
(ctxp + 1)->fpccr = (regarm_t)(fpccr = SCB_FPCCR);
/* Now the FPCCR is modified in order to not restore the FPU status
from the artificial return context.*/
SCB_FPCCR = fpccr | FPCCR_LSPACT;
}
#endif
/* Note, returning without unlocking is intentional, this is done in
order to keep the rest of the context switch atomic.*/
return;
}
<API key>();
}
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<title>File: testcase.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../../../../../../../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
</script>
</head>
<body>
<div id="fileHeader">
<h1>testcase.rb</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>vendor/plugins/rspec-rails/lib/spec/rails/interop/testcase.rb
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>Mon Oct 27 17:22:45 +0100 2008</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
</div>
</div>
<!-- if includes -->
<div id="section">
<!-- if method_list -->
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
|
<?php defined( 'ABSPATH' ) || exit; ?>
<fieldset>
<?php foreach ( $data['options'] as $cb_id => $cb_label ) : ?>
<input
type="checkbox"
name="<?php echo esc_attr( sprintf( '%s[%s]', $data['id'], $cb_id ) ); ?>"
id="<?php echo esc_attr( sprintf( '%s_%s', $data['id'], $cb_id ) ); ?>"
<?php checked( in_array( $cb_id, get_option( $data['id'], array() ), true ) ); ?>
>
<label for="<?php echo esc_attr( sprintf( '%s_%s', $data['id'], $cb_id ) ); ?>" >
<?php echo esc_html( $cb_label ); ?>
</label>
<br>
<?php endforeach; ?>
</fieldset>
<p class="description"><?php echo $data['description']; ?></p>
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
using System;
using System.Collections.Generic;
using System.Configuration;
using ClearCanvas.Desktop;
namespace ClearCanvas.Ris.Client
{
<summary>
Provides services for storing the folder and folder system structure
to an XML document, and rebuilding that folder structure from the document.
</summary>
[<API key>("Configures folder systems.")]
[SettingsProvider(typeof(ClearCanvas.Common.Configuration.<API key>))]
internal sealed partial class <API key>
{
private readonly <API key> _defaultConfig;
private readonly <API key> _userConfig;
private <API key>()
{
<API key>.Instance.RegisterInstance(this);
_defaultConfig = new <API key>(() => this.<API key>);
_userConfig = new <API key>(() => this.<API key>, <API key> =>
{
this.<API key> = <API key>;
Save();
});
}
#region Public API
<summary>
Orders the folder systems according to the default and user specific settings.
</summary>
<param name="folderSystems">Input list of folder systems</param>
public IEnumerable<IFolderSystem> <API key>(IEnumerable<IFolderSystem> folderSystems)
{
folderSystems = _defaultConfig.<API key>(folderSystems);
return _userConfig.<API key>(folderSystems);
}
<summary>
Customizes the folders in the specified folder system according to the default and [optionally] user specific settings,
returning the folders in the order specified by customization.
</summary>
<param name="folderSystem"></param>
<param name="<API key>"></param>
public IEnumerable<IFolder> <API key>(IFolderSystem folderSystem, bool <API key>)
{
var folders = _defaultConfig.<API key>(folderSystem.Id, folderSystem.Folders);
return <API key>
? _userConfig.<API key>(folderSystem.Id, folders)
: folders;
}
<summary>
Customizes the folders in the specified folder system according to the default and user specific settings,
returning the folders in the order specified by customization.
</summary>
<param name="folderSystem"></param>
public IEnumerable<IFolder> <API key>(IFolderSystem folderSystem)
{
return <API key>(folderSystem, true);
}
<summary>
Customizes the specified folder, in the specified folder system, according to the default and user specific setting.
</summary>
<param name="folderSystem"></param>
<param name="folder"></param>
public void <API key>(IFolderSystem folderSystem, IFolder folder)
{
_defaultConfig.<API key>(folderSystem.Id, folder);
_userConfig.<API key>(folderSystem.Id, folder);
}
public delegate void <API key>(<API key> userConfiguration);
<summary>
Allows user configuration to be stored. The update action should be used to invoke methods on the
<see cref="<API key>"/> to set the required user configuration.
</summary>
<param name="updateAction"></param>
public void <API key>(<API key> updateAction)
{
_userConfig.BeginTransaction();
try
{
updateAction(_userConfig);
_userConfig.CommitTransaction();
}
catch
{
_userConfig.RollbackTransaction();
throw;
}
}
<summary>
Indicates that the current user's folder/folder system customizations have been committed.
</summary>
public event EventHandler <API key>
{
add { _userConfig.ChangesCommitted += value; }
remove { _userConfig.ChangesCommitted -= value; }
}
public bool <API key>(IFolderSystem folderSystem)
{
return _defaultConfig.<API key>(folderSystem);
}
#endregion
}
}
|
// SFML - Simple and Fast Multimedia Library
// In no event will the authors be held liable for any damages arising from the use of this software.
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// Headers
#include <SFML/Network/TcpListener.hpp>
#include <SFML/Network/TcpSocket.hpp>
#include <SFML/Network/SocketImpl.hpp>
#include <SFML/System/Err.hpp>
namespace sf
{
TcpListener::TcpListener() :
Socket(Tcp)
{
}
unsigned short TcpListener::getLocalPort() const
{
if (getHandle() != priv::SocketImpl::invalidSocket())
{
// Retrieve informations about the local end of the socket
sockaddr_in address;
priv::SocketImpl::AddrLength size = sizeof(address);
if (getsockname(getHandle(), reinterpret_cast<sockaddr*>(&address), &size) != -1)
{
return ntohs(address.sin_port);
}
}
// We failed to retrieve the port
return 0;
}
Socket::Status TcpListener::listen(unsigned short port)
{
// Create the internal socket if it doesn't exist
create();
// Bind the socket to the specified port
sockaddr_in address = priv::SocketImpl::createAddress(INADDR_ANY, port);
if (bind(getHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1)
{
// Not likely to happen, but...
err() << "Failed to bind listener socket to port " << port << std::endl;
return Error;
}
// Listen to the bound port
if (::listen(getHandle(), 0) == -1)
{
// Oops, socket is deaf
err() << "Failed to listen to port " << port << std::endl;
return Error;
}
return Done;
}
void TcpListener::close()
{
// Simply close the socket
Socket::close();
}
Socket::Status TcpListener::accept(TcpSocket& socket)
{
// Make sure that we're listening
if (getHandle() == priv::SocketImpl::invalidSocket())
{
err() << "Failed to accept a new connection, the socket is not listening" << std::endl;
return Error;
}
// Accept a new connection
sockaddr_in address;
priv::SocketImpl::AddrLength length = sizeof(address);
SocketHandle remote = ::accept(getHandle(), reinterpret_cast<sockaddr*>(&address), &length);
// Check for errors
if (remote == priv::SocketImpl::invalidSocket())
return priv::SocketImpl::getErrorStatus();
// Initialize the new connected socket
socket.close();
socket.create(remote);
return Done;
}
} // namespace sf
|
static char rcsid[] = "$Id: b3dest.c, v3.2.3 10/05/2001 18:00:00 Xuemei Xi Release $";
#include "spice.h"
#include <stdio.h>
#include "util.h"
#include "bsim3def.h"
#include "suffix.h"
void
BSIM3destroy(inModel)
GENmodel **inModel;
{
BSIM3model **model = (BSIM3model**)inModel;
BSIM3instance *here;
BSIM3instance *prev = NULL;
BSIM3model *mod = *model;
BSIM3model *oldmod = NULL;
for (; mod ; mod = mod->BSIM3nextModel)
{ if(oldmod) FREE(oldmod);
oldmod = mod;
prev = (BSIM3instance *)NULL;
for (here = mod->BSIM3instances; here; here = here->BSIM3nextInstance)
{ if(prev) FREE(prev);
prev = here;
}
if(prev) FREE(prev);
}
if(oldmod) FREE(oldmod);
*model = NULL;
return;
}
|
<!DOCTYPE HTML PUBLIC "-
<html>
<head>
<script type="text/javascript">
done = false;
xmlhttp= new XMLHttpRequest();
xmlhttp.open("GET","../integration/isaspx.aspx",false);
xmlhttp.send(null);
if (xmlhttp.status === 200) { //check if "OK" (200)
if (xmlhttp.responseText.trim()=="true") {
window.location="../test.html?tech=aspx";
done = true;
}
// alert(xmlhttp.responseText);
}
xmlhttp= new XMLHttpRequest();
xmlhttp.open("GET","../integration/isphp.php",false);
xmlhttp.send(null);
if (xmlhttp.status === 200) { //check if "OK" (200)
if (xmlhttp.responseText.trim()=="true") {
window.location="../test.html?tech=php";
done = true;
}
// alert(xmlhttp.responseText);
}
if (!done) {
window.location="../test.html?tech=java";
}
</script>
</head>
</html>
|
<?php
/**
* Respresents an API parameter
*
* @author James Cryer(j.r.cryer@gmail.com)
*/
class QueryParameter {
/**
* Parameter name
* @var string
*/
protected $name;
/**
* Parameter value
* @var string
*/
protected $value;
/**
* Constructor
*
* @param string $name
* @param string $value
*/
public function __construct($name, $value) {
$this->setParameter($name, $value);
}
/**
* Set the parameter name and value
*
* @param string $name
* @param string $value
*/
public function setParameter($name, $value) {
$this->setName($name);
$this->setValue($value);
}
/**
* Return the parameters name and value as a name value pair
*
* @return string
*/
public function getParameter() {
return sprintf('%s=%s', $this->getName(), $this->getValue());
}
/**
* Reurns the parameter name
*
* @return string
*/
protected function getName() {
return $this->name;
}
/**
* Set the parameter name
*
* @param string $name
*/
protected function setName($name) {
$this->name = $name;
}
/**
* Returns the parameter value
*
* @return string
*/
protected function getValue() {
if( $this->getName() == 'url' ) {
return urlencode($this->value);
}
return $this->value;
}
/**
* Set the paramter value
*
* @param string $value
*/
protected function setValue($value) {
$this->value = $value;
}
/**
* Returns the parameter as a name value pair
*
* @return string
*/
public function __toString() {
return $this->getParameter();
}
}
|
package com.idega.repository.data;
/**
* PropertyDescription keeps the link between a ResourceDescription and a certain method.
*
* @see PresentationObject#<API key>()
*/
public class PropertyDescription {
private String name = null;
private String parameterId = null;
private ResourceDescription resourceDescription = null;
public PropertyDescription(String name, String parameterId, ResourceDescription resourceDescription) {
this.name = name;
this.parameterId = parameterId;
this.resourceDescription = resourceDescription;
}
public PropertyDescription(String name, String parameterId, String source, String provider, boolean isEjb) {
this(name, parameterId, new ResourceDescription(source, provider, isEjb));
}
public String getName() {
return this.name;
}
public String getParameterId() {
return this.parameterId;
}
public ResourceDescription <API key>() {
return this.resourceDescription;
}
}
|
package cern.colt.matrix.tdouble.algo.solver;
import cern.colt.matrix.tdouble.algo.solver.preconditioner.DoubleICC;
/**
* Test of DoubleIR with ICC
*/
public class DoubleIRICCTest extends DoubleIRTest {
public DoubleIRICCTest(String arg0) {
super(arg0);
}
protected void createSolver() throws Exception {
super.createSolver();
M = new DoubleICC(A.rows());
}
}
|
Hi! Thanks for your interest in contributing to PyWeather, by reporting an issue.
It's simply impossible for me to catch every bug in PyWeather, so you can help! Before you report an issue, run down this to-do list.
* Make sure PyWeather is up-to-date. I do manage to catch a fair amount of bugs in PyWeather releases.
* Make sure your issue isn't on the list of known issues. The page is available in the wiki, [here](https://github.com/o355/PyWeather/wiki/Known-Issues).
* Make sure you've properly set up PyWeather. Basically, this is running setup.py and going through all dialogs.
* If your issue can be replicated, turn on tracebacks in the config file for the script it occurs in. To do this, head into your config file, and enable tracebacks on all options (from False to True). A traceback is extremely helpful in troubleshooting a bug!
In the end, if you're unsure about the requirements above, report the issue anyways.
Done with the list? Here's what you'll need for a report.
* The full traceback provided by Python, if applicable.
* System information (OS, Python version). You can get your Python version by typing in `python3` or `python`, and copying the first two lines outputted. For your OS, a description like `Windows 10`, or `Ubuntu 16.04` works.
* A description detailing the issue. Add as much detail as you can to your description, as the better the description, the faster I can find the bug.
* If a bug is associated with a location, you'll want to generalize the location for your privacy. If you find a bug with weather data at `123 5th Avenue, New York, NY`, try to generalize the location to `New York, NY`.
* Please tell me what type of PyWeather you're using, either the latest release, or the indev code.
You can go the extra mile by adding this stuff to your report.
* A screenshot of the bug. It's highly recommended to attach a screenshot of the bug if it deals with changing weather data.
* Potential solutions. If you can do Python 3 coding, make a pull request, even if it's just one line of code!
* Testing where the issue occurs. Sometimes bugs only occur on a certain OS.
More details on reporting an issue can be found in the .github folder, in the document called `CONTRIBUTING.md`. If you're still confused, have a look at `CONTRIBUTING.md`, or contact me on Reddit, /u/therealo355.
If you'd like to keep this template in your report, that's completely fine. Otherwise, report the issue!
|
#include "coreinit.h"
#include "coreinit_im.h"
#include "coreinit_ios.h"
#include "coreinit_mutex.h"
#include "cafe/<API key>.h"
#include "cafe/cafe_stackobject.h"
#include <libcpu/state.h>
namespace cafe::coreinit
{
struct StaticImData
{
be2_struct<OSMutex> itbMutex;
be2_array<char, 16> itbMutexName;
be2_struct<IMRequest> sharedRequest;
};
static virt_ptr<StaticImData> sImData = nullptr;
static IOSAsyncCallbackFn sImIosAsyncCallback = nullptr;
namespace internal
{
static void
imAcquireItbMutex()
{
OSLockMutex(virt_addrof(sImData->itbMutex));
}
static void
imReleaseItbMutex()
{
OSUnlockMutex(virt_addrof(sImData->itbMutex));
}
static void
imCopyData(virt_ptr<IMRequest> request)
{
if (request->copyDst && request->copySrc && request->copySize) {
std::memcpy(request->copyDst.get(),
request->copySrc.get(),
request->copySize);
}
}
static void
imIosAsyncCallback(IOSError error,
virt_ptr<void> context)
{
auto request = virt_cast<IMRequest *>(context);
if (error == IOSError::OK) {
imCopyData(request);
}
cafe::invoke(cpu::this_core::state(),
request->asyncCallback,
error,
request-><API key>);
}
static IMError
imSendRequest(virt_ptr<IMRequest> request,
uint32_t vecIn,
uint32_t vecOut)
{
auto error = IOSError::OK;
if (request->asyncCallback) {
error = IOS_IoctlvAsync(request->handle,
request->request,
vecIn,
vecOut,
virt_addrof(request->ioctlVecs),
sImIosAsyncCallback,
request);
} else {
error = IOS_Ioctlv(request->handle,
request->request,
vecIn,
vecOut,
virt_addrof(request->ioctlVecs));
if (vecOut > 0 && error == IOSError::OK) {
imCopyData(request);
}
}
return static_cast<IMError>(error);
}
} // namespace internal
IMError
IM_Open()
{
return static_cast<IMError>(IOS_Open(cafe::make_stack_string("/dev/im"),
IOSOpenMode::None));
}
IMError
IM_Close(IOSHandle handle)
{
return static_cast<IMError>(IOS_Close(handle));
}
IMError
<API key>(IOSHandle handle,
virt_ptr<IMRequest> request,
virt_ptr<void> output,
IOSAsyncCallbackFn asyncCallback,
virt_ptr<void> <API key>)
{
std::memset(request.get(), 0, sizeof(IMRequest));
request->ioctlVecs[0].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[0].len = 8u;
request->handle = handle;
request->request = IMCommand::GetHomeButtonParams;
request->asyncCallback = asyncCallback;
request-><API key> = <API key>;
request->copySrc = virt_addrof(request-><API key>);
request->copyDst = output;
request->copySize = 8u;
return internal::imSendRequest(request, 0, 1);
}
IMError
IM_GetParameter(IOSHandle handle,
virt_ptr<IMRequest> request,
IMParameter parameter,
virt_ptr<void> output,
IOSAsyncCallbackFn asyncCallback,
virt_ptr<void> <API key>)
{
std::memset(request.get(), 0, sizeof(IMRequest));
request->getParameterRequest.parameter = parameter;
request->ioctlVecs[0].vaddr = virt_cast<virt_addr>(virt_addrof(request->getParameterRequest));
request->ioctlVecs[0].len = 8u;
request->ioctlVecs[1].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[1].len = 8u;
request->handle = handle;
request->request = IMCommand::GetParameter;
request->asyncCallback = asyncCallback;
request-><API key> = <API key>;
request->copySrc = virt_addrof(request-><API key>.value);
request->copyDst = output;
request->copySize = 4u;
return internal::imSendRequest(request, 1, 1);
}
IMError
IM_GetParameters(virt_ptr<IMParameters> parameters)
{
auto result = IM_Open();
if (result < 0) {
return result;
}
auto handle = static_cast<IOSHandle>(result);
internal::imAcquireItbMutex();
result = IM_GetParameter(handle,
virt_addrof(sImData->sharedRequest),
IMParameter::ResetEnable,
virt_addrof(parameters->resetEnabled),
nullptr,
nullptr);
if (result != IMError::OK) {
goto out;
}
result = IM_GetParameter(handle,
virt_addrof(sImData->sharedRequest),
IMParameter::DimEnabled,
virt_addrof(parameters->dimEnabled),
nullptr,
nullptr);
if (result != IMError::OK) {
goto out;
}
result = IM_GetParameter(handle,
virt_addrof(sImData->sharedRequest),
IMParameter::DimPeriod,
virt_addrof(parameters->dimPeriod),
nullptr,
nullptr);
if (result != IMError::OK) {
goto out;
}
result = IM_GetParameter(handle,
virt_addrof(sImData->sharedRequest),
IMParameter::APDEnabled,
virt_addrof(parameters->apdEnabled),
nullptr,
nullptr);
if (result != IMError::OK) {
goto out;
}
result = IM_GetParameter(handle,
virt_addrof(sImData->sharedRequest),
IMParameter::APDPeriod,
virt_addrof(parameters->apdPeriod),
nullptr,
nullptr);
if (result != IMError::OK) {
goto out;
}
out:
internal::imReleaseItbMutex();
IM_Close(handle);
return result;
}
IMError
IM_GetNvParameter(IOSHandle handle,
virt_ptr<IMRequest> request,
IMParameter parameter,
virt_ptr<void> output,
IOSAsyncCallbackFn asyncCallback,
virt_ptr<void> <API key>)
{
std::memset(request.get(), 0, sizeof(IMRequest));
request-><API key>.parameter = parameter;
request->ioctlVecs[0].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[0].len = 8u;
request->ioctlVecs[1].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[1].len = 8u;
request->handle = handle;
request->request = IMCommand::GetNvParameter;
request->asyncCallback = asyncCallback;
request-><API key> = <API key>;
request->copySrc = virt_addrof(request-><API key>.value);
request->copyDst = output;
request->copySize = 4u;
return internal::imSendRequest(request, 1, 1);
}
IMError
<API key>(IMParameter parameter,
virt_ptr<uint32_t> outValue)
{
auto result = IM_Open();
if (result < 0) {
return result;
}
auto handle = static_cast<IOSHandle>(result);
internal::imAcquireItbMutex();
result = IM_GetNvParameter(handle,
virt_addrof(sImData->sharedRequest),
parameter,
outValue,
nullptr,
nullptr);
internal::imReleaseItbMutex();
IM_Close(handle);
return result;
}
IMError
<API key>(IMParameter parameter,
virt_ptr<uint32_t> outValue)
{
auto result = IM_Open();
if (result < 0) {
return result;
}
auto handle = static_cast<IOSHandle>(result);
internal::imAcquireItbMutex();
result = IM_GetParameter(handle,
virt_addrof(sImData->sharedRequest),
parameter,
outValue,
nullptr,
nullptr);
internal::imReleaseItbMutex();
IM_Close(handle);
return result;
}
IMError
<API key>(IOSHandle handle,
virt_ptr<IMRequest> request,
IMTimer timer,
virt_ptr<void> output,
IOSAsyncCallbackFn asyncCallback,
virt_ptr<void> <API key>)
{
std::memset(request.get(), 0, sizeof(IMRequest));
request-><API key>.timer = timer;
request->ioctlVecs[0].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[0].len = 8u;
request->ioctlVecs[1].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[1].len = static_cast<uint32_t>(sizeof(<API key>));
request->handle = handle;
request->request = IMCommand::GetTimerRemaining;
request->asyncCallback = asyncCallback;
request-><API key> = <API key>;
request->copySrc = virt_addrof(request-><API key>.value);
request->copyDst = output;
request->copySize = 4u;
return internal::imSendRequest(request, 1, 1);
}
IMError
<API key>(IMTimer timer,
virt_ptr<uint32_t> outSeconds)
{
auto result = IM_Open();
if (result < 0) {
return result;
}
auto handle = static_cast<IOSHandle>(result);
internal::imAcquireItbMutex();
result = <API key>(handle,
virt_addrof(sImData->sharedRequest),
timer,
outSeconds,
nullptr,
nullptr);
internal::imReleaseItbMutex();
IM_Close(handle);
return result;
}
IMError
IM_SetParameter(IOSHandle handle,
virt_ptr<IMRequest> request,
IMParameter parameter,
uint32_t value,
IOSAsyncCallbackFn asyncCallback,
virt_ptr<void> <API key>)
{
std::memset(request.get(), 0, sizeof(IMRequest));
request->setParameterRequest.parameter = parameter;
request->setParameterRequest.value = value;
request->ioctlVecs[0].vaddr = virt_cast<virt_addr>(virt_addrof(request->setParameterRequest));
request->ioctlVecs[0].len = 8u;
request->handle = handle;
request->request = IMCommand::SetParameter;
request->asyncCallback = asyncCallback;
request-><API key> = <API key>;
return internal::imSendRequest(request, 1, 0);
}
IMError
IM_SetNvParameter(IOSHandle handle,
virt_ptr<IMRequest> request,
IMParameter parameter,
uint32_t value,
IOSAsyncCallbackFn asyncCallback,
virt_ptr<void> <API key>)
{
std::memset(request.get(), 0, sizeof(IMRequest));
request-><API key>.parameter = parameter;
request-><API key>.value = value;
request->ioctlVecs[0].vaddr = virt_cast<virt_addr>(virt_addrof(request-><API key>));
request->ioctlVecs[0].len = 8u;
request->handle = handle;
request->request = IMCommand::SetNvParameter;
request->asyncCallback = asyncCallback;
request-><API key> = <API key>;
return internal::imSendRequest(request, 1, 0);
}
IMError
<API key>(IMParameter parameter,
uint32_t value)
{
auto result = IM_Open();
if (result < 0) {
return result;
}
auto handle = static_cast<IOSHandle>(result);
internal::imAcquireItbMutex();
result = IM_SetParameter(handle,
virt_addrof(sImData->sharedRequest),
parameter,
value,
nullptr,
nullptr);
internal::imReleaseItbMutex();
IM_Close(handle);
return result;
}
IMError
IMDisableAPD()
{
return <API key>(IMParameter::APDEnabled, FALSE);
}
IMError
IMDisableDim()
{
auto result = <API key>(IMParameter::DimEnabled, FALSE);
if (result != IMError::OK) {
return result;
}
return <API key>(IMParameter::ResetEnable, FALSE);
}
IMError
IMEnableAPD()
{
auto prevValue = StackObject<uint32_t> { };
auto result = <API key>(IMParameter::APDEnabled,
prevValue);
if (result != IMError::OK) {
return result;
}
if (*prevValue == TRUE) {
return IMError::OK;
}
return <API key>(IMParameter::APDEnabled, TRUE);
}
IMError
IMEnableDim()
{
auto prevValue = StackObject<uint32_t> { };
auto result = <API key>(IMParameter::DimEnabled,
prevValue);
if (result != IMError::OK) {
return result;
}
if (*prevValue == TRUE) {
return IMError::OK;
}
result = <API key>(IMParameter::DimEnabled, TRUE);
if (result != IMError::OK) {
return result;
}
result = <API key>(IMParameter::ResetEnable,
prevValue);
if (result != IMError::OK) {
return result;
}
if (*prevValue == TRUE) {
return IMError::OK;
}
return <API key>(IMParameter::ResetEnable, FALSE);
}
IMError
IMIsAPDEnabled(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::APDEnabled, outValue);
}
IMError
<API key>(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::APDEnabled,
outValue);
}
IMError
IMIsDimEnabled(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::DimEnabled, outValue);
}
IMError
IMGetAPDPeriod(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::APDPeriod, outValue);
}
IMError
IMGetDimEnableDRC(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::DimEnableDrc, outValue);
}
IMError
IMGetDimEnableTV(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::DimEnableTv, outValue);
}
IMError
IMGetDimPeriod(virt_ptr<uint32_t> outValue)
{
return <API key>(IMParameter::DimPeriod, outValue);
}
IMError
IMGetTimeBeforeAPD(virt_ptr<uint32_t> outSeconds)
{
return <API key>(IMTimer::APD, outSeconds);
}
IMError
<API key>(virt_ptr<uint32_t> outSeconds)
{
return <API key>(IMTimer::Dim, outSeconds);
}
IMError
IMSetDimEnableDRC(BOOL value)
{
return <API key>(IMParameter::DimEnableTv, value);
}
IMError
IMSetDimEnableTV(BOOL value)
{
return <API key>(IMParameter::DimEnableTv, value);
}
IMError
IMStartAPDVideoMode()
{
auto prevValue = StackObject<uint32_t> { };
auto result = <API key>(IMParameter::APDPeriod,
prevValue);
if (result != IMError::OK) {
return result;
}
if (*prevValue == 14400) {
return IMError::OK;
}
return <API key>(IMParameter::APDPeriod, 14400);
}
namespace internal
{
void
initialiseIm()
{
sImData->itbMutexName = "itb_mutex";
OSInitMutexEx(virt_addrof(sImData->itbMutex),
virt_addrof(sImData->itbMutexName));
}
} // namespace internal
void
Library::registerImSymbols()
{
<API key>(IM_Open);
<API key>(IM_Close);
<API key>(<API key>);
<API key>(IM_GetParameter);
<API key>(IM_GetParameters);
<API key>(IM_GetNvParameter);
<API key>(<API key>);
<API key>(<API key>);
<API key>(<API key>);
<API key>(<API key>);
<API key>(IM_SetParameter);
<API key>(<API key>);
<API key>(IMDisableAPD);
<API key>(IMDisableDim);
<API key>(IMEnableAPD);
<API key>(IMEnableDim);
<API key>(IMIsAPDEnabled);
<API key>(<API key>);
<API key>(IMIsDimEnabled);
<API key>(IMGetAPDPeriod);
<API key>(IMGetDimEnableDRC);
<API key>(IMGetDimEnableTV);
<API key>(IMGetDimPeriod);
<API key>(IMGetTimeBeforeAPD);
<API key>(<API key>);
<API key>(IMSetDimEnableDRC);
<API key>(IMSetDimEnableTV);
<API key>(IMStartAPDVideoMode);
<API key>(sImData);
<API key>(internal::imIosAsyncCallback, sImIosAsyncCallback);
}
} // namespace cafe::coreinit
|
import argparse
import json
import pymongo
from bson.objectid import ObjectId
from pprint import pprint
from os import path
parser = argparse.ArgumentParser(description='Load Variant Effect Prediction JSON file to MongoDB.')
parser.add_argument('--url', default='mongodb://localhost:27017/', help="MongoDB URL, default: mongodb://localhost:27017/")
parser.add_argument('--veps', type=argparse.FileType('r'), nargs="+", required=True, help='one or more VEP JSON files')
args = parser.parse_args()
client = pymongo.MongoClient(args.url)
mcac = client.mcac
veps = mcac.veps
for f in args.veps:
predictions = []
for l in f.readlines():
p = json.loads(l)
del(p['input'])
p['vep_json'] = path.abspath(f.name)
predictions.append(p)
result = veps.insert_many(predictions)
|
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/codecs/<API key>.h"
#include "webrtc/media/engine/webrtcmediaengine.h"
using webrtc::RtpExtension;
namespace cricket {
namespace {
std::vector<RtpExtension> <API key>() {
std::vector<RtpExtension> result;
char name[] = "a";
for (int i = 0; i < 7; ++i) {
result.push_back(RtpExtension(name, 1 + i));
name[0]++;
result.push_back(RtpExtension(name, 14 - i));
name[0]++;
}
return result;
}
std::vector<RtpExtension> <API key>() {
std::vector<RtpExtension> result;
char name[] = "a";
for (int i = 0; i < 7; ++i) {
result.push_back(RtpExtension(name, 1 + i));
result.push_back(RtpExtension(name, 14 - i));
name[0]++;
}
return result;
}
bool <API key>(const std::string& name) {
return name == "c" || name == "i";
}
bool <API key>(const std::string& name) {
return name != "a" && name != "n";
}
bool IsSorted(const std::vector<webrtc::RtpExtension>& extensions) {
const std::string* last = nullptr;
for (const auto& extension : extensions) {
if (last && *last > extension.uri) {
return false;
}
last = &extension.uri;
}
return true;
}
} // namespace
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions;
EXPECT_TRUE(<API key>(extensions));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
EXPECT_TRUE(<API key>(extensions));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
extensions.push_back(RtpExtension("foo", 0));
EXPECT_FALSE(<API key>(extensions));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
extensions.push_back(RtpExtension("foo", 15));
EXPECT_FALSE(<API key>(extensions));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
extensions.push_back(RtpExtension("foo", 1));
EXPECT_FALSE(<API key>(extensions));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
extensions.push_back(RtpExtension("foo", 14));
EXPECT_FALSE(<API key>(extensions));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions;
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, true);
EXPECT_EQ(0, filtered.size());
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, false);
EXPECT_EQ(2, filtered.size());
EXPECT_EQ("c", filtered[0].uri);
EXPECT_EQ("i", filtered[1].uri);
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, false);
EXPECT_EQ(12, filtered.size());
EXPECT_TRUE(IsSorted(filtered));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, true);
EXPECT_EQ(12, filtered.size());
EXPECT_TRUE(IsSorted(filtered));
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, false);
EXPECT_EQ(12, filtered.size());
EXPECT_TRUE(IsSorted(filtered));
EXPECT_EQ(filtered[0].uri, filtered[1].uri);
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions = <API key>();
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, true);
EXPECT_EQ(6, filtered.size());
EXPECT_TRUE(IsSorted(filtered));
EXPECT_NE(filtered[0].uri, filtered[1].uri);
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions;
extensions.push_back(
RtpExtension(RtpExtension::<API key>, 3));
extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 9));
extensions.push_back(RtpExtension(RtpExtension::kAbsSendTimeUri, 6));
extensions.push_back(
RtpExtension(RtpExtension::<API key>, 1));
extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 14));
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, true);
EXPECT_EQ(1, filtered.size());
EXPECT_EQ(RtpExtension::<API key>, filtered[0].uri);
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions;
extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 1));
extensions.push_back(RtpExtension(RtpExtension::kAbsSendTimeUri, 14));
extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 7));
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, true);
EXPECT_EQ(1, filtered.size());
EXPECT_EQ(RtpExtension::kAbsSendTimeUri, filtered[0].uri);
}
TEST(<API key>, <API key>) {
std::vector<RtpExtension> extensions;
extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 2));
extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 14));
std::vector<webrtc::RtpExtension> filtered =
FilterRtpExtensions(extensions, <API key>, true);
EXPECT_EQ(1, filtered.size());
EXPECT_EQ(RtpExtension::kTimestampOffsetUri, filtered[0].uri);
}
TEST(<API key>, CreateOldApi) {
std::unique_ptr<<API key>> engine(
<API key>::Create(nullptr, nullptr, nullptr));
EXPECT_TRUE(engine);
}
TEST(<API key>, <API key>) {
std::unique_ptr<<API key>> engine(<API key>::Create(
nullptr, webrtc::<API key>(), nullptr, nullptr));
EXPECT_TRUE(engine);
}
} // namespace cricket
|
package es.ucm.fdi.edd.core.erlang.model;
public class MFA {
private String module;
private String function;
private Long arity;
public MFA() {
// TODO Auto-generated constructor stub
}
public MFA(String module, String function, Long arity) {
this.module = module;
this.function = function;
this.arity = arity;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getFunction() {
return function;
}
public void setFunction(String function) {
this.function = function;
}
public Long getArity() {
return arity;
}
public void setArity(Long arity) {
this.arity = arity;
}
}
|
#include "skia/ext/<API key>.h"
#include "skia/ext/platform_canvas.h"
namespace skia {
<API key>* <API key>::Create(int width, int height,
bool is_opaque) {
SkBitmap bitmap;
if (bitmap.tryAllocN32Pixels(width, height, is_opaque)) {
// Follow the logic in SkCanvas::createDevice(), initialize the bitmap if it
// is not opaque.
if (!is_opaque)
bitmap.eraseARGB(0, 0, 0, 0);
return new <API key>(bitmap);
}
return NULL;
}
<API key>* <API key>::Create(int width, int height,
bool is_opaque,
uint8_t* data) {
SkBitmap bitmap;
bitmap.setInfo(SkImageInfo::MakeN32(width, height,
is_opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType));
if (data)
bitmap.setPixels(data);
else if (!bitmap.tryAllocPixels())
return NULL;
return new <API key>(bitmap);
}
<API key>::<API key>(const SkBitmap& bitmap)
: SkBitmapDevice(bitmap) {
SetPlatformDevice(this, this);
}
<API key>::~<API key>() {
}
SkBaseDevice* <API key>::onCreateDevice(const CreateInfo& info,
const SkPaint*) {
SkASSERT(info.fInfo.colorType() == kN32_SkColorType);
return <API key>::Create(info.fInfo.width(), info.fInfo.height(),
info.fInfo.isOpaque());
}
<API key> <API key>::BeginPlatformPaint(
const SkMatrix& transform,
const SkIRect& clip_bounds) {
// TODO(zhenghao): What should we return? The ptr to the address of the
// pixels? Maybe this won't be called at all.
SkPixmap pixmap;
return accessPixels(&pixmap) ? pixmap.writable_addr() : nullptr;
}
// PlatformCanvas impl
SkCanvas* <API key>(int width, int height, bool is_opaque,
uint8_t* data, OnFailureType failureType) {
sk_sp<SkBaseDevice> dev(
<API key>::Create(width, height, is_opaque, data));
return CreateCanvas(dev, failureType);
}
} // namespace skia
|
<?php
namespace WP_SMS\Gateway;
class primotexto extends \WP_SMS\Gateway
{
private $wsdl_link = "https://api.primotexto.com/v2/";
public $tariff = "http:
public $unitrial = true;
public $unit;
public $flash = "disable";
public $isflash = false;
public function __construct()
{
parent::__construct();
$this->validateNumber = "Format: 0600000000, +33600000000";
$this->help = 'Vous devez génerer une clé depuis votre <a href="https://www.primotexto.com/webapp/#/developer/keys">interface Primotexto</a> pour pouvoir utiliser l\'API.';
$this->has_key = true;
}
public function SendSMS()
{
/**
* Modify sender number
*
* @param string $this ->from sender number.
* @since 3.4
*
*/
$this->from = apply_filters('wp_sms_from', $this->from);
/**
* Modify Receiver number
*
* @param array $this ->to receiver number
* @since 3.4
*
*/
$this->to = apply_filters('wp_sms_to', $this->to);
/**
* Modify text message
*
* @param string $this ->msg text message.
* @since 3.4
*
*/
$this->msg = apply_filters('wp_sms_msg', $this->msg);
// Get the credit.
$credit = $this->GetCredit();
// Check gateway credit
if (is_wp_error($credit)) {
// Log the result
$this->log($this->from, $this->msg, $this->to, $credit->get_error_message(), 'error');
return $credit;
}
$api = $this->has_key;
$msg = $this->msg;
$from = $this->from;
$result = array();
$error = 0;
try {
foreach ($this->to as $number) {
try {
$args = array(
'headers' => array(
'X-Primotexto-ApiKey' => $api,
'Content-Type' => 'application/json; charset=UTF-8',
),
'body' => json_encode(
array(
'number' => trim($number),
'message' => $msg,
'sender' => $from
))
);
// Authentication
$response = wp_remote_post($this->wsdl_link . "notification/messages/send", $args);
// check response have error or not
if (is_wp_error($response)) {
$result[$number] = $response->get_error_message();
}
// Ger response code
$response_code = <API key>($response);
// Decode response
$response = json_decode($response['body']);
// Check response code
if ($response_code == '200') {
if (isset($response->snapshotId)) {
$result[$number] = $response;
} else {
$result[$number] = array('code' => $response->code, 'error' => $response->error);
$error++;
}
} else {
$result[$number] = array('code' => $response->code, 'error' => $response->error);
$error++;
}
} catch (\Exception $e) {
// Log the result
$result[$number] = $e->getMessage();
$error++;
}
}
// Check if results have error or not
if ($error > 0) {
// Log the result
$this->log($this->from, $this->msg, $this->to, $result, 'error');
return new \WP_Error('send-sms', $result);
}
// Log the result
$this->log($this->from, $this->msg, $this->to, $result);
/**
* Run hook after send sms.
*
* @param string $result result output.
* @since 2.4
*
*/
do_action('wp_sms_send', $result);
return $result;
} catch (\Exception $e) {
// Log the result
$this->log($this->from, $this->msg, $this->to, $e->getMessage(), 'error');
return new \WP_Error('send-sms', $e->getMessage());
}
}
public function GetCredit()
{
// Check username and password
if (!$this->has_key) {
return new \WP_Error('account-credit', __('The API Key for this gateway is not set', 'wp-sms'));
}
// Authentication
$args = array(
'headers' => array(
'X-Primotexto-ApiKey' => $this->has_key,
)
);
$result = wp_remote_get($this->wsdl_link . "account/stats", $args);
$json = json_decode($result['body']);
if (isset($json->error)) {
return new \WP_Error('credit', $json->error);
}
return $json->credits;
}
}
|
#include "branchadddialog.h"
#include "branchmodel.h"
#include "ui_branchadddialog.h"
#include "gitplugin.h"
#include <utils/fancylineedit.h>
#include <utils/hostosinfo.h>
#include <QPushButton>
#include <QRegularExpression>
#include <QValidator>
namespace Git {
namespace Internal {
/*!
* \brief The BranchNameValidator class validates the corresponding string as
* a valid Git branch name.
*
* The class does this by a couple of rules that are applied on the string.
*
*/
class BranchNameValidator : public QValidator
{
public:
BranchNameValidator(const QStringList &localBranches, QObject *parent = nullptr) :
QValidator(parent),
m_invalidChars('(' + GitPlugin::<API key>() + ")+"),
m_localBranches(localBranches)
{
}
State validate(QString &input, int &pos) const override
{
Q_UNUSED(pos)
if (input.isEmpty())
return Intermediate;
input.replace(m_invalidChars, "_");
// "Intermediate" patterns, may change to Acceptable when user edits further:
if (input.endsWith(".lock")) //..may not end with ".lock"
return Intermediate;
if (input.endsWith('.')) // no dot at the end (but allowed in the middle)
return Intermediate;
if (input.endsWith('/')) // no slash at the end (but allowed in the middle)
return Intermediate;
if (m_localBranches.contains(input, Utils::HostOsInfo::isWindowsHost()
? Qt::CaseInsensitive : Qt::CaseSensitive)) {
return Intermediate;
}
// is a valid branch name
return Acceptable;
}
private:
const QRegularExpression m_invalidChars;
QStringList m_localBranches;
};
<API key>::<API key>(QWidget *parent, BranchModel *model)
: QItemDelegate(parent)
, m_model(model)
{
}
QWidget *<API key>::createEditor(QWidget *parent,
const <API key> & /*option*/,
const QModelIndex & /*index*/) const
{
auto lineEdit = new Utils::FancyLineEdit(parent);
BranchNameValidator *validator = new BranchNameValidator(m_model->localBranchNames(), lineEdit);
lineEdit->setValidator(validator);
return lineEdit;
}
BranchAddDialog::BranchAddDialog(const QStringList &localBranches, Type type, QWidget *parent) :
QDialog(parent),
m_ui(new Ui::BranchAddDialog)
{
m_ui->setupUi(this);
m_ui->trackingCheckBox->setVisible(false);
setCheckoutVisible(false);
switch (type) {
case BranchAddDialog::AddBranch:
setWindowTitle(tr("Add Branch"));
break;
case BranchAddDialog::RenameBranch:
setWindowTitle(tr("Rename Branch"));
break;
case BranchAddDialog::AddTag:
setWindowTitle(tr("Add Tag"));
m_ui->branchNameLabel->setText(tr("Tag name:"));
break;
case BranchAddDialog::RenameTag:
setWindowTitle(tr("Rename Tag"));
m_ui->branchNameLabel->setText(tr("Tag name:"));
break;
}
m_ui->branchNameEdit->setValidator(new BranchNameValidator(localBranches, this));
connect(m_ui->branchNameEdit, &QLineEdit::textChanged, this, &BranchAddDialog::updateButtonStatus);
}
BranchAddDialog::~BranchAddDialog()
{
delete m_ui;
}
void BranchAddDialog::setBranchName(const QString &n)
{
m_ui->branchNameEdit->setText(n);
m_ui->branchNameEdit->selectAll();
}
QString BranchAddDialog::branchName() const
{
return m_ui->branchNameEdit->text();
}
void BranchAddDialog::<API key>(const QString &name, bool remote)
{
if (name.isEmpty()) {
m_ui->trackingCheckBox->setVisible(false);
m_ui->trackingCheckBox->setChecked(false);
} else {
m_ui->trackingCheckBox->setText(remote ? tr("Track remote branch \"%1\"").arg(name) :
tr("Track local branch \"%1\"").arg(name));
m_ui->trackingCheckBox->setVisible(true);
m_ui->trackingCheckBox->setChecked(remote);
}
}
bool BranchAddDialog::track() const
{
return m_ui->trackingCheckBox->isChecked();
}
void BranchAddDialog::setCheckoutVisible(bool visible)
{
m_ui->checkoutCheckBox->setVisible(visible);
m_ui->checkoutCheckBox->setChecked(visible);
}
bool BranchAddDialog::checkout() const
{
return m_ui->checkoutCheckBox->isChecked();
}
/*! Updates the ok button enabled state of the dialog according to the validity of the branch name. */
void BranchAddDialog::updateButtonStatus()
{
m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_ui->branchNameEdit->hasAcceptableInput());
}
} // namespace Internal
} // namespace Git
|
import { ResistorColor } from "./resistor-color-duo"
describe("Resistor Colors", () => {
it("Brown and black", () => {
const resistorColor = new ResistorColor(["brown", "black"])
expect(resistorColor.value()).toEqual(10)
})
it("Blue and grey", () => {
const resistorColor = new ResistorColor(["blue", "grey"])
expect(resistorColor.value()).toEqual(68)
})
it("Yellow and violet", () => {
const resistorColor = new ResistorColor(["yellow", "violet"])
expect(resistorColor.value()).toEqual(47)
})
it("Orange and orange", () => {
const resistorColor = new ResistorColor(["orange", "orange"])
expect(resistorColor.value()).toEqual(33)
})
it("Ignore additional colors", () => {
const resistorColor = new ResistorColor(["green", "brown", "orange"])
expect(resistorColor.value()).toEqual(51)
})
it("Throws error when not enough colors", () => {
expect(() => new ResistorColor(["green"])).toThrowError(
"At least two colors need to be present"
)
})
})
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# <API key>: 2014 Anke Boersma <demm@kaosx.us>
# <API key>: 2016 Teo Mrnjavac <teo@kde.org>
# <API key>: 2018 AlmAck <gluca86@gmail.com>
# <API key>: 2018-2019 Adriaan de Groot <groot@kde.org>
# <API key>: GPL-3.0-or-later
import os
import re
import shutil
import libcalamares
import gettext
_ = gettext.translation("calamares-python",
localedir=libcalamares.utils.gettext_path(),
languages=libcalamares.utils.gettext_languages(),
fallback=True).gettext
def pretty_name():
return _("Configuring locales.")
RE_IS_COMMENT = re.compile("^ *
def is_comment(line):
"""
Does the @p line look like a comment? Whitespace, followed by a #
is a comment-only line.
"""
return bool(RE_IS_COMMENT.match(line))
RE_TRAILING_COMMENT = re.compile("
RE_REST_OF_LINE = re.compile("\\s.*$")
def extract_locale(line):
"""
Extracts a locale from the @p line, and returns a pair of
(extracted-locale, uncommented line). The locale is the
first word of the line after uncommenting (in the human-
readable text explanation at the top of most /etc/locale.gen
files, the locales may be bogus -- either "" or e.g. "Configuration")
"""
# Remove leading spaces and comment signs
line = RE_IS_COMMENT.sub("", line)
uncommented = line.strip()
fields = RE_TRAILING_COMMENT.sub("", uncommented).strip().split()
if len(fields) != 2:
# Not exactly two fields, can't be a proper locale line
return "", uncommented
else:
# Drop all but first field
locale = RE_REST_OF_LINE.sub("", uncommented)
return locale, uncommented
def rewrite_locale_gen(srcfilename, destfilename, locale_conf):
"""
Copies a locale.gen file from @p srcfilename to @p destfilename
(this may be the same name), enabling those locales that can
be found in the map @p locale_conf. Also always enables en_US.UTF-8.
"""
en_us_locale = 'en_US.UTF-8'
# Get entire source-file contents
text = []
with open(srcfilename, "r") as gen:
text = gen.readlines()
# we want unique values, so locale_values should have 1 or 2 items
locale_values = set(locale_conf.values())
locale_values.add(en_us_locale) # Always enable en_US as well
enabled_locales = {}
seen_locales = set()
# Write source out again, enabling some
with open(destfilename, "w") as gen:
for line in text:
c = is_comment(line)
locale, uncommented = extract_locale(line)
# Non-comment lines are preserved, and comment lines
# may be enabled if they match a desired locale
if not c:
seen_locales.add(locale)
else:
for locale_value in locale_values:
if locale.startswith(locale_value):
enabled_locales[locale] = uncommented
gen.write(line)
gen.write("\n###\n#\n# Locales enabled by Calamares\n")
for locale, line in enabled_locales.items():
if locale not in seen_locales:
gen.write(line + "\n")
seen_locales.add(locale)
for locale in locale_values:
if locale not in seen_locales:
gen.write("# Missing: %s\n" % locale)
def run():
""" Create locale """
import libcalamares
locale_conf = libcalamares.globalstorage.value("localeConf")
if not locale_conf:
locale_conf = {
'LANG': 'en_US.UTF-8',
'LC_NUMERIC': 'en_US.UTF-8',
'LC_TIME': 'en_US.UTF-8',
'LC_MONETARY': 'en_US.UTF-8',
'LC_PAPER': 'en_US.UTF-8',
'LC_NAME': 'en_US.UTF-8',
'LC_ADDRESS': 'en_US.UTF-8',
'LC_TELEPHONE': 'en_US.UTF-8',
'LC_MEASUREMENT': 'en_US.UTF-8',
'LC_IDENTIFICATION': 'en_US.UTF-8'
}
install_path = libcalamares.globalstorage.value("rootMountPoint")
if install_path is None:
libcalamares.utils.warning("rootMountPoint is empty, {!s}".format(install_path))
return (_("Configuration Error"),
_("No root mount point is given for <pre>{!s}</pre> to use." ).format("localecfg"))
target_locale_gen = "{!s}/etc/locale.gen".format(install_path)
<API key> = target_locale_gen + ".bak"
<API key> = "{!s}/etc/locale.conf".format(install_path)
<API key> = "{!s}/etc/default".format(install_path)
# restore backup if available
if os.path.exists(<API key>):
shutil.copy2(<API key>, target_locale_gen)
libcalamares.utils.debug("Restored backup {!s} -> {!s}"
.format(<API key>, target_locale_gen))
# run locale-gen if detected; this *will* cause an exception
# if the live system has locale.gen, but the target does not:
# in that case, fix your installation filesystem.
if os.path.exists('/etc/locale.gen'):
rewrite_locale_gen(target_locale_gen, target_locale_gen, locale_conf)
libcalamares.utils.target_env_call(['locale-gen'])
libcalamares.utils.debug('{!s} done'.format(target_locale_gen))
# write /etc/locale.conf
with open(<API key>, "w") as lcf:
for k, v in locale_conf.items():
lcf.write("{!s}={!s}\n".format(k, v))
libcalamares.utils.debug('{!s} done'.format(<API key>))
# write /etc/default/locale if /etc/default exists and is a dir
if os.path.isdir(<API key>):
with open(os.path.join(<API key>, "locale"), "w") as edl:
for k, v in locale_conf.items():
edl.write("{!s}={!s}\n".format(k, v))
libcalamares.utils.debug('{!s} done'.format(<API key>))
return None
|
package org.sigmah.shared.command.result;
/**
* Result which contains a boolean.
*
* @author Denis Colliot (dcolliot@ideia.fr)
*/
public class BooleanResult implements Result {
private boolean value;
public BooleanResult() {
// Serialization.
}
public BooleanResult(final boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
public void setValue(final boolean value) {
this.value = value;
}
}
|
package com.artivisi.android.playsms.ui.adapter;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.artivisi.android.playsms.R;
import com.artivisi.android.playsms.domain.Message;
import com.artivisi.android.playsms.ui.db.PlaySmsDb;
import java.util.List;
public class InboxAdapter extends BaseAdapter{
private Context context;
private List<Message> listMessages;
private PlaySmsDb db;
public InboxAdapter (Context context){
this.context = context;
this.db = new PlaySmsDb(context);
this.listMessages = db.getAllInbox();
}
@Override
public int getCount() {
return listMessages.size();
}
@Override
public Message getItem(int position) {
return listMessages.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = getItem(position);
// Typeface robotoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf");
// Typeface robotoRegular = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
Typeface robotoLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.list_inbox, parent, false);
}
LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.layout_list_inbox);
if(message.getRead() == false){
if (Build.VERSION.SDK_INT >= 16){
layout.setBackground(context.getResources().getDrawable(R.color.white_milk));
}
else{
layout.<API key>(context.getResources().getDrawable(R.color.white_milk));
}
} else {
if (Build.VERSION.SDK_INT >= 16){
layout.setBackground(context.getResources().getDrawable(R.color.grey_light));
}
else{
layout.<API key>(context.getResources().getDrawable(R.color.grey_light));
}
}
TextView inboxFrom = (TextView) convertView.findViewById(R.id.txt_inbox_from);
inboxFrom.setText(message.getSrc());
inboxFrom.setTypeface(robotoLight);
TextView inboxMsg = (TextView) convertView.findViewById(R.id.txt_inbox_msg);
inboxMsg.setText(message.getMsg());
inboxMsg.setTypeface(robotoLight);
TextView inboxDate = (TextView) convertView.findViewById(R.id.txt_inbox_date);
inboxDate.setText(message.getDt());
inboxDate.setTypeface(robotoLight);
return convertView;
}
public void updateList(){
listMessages = db.getAllInbox();
<API key>();
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Wed Feb 09 11:31:29 EST 2011 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class net.sf.sketchel.ds.DataManager
</TITLE>
<META NAME="date" CONTENT="2011-02-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sf.sketchel.ds.DataManager";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../net/sf/sketchel/ds/DataManager.html" title="class in net.sf.sketchel.ds"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?net/sf/sketchel/ds//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="DataManager.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>net.sf.sketchel.ds.DataManager</B></H2>
</CENTER>
No usage of net.sf.sketchel.ds.DataManager
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../net/sf/sketchel/ds/DataManager.html" title="class in net.sf.sketchel.ds"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?net/sf/sketchel/ds//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="DataManager.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
#ifndef SVGImageElement_h
#define SVGImageElement_h
#include "core/SVGNames.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/<API key>.h"
#include "core/svg/SVGGraphicsElement.h"
#include "core/svg/SVGImageLoader.h"
#include "core/svg/SVGURIReference.h"
#include "platform/heap/Handle.h"
namespace blink {
class SVGImageElement final : public SVGGraphicsElement,
public SVGURIReference {
<API key>();
<API key>(SVGImageElement);
public:
<API key>(SVGImageElement);
<API key>();
bool <API key>() const;
SVGAnimatedLength* x() const { return m_x.get(); }
SVGAnimatedLength* y() const { return m_y.get(); }
SVGAnimatedLength* width() const { return m_width.get(); }
SVGAnimatedLength* height() const { return m_height.get(); }
<API key>* preserveAspectRatio() {
return <API key>.get();
}
// Exposed for testing.
ImageResource* cachedImage() const { return imageLoader().image(); }
private:
explicit SVGImageElement(Document&);
bool <API key>() const override {
return !hrefString().isNull();
}
void <API key>(const QualifiedName&,
const AtomicString&,
<API key>*) override;
void svgAttributeChanged(const QualifiedName&) override;
void attachLayoutTree(const AttachContext& = AttachContext()) override;
<API key> insertedInto(ContainerNode*) override;
LayoutObject* createLayoutObject(const ComputedStyle&) override;
const AtomicString imageSourceURL() const override;
bool <API key>() override;
bool <API key>() const override;
void <API key>(Document& oldDocument) override;
SVGImageLoader& imageLoader() const { return *m_imageLoader; }
Member<SVGAnimatedLength> m_x;
Member<SVGAnimatedLength> m_y;
Member<SVGAnimatedLength> m_width;
Member<SVGAnimatedLength> m_height;
Member<<API key>> <API key>;
Member<SVGImageLoader> m_imageLoader;
bool <API key> : 1;
};
} // namespace blink
#endif // SVGImageElement_h
|
#ifndef UBUPGRADETOOEF_H
#define UBUPGRADETOOEF_H
#include <QStackedWidget>
#include <QWidget>
#include <Qt>
#include <QTextEdit>
#include "<API key>.h"
#include "UBActionWidget.h"
class QLabel;
class QPushButton;
class QRadioButton;
class QCheckBox;
class QButtonGroup;
class UBUpgradeToOEF : public QStackedWidget
{
Q_OBJECT
public:
explicit UBUpgradeToOEF(QWidget *parent = 0,<API key>* delegate = 0);
signals:
private slots:
void nextWidgetInStack();
void <API key>();
void onContinueClick();
void appendImportingLog(QString log);
void <API key>();
void <API key>(qint64);
private:
void init();
UBActionWidget* loggerWidget(QString loggerTitle, QTextEdit** logger);
QWidget* mInitialWidget;
QWidget* initialWidget();
QTextEdit* <API key>;
UBActionWidget* <API key>;
QWidget* chooseImportsWidget();
QLabel* mCurrentPath;
UBActionWidget* mImportingWidget;
QTextEdit* mImportingLogger;
QWidget* mFinalWidget;
QWidget* finalWidget();
<API key>* mDelegate;
QCheckBox* createCheckBox(PossiblesImport id, QString label);
QMap<PossiblesImport,QCheckBox*> checkBoxes;
QButtonGroup* mButtonGroup;
};
#endif // UBUPGRADETOOEF_H
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\<API key>.idl
*/
#ifndef <API key>
#define <API key>
#ifndef <API key>
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: <API key> */
#define <API key> "<API key>"
#define <API key> \
{0x35412859, 0xb9d9, 0x423c, \
{ 0x88, 0x66, 0x2d, 0x45, 0x59, 0xfd, 0xd2, 0xbe }}
class NS_NO_VTABLE <API key> : public nsISupports {
public:
<API key>(<API key>)
/* void visitHeader (in ACString aHeader, in ACString aValue); */
NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) = 0;
};
<API key>(<API key>, <API key>)
/* Use this macro when declaring classes that implement this interface. */
#define <API key> \
NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define <API key>(_to) \
NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return _to VisitHeader(aHeader, aValue); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define <API key>(_to) \
NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return !_to ? <API key> : _to->VisitHeader(aHeader, aValue); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsHttpHeaderVisitor : public <API key>
{
public:
NS_DECL_ISUPPORTS
<API key>
nsHttpHeaderVisitor();
private:
~nsHttpHeaderVisitor();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsHttpHeaderVisitor, <API key>)
nsHttpHeaderVisitor::nsHttpHeaderVisitor()
{
/* member initializers and constructor code */
}
nsHttpHeaderVisitor::~nsHttpHeaderVisitor()
{
/* destructor code */
}
/* void visitHeader (in ACString aHeader, in ACString aValue); */
NS_IMETHODIMP nsHttpHeaderVisitor::VisitHeader(const nsACString & aHeader, const nsACString & aValue)
{
return <API key>;
}
/* End of implementation class template. */
#endif
#endif /* <API key> */
|
#include "net/http/http_stream_parser.h"
#include <utility>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/profiler/scoped_tracker.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_endpoint.h"
#include "net/base/upload_data_stream.h"
#include "net/http/<API key>.h"
#include "net/http/<API key>.h"
#include "net/http/http_request_info.h"
#include "net/http/<API key>.h"
#include "net/http/<API key>.h"
#include "net/http/http_util.h"
#include "net/log/net_log_event_type.h"
#include "net/socket/<API key>.h"
#include "net/socket/ssl_client_socket.h"
#include "net/ssl/token_binding.h"
#include "url/url_canon.h"
namespace net {
namespace {
enum <API key> {
<API key> = 0,
// Obsolete: <API key> = 1,
<API key> = 2,
<API key> = 3,
<API key> = 4,
<API key> = 5,
<API key> = 6,
<API key> = 7,
NUM_HEADER_EVENTS
};
void <API key>(<API key> header_event) {
<API key>("Net.<API key>", header_event,
NUM_HEADER_EVENTS);
}
const uint64_t <API key> = 1400;
const size_t <API key> = 1 << 14; // 16KB
std::string <API key>(const HttpResponseHeaders& headers) {
std::string raw_headers = headers.raw_headers();
const char* <API key> = raw_headers.c_str();
const char* header_line = <API key>;
std::string <API key>;
while (header_line[0] != 0) {
<API key> += header_line;
<API key> += "\n";
header_line += strlen(header_line) + 1;
}
return <API key>;
}
// Return true if |headers| contain multiple |field_name| fields with different
// values.
bool <API key>(const HttpResponseHeaders& headers,
const std::string& field_name) {
size_t it = 0;
std::string field_value;
if (!headers.EnumerateHeader(&it, field_name, &field_value))
return false;
// There's at least one |field_name| header. Check if there are any more
// such headers, and if so, return true if they have different values.
std::string field_value2;
while (headers.EnumerateHeader(&it, field_name, &field_value2)) {
if (field_value != field_value2)
return true;
}
return false;
}
std::unique_ptr<base::Value> <API key>(
uint64_t length,
bool is_chunked,
bool did_merge,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("length", static_cast<int>(length));
dict->SetBoolean("is_chunked", is_chunked);
dict->SetBoolean("did_merge", did_merge);
return std::move(dict);
}
// Returns true if |error_code| is an error for which we give the server a
// chance to send a body containing error information, if the error was received
// while trying to upload a request body.
bool <API key>(int error_code) {
return (error_code == <API key>);
}
} // namespace
// Similar to DrainableIOBuffer(), but this version comes with its own
// storage. The motivation is to avoid repeated allocations of
// DrainableIOBuffer.
// Example:
// scoped_refptr<SeekableIOBuffer> buf = new SeekableIOBuffer(1024);
// // capacity() == 1024. size() == BytesRemaining() == BytesConsumed() == 0.
// // data() points to the beginning of the buffer.
// // Read() takes an IOBuffer.
// int bytes_read = some_reader->Read(buf, buf->capacity());
// buf->DidAppend(bytes_read);
// // size() == BytesRemaining() == bytes_read. data() is unaffected.
// while (buf->BytesRemaining() > 0) {
// // Write() takes an IOBuffer. If it takes const char*, we could
// simply use the regular IOBuffer like buf->data() + offset.
// int bytes_written = Write(buf, buf->BytesRemaining());
// buf->DidConsume(bytes_written);
// // BytesRemaining() == 0. BytesConsumed() == size().
// // data() points to the end of the consumed bytes (exclusive).
// // If you want to reuse the buffer, be sure to clear the buffer.
// buf->Clear();
// // size() == BytesRemaining() == BytesConsumed() == 0.
// // data() points to the beginning of the buffer.
class HttpStreamParser::SeekableIOBuffer : public IOBuffer {
public:
explicit SeekableIOBuffer(int capacity)
: IOBuffer(capacity),
real_data_(data_),
capacity_(capacity),
size_(0),
used_(0) {
}
// DidConsume() changes the |data_| pointer so that |data_| always points
// to the first unconsumed byte.
void DidConsume(int bytes) {
SetOffset(used_ + bytes);
}
// Returns the number of unconsumed bytes.
int BytesRemaining() const {
return size_ - used_;
}
// Seeks to an arbitrary point in the buffer. The notion of bytes consumed
// and remaining are updated appropriately.
void SetOffset(int bytes) {
DCHECK_GE(bytes, 0);
DCHECK_LE(bytes, size_);
used_ = bytes;
data_ = real_data_ + used_;
}
// Called after data is added to the buffer. Adds |bytes| added to
// |size_|. data() is unaffected.
void DidAppend(int bytes) {
DCHECK_GE(bytes, 0);
DCHECK_GE(size_ + bytes, 0);
DCHECK_LE(size_ + bytes, capacity_);
size_ += bytes;
}
// Changes the logical size to 0, and the offset to 0.
void Clear() {
size_ = 0;
SetOffset(0);
}
// Returns the logical size of the buffer (i.e the number of bytes of data
// in the buffer).
int size() const { return size_; }
// Returns the capacity of the buffer. The capacity is the size used when
// the object is created.
int capacity() const { return capacity_; };
private:
~SeekableIOBuffer() override {
// data_ will be deleted in IOBuffer::~IOBuffer().
data_ = real_data_;
}
char* real_data_;
const int capacity_;
int size_;
int used_;
};
// 2 CRLFs + max of 8 hex chars.
const size_t HttpStreamParser::<API key> = 12;
HttpStreamParser::HttpStreamParser(ClientSocketHandle* connection,
const HttpRequestInfo* request,
GrowableIOBuffer* read_buffer,
const NetLogWithSource& net_log)
: io_state_(STATE_NONE),
request_(request),
request_headers_(nullptr),
<API key>(0),
<API key>(false),
read_buf_(read_buffer),
<API key>(0),
<API key>(-1),
received_bytes_(0),
sent_bytes_(0),
response_(nullptr),
<API key>(-1),
<API key>(false),
response_body_read_(0),
user_read_buf_(nullptr),
user_read_buf_len_(0),
connection_(connection),
net_log_(net_log),
sent_last_chunk_(false),
upload_error_(OK),
weak_ptr_factory_(this) {
io_callback_ = base::Bind(&HttpStreamParser::OnIOComplete,
weak_ptr_factory_.GetWeakPtr());
}
HttpStreamParser::~HttpStreamParser() {
}
int HttpStreamParser::SendRequest(const std::string& request_line,
const HttpRequestHeaders& headers,
HttpResponseInfo* response,
const CompletionCallback& callback) {
DCHECK_EQ(STATE_NONE, io_state_);
DCHECK(callback_.is_null());
DCHECK(!callback.is_null());
DCHECK(response);
net_log_.AddEvent(NetLogEventType::<API key>,
base::Bind(&HttpRequestHeaders::NetLogCallback,
base::Unretained(&headers), &request_line));
DVLOG(1) << __func__ << "() request_line = \"" << request_line << "\""
<< " headers = \"" << headers.ToString() << "\"";
response_ = response;
// Put the peer's IP address and port into the response.
IPEndPoint ip_endpoint;
int result = connection_->socket()->GetPeerAddress(&ip_endpoint);
if (result != OK)
return result;
response_->socket_address = HostPortPair::FromIPEndPoint(ip_endpoint);
std::string request = request_line + headers.ToString();
<API key> = request.size();
if (request_->upload_data_stream != NULL) {
<API key> = new SeekableIOBuffer(<API key>);
if (request_->upload_data_stream->is_chunked()) {
// Read buffer is adjusted to guarantee that |<API key>| is
// large enough to hold the encoded chunk.
<API key> =
new SeekableIOBuffer(<API key> - <API key>);
} else {
// No need to encode request body, just send the raw data.
<API key> = <API key>;
}
}
io_state_ = STATE_SEND_HEADERS;
// If we have a small request body, then we'll merge with the headers into a
// single write.
bool did_merge = false;
if (<API key>(request, request_->upload_data_stream)) {
int merged_size = static_cast<int>(
<API key> + request_->upload_data_stream->size());
scoped_refptr<IOBuffer> <API key>(
new IOBuffer(merged_size));
// We'll repurpose |request_headers_| to store the merged headers and
// body.
request_headers_ = new DrainableIOBuffer(
<API key>.get(), merged_size);
memcpy(request_headers_->data(), request.data(), <API key>);
request_headers_->DidConsume(<API key>);
uint64_t todo = request_->upload_data_stream->size();
while (todo) {
int consumed = request_->upload_data_stream->Read(
request_headers_.get(), static_cast<int>(todo), CompletionCallback());
// Read() must succeed synchronously if not chunked and in memory.
DCHECK_GT(consumed, 0);
request_headers_->DidConsume(consumed);
todo -= consumed;
}
DCHECK(request_->upload_data_stream->IsEOF());
// Reset the offset, so the buffer can be read from the beginning.
request_headers_->SetOffset(0);
did_merge = true;
net_log_.AddEvent(NetLogEventType::<API key>,
base::Bind(&<API key>,
request_->upload_data_stream->size(),
false, /* not chunked */
true /* merged */));
}
if (!did_merge) {
// If we didn't merge the body with the headers, then |request_headers_|
// contains just the HTTP headers.
scoped_refptr<StringIOBuffer> headers_io_buf(new StringIOBuffer(request));
request_headers_ =
new DrainableIOBuffer(headers_io_buf.get(), headers_io_buf->size());
}
result = DoLoop(OK);
if (result == ERR_IO_PENDING)
callback_ = callback;
return result > 0 ? OK : result;
}
int HttpStreamParser::ReadResponseHeaders(const CompletionCallback& callback) {
DCHECK(io_state_ == STATE_NONE || io_state_ == STATE_DONE);
DCHECK(callback_.is_null());
DCHECK(!callback.is_null());
DCHECK_EQ(0, <API key>);
DCHECK(<API key>());
// This function can be called with io_state_ == STATE_DONE if the
// connection is closed after seeing just a 1xx response code.
if (io_state_ == STATE_DONE)
return <API key>;
int result = OK;
io_state_ = STATE_READ_HEADERS;
if (read_buf_->offset() > 0) {
// Simulate the state where the data was just read from the socket.
result = read_buf_->offset();
read_buf_->set_offset(0);
}
if (result > 0)
io_state_ = <API key>;
result = DoLoop(result);
if (result == ERR_IO_PENDING)
callback_ = callback;
return result > 0 ? OK : result;
}
void HttpStreamParser::Close(bool not_reusable) {
if (not_reusable && connection_->socket())
connection_->socket()->Disconnect();
connection_->Reset();
}
int HttpStreamParser::ReadResponseBody(IOBuffer* buf, int buf_len,
const CompletionCallback& callback) {
DCHECK(io_state_ == STATE_NONE || io_state_ == STATE_DONE);
DCHECK(callback_.is_null());
DCHECK(!callback.is_null());
DCHECK_LE(buf_len, kMaxBufSize);
DCHECK(<API key>());
// Added to investigate crbug.com/499663.
CHECK(buf);
if (io_state_ == STATE_DONE)
return OK;
user_read_buf_ = buf;
user_read_buf_len_ = buf_len;
io_state_ = STATE_READ_BODY;
// Invalidate HttpRequestInfo pointer. This is to allow the stream to be
// shared across multiple consumers.
// It is safe to reset it at this point since request_->upload_data_stream
// is also not needed anymore.
request_ = nullptr;
int result = DoLoop(OK);
if (result == ERR_IO_PENDING)
callback_ = callback;
return result;
}
void HttpStreamParser::OnIOComplete(int result) {
result = DoLoop(result);
// The client callback can do anything, including destroying this class,
// so any pending callback must be issued after everything else is done.
if (result != ERR_IO_PENDING && !callback_.is_null()) {
CompletionCallback c = callback_;
callback_.Reset();
c.Run(result);
}
}
int HttpStreamParser::DoLoop(int result) {
do {
DCHECK_NE(ERR_IO_PENDING, result);
DCHECK_NE(STATE_DONE, io_state_);
DCHECK_NE(STATE_NONE, io_state_);
State state = io_state_;
io_state_ = STATE_NONE;
switch (state) {
case STATE_SEND_HEADERS:
DCHECK_EQ(OK, result);
result = DoSendHeaders();
DCHECK_NE(STATE_NONE, io_state_);
break;
case <API key>:
result = <API key>(result);
DCHECK_NE(STATE_NONE, io_state_);
break;
case STATE_SEND_BODY:
DCHECK_EQ(OK, result);
result = DoSendBody();
DCHECK_NE(STATE_NONE, io_state_);
break;
case <API key>:
result = DoSendBodyComplete(result);
DCHECK_NE(STATE_NONE, io_state_);
break;
case <API key>:
result = <API key>(result);
DCHECK_NE(STATE_NONE, io_state_);
break;
case <API key>:
result = <API key>(result);
break;
case STATE_READ_HEADERS:
net_log_.BeginEvent(NetLogEventType::<API key>);
DCHECK_GE(result, 0);
result = DoReadHeaders();
break;
case <API key>:
result = <API key>(result);
net_log_.<API key>(
NetLogEventType::<API key>, result);
break;
case STATE_READ_BODY:
DCHECK_GE(result, 0);
result = DoReadBody();
break;
case <API key>:
result = DoReadBodyComplete(result);
break;
default:
NOTREACHED();
break;
}
} while (result != ERR_IO_PENDING &&
(io_state_ != STATE_DONE && io_state_ != STATE_NONE));
return result;
}
int HttpStreamParser::DoSendHeaders() {
// TODO(mmenke): Remove ScopedTracker below once crbug.com/424359 is fixed.
tracked_objects::ScopedTracker tracking_profile(
<API key>(
"424359 HttpStreamParser::DoSendHeaders"));
int bytes_remaining = request_headers_->BytesRemaining();
DCHECK_GT(bytes_remaining, 0);
// Record our best estimate of the 'request time' as the time when we send
// out the first bytes of the request headers.
if (bytes_remaining == request_headers_->size())
response_->request_time = base::Time::Now();
io_state_ = <API key>;
return connection_->socket()
->Write(request_headers_.get(), bytes_remaining, io_callback_);
}
int HttpStreamParser::<API key>(int result) {
if (result < 0) {
// In the unlikely case that the headers and body were merged, all the
// the headers were sent, but not all of the body way, and |result| is
// an error that this should try reading after, stash the error for now and
// act like the request was successfully sent.
io_state_ = <API key>;
if (request_headers_->BytesConsumed() >= <API key> &&
<API key>(result)) {
upload_error_ = result;
return OK;
}
return result;
}
sent_bytes_ += result;
request_headers_->DidConsume(result);
if (request_headers_->BytesRemaining() > 0) {
io_state_ = STATE_SEND_HEADERS;
return OK;
}
if (request_->upload_data_stream != NULL &&
(request_->upload_data_stream->is_chunked() ||
// !IsEOF() indicates that the body wasn't merged.
(request_->upload_data_stream->size() > 0 &&
!request_->upload_data_stream->IsEOF()))) {
net_log_.AddEvent(NetLogEventType::<API key>,
base::Bind(&<API key>,
request_->upload_data_stream->size(),
request_->upload_data_stream->is_chunked(),
false /* not merged */));
io_state_ = STATE_SEND_BODY;
return OK;
}
// Finished sending the request.
io_state_ = <API key>;
return OK;
}
int HttpStreamParser::DoSendBody() {
if (<API key>->BytesRemaining() > 0) {
io_state_ = <API key>;
return connection_->socket()
->Write(<API key>.get(),
<API key>->BytesRemaining(),
io_callback_);
}
if (request_->upload_data_stream->is_chunked() && sent_last_chunk_) {
// Finished sending the request.
io_state_ = <API key>;
return OK;
}
<API key>->Clear();
io_state_ = <API key>;
return request_->upload_data_stream->Read(<API key>.get(),
<API key>->capacity(),
io_callback_);
}
int HttpStreamParser::DoSendBodyComplete(int result) {
if (result < 0) {
// If |result| is an error that this should try reading after, stash the
// error for now and act like the request was successfully sent.
io_state_ = <API key>;
if (<API key>(result)) {
upload_error_ = result;
return OK;
}
return result;
}
sent_bytes_ += result;
<API key>->DidConsume(result);
io_state_ = STATE_SEND_BODY;
return OK;
}
int HttpStreamParser::<API key>(int result) {
// |result| is the result of read from the request body from the last call to
// DoSendBody().
if (result < 0) {
io_state_ = <API key>;
return result;
}
// Chunked data needs to be encoded.
if (request_->upload_data_stream->is_chunked()) {
if (result == 0) { // Reached the end.
DCHECK(request_->upload_data_stream->IsEOF());
sent_last_chunk_ = true;
}
// Encode the buffer as 1 chunk.
const base::StringPiece payload(<API key>->data(), result);
<API key>->Clear();
result = EncodeChunk(payload,
<API key>->data(),
<API key>->capacity());
}
if (result == 0) { // Reached the end.
// Reaching EOF means we can finish sending request body unless the data is
// chunked. (i.e. No need to send the terminal chunk.)
DCHECK(request_->upload_data_stream->IsEOF());
DCHECK(!request_->upload_data_stream->is_chunked());
// Finished sending the request.
io_state_ = <API key>;
} else if (result > 0) {
<API key>->DidAppend(result);
result = 0;
io_state_ = STATE_SEND_BODY;
}
return result;
}
int HttpStreamParser::<API key>(int result) {
DCHECK_NE(result, ERR_IO_PENDING);
request_headers_ = nullptr;
<API key> = nullptr;
<API key> = nullptr;
return result;
}
int HttpStreamParser::DoReadHeaders() {
io_state_ = <API key>;
// Grow the read buffer if necessary.
if (read_buf_->RemainingCapacity() == 0)
read_buf_->SetCapacity(read_buf_->capacity() + <API key>);
// See if the user is passing in an IOBuffer with a NULL |data_|.
CHECK(read_buf_->data());
return connection_->socket()
->Read(read_buf_.get(), read_buf_->RemainingCapacity(), io_callback_);
}
int HttpStreamParser::<API key>(int result) {
// <API key> is called with the result of Socket::Read, which is a
// (byte_count | error), and returns (error | OK).
result = <API key>(result);
// TODO(mmenke): The code below is ugly and hacky. A much better and more
// flexible long term solution would be to separate out the read and write
// loops, though this would involve significant changes, both here and
// elsewhere (WebSockets, for instance).
// If still reading the headers, or there was no error uploading the request
// body, just return the result.
if (io_state_ == STATE_READ_HEADERS || upload_error_ == OK)
return result;
// If the result is ERR_IO_PENDING, |io_state_| should be STATE_READ_HEADERS.
DCHECK_NE(ERR_IO_PENDING, result);
// On errors, use the original error received when sending the request.
// The main cases where these are different is when there's a header-related
// error code, or when there's an <API key>, which can result in
// special handling of partial responses and HTTP/0.9 responses.
if (result < 0) {
// Nothing else to do. In the HTTP/0.9 or only partial headers received
// cases, can normally go to other states after an error reading headers.
io_state_ = STATE_DONE;
// Don't let caller see the headers.
response_->headers = nullptr;
return upload_error_;
}
// Skip over 1xx responses as usual, and allow 4xx/5xx error responses to
// override the error received while uploading the body.
int response_code_class = response_->headers->response_code() / 100;
if (response_code_class == 1 || response_code_class == 4 ||
response_code_class == 5) {
return result;
}
// All other status codes are not allowed after an error during upload, to
// make sure the consumer has some indication there was an error.
// Nothing else to do.
io_state_ = STATE_DONE;
// Don't let caller see the headers.
response_->headers = nullptr;
return upload_error_;
}
int HttpStreamParser::DoReadBody() {
io_state_ = <API key>;
// Added to investigate crbug.com/499663.
CHECK(user_read_buf_.get());
// There may be some data left over from reading the response headers.
if (read_buf_->offset()) {
int available = read_buf_->offset() - <API key>;
if (available) {
CHECK_GT(available, 0);
int bytes_from_buffer = std::min(available, user_read_buf_len_);
memcpy(user_read_buf_->data(),
read_buf_->StartOfBuffer() + <API key>,
bytes_from_buffer);
<API key> += bytes_from_buffer;
if (bytes_from_buffer == available) {
read_buf_->SetCapacity(0);
<API key> = 0;
}
return bytes_from_buffer;
} else {
read_buf_->SetCapacity(0);
<API key> = 0;
}
}
// Check to see if we're done reading.
if (<API key>())
return 0;
DCHECK_EQ(0, read_buf_->offset());
return connection_->socket()
->Read(user_read_buf_.get(), user_read_buf_len_, io_callback_);
}
int HttpStreamParser::DoReadBodyComplete(int result) {
// When the connection is closed, there are numerous ways to interpret it.
// - If a Content-Length header is present and the body contains exactly that
// number of bytes at connection close, the response is successful.
// - If a Content-Length header is present and the body contains fewer bytes
// than promised by the header at connection close, it may indicate that
// the connection was closed prematurely, or it may indicate that the
// server sent an invalid Content-Length header. Unfortunately, the invalid
// Content-Length header case does occur in practice and other browsers are
// tolerant of it. We choose to treat it as an error for now, but the
// download system treats it as a non-error, and URLRequestHttpJob also
// treats it as OK if the Content-Length is the post-decoded body content
// length.
// - If chunked encoding is used and the terminating chunk has been processed
// when the connection is closed, the response is successful.
// - If chunked encoding is used and the terminating chunk has not been
// processed when the connection is closed, it may indicate that the
// connection was closed prematurely or it may indicate that the server
// sent an invalid chunked encoding. We choose to treat it as
// an invalid chunked encoding.
// - If a Content-Length is not present and chunked encoding is not used,
// connection close is the only way to signal that the response is
// complete. Unfortunately, this also means that there is no way to detect
// early close of a connection. No error is returned.
if (result == 0 && !<API key>() && <API key>()) {
if (chunked_decoder_.get())
result = <API key>;
else
result = <API key>;
}
if (result > 0)
received_bytes_ += result;
// Filter incoming data if appropriate. FilterBuf may return an error.
if (result > 0 && chunked_decoder_.get()) {
result = chunked_decoder_->FilterBuf(user_read_buf_->data(), result);
if (result == 0 && !chunked_decoder_->reached_eof()) {
// Don't signal completion of the Read call yet or else it'll look like
// we received end-of-file. Wait for more data.
io_state_ = STATE_READ_BODY;
return OK;
}
}
if (result > 0)
response_body_read_ += result;
if (result <= 0 || <API key>()) {
io_state_ = STATE_DONE;
// Save the overflow data, which can be in two places. There may be
// some left over in |user_read_buf_|, plus there may be more
// in |read_buf_|. But the part left over in |user_read_buf_| must have
// come from the |read_buf_|, so there's room to put it back at the
// start first.
int <API key> = read_buf_->offset() - <API key>;
int save_amount = 0;
if (chunked_decoder_.get()) {
save_amount = chunked_decoder_->bytes_after_eof();
} else if (<API key> >= 0) {
int64_t extra_data_read = response_body_read_ - <API key>;
if (extra_data_read > 0) {
save_amount = static_cast<int>(extra_data_read);
if (result > 0)
result -= save_amount;
}
}
CHECK_LE(save_amount + <API key>, kMaxBufSize);
if (read_buf_->capacity() < save_amount + <API key>) {
read_buf_->SetCapacity(save_amount + <API key>);
}
if (save_amount) {
received_bytes_ -= save_amount;
memcpy(read_buf_->StartOfBuffer(), user_read_buf_->data() + result,
save_amount);
}
read_buf_->set_offset(save_amount);
if (<API key>) {
memmove(read_buf_->data(),
read_buf_->StartOfBuffer() + <API key>,
<API key>);
read_buf_->set_offset(save_amount + <API key>);
}
<API key> = 0;
} else {
// Now waiting for more of the body to be read.
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
}
return result;
}
int HttpStreamParser::<API key>(int result) {
DCHECK_EQ(0, <API key>);
if (result == 0)
result = <API key>;
if (result == <API key>) {
// The connection closed without getting any more data.
if (read_buf_->offset() == 0) {
io_state_ = STATE_DONE;
// If the connection has not been reused, it may have been a 0-length
// HTTP/0.9 responses, but it was most likely an error, so just return
// ERR_EMPTY_RESPONSE instead. If the connection was reused, just pass
// on the original connection close error, as rather than being an
// empty HTTP/0.9 response it's much more likely the server closed the
// socket before it received the request.
if (!connection_->is_reused())
return ERR_EMPTY_RESPONSE;
return result;
}
// Accepting truncated headers over HTTPS is a potential security
// vulnerability, so just return an error in that case.
// If <API key> is -1, this may be a < 8 byte HTTP/0.9
// response. However, accepting such a response over HTTPS would allow a
// MITM to truncate an HTTP/1.x status line to look like a short HTTP/0.9
// response if the peer put a record boundary at the first 8 bytes. To
// ensure that all response headers received over HTTPS are pristine, treat
// such responses as errors.
// TODO(mmenke): Returning <API key> when a response
// looks like an HTTP/0.9 response is weird. Should either come up with
// another error code, or, better, disable HTTP/0.9 over HTTPS (and give
// that a new error code).
if (request_->url.<API key>()) {
io_state_ = STATE_DONE;
return <API key>;
}
// Parse things as well as we can and let the caller decide what to do.
int end_offset;
if (<API key> >= 0) {
// The response looks to be a truncated set of HTTP headers.
io_state_ = <API key>;
end_offset = read_buf_->offset();
<API key>(<API key>);
} else {
// The response is apparently using HTTP/0.9. Treat the entire response
// as the body.
end_offset = 0;
}
int rv = <API key>(end_offset);
if (rv < 0)
return rv;
return result;
}
if (result < 0) {
io_state_ = STATE_DONE;
return result;
}
// Record our best estimate of the 'response time' as the time when we read
// the first bytes of the response headers.
if (read_buf_->offset() == 0)
response_->response_time = base::Time::Now();
read_buf_->set_offset(read_buf_->offset() + result);
DCHECK_LE(read_buf_->offset(), read_buf_->capacity());
DCHECK_GT(result, 0);
int <API key> = <API key>();
// Note: -1 is special, it indicates we haven't found the end of headers.
// Anything less than -1 is a net::Error, so we bail out.
if (<API key> < -1)
return <API key>;
if (<API key> == -1) {
io_state_ = STATE_READ_HEADERS;
// Prevent growing the headers buffer indefinitely.
if (read_buf_->offset() >= kMaxHeaderBufSize) {
io_state_ = STATE_DONE;
return <API key>;
}
} else {
<API key>();
// If the body is zero length, the caller may not call ReadResponseBody,
// which is where any extra data is copied to read_buf_, so we move the
// data here.
if (<API key> == 0) {
int extra_bytes = read_buf_->offset() - <API key>;
if (extra_bytes) {
CHECK_GT(extra_bytes, 0);
memmove(read_buf_->StartOfBuffer(),
read_buf_->StartOfBuffer() + <API key>,
extra_bytes);
}
read_buf_->SetCapacity(extra_bytes);
if (response_->headers->response_code() / 100 == 1) {
// After processing a 1xx response, the caller will ask for the next
// header, so reset state to support that. We don't completely ignore a
// 1xx response because it cannot be returned in reply to a CONNECT
// request so we return OK here, which lets the caller inspect the
// response and reject it in the event that we're setting up a CONNECT
// tunnel.
<API key> = -1;
<API key> = -1;
// Now waiting for the second set of headers to be read.
} else {
// Only set keep-alive based on final set of headers.
<API key> = response_->headers->IsKeepAlive();
io_state_ = STATE_DONE;
}
return OK;
}
// Only set keep-alive based on final set of headers.
<API key> = response_->headers->IsKeepAlive();
// Note where the headers stop.
<API key> = <API key>;
// Now waiting for the body to be read.
}
return OK;
}
int HttpStreamParser::<API key>() {
int end_offset = -1;
DCHECK_EQ(0, <API key>);
// Look for the start of the status line, if it hasn't been found yet.
if (<API key> < 0) {
<API key> = HttpUtil::<API key>(
read_buf_->StartOfBuffer(), read_buf_->offset());
}
if (<API key> >= 0) {
end_offset = HttpUtil::LocateEndOfHeaders(read_buf_->StartOfBuffer(),
read_buf_->offset(),
<API key>);
} else if (read_buf_->offset() >= 8) {
// Enough data to decide that this is an HTTP/0.9 response.
// 8 bytes = (4 bytes of junk) + "http".length()
end_offset = 0;
}
if (end_offset == -1)
return -1;
int rv = <API key>(end_offset);
if (rv < 0)
return rv;
return end_offset;
}
int HttpStreamParser::<API key>(int end_offset) {
scoped_refptr<HttpResponseHeaders> headers;
DCHECK_EQ(0, <API key>);
<API key>(<API key>);
if (<API key> > 0) {
bool <API key> = false;
for (int i = 0; i < <API key>; ++i) {
if (!strchr(" \t\r\n", read_buf_->StartOfBuffer()[i])) {
<API key> = true;
break;
}
}
if (<API key>) {
<API key>(<API key>);
} else {
<API key>(<API key>);
}
}
if (<API key> >= 0) {
received_bytes_ += end_offset;
std::string raw_headers =
HttpUtil::AssembleRawHeaders(read_buf_->StartOfBuffer(), end_offset);
ValidateStatusLine(
std::string(read_buf_->StartOfBuffer(), raw_headers.find('\0')));
headers = new HttpResponseHeaders(raw_headers);
} else {
// Enough data was read -- there is no status line, so this is HTTP/0.9, or
// the server is broken / doesn't speak HTTP.
// If the port is not the default for the scheme, assume it's not a real
// HTTP/0.9 response, and fail the request.
// TODO(crbug.com/624462): Further restrict the cases in which we allow
// HTTP/0.9.
std::string scheme(request_->url.scheme());
if (!<API key> &&
url::<API key>(scheme.c_str(), scheme.length()) !=
request_->url.EffectiveIntPort()) {
return <API key>;
}
headers = new HttpResponseHeaders(std::string("HTTP/0.9 200 OK"));
if (request_->url.<API key>()) {
<API key>(<API key>);
} else {
<API key>(<API key>);
}
if (connection_->is_reused())
<API key>(<API key>);
}
// Check for multiple Content-Length headers when the response is not
// chunked-encoded. If they exist, and have distinct values, it's a potential
// response smuggling attack.
if (!headers->IsChunkEncoded()) {
if (<API key>(*headers, "Content-Length"))
return <API key>;
}
// Check for multiple Content-Disposition or Location headers. If they exist,
// it's also a potential response smuggling attack.
if (<API key>(*headers, "Content-Disposition"))
return <API key>;
if (<API key>(*headers, "Location"))
return <API key>;
response_->headers = headers;
if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
response_->connection_info = HttpResponseInfo::<API key>;
} else if (headers->GetHttpVersion() == HttpVersion(1, 0)) {
response_->connection_info = HttpResponseInfo::<API key>;
} else if (headers->GetHttpVersion() == HttpVersion(1, 1)) {
response_->connection_info = HttpResponseInfo::<API key>;
}
response_->vary_data.Init(*request_, *response_->headers);
DVLOG(1) << __func__ << "() content_length = \""
<< response_->headers->GetContentLength() << "\n\""
<< " headers = \"" << <API key>(*response_->headers)
<< "\"";
return OK;
}
void HttpStreamParser::<API key>() {
// Figure how to determine EOF:
// For certain responses, we know the content length is always 0. From
// RFC 7230 Section 3.3 Message Body:
// The presence of a message body in a response depends on both the
// request method to which it is responding and the response status code
// (Section 3.1.2). Responses to the HEAD request method (Section 4.3.2
// of [RFC7231]) never include a message body because the associated
// response header fields (e.g., Transfer-Encoding, Content-Length,
// etc.), if present, indicate only what their values would have been if
// the request method had been GET (Section 4.3.1 of [RFC7231]). 2xx
// (Successful) responses to a CONNECT request method (Section 4.3.6 of
// [RFC7231]) switch to tunnel mode instead of having a message body.
// All 1xx (Informational), 204 (No Content), and 304 (Not Modified)
// responses do not include a message body. All other responses do
// include a message body, although the body might be of zero length.
// From RFC 7231 Section 6.3.6 205 Reset Content:
// Since the 205 status code implies that no additional content will be
// provided, a server MUST NOT generate a payload in a 205 response.
if (response_->headers->response_code() / 100 == 1) {
<API key> = 0;
} else {
switch (response_->headers->response_code()) {
case 204: // No Content
case 205: // Reset Content
case 304: // Not Modified
<API key> = 0;
break;
}
}
if (request_->method == "HEAD")
<API key> = 0;
if (<API key> == -1) {
// "Transfer-Encoding: chunked" trumps "Content-Length: N"
if (response_->headers->IsChunkEncoded()) {
chunked_decoder_.reset(new HttpChunkedDecoder());
} else {
<API key> = response_->headers->GetContentLength();
// If <API key> is still -1, then we have to wait
// for the server to close the connection.
}
}
}
bool HttpStreamParser::<API key>() const {
if (chunked_decoder_.get())
return chunked_decoder_->reached_eof();
if (<API key> != -1)
return response_body_read_ >= <API key>;
return false; // Must read to EOF.
}
bool HttpStreamParser::<API key>() const {
return chunked_decoder_.get() || <API key> >= 0;
}
bool HttpStreamParser::IsMoreDataBuffered() const {
return read_buf_->offset() > <API key>;
}
bool HttpStreamParser::IsConnectionReused() const {
ClientSocketHandle::SocketReuseType reuse_type = connection_->reuse_type();
return connection_->is_reused() ||
reuse_type == ClientSocketHandle::UNUSED_IDLE;
}
void HttpStreamParser::SetConnectionReused() {
connection_->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
}
bool HttpStreamParser::CanReuseConnection() const {
if (!<API key>())
return false;
if (!<API key>)
return false;
// Check if extra data was received after reading the entire response body. If
// extra data was received, reusing the socket is not a great idea. This does
// have the down side of papering over certain server bugs, but seems to be
// the best option here.
// TODO(mmenke): Consider logging this - hard to decipher socket reuse
// behavior makes NetLogs harder to read.
if (<API key>() && IsMoreDataBuffered())
return false;
return connection_->socket() && connection_->socket()->IsConnected();
}
void HttpStreamParser::GetSSLInfo(SSLInfo* ssl_info) {
if (request_->url.<API key>() && connection_->socket()) {
SSLClientSocket* ssl_socket =
static_cast<SSLClientSocket*>(connection_->socket());
ssl_socket->GetSSLInfo(ssl_info);
}
}
void HttpStreamParser::<API key>(
SSLCertRequestInfo* cert_request_info) {
if (request_->url.<API key>() && connection_->socket()) {
SSLClientSocket* ssl_socket =
static_cast<SSLClientSocket*>(connection_->socket());
ssl_socket-><API key>(cert_request_info);
}
}
Error HttpStreamParser::Get<API key>(crypto::ECPrivateKey* key,
TokenBindingType tb_type,
std::vector<uint8_t>* out) {
if (!request_->url.<API key>() || !connection_->socket()) {
NOTREACHED();
return ERR_FAILED;
}
SSLClientSocket* ssl_socket =
static_cast<SSLClientSocket*>(connection_->socket());
return ssl_socket->Get<API key>(key, tb_type, out);
}
int HttpStreamParser::EncodeChunk(const base::StringPiece& payload,
char* output,
size_t output_size) {
if (output_size < payload.size() + <API key>)
return <API key>;
char* cursor = output;
// Add the header.
const int num_chars = base::snprintf(output, output_size,
"%X\r\n",
static_cast<int>(payload.size()));
cursor += num_chars;
// Add the payload if any.
if (payload.size() > 0) {
memcpy(cursor, payload.data(), payload.size());
cursor += payload.size();
}
// Add the trailing CRLF.
memcpy(cursor, "\r\n", 2);
cursor += 2;
return cursor - output;
}
// static
bool HttpStreamParser::<API key>(
const std::string& request_headers,
const UploadDataStream* request_body) {
if (request_body != NULL &&
// IsInMemory() ensures that the request body is not chunked.
request_body->IsInMemory() &&
request_body->size() > 0) {
uint64_t merged_size = request_headers.size() + request_body->size();
if (merged_size <= <API key>)
return true;
}
return false;
}
void HttpStreamParser::ValidateStatusLine(const std::string& status_line) {
<API key>::StatusLineStatus status =
<API key>::ValidateStatusLine(status_line);
<API key>("Net.<API key>", status,
<API key>::STATUS_LINE_MAX);
}
bool HttpStreamParser::<API key>() {
return request_headers_ == nullptr && <API key> == nullptr &&
<API key> == nullptr;
}
} // namespace net
|
SAAS Admin Scripts
===
Scripts for Google Apps Manager, and other things
## User provisioning scripts
* `create_user.sh`: Create a Google Apps user, email them, put them in a 2FA exception group
* `remove_user.sh`: Start the process (currently using CloudPages) to remove the user (and keep backups)
* `dropbox.sh`: Add or remove users in DropBox.
* `trello.sh`: Invite a user to your Trello organisation
* `slack.sh`: Inite a user to your Slack organisation
* `aws_user.sh`: Add an IAM user to Amazon Web Services
## Misc scripts
* `forwarder.sh`: report on who is forwarding email
* `inactive_users.sh`: report on who isn't using their accounts
## Dependencies
* `pwgen` (from homebrew on osx)
* you're best to use virtualenv for python: `virtualenv . && . ./bin/activate`
* at least 1 python dependency: `./pip install -r requirements.txt`
|
/* Project name: nstd - non-standard library */
/* File name: nstd_memory.cpp */
/* Description: memory managers module */
/* Email: vlasov at academ.org */
#pragma once
#include "memory/allocator/<API key>.cpp"
#include "memory/exception/<API key>.cpp"
#include "memory/storage/nstd_memory_storage.cpp"
#include "memory/unit/nstd_memory_unit.cpp"
#include "memory/nstd_memory_Factory.cpp"
#include "memory/<API key>.cpp"
#include "memory/<API key>.cpp"
#include "memory/nstd_memory_Space.cpp"
#include "memory/nstd_memory_Unit.cpp"
#include "memory/<API key>.cpp"
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>org.argouml.kernel package</title>
<!
Copyright (c) 1996-99 The Regents of the University of California. All
Rights Reserved. Permission to use, copy, modify, and distribute this
software and its documentation without fee, and without a written
agreement is hereby granted, provided that the above copyright notice
and this paragraph appear in all copies. This software program and
documentation are copyrighted by The Regents of the University of
California. The software program and documentation are supplied "AS
IS", without any accompanying services from The Regents. The Regents
does not warrant that the operation of the program will be
uninterrupted or error-free. The end-user understands that the program
was developed for research purposes and is advised not to rely
exclusively on the program for any reason. IN NO EVENT SHALL THE
UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
</head>
<body bgcolor="white">
<p>contains the graph model for a class diagram.
<h2>Package Specification</h2>
(none)
<h2>Related Documentation </h2>
(none)
</body>
</html>
|
#ifndef FAILURE_H
#define FAILURE_H
// Failure records the circumstances surrounding a test failure. Using C++
// macros were are able to record the name of the file where the failure
// occurred, the line number, and the text of the condition which provoked
// the failure.
#include <string>
class Failure
{
public:
Failure(std::string theCondition, std::string theTestName, std::string theFileName, long theLineNumber)
: condition(theCondition), testName(theTestName), fileName(theFileName), lineNumber(theLineNumber) {
}
std::string condition;
std::string testName;
std::string fileName;
long lineNumber;
};
inline std::ostream& operator<< (std::ostream& stream, Failure& failure)
{
stream
<< "Failure: \"" << failure.condition.c_str() << "\" "
<< "line " << failure.lineNumber << " in "
<< failure.fileName.c_str()
<< std::endl;
return stream;
}
#endif
|
#ifndef _LOGGING_H
#define _LOGGING_H
/*
* Logging.
* Every error/warning is reported to the global error log using
* uperf_log(type, errno, msg). The logger stores upto NUM_ERR_STR
* messages, and if full, the log is flushed.
* If the previous message is the same as the current message,
* the count for the previous message is incremented, and this
* message is discarded.
*
* Periodic flushes of the log can also be accomplished using
* uperf_log_flush()
*
* Log messages are of type <msg, count> where count is the
* number of times this message was successively received
*/
#include <pthread.h>
#define NUM_ERRNOS 256
#define NUM_ERR_STR 256
#define ERR_STR_LEN 512
typedef enum {
UPERF_NONVERBOSE = 0, /* Prints only critical msgs */
UPERF_VERBOSE = 2, /* Prints misc info msgs */
} uperf_log_level;
typedef enum {
UPERF_LOG_ERROR = 0,
UPERF_LOG_QUIT,
UPERF_LOG_ABORT,
UPERF_LOG_INFO,
UPERF_LOG_DEBUG,
UPERF_LOG_WARN
}uperf_msg_type;
typedef struct {
pthread_mutex_t lock;
pthread_mutexattr_t attr;
struct _errstr {
int myerrno;
uperf_msg_type type;
int count;
char str[ERR_STR_LEN];
}msg[NUM_ERR_STR];
int num_msg;
} uperf_log_t;
int uperf_log_init(uperf_log_t *);
int uperf_log_flush();
int <API key>(char *, int);
int uperf_log_msg(uperf_msg_type, int, char *);
int ulog(uperf_msg_type type, int myerrno, char *fmt, ...);
int uperf_log_num_msgs();
void uperf_printer(uperf_log_level, uperf_msg_type, const char *, ...);
int uperf_set_log_level(uperf_log_level);
/*
* Macros that define the error functions and maps back to uperf_printer
* basic function
*/
#define uperf_error(...) uperf_printer(UPERF_NONVERBOSE, \
UPERF_LOG_ERROR,__VA_ARGS__);
#define uperf_fatal(...) {uperf_printer(UPERF_NONVERBOSE, \
UPERF_LOG_ERROR,__VA_ARGS__); exit(1); }
#define uperf_quit(...) {uperf_printer(UPERF_NONVERBOSE, \
UPERF_LOG_QUIT,__VA_ARGS__); exit(1); }
#define uperf_abort(...) {uperf_printer(UPERF_NONVERBOSE, \
UPERF_LOG_ABORT,__VA_ARGS__); abort();exit(1);}
#define uperf_warn(...) {uperf_printer(UPERF_VERBOSE, \
UPERF_LOG_WARN, __VA_ARGS__);}
#define uperf_info(...) {uperf_printer(UPERF_VERBOSE, \
UPERF_LOG_INFO, __VA_ARGS__);}
#define ulog_err(...) ulog(UPERF_LOG_ERROR, errno, __VA_ARGS__);
#define ulog_warn(...) ulog(UPERF_LOG_WARN, errno, __VA_ARGS__);
#ifdef DEBUG
#define uperf_debug(...) {uperf_printer(UPERF_NONVERBOSE, \
UPERF_LOG_DEBUG, __VA_ARGS__);}
#else
#define uperf_debug(...)
#endif
#endif /* _LOGGING_H */
|
#include "includes.h"
#include "librpc/gen_ndr/libnetapi.h"
#include "lib/netapi/netapi.h"
#include "lib/netapi/netapi_private.h"
#include "lib/netapi/libnetapi.h"
#include "../librpc/gen_ndr/cli_samr.h"
#include "../librpc/gen_ndr/cli_lsa.h"
static NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *domain_handle,
const char *group_name,
uint32_t access_rights,
struct policy_handle *alias_handle)
{
NTSTATUS status;
struct lsa_String lsa_account_name;
struct samr_Ids user_rids, name_types;
init_lsa_String(&lsa_account_name, group_name);
status = <API key>(pipe_cli, mem_ctx,
domain_handle,
1,
&lsa_account_name,
&user_rids,
&name_types);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
switch (name_types.ids[0]) {
case SID_NAME_ALIAS:
case SID_NAME_WKN_GRP:
break;
default:
return <API key>;
}
return <API key>(pipe_cli, mem_ctx,
domain_handle,
access_rights,
user_rids.ids[0],
alias_handle);
}
static NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *handle,
uint32_t rid,
uint32_t access_rights,
enum samr_AliasInfoEnum level,
union samr_AliasInfo **alias_info)
{
NTSTATUS status;
struct policy_handle alias_handle;
union samr_AliasInfo *_alias_info = NULL;
ZERO_STRUCT(alias_handle);
status = <API key>(pipe_cli, mem_ctx,
handle,
access_rights,
rid,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
status = <API key>(pipe_cli, mem_ctx,
&alias_handle,
level,
&_alias_info);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
*alias_info = _alias_info;
done:
if (is_valid_policy_hnd(&alias_handle)) {
rpccli_samr_Close(pipe_cli, mem_ctx, &alias_handle);
}
return status;
}
WERROR NetLocalGroupAdd_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t rid;
struct LOCALGROUP_INFO_0 *info0 = NULL;
struct LOCALGROUP_INFO_1 *info1 = NULL;
const char *alias_name = NULL;
if (!r->in.buffer) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)r->in.buffer;
alias_name = info0->lgrpi0_name;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)r->in.buffer;
alias_name = info1->lgrpi1_name;
break;
default:
werr = WERR_UNKNOWN_LEVEL;
goto done;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&builtin_handle,
alias_name,
<API key>,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
werr = WERR_ALIAS_EXISTS;
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key> |
<API key>,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, alias_name);
status = <API key>(pipe_cli, ctx,
&domain_handle,
&lsa_account_name,
SEC_STD_DELETE |
<API key>,
&alias_handle,
&rid);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (r->in.level == 1 && info1->lgrpi1_comment) {
union samr_AliasInfo alias_info;
init_lsa_String(&alias_info.description, info1->lgrpi1_comment);
status = <API key>(pipe_cli, ctx,
&alias_handle,
<API key>,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
rpccli_samr_Close(pipe_cli, ctx, &alias_handle);
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
<API key>(ctx, &builtin_handle);
<API key>(ctx, &connect_handle);
}
return werr;
}
WERROR NetLocalGroupAdd_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
<API key>(ctx, r, NetLocalGroupAdd);
}
WERROR NetLocalGroupDel_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto delete_alias;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key> |
<API key>,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
delete_alias:
status = <API key>(pipe_cli, ctx,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
ZERO_STRUCT(alias_handle);
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
rpccli_samr_Close(pipe_cli, ctx, &alias_handle);
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
<API key>(ctx, &builtin_handle);
<API key>(ctx, &connect_handle);
}
return werr;
}
WERROR NetLocalGroupDel_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
<API key>(ctx, r, NetLocalGroupDel);
}
static WERROR <API key>(TALLOC_CTX *mem_ctx,
const char *alias_name,
struct samr_AliasInfoAll *info,
uint32_t level,
uint32_t *entries_read,
uint8_t **buffer)
{
struct LOCALGROUP_INFO_0 g0;
struct LOCALGROUP_INFO_1 g1;
struct <API key> g1002;
switch (level) {
case 0:
g0.lgrpi0_name = talloc_strdup(mem_ctx, alias_name);
<API key>(g0.lgrpi0_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_0, g0,
(struct LOCALGROUP_INFO_0 **)buffer, entries_read);
break;
case 1:
g1.lgrpi1_name = talloc_strdup(mem_ctx, alias_name);
g1.lgrpi1_comment = talloc_strdup(mem_ctx, info->description.string);
<API key>(g1.lgrpi1_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1, g1,
(struct LOCALGROUP_INFO_1 **)buffer, entries_read);
break;
case 1002:
g1002.lgrpi1002_comment = talloc_strdup(mem_ctx, info->description.string);
ADD_TO_ARRAY(mem_ctx, struct <API key>, g1002,
(struct <API key> **)buffer, entries_read);
break;
default:
return WERR_UNKNOWN_LEVEL;
}
return WERR_OK;
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
union samr_AliasInfo *alias_info = NULL;
uint32_t entries_read = 0;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
<API key>,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto query_alias;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key> |
<API key>,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
<API key>,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
query_alias:
status = <API key>(pipe_cli, ctx,
&alias_handle,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
werr = <API key>(ctx,
r->in.group_name,
&alias_info->all,
r->in.level, &entries_read,
r->out.buffer);
done:
if (is_valid_policy_hnd(&alias_handle)) {
rpccli_samr_Close(pipe_cli, ctx, &alias_handle);
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
<API key>(ctx, &builtin_handle);
<API key>(ctx, &connect_handle);
}
return werr;
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
<API key>(ctx, r, <API key>);
}
static WERROR <API key>(TALLOC_CTX *mem_ctx,
uint32_t level,
uint8_t *buffer,
enum samr_AliasInfoEnum *alias_level,
union samr_AliasInfo **alias_info)
{
struct LOCALGROUP_INFO_0 *info0;
struct LOCALGROUP_INFO_1 *info1;
struct <API key> *info1002;
union samr_AliasInfo *info = NULL;
info = TALLOC_ZERO_P(mem_ctx, union samr_AliasInfo);
<API key>(info);
switch (level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)buffer;
init_lsa_String(&info->name, info0->lgrpi0_name);
*alias_level = ALIASINFONAME;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)buffer;
/* group name will be ignored */
init_lsa_String(&info->description, info1->lgrpi1_comment);
*alias_level = <API key>;
break;
case 1002:
info1002 = (struct <API key> *)buffer;
init_lsa_String(&info->description, info1002->lgrpi1002_comment);
*alias_level = <API key>;
break;
}
*alias_info = info;
return WERR_OK;
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
enum samr_AliasInfoEnum alias_level = 0;
union samr_AliasInfo *alias_info = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = <API key>(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
<API key>,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto set_alias;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
<API key>,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
}
set_alias:
werr = <API key>(ctx, r->in.level, r->in.buffer,
&alias_level, &alias_info);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(pipe_cli, ctx,
&alias_handle,
alias_level,
alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
rpccli_samr_Close(pipe_cli, ctx, &alias_handle);
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
<API key>(ctx, &builtin_handle);
<API key>(ctx, &connect_handle);
}
return werr;
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
<API key>(ctx, r, <API key>);
}
WERROR NetLocalGroupEnum_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t entries_read = 0;
union samr_DomainInfo *domain_info = NULL;
union samr_DomainInfo *builtin_info = NULL;
struct samr_SamArray *domain_sam_array = NULL;
struct samr_SamArray *builtin_sam_array = NULL;
int i;
if (!r->out.buffer) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->out.total_entries) {
*r->out.total_entries = 0;
}
if (r->out.entries_read) {
*r->out.entries_read = 0;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key> |
<API key> |
<API key>,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key> |
<API key> |
<API key>,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(pipe_cli, ctx,
&builtin_handle,
2,
&builtin_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += builtin_info->general.num_aliases;
}
status = <API key>(pipe_cli, ctx,
&domain_handle,
2,
&domain_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += domain_info->general.num_aliases;
}
status = <API key>(pipe_cli, ctx,
&builtin_handle,
r->in.resume_handle,
&builtin_sam_array,
r->in.prefmaxlen,
&entries_read);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
for (i=0; i<builtin_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = <API key>(ctx, pipe_cli,
&builtin_handle,
builtin_sam_array->entries[i].idx,
<API key>,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = <API key>(ctx,
builtin_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
status = <API key>(pipe_cli, ctx,
&domain_handle,
r->in.resume_handle,
&domain_sam_array,
r->in.prefmaxlen,
&entries_read);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
for (i=0; i<domain_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = <API key>(ctx, pipe_cli,
&domain_handle,
domain_sam_array->entries[i].idx,
<API key>,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = <API key>(ctx,
domain_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
done:
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
<API key>(ctx, &builtin_handle);
<API key>(ctx, &connect_handle);
}
return werr;
}
WERROR NetLocalGroupEnum_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
<API key>(ctx, r, NetLocalGroupEnum);
}
static NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *lsa_pipe,
const char *name,
struct dom_sid *sid)
{
NTSTATUS status;
struct policy_handle lsa_handle;
struct lsa_RefDomainList *domains = NULL;
struct lsa_TransSidArray3 sids;
uint32_t count = 0;
struct lsa_String names;
uint32_t num_names = 1;
if (!sid || !name) {
return <API key>;
}
ZERO_STRUCT(sids);
init_lsa_String(&names, name);
status = <API key>(lsa_pipe, mem_ctx,
false,
<API key> |
<API key> |
<API key>,
&lsa_handle);
<API key>(status);
status = <API key>(lsa_pipe, mem_ctx,
&lsa_handle,
num_names,
&names,
&domains,
&sids,
<API key>, /* sure ? */
&count,
0, 0);
<API key>(status);
if (count != 1 || sids.count != 1) {
return <API key>;
}
sid_copy(sid, sids.sids[0].sid);
return NT_STATUS_OK;
}
static WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *add,
struct <API key> *del,
struct <API key> *set)
{
struct <API key> *r = NULL;
struct rpc_pipe_client *pipe_cli = NULL;
struct rpc_pipe_client *lsa_pipe = NULL;
NTSTATUS status;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dom_sid *member_sids = NULL;
int i = 0, k = 0;
struct <API key> *info0 = NULL;
struct <API key> *info3 = NULL;
struct dom_sid *add_sids = NULL;
struct dom_sid *del_sids = NULL;
size_t num_add_sids = 0;
size_t num_del_sids = 0;
if ((!add && !del && !set) || (add && del && set)) {
return WERR_INVALID_PARAM;
}
if (add) {
r = add;
}
if (del) {
r = (struct <API key> *)del;
}
if (set) {
r = (struct <API key> *)set;
}
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 3:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->in.total_entries == 0 || !r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
member_sids = TALLOC_ZERO_ARRAY(ctx, struct dom_sid,
r->in.total_entries);
<API key>(member_sids);
switch (r->in.level) {
case 0:
info0 = (struct <API key> *)r->in.buffer;
for (i=0; i < r->in.total_entries; i++) {
sid_copy(&member_sids[i], (struct dom_sid *)info0[i].lgrmi0_sid);
}
break;
case 3:
info3 = (struct <API key> *)r->in.buffer;
break;
default:
break;
}
if (r->in.level == 3) {
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_lsarpc.syntax_id,
&lsa_pipe);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
for (i=0; i < r->in.total_entries; i++) {
status = <API key>(ctx, lsa_pipe,
info3[i].<API key>,
&member_sids[i]);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
TALLOC_FREE(lsa_pipe);
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = <API key>(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
<API key> |
<API key> |
<API key> |
<API key>,
&alias_handle);
if (ctx-><API key>) {
<API key>(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto modify_membership;
}
werr = <API key>(ctx, pipe_cli,
<API key> |
<API key>,
<API key>,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = <API key>(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
<API key> |
<API key> |
<API key> |
<API key>,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
}
modify_membership:
if (add) {
for (i=0; i < r->in.total_entries; i++) {
status = <API key>(ctx, &member_sids[i],
&add_sids,
&num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (del) {
for (i=0; i < r->in.total_entries; i++) {
status = <API key>(ctx, &member_sids[i],
&del_sids,
&num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (set) {
struct lsa_SidArray current_sids;
status = <API key>(pipe_cli, ctx,
&alias_handle,
¤t_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
/* add list */
for (i=0; i < r->in.total_entries; i++) {
bool already_member = false;
for (k=0; k < current_sids.num_sids; k++) {
if (sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
already_member = true;
break;
}
}
if (!already_member) {
status = <API key>(ctx,
&member_sids[i],
&add_sids, &num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
/* del list */
for (k=0; k < current_sids.num_sids; k++) {
bool keep_member = false;
for (i=0; i < r->in.total_entries; i++) {
if (sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
keep_member = true;
break;
}
}
if (!keep_member) {
status = <API key>(ctx,
current_sids.sids[k].sid,
&del_sids, &num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
}
/* add list */
for (i=0; i < num_add_sids; i++) {
status = <API key>(pipe_cli, ctx,
&alias_handle,
&add_sids[i]);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
/* del list */
for (i=0; i < num_del_sids; i++) {
status = <API key>(pipe_cli, ctx,
&alias_handle,
&del_sids[i]);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
rpccli_samr_Close(pipe_cli, ctx, &alias_handle);
}
if (ctx-><API key>) {
<API key>(ctx, &domain_handle);
<API key>(ctx, &builtin_handle);
<API key>(ctx, &connect_handle);
}
return werr;
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
return <API key>(ctx, r, NULL, NULL);
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
<API key>(ctx, r, <API key>);
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
return <API key>(ctx, NULL, r, NULL);
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
<API key>(ctx, r, <API key>);
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
return WERR_NOT_SUPPORTED;
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
<API key>(ctx, r, <API key>);
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
return <API key>(ctx, NULL, NULL, r);
}
WERROR <API key>(struct libnetapi_ctx *ctx,
struct <API key> *r)
{
<API key>(ctx, r, <API key>);
}
|
package fr.orsay.lri.varna.applications;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D.Double;
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import javax.swing.DefaultListModel;
import javax.swing.<API key>;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.<API key>;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.<API key>;
import javax.swing.text.<API key>;
import javax.swing.text.DefaultHighlighter;
import fr.orsay.lri.varna.VARNAPanel;
import fr.orsay.lri.varna.components.ReorderableJList;
import fr.orsay.lri.varna.exceptions.<API key>;
import fr.orsay.lri.varna.exceptions.<API key>;
import fr.orsay.lri.varna.exceptions.<API key>;
import fr.orsay.lri.varna.exceptions.<API key>;
import fr.orsay.lri.varna.factories.RNAFactory;
import fr.orsay.lri.varna.interfaces.<API key>;
import fr.orsay.lri.varna.interfaces.<API key>;
import fr.orsay.lri.varna.interfaces.<API key>;
import fr.orsay.lri.varna.models.BaseList;
import fr.orsay.lri.varna.models.FullBackup;
import fr.orsay.lri.varna.models.VARNAConfig;
import fr.orsay.lri.varna.models.rna.Mapping;
import fr.orsay.lri.varna.models.rna.ModeleBP;
import fr.orsay.lri.varna.models.rna.ModeleBase;
import fr.orsay.lri.varna.models.rna.RNA;
public class VARNAGUI extends JFrame implements DropTargetListener, <API key>, MouseListener {
private static final long serialVersionUID = -790155708306987257L;
private static final String DEFAULT_SEQUENCE = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
private static final String DEFAULT_STRUCTURE1 = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
private static final String DEFAULT_STRUCTURE2 = "..(((((...(((((...(((((........(((((...(((((.....)))))...)))))..................))))).....)))))...)))))..";
// private static final String DEFAULT_STRUCTURE1 = "((((....))))";
// private static final String DEFAULT_STRUCTURE2 =
private VARNAPanel _vp;
private JPanel _tools = new JPanel();
private JPanel _input = new JPanel();
private JPanel _seqPanel = new JPanel();
private JPanel _strPanel = new JPanel();
private JLabel _info = new JLabel();
private JTextField _str = new JTextField(DEFAULT_STRUCTURE1);
Object _hoverHighlightStr = null;
ArrayList<Object> <API key> = new ArrayList<Object>();
private JTextField _seq = new JTextField(DEFAULT_SEQUENCE);
Object _hoverHighlightSeq = null;
ArrayList<Object> <API key> = new ArrayList<Object>();
private JLabel _strLabel = new JLabel(" Str:");
private JLabel _seqLabel = new JLabel(" Seq:");
private JButton _createButton = new JButton("Create");
private JButton _deleteButton = new JButton("Delete");
private JButton _duplicateButton = new JButton("Snapshot");
private JPanel _listPanel = new JPanel();
private ReorderableJList _sideList = null;
private static String errorOpt = "error";
@SuppressWarnings("unused")
private boolean _error;
private Color _backgroundColor = Color.white;
private static int _nextID = 1;
@SuppressWarnings("unused")
private int _algoCode;
private BackupHolder _rnaList;
public VARNAGUI() {
super("VARNA GUI");
RNAPanelDemoInit();
}
private void RNAPanelDemoInit()
{
DefaultListModel dlm = new DefaultListModel();
int marginTools = 40;
<API key> m = new <API key>();
m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
m.<API key>(false);
_sideList = new ReorderableJList();
_sideList.setModel(dlm);
_sideList.addMouseListener(this);
_sideList.setSelectionModel(m);
_sideList.setPreferredSize(new Dimension(100, 0));
_sideList.<API key>( new <API key>(){
public void valueChanged(ListSelectionEvent arg0) {
//System.out.println(arg0);
if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
{
FullBackup sel = (FullBackup) _sideList.getSelectedValue();
Mapping map = Mapping.<API key>(_vp.getRNA().getSize(), sel.rna.getSize());
_vp.showRNAInterpolated(sel.rna,sel.config,map);
_seq.setText(sel.rna.getSeq());
_str.setText(sel.rna.getStructDBN(true));
}
}
});
_rnaList = new BackupHolder(dlm,_sideList);
RNA _RNA1 = new RNA("User defined 1");
RNA _RNA2 = new RNA("User defined 2");
try {
_vp = new VARNAPanel("0",".");
_RNA1.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE1);
_RNA1.drawRNARadiate(_vp.getConfig());
_RNA2.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE2);
_RNA2.drawRNARadiate(_vp.getConfig());
} catch (<API key> e) {
_vp.errorDialog(e);
} catch (<API key> e2) {
e2.printStackTrace();
} catch (<API key> e3) {
e3.printStackTrace();
}
_vp.setPreferredSize(new Dimension(400, 400));
_rnaList.add(_vp.getConfig().clone(),_RNA2,generateDefaultName());
_rnaList.add(_vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
JScrollPane listScroller = new JScrollPane(_sideList);
listScroller.setPreferredSize(new Dimension(150, 0));
setBackground(_backgroundColor);
_vp.setBackground(_backgroundColor);
Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
_seqLabel.<API key>(JLabel.LEFT);
_seqLabel.setPreferredSize(new Dimension(marginTools, 15));
_seq.setFont(textFieldsFont);
_seq.setText(DEFAULT_SEQUENCE);
_createButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RNA nRNA = new RNA(generateDefaultName());
nRNA.setRNA(_seq.getText(), _str.getText());
nRNA.drawRNARadiate(_vp.getConfig());
_rnaList.add(new VARNAConfig(),nRNA,true);
} catch (<API key> e1) {
JOptionPane.showMessageDialog(_vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
} catch (<API key> e1) {
JOptionPane.showMessageDialog(_vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
_seqPanel.setLayout(new BorderLayout());
_seqPanel.add(_seqLabel, BorderLayout.WEST);
_seqPanel.add(_seq, BorderLayout.CENTER);
_strLabel.setPreferredSize(new Dimension(marginTools, 15));
_strLabel.<API key>(JLabel.LEFT);
_str.setFont(textFieldsFont);
_strPanel.setLayout(new BorderLayout());
_strPanel.add(_strLabel, BorderLayout.WEST);
_strPanel.add(_str, BorderLayout.CENTER);
_input.setLayout(new GridLayout(2, 0));
_input.add(_seqPanel);
_input.add(_strPanel);
JPanel goPanel = new JPanel();
goPanel.setLayout(new BorderLayout());
_tools.setLayout(new BorderLayout());
_tools.add(_input, BorderLayout.CENTER);
_tools.add(_info, BorderLayout.SOUTH);
_tools.add(goPanel, BorderLayout.EAST);
_deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
_rnaList.removeSelected();
}
});
_duplicateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
_rnaList.add((VARNAConfig)_vp.getConfig().clone(),_vp.getRNA().clone(),_vp.getRNA().getName()+"-"+DateFormat.getTimeInstance(DateFormat.LONG).format(new Date()),true);
}});
JPanel ops = new JPanel();
ops.setLayout(new GridLayout(1,2));
ops.add(_deleteButton);
ops.add(_duplicateButton);
JLabel j = new JLabel("Structures Manager",JLabel.CENTER);
_listPanel.setLayout(new BorderLayout());
_listPanel.add(ops,BorderLayout.SOUTH);
_listPanel.add(j,BorderLayout.NORTH);
_listPanel.add(listScroller,BorderLayout.CENTER);
goPanel.add(_createButton, BorderLayout.CENTER);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,_listPanel,_vp);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(split, BorderLayout.CENTER);
getContentPane().add(_tools, BorderLayout.NORTH);
setVisible(true);
DropTarget dt = new DropTarget(_vp, this);
_vp.addRNAListener(new <API key>(){
public void onSequenceChanged(int index, String oldseq, String newseq) {
//System.out.println("Sequence changed: Index:"+index+" ["+oldseq+"]=>["+newseq+"]");
}
public void onStructureChanged(Set<ModeleBP> current,
Set<ModeleBP> addedBasePairs, Set<ModeleBP> removedBasePairs) {
String result = "";
//System.out.println("Structure changed: ");
for (ModeleBP s:addedBasePairs)
{ result +=s; }
//System.out.println(" Added: "+result);
result = "";
for (ModeleBP s:removedBasePairs)
{ result +=s; }
//System.out.println(" Removed: "+result);
}
public void onLayoutChanged(Hashtable<Integer, Double> previousPositions) {
//System.out.print("Layout changed, bases
String result = "";
for (Integer s:previousPositions.keySet())
{ result +=s+" "; }
//System.out.println(result);
}
});
_vp.<API key>(new <API key>(){
public void onHoverChanged(ModeleBase oldbase, ModeleBase newBase) {
if (_hoverHighlightSeq!=null)
{
_seq.getHighlighter().removeHighlight(_hoverHighlightSeq);
_hoverHighlightSeq = null;
}
if (_hoverHighlightStr!=null)
{
_str.getHighlighter().removeHighlight(_hoverHighlightStr);
_hoverHighlightStr = null;
}
if (newBase!=null)
{
try {
_hoverHighlightSeq = _seq.getHighlighter().addHighlight(newBase.getIndex(), newBase.getIndex()+1, new DefaultHighlighter.<API key>(Color.green) );
_hoverHighlightStr = _str.getHighlighter().addHighlight(newBase.getIndex(), newBase.getIndex()+1, new DefaultHighlighter.<API key>(Color.green) );
} catch (<API key> e) {
e.printStackTrace();
}
}
}
public void onSelectionChanged(BaseList selection,
BaseList addedBases, BaseList removedBases) {
for(Object tag: <API key>)
{
_seq.getHighlighter().removeHighlight(tag);
}
<API key>.clear();
for(Object tag: <API key>)
{
_str.getHighlighter().removeHighlight(tag);
}
<API key>.clear();
for (ModeleBase m: selection.getBases())
{
try {
<API key>.add(_seq.getHighlighter().addHighlight(m.getIndex(), m.getIndex()+1, new DefaultHighlighter.<API key>(Color.orange) ));
<API key>.add(_str.getHighlighter().addHighlight(m.getIndex(), m.getIndex()+1, new DefaultHighlighter.<API key>(Color.orange) ));
} catch (<API key> e) {
e.printStackTrace();
}
}
}
});
_vp.addVARNAListener(this);
}
public static String generateDefaultName()
{
return "User file #"+_nextID++;
}
public RNA getRNA() {
return (RNA)_sideList.getSelectedValue();
}
public String[][] getParameterInfo() {
String[][] info = {
// Parameter Name Kind of Value Description,
{ "sequenceDBN", "String", "A raw RNA sequence" },
{ "structureDBN", "String",
"An RNA structure in dot bracket notation (DBN)" },
{ errorOpt, "boolean", "To show errors" }, };
return info;
}
public void init() {
_vp.setBackground(_backgroundColor);
_error = true;
}
@SuppressWarnings("unused")
private Color getSafeColor(String col, Color def) {
Color result;
try {
result = Color.decode(col);
} catch (Exception e) {
try {
result = Color.getColor(col, def);
} catch (Exception e2) {
return def;
}
}
return result;
}
public VARNAPanel get_varnaPanel() {
return _vp;
}
public void set_varnaPanel(VARNAPanel surface) {
_vp = surface;
}
public JTextField get_seq() {
return _seq;
}
public void set_seq(JTextField _seq) {
this._seq = _seq;
}
public JLabel get_info() {
return _info;
}
public void set_info(JLabel _info) {
this._info = _info;
}
public static void main(String[] args) {
VARNAGUI d = new VARNAGUI();
d.<API key>(JFrame.EXIT_ON_CLOSE);
d.pack();
d.setVisible(true);
}
public void dragEnter(DropTargetDragEvent arg0) {
// TODO Auto-generated method stub
}
public void dragExit(DropTargetEvent arg0) {
// TODO Auto-generated method stub
}
public void dragOver(DropTargetDragEvent arg0) {
// TODO Auto-generated method stub
}
public void drop(DropTargetDropEvent dtde) {
try {
Transferable tr = dtde.getTransferable();
DataFlavor[] flavors = tr.<API key>();
for (int i = 0; i < flavors.length; i++) {
if (flavors[i].<API key>()) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Object ob = tr.getTransferData(flavors[i]);
if (ob instanceof List)
{
List list = (List) ob;
for (int j = 0; j < list.size(); j++) {
Object o = list.get(j);
if (dtde.getSource() instanceof DropTarget)
{
DropTarget dt = (DropTarget) dtde.getSource();
Component c = dt.getComponent();
if (c instanceof VARNAPanel)
{
String path = o.toString();
VARNAPanel vp = (VARNAPanel) c;
try{
FullBackup bck = VARNAPanel.importSession(path);
_rnaList.add(bck.config, bck.rna,bck.name,true);
}
catch (<API key> e3)
{
Collection<RNA> rnas = RNAFactory.loadSecStr(path);
if (rnas.isEmpty())
{
throw new <API key>("No RNA could be parsed from that source.");
}
int id = 1;
for(RNA r: rnas)
{
r.drawRNA(vp.getConfig());
String name = r.getName();
if (name.equals(""))
{
name = path.substring(path.lastIndexOf(File.separatorChar)+1);
}
if (rnas.size()>1)
{
name += " - Molecule
}
_rnaList.add(vp.getConfig().clone(),r,name,true);
}
}
}
}
}
}
// If we made it this far, everything worked.
dtde.dropComplete(true);
return;
}
}
// Hmm, the user must not have dropped a file list
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
public void dropActionChanged(DropTargetDragEvent arg0) {
}
private class BackupHolder{
private DefaultListModel _rnaList;
private ArrayList<RNA> _rnas = new ArrayList<RNA>();
JList _l;
public BackupHolder(DefaultListModel rnaList, JList l)
{
_rnaList = rnaList;
_l = l;
}
public void add(VARNAConfig c, RNA r)
{
add(c, r, r.getName(),false);
}
public void add(VARNAConfig c, RNA r,boolean select)
{
add(c, r, r.getName(),select);
}
public void add(VARNAConfig c, RNA r, String name)
{
add(c, r, name,false);
}
public void add(VARNAConfig c, RNA r, String name, boolean select)
{
if (select){
_l.<API key>(0, _rnaList.size());
}
if (name.equals(""))
{
name = generateDefaultName();
}
FullBackup bck = new FullBackup(c,r,name);
_rnas.add(0, r);
_rnaList.add(0,bck);
if (select){
_l.setSelectedIndex(0);
}
}
public void remove(int i)
{
_rnas.remove(i);
_rnaList.remove(i);
}
public DefaultListModel getModel()
{
return _rnaList;
}
public boolean contains(RNA r)
{
return _rnas.contains(r);
}
/*public int getSize()
{
return _rnaList.getSize();
}*/
public FullBackup getElementAt(int i)
{
return (FullBackup) _rnaList.getElementAt(i);
}
public void removeSelected()
{
int i = _l.getSelectedIndex();
if (i!=-1)
{
if (_rnaList.getSize()==1)
{
RNA r = new RNA();
try {
r.setRNA(" ", ".");
} catch (<API key> e1) {
} catch (<API key> e1) {
}
_vp.showRNA(r);
_vp.repaint();
}
else
{
int newi = i+1;
if (newi==_rnaList.getSize())
{
newi = _rnaList.getSize()-2;
}
FullBackup bck = (FullBackup) _rnaList.getElementAt(newi);
_l.setSelectedValue(bck,true);
}
_rnaList.remove(i);
}
}
}
public void onStructureRedrawn() {
// TODO Auto-generated method stub
}
public void onUINewStructure(VARNAConfig v, RNA r) {
_rnaList.add(v, r,"",true);
}
public void onWarningEmitted(String s) {
// TODO Auto-generated method stub
}
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2){
int index = _sideList.locationToIndex(e.getPoint());
ListModel dlm = _sideList.getModel();
FullBackup item = (FullBackup) dlm.getElementAt(index);;
_sideList.<API key>(index);
Object newName = JOptionPane.showInputDialog(
this,
"Specify a new name for this RNA",
"Rename RNA",
JOptionPane.QUESTION_MESSAGE,
(Icon)null,
null,
item.toString());
if (newName!=null)
{
item.name = newName.toString();
this._sideList.repaint();
}
}
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
|
#!/usr/bin/env bash
# Author [Jean Pourroy - jean.pourroy at g_:) _mail.com]
# Description: Bash file using to start/stop uncore counters for Skylake Architecture with the lspci command
# ref: bash template from
# ref: code inspired from John Mc Calpin answers on intel forum
VERSION=1.0
USAGE="Usage: $0 {start, stop, read, reset}
- start setup and start the uncore counters
- stop stop the uncore counters
- read dump the uncore counters
- reset set the value 0 in the uncore counters\n"
while getopts ":vh" optname
do
case "$optname" in
"v")
echo "Version $VERSION"
exit 0;
;;
"h")
printf "$USAGE"
exit 0;
;;
"?")
echo "Unknown option $OPTARG"
exit 0;
;;
":")
echo "No argument value for option $OPTARG"
exit 0;
;;
*)
echo "Unknown error while processing options"
exit 0;
;;
esac
done
shift $(($OPTIND - 1))
cmd=$1
param=$2
command="command_$1"
#Get results with:
#while sleep .1 ; do nice -n -20 ./setpci_msr.sh | grep TOTAL | awk '{ print $4 }' | tr '\n' ' ' ; echo "" ; done
#all busses
export mybusses=` lspci |grep -i 'System peripheral: Intel Corporation Device 2066'| cut -f 1 -d : | sort | uniq`
#Just my CPU
export mybusses=$(res=`rdmsr 0x300` && printf "%x" $(( ( 0x$res >> 16 & 0xff ) )))
export myfunctions=`lspci |grep-i "\(2042\|2046\|204A\)"| cut -f 2 -d : | cut -f 2 -d . |cut -f 1 -d ' ' | sort | uniq `
export mychannels=`seq 0 5`
#Channel 0 1 2 3 4 5
export devices=( 0a 0a 0b 0c 0c 0d)
export function=( 2 6 2 2 6 2)
source <API key>
#This will set the following variable
#pmonunitctrl_hi
#pmonunitctrl_lo
#Counter (config)
#pmoncntrcfg_0
#pmoncntrcfg_1
#Counter (data)
#pmoncntrupper1_0#counter 0
#pmoncntrlower1_0#counter 0
#pmoncntrupper1_1#counter 1
#pmoncntrlower1_1#counter 1
#Event
#ev_read #CAS_COUNT.RD = ENABLE | RESET | umask:b00000011 | event:0x04
#ev_write #CAS_COUNT.WR = ENABLE | RESET | umask:b00001100 | event:0x04
echo "
echo " - command: " $command
echo " - mybusses: " $mybusses
echo " - mydevices: " ${devices[@]}
echo " - myfunctions: " ${function[@]}
echo " - mychannels: " $mychannels
echo " - myeventts: " $ev_read " " $ev_write
echo "
if [ -z $ev_read ] ; then
echo "Error: source the Skylake information file (currently NDA), if you have it :)"
exit
fi
function command_start (){
echo "Setting up IMC Performance Counters"
for BUS in $mybusses #ONE PER CPU
do
for CHAN in $mychannels
do
# FREEZE and RESET
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_hi}=0x1
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_lo}=0x2
# ZERO
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrupper1_0}=0x0 #ctr0
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrlower1_0}=0x0 #ctr0
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrupper1_1}=0x0 #ctr1
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrlower1_1}=0x0 #ctr1
# RESET MONITORING CTRL REGISTERS
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_lo}=0x1
# CONFIGURE COUNTER #0 FOR CAS_COUNT.RD and #1 for CAS_COUNT_WR
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrcfg_0}=${ev_read}
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrcfg_1}=${ev_write}
# RELEASE COUNTERS
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_hi}=0x0
done
done
}
function command_read(){
echo "Reading IMC CycleCounter and Programmable counters "
sum_r=0
sum_w=0
for BUS in $mybusses #ONE PER CPU
do
for CHAN in $mychannels
do
# FREEZE
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_hi}=0x1
# READ RESULTS
hi=`setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrupper1_0}`
lo=`setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrlower1_0}`
r=`echo -n "$((0x$hi$lo)) "`
hi=`setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrupper1_1}`
lo=`setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrlower1_1}`
w=`echo -n "$((0x$hi$lo)) "`
sum_r=$(( $sum_r + $r ))
sum_w=$(( $sum_w + $w ))
# ZERO
#command_reset
# RELEASE COUNTERS
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_hi}=0x0
done
done
echo " TOTAL READ = $sum_r"
echo " TOTAL WRITE = $sum_w"
}
function command_reset(){
echo "Reset IMC CycleCounter and Programmable counters "
for BUS in $mybusses #ONE PER CPU
do
for CHAN in $mychannels
do
# ZERO
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrupper1_0}=0x0 #ctr0
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrlower1_0}=0x0 #ctr0
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrupper1_1}=0x0 #ctr1
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmoncntrlower1_1}=0x0 #ctr1
done
done
}
function command_stop (){
echo "STOP IMC CycleCounter and Programmable counters "
for BUS in $mybusses #ONE PER CPU
do
for CHAN in $mychannels
do
# FREEZE
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_hi}=0x1 #FREEZE
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_lo}=0x2 #RESET
setpci -s ${BUS}:${devices[CHAN]}.${function[CHAN]} ${pmonunitctrl_lo}=0x1 #RESET MONITORING CTRL REGISTERS
done
done
}
if [ -n "$(type -t ${command})" ] && [ "$(type -t ${command})" = function ]; then
${command}
else
echo "'${cmd}' is NOT a command";
fi
|
<?php
// This program is free software: you can redistribute it and/or modify
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// If you purchased an openITCOCKPIT Enterprise Edition you can use this file
// confirmation.
namespace itnovum\openITCOCKPIT\Core;
class CommandArgReplacer {
/**
* @var array
*/
private $<API key>;
/**
* CommandArgReplacer constructor.
* @param array $<API key>
*/
public function __construct($<API key>) {
$this-><API key> = $<API key>;
}
/**
* Replace the folowing Macros:
* - $ARG1$
* - $ARG2$
* - $ARGn$
*
* @param string $msg
* @return string
*/
public function replace($cmdStr) {
$mapping = $this->buildMapping('basic');
return str_replace($mapping['search'], $mapping['replace'], $cmdStr);
}
/**
* @return array
*/
private function buildMapping() {
$mapping = [
'search' => [],
'replace' => [],
];
foreach ($this-><API key> as $<API key>) {
$argn = $<API key>['commandargument']['name'];
$value = $<API key>['value'];
$mapping['search'][] = $argn;
$mapping['replace'][] = $value;
}
return $mapping;
}
}
|
#include "argList.H"
#include "timeSelector.H"
#include "Time.H"
#include "polyMesh.H"
#include "OFstream.H"
#include "meshTools.H"
#include "cellSet.H"
#include "faceSet.H"
using namespace Foam;
void writeOBJ(const point& pt, Ostream& os)
{
os << "v " << pt.x() << ' ' << pt.y() << ' ' << pt.z() << nl;
}
// All edges of mesh
void writePoints(const polyMesh& mesh, const fileName& timeName)
{
label vertI = 0;
fileName pointFile(mesh.time().path()/"meshPoints_" + timeName + ".obj");
Info << "Writing mesh points and edges to " << pointFile << endl;
OFstream pointStream(pointFile);
forAll(mesh.points(), pointI)
{
writeOBJ(mesh.points()[pointI], pointStream);
vertI++;
}
forAll(mesh.edges(), edgeI)
{
const edge& e = mesh.edges()[edgeI];
pointStream << "l " << e.start() + 1 << ' ' << e.end() + 1 << nl;
}
}
// Edges for subset of cells
void writePoints
(
const polyMesh& mesh,
const labelList& cellLabels,
const fileName& timeName
)
{
fileName fName(mesh.time().path()/"meshPoints_" + timeName + ".obj");
Info << "Writing mesh points and edges to " << fName << endl;
OFstream str(fName);
// OBJ file vertex
label vertI = 0;
// From point to OBJ file vertex
Map<label> pointToObj(6*cellLabels.size());
forAll(cellLabels, i)
{
label cellI = cellLabels[i];
const labelList& cEdges = mesh.cellEdges()[cellI];
forAll(cEdges, cEdgeI)
{
const edge& e = mesh.edges()[cEdges[cEdgeI]];
label v0;
Map<label>::iterator e0Fnd = pointToObj.find(e[0]);
if (e0Fnd == pointToObj.end())
{
meshTools::writeOBJ(str, mesh.points()[e[0]]);
v0 = vertI++;
pointToObj.insert(e[0], v0);
}
else
{
v0 = e0Fnd();
}
label v1;
Map<label>::iterator e1Fnd = pointToObj.find(e[1]);
if (e1Fnd == pointToObj.end())
{
meshTools::writeOBJ(str, mesh.points()[e[1]]);
v1 = vertI++;
pointToObj.insert(e[1], v1);
}
else
{
v1 = e1Fnd();
}
str << "l " << v0+1 << ' ' << v1+1 << nl;
}
}
}
// Edges of single cell
void writePoints
(
const polyMesh& mesh,
const label cellI,
const fileName& timeName
)
{
fileName fName
(
mesh.time().path()
/ "meshPoints_" + timeName + '_' + name(cellI) + ".obj"
);
Info << "Writing mesh points and edges to " << fName << endl;
OFstream pointStream(fName);
const cell& cFaces = mesh.cells()[cellI];
meshTools::writeOBJ(pointStream, mesh.faces(), mesh.points(), cFaces);
}
// All face centres
void writeFaceCentres(const polyMesh& mesh,const fileName& timeName)
{
fileName faceFile
(
mesh.time().path()
/ "meshFaceCentres_" + timeName + ".obj"
);
Info << "Writing mesh face centres to " << faceFile << endl;
OFstream faceStream(faceFile);
forAll(mesh.faceCentres(), faceI)
{
writeOBJ(mesh.faceCentres()[faceI], faceStream);
}
}
void writeCellCentres(const polyMesh& mesh, const fileName& timeName)
{
fileName cellFile
(
mesh.time().path()/"meshCellCentres_" + timeName + ".obj"
);
Info << "Writing mesh cell centres to " << cellFile << endl;
OFstream cellStream(cellFile);
forAll(mesh.cellCentres(), cellI)
{
writeOBJ(mesh.cellCentres()[cellI], cellStream);
}
}
void writePatchCentres
(
const polyMesh& mesh,
const fileName& timeName
)
{
const polyBoundaryMesh& patches = mesh.boundaryMesh();
forAll(patches, patchI)
{
const polyPatch& pp = patches[patchI];
fileName faceFile
(
mesh.time().path()/"patch_" + pp.name() + '_' + timeName + ".obj"
);
Info << "Writing patch face centres to " << faceFile << endl;
OFstream patchFaceStream(faceFile);
forAll(pp.faceCentres(), faceI)
{
writeOBJ(pp.faceCentres()[faceI], patchFaceStream);
}
}
}
void writePatchFaces
(
const polyMesh& mesh,
const fileName& timeName
)
{
const polyBoundaryMesh& patches = mesh.boundaryMesh();
forAll(patches, patchI)
{
const polyPatch& pp = patches[patchI];
fileName faceFile
(
mesh.time().path()
/ "patchFaces_" + pp.name() + '_' + timeName + ".obj"
);
Info << "Writing patch faces to " << faceFile << endl;
OFstream patchFaceStream(faceFile);
forAll(pp.localPoints(), pointI)
{
writeOBJ(pp.localPoints()[pointI], patchFaceStream);
}
forAll(pp.localFaces(), faceI)
{
const face& f = pp.localFaces()[faceI];
patchFaceStream<< 'f';
forAll(f, fp)
{
patchFaceStream << ' ' << f[fp]+1;
}
patchFaceStream << nl;
}
}
}
void <API key>
(
const polyMesh& mesh,
const fileName& timeName
)
{
const polyBoundaryMesh& patches = mesh.boundaryMesh();
forAll(patches, patchI)
{
const polyPatch& pp = patches[patchI];
fileName edgeFile
(
mesh.time().path()
/ "patchEdges_" + pp.name() + '_' + timeName + ".obj"
);
Info << "Writing patch edges to " << edgeFile << endl;
OFstream patchEdgeStream(edgeFile);
forAll(pp.localPoints(), pointI)
{
writeOBJ(pp.localPoints()[pointI], patchEdgeStream);
}
for (label edgeI = pp.nInternalEdges(); edgeI < pp.nEdges(); edgeI++)
{
if (pp.edgeFaces()[edgeI].size() == 1)
{
const edge& e = pp.edges()[edgeI];
patchEdgeStream<< "l " << e[0]+1 << ' ' << e[1]+1 << nl;
}
}
}
}
void writePointCells
(
const polyMesh& mesh,
const label pointI,
const fileName& timeName
)
{
const labelList& pCells = mesh.pointCells()[pointI];
labelHashSet allEdges(6*pCells.size());
forAll(pCells, i)
{
const labelList& cEdges = mesh.cellEdges()[pCells[i]];
forAll(cEdges, i)
{
allEdges.insert(cEdges[i]);
}
}
fileName pFile
(
mesh.time().path()
/ "pointEdges_" + timeName + '_' + name(pointI) + ".obj"
);
Info << "Writing pointEdges to " << pFile << endl;
OFstream pointStream(pFile);
label vertI = 0;
for
(
labelHashSet::const_iterator iter = allEdges.begin();
iter != allEdges.end();
++iter
)
{
const edge& e = mesh.edges()[iter.key()];
meshTools::writeOBJ(pointStream, mesh.points()[e[0]]); vertI++;
meshTools::writeOBJ(pointStream, mesh.points()[e[1]]); vertI++;
pointStream<< "l " << vertI-1 << ' ' << vertI << nl;
}
}
// Main program:
int main(int argc, char *argv[])
{
timeSelector::addOptions();
argList::validOptions.insert("patchFaces", "");
argList::validOptions.insert("patchEdges", "");
argList::validOptions.insert("cell", "cellI");
argList::validOptions.insert("face", "faceI");
argList::validOptions.insert("point", "pointI");
argList::validOptions.insert("cellSet", "setName");
argList::validOptions.insert("faceSet", "setName");
# include "addRegionOption.H"
# include "setRootCase.H"
# include "createTime.H"
runTime.functionObjects().off();
bool patchFaces = args.optionFound("patchFaces");
bool patchEdges = args.optionFound("patchEdges");
bool doCell = args.optionFound("cell");
bool doPoint = args.optionFound("point");
bool doFace = args.optionFound("face");
bool doCellSet = args.optionFound("cellSet");
bool doFaceSet = args.optionFound("faceSet");
Info<< "Writing mesh objects as .obj files such that the object"
<< " numbering" << endl
<< "(for points, faces, cells) is consistent with"
<< " Foam numbering (starting from 0)." << endl << endl;
instantList timeDirs = timeSelector::select0(runTime, args);
# include "createNamedPolyMesh.H"
forAll(timeDirs, timeI)
{
runTime.setTime(timeDirs[timeI], timeI);
Info<< "Time = " << runTime.timeName() << endl;
polyMesh::readUpdateState state = mesh.readUpdate();
if (!timeI || state != polyMesh::UNCHANGED)
{
if (patchFaces)
{
writePatchFaces(mesh, runTime.timeName());
}
if (patchEdges)
{
<API key>(mesh, runTime.timeName());
}
if (doCell)
{
label cellI = args.optionRead<label>("cell");
writePoints(mesh, cellI, runTime.timeName());
}
if (doPoint)
{
label pointI = args.optionRead<label>("point");
writePointCells(mesh, pointI, runTime.timeName());
}
if (doFace)
{
label faceI = args.optionRead<label>("face");
fileName fName
(
mesh.time().path()
/ "meshPoints_"
+ runTime.timeName()
+ '_'
+ name(faceI)
+ ".obj"
);
Info<< "Writing mesh points and edges to " << fName << endl;
OFstream str(fName);
const face& f = mesh.faces()[faceI];
meshTools::writeOBJ(str, faceList(1, f), mesh.points());
}
if (doCellSet)
{
word setName(args.option("cellSet"));
cellSet cells(mesh, setName);
Info<< "Read " << cells.size() << " cells from set " << setName
<< endl;
writePoints(mesh, cells.toc(), runTime.timeName());
}
if (doFaceSet)
{
word setName(args.option("faceSet"));
faceSet faces(mesh, setName);
Info<< "Read " << faces.size() << " faces from set " << setName
<< endl;
fileName fName
(
mesh.time().path()
/ "meshPoints_"
+ runTime.timeName()
+ '_'
+ setName
+ ".obj"
);
Info << "Writing mesh points and edges to " << fName << endl;
OFstream str(fName);
meshTools::writeOBJ
(
str,
mesh.faces(),
mesh.points(),
faces.toc()
);
}
else if
(
!patchFaces
&& !patchEdges
&& !doCell
&& !doPoint
&& !doFace
&& !doCellSet
&& !doFaceSet
)
{
// points & edges
writePoints(mesh, runTime.timeName());
// face centres
writeFaceCentres(mesh, runTime.timeName());
// cell centres
writeCellCentres(mesh, runTime.timeName());
// Patch face centres
writePatchCentres(mesh, runTime.timeName());
}
}
else
{
Info << "No mesh." << endl;
}
Info << nl << endl;
}
Info << "End\n" << endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.